diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/ccw.core/src/java/ccw/builder/ClojureVisitor.java b/ccw.core/src/java/ccw/builder/ClojureVisitor.java index 7fb51a8f..aa499217 100644 --- a/ccw.core/src/java/ccw/builder/ClojureVisitor.java +++ b/ccw.core/src/java/ccw/builder/ClojureVisitor.java @@ -1,168 +1,169 @@ /******************************************************************************* * Copyright (c) 2009 Anyware Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Gaetan Morice (Anyware Technologies) - initial implementation *******************************************************************************/ package ccw.builder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.texteditor.MarkerUtilities; import ccw.CCWPlugin; import ccw.ClojureCore; import ccw.editors.clojure.CompileLibAction; import clojure.tools.nrepl.Connection; import clojure.tools.nrepl.Connection.Response; public class ClojureVisitor implements IResourceVisitor { private Map.Entry<IFolder, IFolder> currentSrcFolder; private Map<IFolder, IFolder> srcFolders; private final List<String> clojureLibs = new ArrayList<String>(); private final Connection repl; public ClojureVisitor() { repl = null; } public ClojureVisitor (Connection repl) { this.repl = repl; } public void visit (Map<IFolder, IFolder> srcFolders) throws CoreException { this.srcFolders = new HashMap<IFolder, IFolder>(srcFolders); for(Map.Entry<IFolder, IFolder> srcFolderEntry : srcFolders.entrySet()){ setSrcFolder(srcFolderEntry); srcFolderEntry.getKey().accept(this); } if (repl != null) { try { for (String maybeLibName: clojureLibs) { // System.out.println("compiling:'" + maybeLibName + "'"); String compileLibCommand = CompileLibAction.compileLibCommand(maybeLibName); // System.out.println("Sending command: '" + compileLibCommand + "'"); Response res = repl.send("op", "eval", "code", compileLibCommand); // System.out.println("compilation response: '" + res + "'"); if (res.values().isEmpty()) { // System.out.println(("oops, weird error when compiling '" + maybeLibName + "'")); } else { Object result = res.values().get(0); // System.out.println("ClojureVisitor: " + result); if (result instanceof Map) { Map resultMap = (Map) result; Collection<Map> response = (Collection<Map>)resultMap.get("response"); if (response != null) { Map<?,?> errorMap = (Map<?,?>) response.iterator().next(); if (errorMap != null) { String message = (String) errorMap.get("message"); if (message != null) { // System.out.println("error message:" + message); Matcher matcher = ERROR_MESSAGE_PATTERN.matcher(message); if (matcher.matches()) { // System.out.println("match found for message:'" + message + "'"); String messageBody = matcher.group(MESSAGE_GROUP); String filename = matcher.group(FILENAME_GROUP); String lineStr = matcher.group(LINE_GROUP); // System.out.println("message:" + messageBody); // System.out.println("file:" + filename); // System.out.println("line:" + lineStr); if (!NO_SOURCE_FILE.equals(filename)) { createMarker(filename, Integer.parseInt(lineStr), messageBody); } } else { // System.out.println("no match found for message:'" + message + "'"); } } } } } } } } catch (Exception e) { - throw new WorkbenchException("Could not visit: " + clojureLibs, e); + throw new WorkbenchException( + String.format("Could not visit: %s.\nDid you kill the project's JVM during the build?", clojureLibs), e); } } } //"java.lang.Exception: Unable to resolve symbol: pairs in this context (sudoku_solver.clj:130)" private static final Pattern ERROR_MESSAGE_PATTERN = Pattern.compile("^(java.lang.Exception: )?(.*)\\((.+):(\\d+)\\)$"); private static final int MESSAGE_GROUP = 2; private static final int FILENAME_GROUP = 3; private static final int LINE_GROUP = 4; private static final String NO_SOURCE_FILE = "NO_SOURCE_FILE"; public boolean visit(IResource resource) throws CoreException { if (resource instanceof IFile) { String maybeLibName = ClojureCore.findMaybeLibNamespace( (IFile) resource, currentSrcFolder.getKey().getFullPath()); if (maybeLibName != null) { clojureLibs.add(maybeLibName); // System.out.println("maybe lib: " + resource.getLocation() + " recognized as a lib"); } else { // System.out.println("maybe lib: " + resource.getLocation() + " NOT recognized as a lib"); } } return true; } private void createMarker(final String filename, final int line, final String message) { try { // System.out.println("(trying to) create a marker for " + filename); for (IFolder srcFolder: srcFolders.keySet()) { srcFolder.accept(new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { if (resource.getType() == IResource.FILE) { // System.out.println(" file found: " + resource.getName()); if (resource.getName().equals(filename)) { Map attrs = new HashMap(); MarkerUtilities.setLineNumber(attrs, line); MarkerUtilities.setMessage(attrs, message); attrs.put(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); MarkerUtilities.createMarker(resource, attrs, ClojureBuilder.CLOJURE_COMPILER_PROBLEM_MARKER_TYPE); // System.out.println("created marker !"); } } return true; } }); } } catch (CoreException e) { CCWPlugin.logError("error while creating marker for file : " + filename + " at line " + line + " with message :'" + message + "'", e); } } public String[] getClojureLibs() { return clojureLibs.toArray(new String[clojureLibs.size()]); } /** * @param srcFolder */ public void setSrcFolder(Map.Entry<IFolder, IFolder> srcFolder) { this.currentSrcFolder = srcFolder; } }
true
true
public void visit (Map<IFolder, IFolder> srcFolders) throws CoreException { this.srcFolders = new HashMap<IFolder, IFolder>(srcFolders); for(Map.Entry<IFolder, IFolder> srcFolderEntry : srcFolders.entrySet()){ setSrcFolder(srcFolderEntry); srcFolderEntry.getKey().accept(this); } if (repl != null) { try { for (String maybeLibName: clojureLibs) { // System.out.println("compiling:'" + maybeLibName + "'"); String compileLibCommand = CompileLibAction.compileLibCommand(maybeLibName); // System.out.println("Sending command: '" + compileLibCommand + "'"); Response res = repl.send("op", "eval", "code", compileLibCommand); // System.out.println("compilation response: '" + res + "'"); if (res.values().isEmpty()) { // System.out.println(("oops, weird error when compiling '" + maybeLibName + "'")); } else { Object result = res.values().get(0); // System.out.println("ClojureVisitor: " + result); if (result instanceof Map) { Map resultMap = (Map) result; Collection<Map> response = (Collection<Map>)resultMap.get("response"); if (response != null) { Map<?,?> errorMap = (Map<?,?>) response.iterator().next(); if (errorMap != null) { String message = (String) errorMap.get("message"); if (message != null) { // System.out.println("error message:" + message); Matcher matcher = ERROR_MESSAGE_PATTERN.matcher(message); if (matcher.matches()) { // System.out.println("match found for message:'" + message + "'"); String messageBody = matcher.group(MESSAGE_GROUP); String filename = matcher.group(FILENAME_GROUP); String lineStr = matcher.group(LINE_GROUP); // System.out.println("message:" + messageBody); // System.out.println("file:" + filename); // System.out.println("line:" + lineStr); if (!NO_SOURCE_FILE.equals(filename)) { createMarker(filename, Integer.parseInt(lineStr), messageBody); } } else { // System.out.println("no match found for message:'" + message + "'"); } } } } } } } } catch (Exception e) { throw new WorkbenchException("Could not visit: " + clojureLibs, e); } } }
public void visit (Map<IFolder, IFolder> srcFolders) throws CoreException { this.srcFolders = new HashMap<IFolder, IFolder>(srcFolders); for(Map.Entry<IFolder, IFolder> srcFolderEntry : srcFolders.entrySet()){ setSrcFolder(srcFolderEntry); srcFolderEntry.getKey().accept(this); } if (repl != null) { try { for (String maybeLibName: clojureLibs) { // System.out.println("compiling:'" + maybeLibName + "'"); String compileLibCommand = CompileLibAction.compileLibCommand(maybeLibName); // System.out.println("Sending command: '" + compileLibCommand + "'"); Response res = repl.send("op", "eval", "code", compileLibCommand); // System.out.println("compilation response: '" + res + "'"); if (res.values().isEmpty()) { // System.out.println(("oops, weird error when compiling '" + maybeLibName + "'")); } else { Object result = res.values().get(0); // System.out.println("ClojureVisitor: " + result); if (result instanceof Map) { Map resultMap = (Map) result; Collection<Map> response = (Collection<Map>)resultMap.get("response"); if (response != null) { Map<?,?> errorMap = (Map<?,?>) response.iterator().next(); if (errorMap != null) { String message = (String) errorMap.get("message"); if (message != null) { // System.out.println("error message:" + message); Matcher matcher = ERROR_MESSAGE_PATTERN.matcher(message); if (matcher.matches()) { // System.out.println("match found for message:'" + message + "'"); String messageBody = matcher.group(MESSAGE_GROUP); String filename = matcher.group(FILENAME_GROUP); String lineStr = matcher.group(LINE_GROUP); // System.out.println("message:" + messageBody); // System.out.println("file:" + filename); // System.out.println("line:" + lineStr); if (!NO_SOURCE_FILE.equals(filename)) { createMarker(filename, Integer.parseInt(lineStr), messageBody); } } else { // System.out.println("no match found for message:'" + message + "'"); } } } } } } } } catch (Exception e) { throw new WorkbenchException( String.format("Could not visit: %s.\nDid you kill the project's JVM during the build?", clojureLibs), e); } } }
diff --git a/src/com/asksven/android/common/kernelutils/AlarmsDumpsys.java b/src/com/asksven/android/common/kernelutils/AlarmsDumpsys.java index fca5f55..aae25ec 100644 --- a/src/com/asksven/android/common/kernelutils/AlarmsDumpsys.java +++ b/src/com/asksven/android/common/kernelutils/AlarmsDumpsys.java @@ -1,150 +1,150 @@ /** * */ package com.asksven.android.common.kernelutils; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Log; import com.asksven.android.common.shellutils.Exec; import com.asksven.android.common.shellutils.ExecResult; /** * Parses the content of 'dumpsys alarm' * processes the result of 'dumpsys alarm' as explained in KB article * https://github.com/asksven/BetterBatteryStats-Knowledge-Base/wiki/AlarmManager * @author sven */ public class AlarmsDumpsys { static final String TAG = "AlarmsDumpsys"; /** * Returns a list of alarm value objects * @return * @throws Exception */ public static ArrayList<Alarm> getAlarms() { ArrayList<Alarm> myAlarms = null; // ExecResult res = Exec.execPrint(new String[]{"/system/bin/su", "-c", "/system/bin/dumpsys alarm"}); ExecResult res = Exec.execPrint(new String[]{"su", "-c", "dumpsys alarm"}); if (res.getSuccess()) { String strRes = res.getResultLine(); if (!strRes.contains("Permission Denial")) { Pattern begin = Pattern.compile("Alarm Stats"); boolean bParsing = false; ArrayList<String> myRes = res.getResult(); // we are looking for multiline entries in the format // ' <package name> // ' <time> ms running, <number> wakeups // ' <number> alarms: act=<intent name> flg=<flag> (repeating 1..n times) - Pattern packagePattern = Pattern.compile("\\s\\s([a-z\\.]+)"); + Pattern packagePattern = Pattern.compile("\\s\\s([a-zA-Z0-9\\.]+)"); Pattern timePattern = Pattern.compile("\\s\\s(\\d+)ms running, (\\d+) wakeups"); Pattern numberPattern = Pattern.compile("\\s\\s(\\d+) alarms: act=([A-Za-z0-9\\-\\_\\.]+)"); myAlarms = new ArrayList<Alarm>(); Alarm myAlarm = null; // process the file for (int i=0; i < myRes.size(); i++) { // skip till start mark found if (bParsing) { // parse the alarms by block String line = myRes.get(i); Matcher mPackage = packagePattern.matcher(line); Matcher mTime = timePattern.matcher(line); Matcher mNumber = numberPattern.matcher(line); // first line if ( mPackage.find() ) { try { // if there was a previous Alarm populated store it if (myAlarm != null) { myAlarms.add(myAlarm); } // we are interested in the first token String strPackageName = mPackage.group(1); myAlarm = new Alarm(strPackageName); } catch (Exception e) { Log.e(TAG, "Error: parsing error in package line (" + line + ")"); } } // second line if ( mTime.find() ) { try { // we are interested in the second token String strWakeups = mTime.group(2); long nWakeups = Long.parseLong(strWakeups); if (myAlarm == null) { Log.e(TAG, "Error: time line found but without alarm object (" + line + ")"); } else { myAlarm.setWakeups(nWakeups); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in time line (" + line + ")"); } } // third line (and following till next package if ( mNumber.find() ) { try { // we are interested in the first and second token String strNumber = mNumber.group(1); String strIntent = mNumber.group(2); long nNumber = Long.parseLong(strNumber); if (myAlarm == null) { Log.e(TAG, "Error: number line found but without alarm object (" + line + ")"); } else { myAlarm.addItem(nNumber, strIntent); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in number line (" + line + ")"); } } } else { // look for beginning Matcher line = begin.matcher(myRes.get(i)); if (line.find()) { bParsing = true; } } } } } return myAlarms; } }
true
true
public static ArrayList<Alarm> getAlarms() { ArrayList<Alarm> myAlarms = null; // ExecResult res = Exec.execPrint(new String[]{"/system/bin/su", "-c", "/system/bin/dumpsys alarm"}); ExecResult res = Exec.execPrint(new String[]{"su", "-c", "dumpsys alarm"}); if (res.getSuccess()) { String strRes = res.getResultLine(); if (!strRes.contains("Permission Denial")) { Pattern begin = Pattern.compile("Alarm Stats"); boolean bParsing = false; ArrayList<String> myRes = res.getResult(); // we are looking for multiline entries in the format // ' <package name> // ' <time> ms running, <number> wakeups // ' <number> alarms: act=<intent name> flg=<flag> (repeating 1..n times) Pattern packagePattern = Pattern.compile("\\s\\s([a-z\\.]+)"); Pattern timePattern = Pattern.compile("\\s\\s(\\d+)ms running, (\\d+) wakeups"); Pattern numberPattern = Pattern.compile("\\s\\s(\\d+) alarms: act=([A-Za-z0-9\\-\\_\\.]+)"); myAlarms = new ArrayList<Alarm>(); Alarm myAlarm = null; // process the file for (int i=0; i < myRes.size(); i++) { // skip till start mark found if (bParsing) { // parse the alarms by block String line = myRes.get(i); Matcher mPackage = packagePattern.matcher(line); Matcher mTime = timePattern.matcher(line); Matcher mNumber = numberPattern.matcher(line); // first line if ( mPackage.find() ) { try { // if there was a previous Alarm populated store it if (myAlarm != null) { myAlarms.add(myAlarm); } // we are interested in the first token String strPackageName = mPackage.group(1); myAlarm = new Alarm(strPackageName); } catch (Exception e) { Log.e(TAG, "Error: parsing error in package line (" + line + ")"); } } // second line if ( mTime.find() ) { try { // we are interested in the second token String strWakeups = mTime.group(2); long nWakeups = Long.parseLong(strWakeups); if (myAlarm == null) { Log.e(TAG, "Error: time line found but without alarm object (" + line + ")"); } else { myAlarm.setWakeups(nWakeups); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in time line (" + line + ")"); } } // third line (and following till next package if ( mNumber.find() ) { try { // we are interested in the first and second token String strNumber = mNumber.group(1); String strIntent = mNumber.group(2); long nNumber = Long.parseLong(strNumber); if (myAlarm == null) { Log.e(TAG, "Error: number line found but without alarm object (" + line + ")"); } else { myAlarm.addItem(nNumber, strIntent); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in number line (" + line + ")"); } } } else { // look for beginning Matcher line = begin.matcher(myRes.get(i)); if (line.find()) { bParsing = true; } } } } } return myAlarms; }
public static ArrayList<Alarm> getAlarms() { ArrayList<Alarm> myAlarms = null; // ExecResult res = Exec.execPrint(new String[]{"/system/bin/su", "-c", "/system/bin/dumpsys alarm"}); ExecResult res = Exec.execPrint(new String[]{"su", "-c", "dumpsys alarm"}); if (res.getSuccess()) { String strRes = res.getResultLine(); if (!strRes.contains("Permission Denial")) { Pattern begin = Pattern.compile("Alarm Stats"); boolean bParsing = false; ArrayList<String> myRes = res.getResult(); // we are looking for multiline entries in the format // ' <package name> // ' <time> ms running, <number> wakeups // ' <number> alarms: act=<intent name> flg=<flag> (repeating 1..n times) Pattern packagePattern = Pattern.compile("\\s\\s([a-zA-Z0-9\\.]+)"); Pattern timePattern = Pattern.compile("\\s\\s(\\d+)ms running, (\\d+) wakeups"); Pattern numberPattern = Pattern.compile("\\s\\s(\\d+) alarms: act=([A-Za-z0-9\\-\\_\\.]+)"); myAlarms = new ArrayList<Alarm>(); Alarm myAlarm = null; // process the file for (int i=0; i < myRes.size(); i++) { // skip till start mark found if (bParsing) { // parse the alarms by block String line = myRes.get(i); Matcher mPackage = packagePattern.matcher(line); Matcher mTime = timePattern.matcher(line); Matcher mNumber = numberPattern.matcher(line); // first line if ( mPackage.find() ) { try { // if there was a previous Alarm populated store it if (myAlarm != null) { myAlarms.add(myAlarm); } // we are interested in the first token String strPackageName = mPackage.group(1); myAlarm = new Alarm(strPackageName); } catch (Exception e) { Log.e(TAG, "Error: parsing error in package line (" + line + ")"); } } // second line if ( mTime.find() ) { try { // we are interested in the second token String strWakeups = mTime.group(2); long nWakeups = Long.parseLong(strWakeups); if (myAlarm == null) { Log.e(TAG, "Error: time line found but without alarm object (" + line + ")"); } else { myAlarm.setWakeups(nWakeups); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in time line (" + line + ")"); } } // third line (and following till next package if ( mNumber.find() ) { try { // we are interested in the first and second token String strNumber = mNumber.group(1); String strIntent = mNumber.group(2); long nNumber = Long.parseLong(strNumber); if (myAlarm == null) { Log.e(TAG, "Error: number line found but without alarm object (" + line + ")"); } else { myAlarm.addItem(nNumber, strIntent); } } catch (Exception e) { Log.e(TAG, "Error: parsing error in number line (" + line + ")"); } } } else { // look for beginning Matcher line = begin.matcher(myRes.get(i)); if (line.find()) { bParsing = true; } } } } } return myAlarms; }
diff --git a/src/edu/unsw/comp9321/logic/Controller.java b/src/edu/unsw/comp9321/logic/Controller.java index c432037..75667a4 100644 --- a/src/edu/unsw/comp9321/logic/Controller.java +++ b/src/edu/unsw/comp9321/logic/Controller.java @@ -1,270 +1,277 @@ package edu.unsw.comp9321.logic; import java.io.IOException; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.DefaultFileItemFactory; import org.apache.tomcat.util.http.fileupload.FileItem; import edu.unsw.comp9321.beans.SessionBean; import edu.unsw.comp9321.common.ServiceLocatorException; import edu.unsw.comp9321.exception.EmptyResultException; import edu.unsw.comp9321.jdbc.ActorDAO; import edu.unsw.comp9321.jdbc.ActorDTO; import edu.unsw.comp9321.jdbc.CastDAO; import edu.unsw.comp9321.jdbc.CinemaDAO; import edu.unsw.comp9321.jdbc.CommentDTO; import edu.unsw.comp9321.jdbc.DerbyDAOImpl; import edu.unsw.comp9321.jdbc.MovieDAO; import edu.unsw.comp9321.jdbc.MovieDTO; import edu.unsw.comp9321.jdbc.MySQLDAOImpl; import edu.unsw.comp9321.jdbc.CharacterDTO; import edu.unsw.comp9321.jdbc.UserDAO; import edu.unsw.comp9321.jdbc.UserDTO; import edu.unsw.comp9321.mail.MailSender; import edu.unsw.comp9321.mail.MailSenderTest; /** * Servlet implementation class Controller */ public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; static Logger logger = Logger.getLogger(Controller.class.getName()); private CastDAO cast; private MovieDAO movies; private ActorDAO actors; private UserDAO users; private UserDTO currentUser; private CinemaDAO cinemas; private SessionBean sessionBean; DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); // upload stuff private static final String UPLOAD_DIRECTORY = "images"; private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB /** * @throws ServletException * @see HttpServlet#HttpServlet() */ public Controller() throws ServletException { // TODO Auto-generated constructor stub super(); try { movies = new MovieDAO(); users = new UserDAO(); actors = new ActorDAO(); cast = new DerbyDAOImpl(); cinemas = new CinemaDAO(); } catch (ServiceLocatorException e) { logger.severe("Trouble connecting to database "+e.getStackTrace()); throw new ServletException(); } catch (SQLException e) { logger.severe("Trouble connecting to database "+e.getStackTrace()); throw new ServletException(); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardPage = ""; sessionBean = (SessionBean) request.getSession().getAttribute("sessionBean"); if(request.getParameter("action").equals("nowShowing")){ List<MovieDTO> resSet = movies.findNowShowing(); request.setAttribute("movieDeets", resSet); // request.setAttribute("userInfo"); forwardPage = "nowShowing.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("comingSoon")){ List<MovieDTO> resSet = movies.findComingSoon(); request.setAttribute("movieDeets", resSet); forwardPage = "comingSoon.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("signup")){ String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String confirmEmail = request.getParameter("confirmEmail"); //Check is the data that the user has entered is valid String errorMessage = ""; boolean error = false; if(!email.equals(confirmEmail)){ errorMessage = "Emails don't match"; error = true; } if(!password.equals(confirmPassword)){ errorMessage = "Passwords don't match"; error = true; } if(username == "" && password == "" && email == ""){ errorMessage = "Not all values completed"; error = true; } if(users.checkUsername(username)){ errorMessage = "Username already in use, please choose a different username"; error = true; } if(!error){ System.out.println("i made it"); //store data to database // default to 1, presumably, admins added by direct insert users.addUserDetails(username, 1, password, confirmPassword, email, confirmEmail); //send email //TODO: what does 'confirming' actually do? nothing? MailSenderTest ms = new MailSenderTest(); ms.sendConfirmationEmail(username, email); //return to check email page forwardPage = "confirmSignup.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { //return to check email page request.setAttribute("message", errorMessage); forwardPage = "signupError.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if(request.getParameter("action").equals("confirmSignup")){ UserDTO user = users.getUserDetails(request.getParameter("username")); ArrayList<ActorDTO> actorList = actors.getAll(); request.setAttribute("user", user); request.setAttribute("actorList", actorList); forwardPage = "editProfile.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("editProfile")){ //Get data from form String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String nickName = request.getParameter("nickName"); int yearOfBirth = Integer.parseInt(request.getParameter("yearOfBirth")); //send the data to the database users.addUserDetails(username, password, email, firstName, lastName, nickName, yearOfBirth); //send user to confirmation page forwardPage = "editProfileConfirm.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); + } else if(request.getParameter("action").equals("viewProfile")){ + //Get data from form + //send the data to the database + //send user to confirmation page + forwardPage = "myProfile.jsp"; + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); + dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addCinema")){ String name = request.getParameter("name"); String location = request.getParameter("location"); int capacity = Integer.parseInt(request.getParameter("capacity")); String[] amenities = request.getParameterValues("amenities"); cinemas.addCinema(name, location, capacity, amenities); request.setAttribute("adminResponse", new String("Cinema Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addMovie")){ String title = request.getParameter("title"); String actors = request.getParameter("actors"); String genres = request.getParameter("genres"); String director = request.getParameter("director"); String synopsis = request.getParameter("synopsis"); String ageRating = request.getParameter("agerating"); Date releaseDate = null; try { releaseDate = fmt.parse(request.getParameter("releasedate")); } catch (ParseException e) { e.printStackTrace(); } // file upload stuff: // http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet request.setAttribute("adminResponse", new String("Movie Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("login")) { UserDTO attempedLogin = users.getUserDetails(request.getParameter("username")); if (!request.getParameter("password").equals(attempedLogin.getPassword())) { request.setAttribute("failedLogin", new String("Incorrect Password! Please try again")); forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { sessionBean.setUserType(attempedLogin.getUserType()); sessionBean.setUser(attempedLogin); request.getSession().setAttribute("sessionBean", sessionBean); //TODO: figure out a way to fix this. How do I know which page to redirect // http://stackoverflow.com/questions/12013707/servlet-forward-response-to-caller-previous-page forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if (request.getParameter("action").equals("logout")) { forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); request.getSession().invalidate(); dispatcher.forward(request, response); } } private String handlePostcomment(HttpServletRequest request, HttpServletResponse response){ String forwardPage = ""; String character = (String) request.getParameter("character"); logger.info("Comment on character: "+character); try{ CharacterDTO mchar = cast.findChar(character); String commentString = request.getParameter("comments"); CommentDTO comment = new CommentDTO(mchar.getId(), mchar.getName(), "SKV", new Date(), commentString); cast.storeComment(comment); request.setAttribute("comments", cast.getComments(character)); forwardPage = "success.jsp"; }catch(Exception e){ e.printStackTrace(); forwardPage = "error.jsp"; } return forwardPage; } }
true
true
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardPage = ""; sessionBean = (SessionBean) request.getSession().getAttribute("sessionBean"); if(request.getParameter("action").equals("nowShowing")){ List<MovieDTO> resSet = movies.findNowShowing(); request.setAttribute("movieDeets", resSet); // request.setAttribute("userInfo"); forwardPage = "nowShowing.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("comingSoon")){ List<MovieDTO> resSet = movies.findComingSoon(); request.setAttribute("movieDeets", resSet); forwardPage = "comingSoon.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("signup")){ String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String confirmEmail = request.getParameter("confirmEmail"); //Check is the data that the user has entered is valid String errorMessage = ""; boolean error = false; if(!email.equals(confirmEmail)){ errorMessage = "Emails don't match"; error = true; } if(!password.equals(confirmPassword)){ errorMessage = "Passwords don't match"; error = true; } if(username == "" && password == "" && email == ""){ errorMessage = "Not all values completed"; error = true; } if(users.checkUsername(username)){ errorMessage = "Username already in use, please choose a different username"; error = true; } if(!error){ System.out.println("i made it"); //store data to database // default to 1, presumably, admins added by direct insert users.addUserDetails(username, 1, password, confirmPassword, email, confirmEmail); //send email //TODO: what does 'confirming' actually do? nothing? MailSenderTest ms = new MailSenderTest(); ms.sendConfirmationEmail(username, email); //return to check email page forwardPage = "confirmSignup.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { //return to check email page request.setAttribute("message", errorMessage); forwardPage = "signupError.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if(request.getParameter("action").equals("confirmSignup")){ UserDTO user = users.getUserDetails(request.getParameter("username")); ArrayList<ActorDTO> actorList = actors.getAll(); request.setAttribute("user", user); request.setAttribute("actorList", actorList); forwardPage = "editProfile.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("editProfile")){ //Get data from form String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String nickName = request.getParameter("nickName"); int yearOfBirth = Integer.parseInt(request.getParameter("yearOfBirth")); //send the data to the database users.addUserDetails(username, password, email, firstName, lastName, nickName, yearOfBirth); //send user to confirmation page forwardPage = "editProfileConfirm.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addCinema")){ String name = request.getParameter("name"); String location = request.getParameter("location"); int capacity = Integer.parseInt(request.getParameter("capacity")); String[] amenities = request.getParameterValues("amenities"); cinemas.addCinema(name, location, capacity, amenities); request.setAttribute("adminResponse", new String("Cinema Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addMovie")){ String title = request.getParameter("title"); String actors = request.getParameter("actors"); String genres = request.getParameter("genres"); String director = request.getParameter("director"); String synopsis = request.getParameter("synopsis"); String ageRating = request.getParameter("agerating"); Date releaseDate = null; try { releaseDate = fmt.parse(request.getParameter("releasedate")); } catch (ParseException e) { e.printStackTrace(); } // file upload stuff: // http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet request.setAttribute("adminResponse", new String("Movie Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("login")) { UserDTO attempedLogin = users.getUserDetails(request.getParameter("username")); if (!request.getParameter("password").equals(attempedLogin.getPassword())) { request.setAttribute("failedLogin", new String("Incorrect Password! Please try again")); forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { sessionBean.setUserType(attempedLogin.getUserType()); sessionBean.setUser(attempedLogin); request.getSession().setAttribute("sessionBean", sessionBean); //TODO: figure out a way to fix this. How do I know which page to redirect // http://stackoverflow.com/questions/12013707/servlet-forward-response-to-caller-previous-page forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if (request.getParameter("action").equals("logout")) { forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); request.getSession().invalidate(); dispatcher.forward(request, response); } }
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardPage = ""; sessionBean = (SessionBean) request.getSession().getAttribute("sessionBean"); if(request.getParameter("action").equals("nowShowing")){ List<MovieDTO> resSet = movies.findNowShowing(); request.setAttribute("movieDeets", resSet); // request.setAttribute("userInfo"); forwardPage = "nowShowing.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("comingSoon")){ List<MovieDTO> resSet = movies.findComingSoon(); request.setAttribute("movieDeets", resSet); forwardPage = "comingSoon.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("signup")){ String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String confirmEmail = request.getParameter("confirmEmail"); //Check is the data that the user has entered is valid String errorMessage = ""; boolean error = false; if(!email.equals(confirmEmail)){ errorMessage = "Emails don't match"; error = true; } if(!password.equals(confirmPassword)){ errorMessage = "Passwords don't match"; error = true; } if(username == "" && password == "" && email == ""){ errorMessage = "Not all values completed"; error = true; } if(users.checkUsername(username)){ errorMessage = "Username already in use, please choose a different username"; error = true; } if(!error){ System.out.println("i made it"); //store data to database // default to 1, presumably, admins added by direct insert users.addUserDetails(username, 1, password, confirmPassword, email, confirmEmail); //send email //TODO: what does 'confirming' actually do? nothing? MailSenderTest ms = new MailSenderTest(); ms.sendConfirmationEmail(username, email); //return to check email page forwardPage = "confirmSignup.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { //return to check email page request.setAttribute("message", errorMessage); forwardPage = "signupError.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if(request.getParameter("action").equals("confirmSignup")){ UserDTO user = users.getUserDetails(request.getParameter("username")); ArrayList<ActorDTO> actorList = actors.getAll(); request.setAttribute("user", user); request.setAttribute("actorList", actorList); forwardPage = "editProfile.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("editProfile")){ //Get data from form String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmPassword = request.getParameter("confirmPassword"); String email = request.getParameter("email"); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String nickName = request.getParameter("nickName"); int yearOfBirth = Integer.parseInt(request.getParameter("yearOfBirth")); //send the data to the database users.addUserDetails(username, password, email, firstName, lastName, nickName, yearOfBirth); //send user to confirmation page forwardPage = "editProfileConfirm.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if(request.getParameter("action").equals("viewProfile")){ //Get data from form //send the data to the database //send user to confirmation page forwardPage = "myProfile.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addCinema")){ String name = request.getParameter("name"); String location = request.getParameter("location"); int capacity = Integer.parseInt(request.getParameter("capacity")); String[] amenities = request.getParameterValues("amenities"); cinemas.addCinema(name, location, capacity, amenities); request.setAttribute("adminResponse", new String("Cinema Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("addMovie")){ String title = request.getParameter("title"); String actors = request.getParameter("actors"); String genres = request.getParameter("genres"); String director = request.getParameter("director"); String synopsis = request.getParameter("synopsis"); String ageRating = request.getParameter("agerating"); Date releaseDate = null; try { releaseDate = fmt.parse(request.getParameter("releasedate")); } catch (ParseException e) { e.printStackTrace(); } // file upload stuff: // http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet request.setAttribute("adminResponse", new String("Movie Added!")); forwardPage = "admin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else if (request.getParameter("action").equals("login")) { UserDTO attempedLogin = users.getUserDetails(request.getParameter("username")); if (!request.getParameter("password").equals(attempedLogin.getPassword())) { request.setAttribute("failedLogin", new String("Incorrect Password! Please try again")); forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } else { sessionBean.setUserType(attempedLogin.getUserType()); sessionBean.setUser(attempedLogin); request.getSession().setAttribute("sessionBean", sessionBean); //TODO: figure out a way to fix this. How do I know which page to redirect // http://stackoverflow.com/questions/12013707/servlet-forward-response-to-caller-previous-page forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); dispatcher.forward(request, response); } } else if (request.getParameter("action").equals("logout")) { forwardPage = request.getParameter("source"); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/"+forwardPage); request.getSession().invalidate(); dispatcher.forward(request, response); } }
diff --git a/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java b/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java index 3c30119c..9f110594 100644 --- a/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java +++ b/Servers/JavaServer/src/dbs/search/qb/QueryBuilder.java @@ -1,1155 +1,1157 @@ package dbs.search.qb; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Vector; import java.util.List; import java.util.Iterator; import java.util.Set; import dbs.search.parser.Constraint; import dbs.search.graph.GraphUtil; import dbs.sql.DBSSql; import dbs.util.Validate; import edu.uci.ics.jung.graph.Vertex; import edu.uci.ics.jung.graph.Edge; public class QueryBuilder { KeyMap km; //RelationMap rm = new RelationMap(); private ArrayList bindValues; private ArrayList bindIntValues; GraphUtil u = null; private String db = ""; private String countQuery = ""; public QueryBuilder(String db) { this.db = db; bindValues = new ArrayList(); bindIntValues = new ArrayList(); km = new KeyMap(); //u = GraphUtil.getInstance("/home/sekhri/DBS/Servers/JavaServer/etc/DBSSchemaGraph.xml"); u = GraphUtil.getInstance("WEB-INF/DBSSchemaGraph.xml"); } private String owner() throws Exception { return DBSSql.owner(); } public String getCountQuery() { return countQuery; } public ArrayList getBindValues() { return bindValues; } public ArrayList getBindIntValues() { return bindIntValues; } public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws) throws Exception{ return genQuery(kws, cs, okws, "", ""); } //public String genQuery(ArrayList kws, ArrayList cs, String begin, String end) throws Exception{ public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String begin, String end) throws Exception{ //Store all the keywors both from select and where in allKws String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String pathParentWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean datasetParentAdded = false; boolean procDsParentAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } String query = "SELECT DISTINCT \n\t"; for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); - sumQuery = "SELECT SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; + if(sumQuery.length() != 0) sumQuery += ",\n\t"; + else sumQuery += "SELECT "; + sumQuery += "SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; } else if(aKw.toLowerCase().startsWith("count")) { aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { sumQuery += ",\n\t PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); } //System.out.println("line 3"); StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS" + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token, "release")) { String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "count")) { String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { sumQuery += ",\n\t" + tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //System.out.println("line 8"); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { sumQuery += ",\n\t Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; } if(Util.isSame(token, "dataset")) { allKws = addUniqueInList(allKws, "ProcessedDataset"); } Vertex vCombined = u.getMappedVertex(aKw); if(vCombined == null) { if(addQuery) { String mapVal = km.getMappedValue(aKw, true); //if(mapVal.equals(aKw)) throw new Exception("The keyword " + aKw + " not yet implemented in Query Builder" ); query += mapVal + makeAs(mapVal); if(iLumi) groupByQuery += mapVal + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(mapVal)); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } else { allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); if(addQuery) { String tmp = makeQueryFromDefaults(vCombined); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vCombined); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } } } } if(iLumi && (cs.size() > 0) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); } for (int i =0 ; i!= cs.size(); ++i) { Object obj = cs.get(i); if(i%2 == 0) { Constraint o = (Constraint)obj; String key = (String)o.getKey(); if(Util.isSame(key, "dataset")) { } else if(Util.isSame(key, "release")) { if(isInList(kws, "procds") || isInList(kws, "dataset")) allKws = addUniqueInList(allKws, "ProcAlgo"); else addUniqueInList(allKws, "FileAlgo"); } else if(Util.isSame(key, "dq")) { allKws = addUniqueInList(allKws, km.getMappedValue(key, false)); } else { if(Util.isSame(key, "file.status")) invalidFile = false; StringTokenizer st = new StringTokenizer(key, "."); int count = st.countTokens(); allKws = addUniqueInList(allKws, u.getMappedRealName(st.nextToken())); if(count != 1) { Vertex vCombined = u.getMappedVertex(key); if(vCombined != null) allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); } } /*else { //allKws = addUniqueInList(allKws, "ProcessedDataset"); allKws = addUniqueInList(allKws, "Block"); }*/ } } //Get the route which determines the join table if(allKws.size() > 0) allKws = makeCompleteListOfVertexs(allKws); //If File is not there then add Block //Otherwise for (int i =0 ; i!= cs.size(); ++i) { Object obj = cs.get(i); if(i%2 == 0) { Constraint o = (Constraint)obj; String key = (String)o.getKey(); if(Util.isSame(key, "dataset")) { if(!isIn(allKws, "Files")) allKws = addUniqueInList(allKws, "Block"); }else if(key.startsWith("dataset")) allKws = addUniqueInList(allKws, "ProcessedDataset"); } } if(allKws.size() > 0) { allKws = makeCompleteListOfVertexs(allKws); allKws = sortVertexs(allKws); } int len = allKws.size(); /*for(int i = 0 ; i != len ; ++i ) { System.out.println("kw " + (String)allKws.get(i)); }*/ if(isInList(kws, "ilumi")) { if(len == 0) query += getIntLumiFromQuery(); else { query += genJoins(allKws); query += getIntLumiJoinQuery(); } } else query += genJoins(allKws); query += personJoinQuery; query += parentJoinQuery; query += childJoinQuery; personJoinQuery = ""; parentJoinQuery = ""; childJoinQuery = ""; String queryWhere = ""; if (cs.size() > 0) queryWhere += "\nWHERE\n"; for (int i =0 ; i!= cs.size(); ++i) { Object obj = cs.get(i); if(i%2 == 0) { Constraint co = (Constraint)obj; String key = (String)co.getKey(); String op = (String)co.getOp(); String val = (String)co.getValue(); if(Util.isSame(key, "dataset")) { if(pathParentWhereQuery.length() > 0) { queryWhere += pathParentWhereQuery + ""; bindValues.add(val); }else { // If path is given in where clause it should op should always be = //if(!Util.isSame(op, "=")) throw new Exception("When Path is provided operater should be = . Invalid operater given " + op); //queryWhere += "\tProcessedDataset.ID " + handlePath(val); if(isIn(allKws, "Files")) queryWhere += "\tFiles.Block "; else queryWhere += "\tBlock.ID "; queryWhere += handlePath(val, op); } } else if(Util.isSame(key, "dq")) { if(!Util.isSame(op, "=")) throw new Exception("When dq is provided operator should be = . Invalid operator given " + op); queryWhere += "\tRuns.ID" + handleDQ(val); } else if(Util.isSame(key, "release")) { //FIXME add FILEALGO and ProcALgo first boolean useAnd = false; if(isInList(kws, "procds") || isInList(kws, "dataset")) { queryWhere += "\tProcAlgo.Algorithm " + handleRelease(op, val); useAnd = true; } else { if(useAnd) queryWhere += "\tAND\n"; queryWhere += "\tFileAlgo.Algorithm " + handleRelease(op, val); } } else if(Util.isSame(key, "file.release")) { queryWhere += "\tFileAlgo.Algorithm" + handleRelease(op, val); } else if(Util.isSame(key, "file.tier")) { queryWhere += "\tFileTier.DataTier" + handleTier(op, val); } else if(Util.isSame(key, "lumi.evnum")) { if(!Util.isSame(op, "=")) throw new Exception("When evnum is provided operator should be = . Invalid operator given " + op); queryWhere += handleEvNum(val); } else if(Util.isSame(key, "procds.release")) { queryWhere += "\tProcAlgo.Algorithm " + handleRelease(op, val); } else if(Util.isSame(key, "procds.tier")) { queryWhere += "\tProcDSTier.DataTier" + handleTier(op, val); } else if(key.endsWith("createdate") || key.endsWith("moddate")) { queryWhere += "\t" + km.getMappedValue(key, true) + handleDate(op, val); } else { //if(key.indexOf(".") == -1) throw new Exception("In specifying constraints qualify keys with dot operater. Invalid key " + key); StringTokenizer st = new StringTokenizer(key, "."); int count = st.countTokens(); boolean doGeneric = false; if(count == 2) { String token = st.nextToken(); String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; personField = "LastModifiedBy"; modByAdded = true; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) personJoinQuery += "\tJOIN Person " + tmpTableName + "\n" + "\t\tON " + u.getMappedRealName(token) + "." + personField + " = " + tmpTableName + ".ID\n"; queryWhere += tmpTableName + ".DistinguishedName "; } else if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); queryWhere += tmpTableName + ".LogicalFileName "; } else if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; //String tmpTableName = token + "_" + token2; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); queryWhere += tmpTableName + ".Name "; } else if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); queryWhere += tmpTableName + ".LogicalFileName "; } else doGeneric = true; }else doGeneric = true; if(doGeneric) { //Vertex vFirst = u.getMappedVertex(token); Vertex vCombined = u.getMappedVertex(key); if(vCombined == null) { queryWhere += "\t" + km.getMappedValue(key, true) + " " ; } else { queryWhere += "\t" + u.getRealFromVertex(vCombined) + "." + u.getDefaultFromVertex(vCombined) + " "; //FIXME default can be list } } queryWhere += handleOp(op, val); } } else { //System.out.println("REL " + (String)obj); queryWhere += "\n" + ((String)obj).toUpperCase() + "\n"; } } //System.out.println("\n\nFINAL query is \n\n" + query); String circularConst = ""; boolean useAnd = false; if((queryWhere.length() == 0) && isIn(allKws, "FileRunLumi")) circularConst = "\nWHERE "; if(isIn(allKws, "Files") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "FileRunLumi.Fileid = Files.ID"; useAnd = true; } if(isIn(allKws, "Runs") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "\n\tFileRunLumi.Run = Runs.ID"; useAnd = true; } if(isIn(allKws, "LumiSection") && isIn(allKws, "FileRunLumi")) { if(queryWhere.length() != 0 || useAnd) circularConst += "\n\tAND "; circularConst += "\n\tFileRunLumi.Lumi = LumiSection.ID"; } String invalidFileQuery = "FileStatus.Status <> ?"; String invalidConst = ""; if((queryWhere.length() == 0) && (circularConst.length() == 0) && (invalidFile)) { invalidConst = "\nWHERE " + invalidFileQuery; bindValues.add("INVALID"); } if(((queryWhere.length() != 0) || (circularConst.length() != 0)) && (invalidFile)) { invalidConst = "\nAND " + invalidFileQuery; bindValues.add("INVALID"); } query += personJoinQuery + parentJoinQuery + childJoinQuery + queryWhere + circularConst + invalidConst; if(groupByQuery.length() > 0) { groupByQuery = groupByQuery.substring(0, groupByQuery.length() - 1);// to get rid of extra comma query += "\n GROUP BY " + groupByQuery; } boolean orderOnce = false; for(Object o: okws){ String orderBy = (String)o; if(!orderOnce) { query += " ORDER BY "; } if(orderOnce) query += ","; String orderToken = ""; Vertex vCombined = u.getMappedVertex(orderBy); if(vCombined == null) orderToken = km.getMappedValue(orderBy, true); else orderToken = u.getRealFromVertex(vCombined) + "." + u.getDefaultFromVertex(vCombined); query += orderToken; orderOnce = true; } if(sumQuery.length() != 0) { query = sumQuery + " FROM (" + query + ") sumtable "; if(sumGroupByQuery.length() > 0) { sumGroupByQuery = sumGroupByQuery.substring(0, sumGroupByQuery.length() - 1);// to get rid of extra comma query += "\n GROUP BY " + sumGroupByQuery; } } //countQuery = "SELECT COUNT(*) " + query.substring(query.indexOf("FROM")); countQuery = "SELECT COUNT(*) FROM (" + query + ") x"; if(!begin.equals("") && !end.equals("")) { int bInt = Integer.parseInt(begin); int eInt = Integer.parseInt(end); bindIntValues.add(new Integer(bInt)); if(db.equals("mysql")) { bindIntValues.add(new Integer(eInt - bInt)); query += "\n\tLIMIT ?, ?"; } if(db.equals("oracle")) { bindIntValues.add(new Integer(eInt)); //query = "SELECT * FROM (SELECT x.*, rownum as rnum FROM (\n" + query + "\n) x) where rnum between ? and ?"; query = genOraclePageQuery(query); } } return query; } private String makeSumSelect(String tmp) { String asStr = "AS"; int asIndex = tmp.indexOf(asStr); if(asIndex != -1) { return tmp.substring(asIndex + asStr.length(), tmp.length()).trim(); } return ""; } private String makeAs(String in) { return " AS " + in.replace('.', '_') + " "; } private String genOraclePageQuery(String query) { System.out.println(query); String tokenAS = "AS"; String tokenFrom = "FROM"; String tokenDistinct = "DISTINCT"; int indexOfFrom = query.indexOf(tokenFrom); int indexOfDistinct = query.indexOf(tokenDistinct); if(indexOfFrom == -1 || indexOfDistinct == -1) return query; //System.out.println(indexOfFrom); //System.out.println(indexOfDistinct); String tmpStr = query.substring(indexOfDistinct + tokenDistinct.length(), indexOfFrom); //System.out.println("tmp str " + tmpStr); StringTokenizer st = new StringTokenizer(tmpStr, ","); int numberOfKeywords = st.countTokens(); String toReturn = "SELECT "; for(int i = 0; i != numberOfKeywords; ++i) { String tmpToken = st.nextToken(); int indexOfAs = tmpToken.indexOf(tokenAS); if(indexOfAs == -1) return query; String finalKeyword = tmpToken.substring(indexOfAs + tokenAS.length(), tmpToken.length()).trim(); //System.out.println("Keyword " + finalKeyword); if(i != 0) toReturn += ", "; toReturn += finalKeyword; } toReturn += " FROM (SELECT x.*, rownum as rnum FROM (\n" + query + "\n) x) where rnum between ? and ?"; return toReturn; } private String makeQueryFromDefaults(Vertex v){ String realVal = u.getRealFromVertex(v); StringTokenizer st = new StringTokenizer(u.getDefaultFromVertex(v), ","); int countDefTokens = st.countTokens(); String query = ""; for (int j = 0; j != countDefTokens; ++j) { if(j != 0) query += ","; String token = st.nextToken(); query += realVal + "." + token + makeAs(realVal + "." + token); } return query; } private String makeGroupQueryFromDefaults(Vertex v){ String realVal = u.getRealFromVertex(v); StringTokenizer st = new StringTokenizer(u.getDefaultFromVertex(v), ","); int countDefTokens = st.countTokens(); String query = ""; for (int j = 0; j != countDefTokens; ++j) { String token = st.nextToken(); query += realVal + "." + token + ","; } return query; } private String genJoins(ArrayList lKeywords) throws Exception { //ArrayList uniquePassed = new ArrayList(); String prev = ""; String query = "\nFROM\n\t" + owner() + (String)lKeywords.get(0) + "\n"; int len = lKeywords.size(); for(int i = 1 ; i != len ; ++i ) { for(int j = (i-1) ; j != -1 ; --j ) { String v1 = (String)lKeywords.get(i); String v2 = (String)lKeywords.get(j); //if(! (isIn(uniquePassed, v1 + "," + v2 )) && !(isIn(uniquePassed, v2 + "," + v1))) { if(u.doesEdgeExist(v1, v2)) { //System.out.println("Relation bwteen " + v1 + " and " + v2 + " is " + u.getRealtionFromVertex(v1, v2)); String tmp = u.getRealtionFromVertex(v1, v2); query += "\t"; if(Util.isSame(v1, "FileChildage")) v1 = "FileParentage"; if(Util.isSame(v1, "FileParentage") || Util.isSame(v1, "ProcDSParent")) query += "LEFT OUTER "; query += "JOIN " + owner() + v1 + "\n"; query += "\t\tON " + tmp + "\n"; //uniquePassed.add(v1 + "," + v2); break; } //} } } return query; } private boolean isIn(ArrayList aList, String key) { for (int i = 0 ; i != aList.size(); ++i) { if( ((String)(aList.get(i) )).equals(key)) return true; } return false; } /*private String genJoins(String[] routes) { String prev = ""; String query = "\nFROM\n\t"; for(String s: routes) { if(!prev.equals("")) { //System.out.println(prev + "," + s); String tmp = rm.getMappedValue(prev + "," + s); //System.out.println(tmp); query += "\tJOIN " + s + "\n"; query += "\t\tON " + tmp + "\n"; } else query += s + "\n"; prev = s; } return query; }*/ private String handleParent(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ItsParent\n" ); } private String handleChild(String tmpTableName, String table1, String table2) throws Exception { return ( "\tLEFT OUTER JOIN " + owner() + table1 + " " + tmpTableName + "\n" + "\t\tON " + tmpTableName + ".ID = " + table2 + ".ThisFile\n" ); } private String handlePathParent() throws Exception { String sql = "Block.ID in \n" + "\t(" + DBSSql.listPathParent() + ")\n"; return sql; } private String handleLike(String val) { bindValues.add(val.replace('*','%')); return "LIKE ?"; } private String handleIn(String val) { String query = "IN ("; StringTokenizer st = new StringTokenizer(val, ","); int count = st.countTokens(); for(int k = 0 ; k != count ; ++k) { if(k != 0) query += ","; //query += "'" + st.nextToken() + "'"; query += "?"; bindValues.add(st.nextToken()); } query += ")"; return query; } private String handleOp(String op, String val) { String query = ""; if(Util.isSame(op, "in")) query += handleIn(val); else if(Util.isSame(op, "like")) query += handleLike(val); else { query += op + " ?\n"; bindValues.add(val); } return query; } private String handleEvNum(String val) { String query = "\tLumiSection.StartEventNumber <= ?\n" + "\t AND \n" + "\tLumiSection.EndEventNumber >= ?\n"; bindValues.add(val); bindValues.add(val); return query; } /*private String handlePath(String path) throws Exception { Validate.checkPath(path); String[] data = path.split("/"); if(data.length != 4) { throw new Exception("Invalid path " + path); } ArrayList route = new ArrayList(); route.add("PrimaryDataset"); route.add("ProcessedDataset"); String query = " IN ( \n" + "SELECT \n" + "\tProcessedDataset.ID " + genJoins(route) + "WHERE \n" + //"\tPrimaryDataset.Name = '" + data[1] + "'\n" + "\tPrimaryDataset.Name = ?\n" + "\tAND\n" + //"\tProcessedDataset.Name = '" + data[2] + "'" + "\tProcessedDataset.Name = ?" + ")"; bindValues.add(data[1]); bindValues.add(data[2]); return query; }*/ private String handleDate(String op, String val) throws Exception { if(Util.isSame(op, "in")) throw new Exception("Operator IN not supported with date. Please use =, < or >"); if(Util.isSame(op, "like")) throw new Exception("Operator LIKE not supported with date. Please use =, < or >"); String query = ""; String epoch1 = String.valueOf(DateUtil.dateStr2Epoch(val) / 1000); if(Util.isSame(op, "=")) { String epoch2 = String.valueOf(DateUtil.getNextDate(val).getTime() / 1000); query += " BETWEEN ? AND ?\n"; bindValues.add(epoch1); bindValues.add(epoch2); } else { query += " " + op + " ?\n"; bindValues.add(epoch1); } return query; } private String handlePath(String path, String op) throws Exception { String query = " IN ( \n" + "SELECT \n" + "\tBlock.ID FROM " + owner() + "Block" + "\tWHERE \n" + //"\tBlock.Path " + op + " '" + path + "'\n" + "\tBlock.Path ";// + op + " ?\n" + //")"; /*if(Util.isSame(op, "in")) query += handleIn(path); else if(Util.isSame(op, "like")) query += handleLike(path); else { query += op + " ?\n"; bindValues.add(path); }*/ query += handleOp(op, path) + ")"; return query; } private String handleDQ(String val) throws Exception { //System.out.println("VAL is " + val); ArrayList sqlObj = DBSSql.listRunsForRunLumiDQ(null, val); String dqQuery = ""; if(sqlObj.size() == 2) { dqQuery = (String)sqlObj.get(0); Vector bindVals = (Vector)sqlObj.get(1); for(Object s: bindVals) bindValues.add((String)s); } //call DQ function //List<String> bindValuesFromDQ = ; //Get from DQ function //for(String s: bindValues) bindValues.add(s); String query = " IN ( \n" + dqQuery + ")"; return query; } private String handleRelease(String op, String version) throws Exception { Validate.checkWord("AppVersion", version); ArrayList route = new ArrayList(); route.add("AlgorithmConfig"); route.add("AppVersion"); String query = " IN ( \n" + "SELECT \n" + "\tAlgorithmConfig.ID " + genJoins(route) + "WHERE \n" + //"\tAppVersion.Version = '" + version + "'\n" + "\tAppVersion.Version " + handleOp(op, version) + "\n" + ")"; return query; } private String handleTier(String op, String tier) throws Exception { Validate.checkWord("DataTier", tier); ArrayList route = new ArrayList(); String query = " IN ( \n" + "SELECT \n" + "\tDataTier.ID FROM " + owner() + "DataTier " + "WHERE \n" + "\tDataTier.Name " + handleOp(op, tier) + "\n" + ")"; return query; } private ArrayList addUniqueInList(ArrayList keyWords, String aKw) { for(Object kw: keyWords) { if(((String)kw).equals(aKw))return keyWords; } keyWords.add(aKw); return keyWords; } private boolean isInList(ArrayList keyWords, String aKw) { //System.out.println("line 3.1"); for(Object kw: keyWords) { if(((String)kw).equals(aKw))return true; } return false; } private String getIntLumiSelectQuery() { return ("\n\tSUM(ldblsum.INSTANT_LUMI * 93 * (1 - ldblsum.DEADTIME_NORMALIZATION) * ldblsum.NORMALIZATION) AS INTEGRATED_LUMINOSITY, " + "\n\tSUM(ldblsum.INSTANT_LUMI_ERR * ldblsum.INSTANT_LUMI_ERR) AS INTEGRATED_ERROR"); } private String getIntLumiFromQuery() { return ("\n\tFROM CMS_LUMI_PROD_OFFLINE.LUMI_SUMMARIES ldblsum" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SECTIONS ldbls" + "\n\t\tON ldblsum.SECTION_ID = ldbls.SECTION_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_VERSION_TAG_MAPS ldblvtm" + "\n\t\tON ldblvtm.LUMI_SUMMARY_ID = ldblsum.LUMI_SUMMARY_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_TAGS ldblt" + "\n\t\tON ldblt.LUMI_TAG_ID = ldblvtm.LUMI_TAG_ID"); } private String getIntLumiJoinQuery() { return ("\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SECTIONS ldbls" + "\n\t\tON Runs.RunNumber = ldbls.RUN_NUMBER" + "\n\t\tAND LumiSection.LumiSectionNumber = ldbls.LUMI_SECTION_NUMBER" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_SUMMARIES ldblsum" + "\n\t\tON ldblsum.SECTION_ID = ldbls.SECTION_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_VERSION_TAG_MAPS ldblvtm" + "\n\t\tON ldblvtm.LUMI_SUMMARY_ID = ldblsum.LUMI_SUMMARY_ID" + "\n\tJOIN CMS_LUMI_PROD_OFFLINE.LUMI_TAGS ldblt" + "\n\t\tON ldblt.LUMI_TAG_ID = ldblvtm.LUMI_TAG_ID"); } private ArrayList makeCompleteListOfVertexsOld(ArrayList lKeywords) { int len = lKeywords.size(); if(len <= 1) return lKeywords; for(int i = 0 ; i != len ; ++i ) { boolean isEdge = false; for(int j = 0 ; j != len ; ++j ) { if(i != j) { //System.out.println("Checking " + lKeywords.get(i) + " with " + lKeywords.get(j) ); if(u.doesEdgeExist((String)lKeywords.get(i), (String)lKeywords.get(j))) { isEdge = true; break; } } } if(!isEdge) { //System.out.println("Shoertest edge in " + (String)lKeywords.get(i) + " --- " + (String)lKeywords.get((i+1)%len)); List<Edge> lEdges = u.getShortestPath((String)lKeywords.get(i), (String)lKeywords.get((i+1)%len)); for (Edge e: lEdges) { //System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); lKeywords = addUniqueInList(lKeywords, u.getFirstNameFromEdge(e)); lKeywords = addUniqueInList(lKeywords, u.getSecondNameFromEdge(e)); } //System.out.println("No edge callin again ---------> \n"); lKeywords = makeCompleteListOfVertexs (lKeywords); return lKeywords; } } return lKeywords; } private ArrayList makeCompleteListOfVertexs(ArrayList lKeywords) { ArrayList myRoute = new ArrayList(); myRoute.add(lKeywords.get(0)); lKeywords.remove(0); int len = lKeywords.size(); int prevLen = 0; while(len != 0) { boolean breakFree = false; for(int i = 0 ; i != len ; ++i ) { int lenRount = myRoute.size(); for(int j = 0 ; j != lenRount ; ++j ) { String keyInMyRoute = (String)myRoute.get(j); String keyInArray = (String)lKeywords.get(i); if(keyInArray.equals(keyInMyRoute)) { lKeywords.remove(i); breakFree = true; break; } else if(u.doesEdgeExist(keyInMyRoute, keyInArray)) { myRoute = addUniqueInList(myRoute, keyInArray); lKeywords.remove(i); breakFree = true; break; } } if(breakFree) break; } if(prevLen == len) { //System.out.println("Shortest edge in " + (String)lKeywords.get(0) + " --- " + (String)myRoute.get(0)); List<Edge> lEdges = u.getShortestPath((String)lKeywords.get(0), (String)myRoute.get(0)); for (Edge e: lEdges) { //System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); myRoute = addUniqueInList(myRoute, u.getFirstNameFromEdge(e)); myRoute = addUniqueInList(myRoute, u.getSecondNameFromEdge(e)); } if(lEdges.size() > 0) lKeywords.remove(0); else { myRoute = addUniqueInList(myRoute, (String)lKeywords.get(0)); lKeywords.remove(0); ////System.out.println("Path length is 0"); } } prevLen = len; len = lKeywords.size(); } return myRoute; } public ArrayList sortVertexs(ArrayList lKeywords) { //System.out.println("INSIDE sortVertexs"); int len = lKeywords.size(); String leaf = ""; for(int i = 0 ; i != len ; ++i ) { String aVertex = (String)lKeywords.get(i); if(isLeaf(aVertex, lKeywords)) { leaf = aVertex; break; } } //System.out.println("leaf " + leaf); if(leaf.equals("")) leaf = (String)lKeywords.get(0); //System.out.println("leaf again " + leaf); ArrayList toReturn = new ArrayList(); toReturn.add(leaf); int reps = -1; while( toReturn.size() != len) { ++reps; for(int j = 0 ; j != len ; ++j ) { String aVertex = (String)lKeywords.get(j); if(!aVertex.equals(leaf)) { if(!isIn(toReturn, aVertex)) { if(isLeaf(aVertex, lKeywords)) { //System.out.println(aVertex + " is a leaf toreturn size " + toReturn.size() + " len -1 " + (len - 1)); //if(toReturn.size() ==1) System.out.println("toReturn.0 " + (String)toReturn.get(0)); if(toReturn.size() == (len - 1)) toReturn = addUniqueInList(toReturn, aVertex); else if(reps > len) { toReturn = addUniqueInList(toReturn, aVertex); //System.out.println("adding " + aVertex); } } else { for (int k = (toReturn.size() - 1) ; k != -1 ; --k) { //System.out.println("Cheking edge between " + (String)toReturn.get(k) + " and " + aVertex); if(u.doesEdgeExist((String)toReturn.get(k), aVertex)) { toReturn = addUniqueInList(toReturn, aVertex); break; } else { if(reps > len) toReturn = addUniqueInList(toReturn, aVertex); //System.out.println("no edge between " + (String)toReturn.get(k) + " and " + aVertex); } } } } } } } return toReturn; } private boolean isLeaf(String aVertex, ArrayList lKeyword) { int count = 0; Set s = u.getVertex(aVertex).getNeighbors(); for (Iterator eIt = s.iterator(); eIt.hasNext(); ) { String neighbor = u.getRealFromVertex((Vertex) eIt.next()); //System.out.println("neighbour " + neighbor); if(isIn(lKeyword, neighbor)) ++count; } if(count == 1) return true; return false; } public static void main(String args[]) throws Exception{ QueryBuilder qb = new QueryBuilder("oracle"); ArrayList tmp = new ArrayList(); /*GraphUtil u = GraphUtil.getInstance("/home/sekhri/DBS/Servers/JavaServer/etc/DBSSchemaGraph.xml"); List<Edge> lEdges = u.getShortestPath("ProcessedDataset", "LumiSection"); for (Edge e: lEdges) { System.out.println("PATH " + u.getFirstNameFromEdge(e) + " --- " + u.getSecondNameFromEdge(e)); }*/ //tmp.add("PrimaryDataset"); tmp.add("file"); System.out.println(qb.genQuery(tmp, new ArrayList(),new ArrayList(), "4", "10")); //tmp.add("Runs"); //tmp.add("FileRunLumi"); //tmp.add("ProcessedDataset"); //tmp.add("FileType"); //tmp.add("ProcDSRuns"); /*tmp = qb.sortVertexs(tmp); //tmp = qb.makeCompleteListOfVertexs(tmp); for (int i =0 ; i!=tmp.size() ;++i ) { System.out.println("ID " + tmp.get(i)); }*/ } }
true
true
public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String begin, String end) throws Exception{ //Store all the keywors both from select and where in allKws String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String pathParentWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean datasetParentAdded = false; boolean procDsParentAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } String query = "SELECT DISTINCT \n\t"; for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); sumQuery = "SELECT SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; } else if(aKw.toLowerCase().startsWith("count")) { aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { sumQuery += ",\n\t PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); } //System.out.println("line 3"); StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS" + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token, "release")) { String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "count")) { String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { sumQuery += ",\n\t" + tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //System.out.println("line 8"); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { sumQuery += ",\n\t Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; } if(Util.isSame(token, "dataset")) { allKws = addUniqueInList(allKws, "ProcessedDataset"); } Vertex vCombined = u.getMappedVertex(aKw); if(vCombined == null) { if(addQuery) { String mapVal = km.getMappedValue(aKw, true); //if(mapVal.equals(aKw)) throw new Exception("The keyword " + aKw + " not yet implemented in Query Builder" ); query += mapVal + makeAs(mapVal); if(iLumi) groupByQuery += mapVal + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(mapVal)); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } else { allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); if(addQuery) { String tmp = makeQueryFromDefaults(vCombined); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vCombined); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } } }
public String genQuery(ArrayList kws, ArrayList cs, ArrayList okws, String begin, String end) throws Exception{ //Store all the keywors both from select and where in allKws String personJoinQuery = ""; String parentJoinQuery = ""; String childJoinQuery = ""; String pathParentWhereQuery = ""; String groupByQuery = ""; String sumGroupByQuery = ""; String sumQuery = ""; boolean invalidFile = false; boolean modByAdded = false; boolean createByAdded = false; boolean fileParentAdded = false; boolean fileChildAdded = false; boolean datasetParentAdded = false; boolean procDsParentAdded = false; boolean iLumi = isInList(kws, "ilumi"); boolean countPresent = false; boolean sumPresent = false; ArrayList allKws = new ArrayList(); if(isInList(kws, "file") || isInList(kws, "file.status")) { invalidFile = true; allKws = addUniqueInList(allKws, "FileStatus"); } for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if(aKw.toLowerCase().startsWith("count") || aKw.toLowerCase().endsWith("count")) countPresent = true; if(aKw.toLowerCase().startsWith("sum")) sumPresent = true; } String query = "SELECT DISTINCT \n\t"; for (int i =0 ; i!= kws.size(); ++i) { String aKw = (String)kws.get(i); if (i!=0) query += "\n\t,"; //If path supplied in select then always use block path. If supplied in where then user procDS ID if(Util.isSame(aKw, "ilumi")) { query += getIntLumiSelectQuery(); //System.out.println("line 2.1.1"); } else if(aKw.toLowerCase().startsWith("sum")) { aKw = aKw.toLowerCase(); String keyword = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); keyword = keyword.trim(); String asKeyword = keyword.replace('.', '_'); String entity = (new StringTokenizer(keyword, ".")).nextToken(); //System.out.println("entity " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "SUM(" + asKeyword + ") AS SUM_" + asKeyword + " "; //query += "SUM(" + km.getMappedValue(keyword, true) + ") AS SUM_" + keyword.replace('.', '_') ; String tmpKw = km.getMappedValue(keyword, true); query += tmpKw + " AS " + asKeyword ; if(iLumi) groupByQuery += tmpKw + ","; String tmp = makeQueryFromDefaults(u.getMappedVertex(entity)); tmp = tmp.substring(0, tmp.length() - 1); // To get rid of last space query += "\n\t," + tmp + "_SUM "; } else if(aKw.toLowerCase().startsWith("count")) { aKw = aKw.toLowerCase(); String entity = aKw.substring(aKw.indexOf("(") + 1, aKw.indexOf(")")); entity = entity.trim(); //System.out.println("entity = " + entity); String realName = u.getMappedRealName(entity); allKws = addUniqueInList(allKws, realName); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + entity + ")"); //query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT"; sumGroupByQuery += " COUNT ,"; }*/ } else if(Util.isSame(aKw, "dataset")) { allKws = addUniqueInList(allKws, "Block"); query += "Block.Path AS PATH"; if(iLumi) groupByQuery += "Block.Path,"; if(sumPresent || countPresent) { sumQuery += ",\n\t PATH AS PATH"; sumGroupByQuery += " PATH ,"; } } else { //System.out.println("line 2.2"); if(iLumi && (i < 2) ) { allKws = addUniqueInList(allKws, "Runs"); allKws = addUniqueInList(allKws, "LumiSection"); } //System.out.println("line 3"); StringTokenizer st = new StringTokenizer(aKw, "."); int count = st.countTokens(); String token = st.nextToken(); Vertex vFirst = u.getMappedVertex(token); String real = u.getRealFromVertex(vFirst); allKws = addUniqueInList(allKws, real); //System.out.println("line 4"); //if(Util.isSame(real, "LumiSection")) allKws = addUniqueInList(allKws, "Runs"); if(count == 1) { //Get default from vertex //System.out.println("line 5"); String tmp = makeQueryFromDefaults(vFirst); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vFirst); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS" + toSelect; sumGroupByQuery += toSelect + ","; } } } else { //System.out.println("line 6"); boolean addQuery = true; String token2 = st.nextToken(); String tmpTableName = token + "_" + token2; /*if(Util.isSame(token2, "algo")) { allKws = addUniqueInList(allKws, "AppFamily"); allKws = addUniqueInList(allKws, "AppVersion"); allKws = addUniqueInList(allKws, "AppExecutable"); allKws = addUniqueInList(allKws, "QueryableParameterSet"); query += makeQueryFromDefaults(u.getVertex("AppFamily")); query += makeQueryFromDefaults(u.getVertex("AppVersion")); query += makeQueryFromDefaults(u.getVertex("AppExecutable")); query += makeQueryFromDefaults(u.getVertex("QueryableParameterSet")); adQuery = false; }*/ if(Util.isSame(token2, "release") || Util.isSame(token2, "tier")) { String realName = u.getMappedRealName(token2);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token, "release")) { String realName = u.getMappedRealName(token);//AppVersion allKws = addUniqueInList(allKws, realName); String tmp = makeQueryFromDefaults(u.getVertex(realName)); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(u.getVertex(realName)); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "count")) { String realName = u.getMappedRealName(token); String defaultStr = u.getDefaultFromVertex(u.getVertex(realName)); if(defaultStr.indexOf(",") != -1) throw new Exception("Cannot use count(" + token + ")"); query += realName + "." + defaultStr + " AS COUNT_SUB_" + realName; if(sumQuery.length() != 0) sumQuery += ",\n\t"; else sumQuery += "SELECT "; sumQuery += "COUNT(DISTINCT COUNT_SUB_" + realName + ") AS COUNT_" + realName; /*query += "COUNT(DISTINCT " + realName + "." + defaultStr + ") AS COUNT"; if(sumPresent) { sumQuery += ",\n\t COUNT AS COUNT "; sumGroupByQuery += " COUNT ,"; }*/ addQuery = false; } if(Util.isSame(token2, "modby") || Util.isSame(token2, "createby")) { boolean dontJoin = false; String personField = "CreatedBy"; if(Util.isSame(token2, "modby")) { if(modByAdded) dontJoin = true; modByAdded = true; personField = "LastModifiedBy"; } else { if(createByAdded) dontJoin = true; createByAdded = true; } //String tmpTableName = token + "_" + token2; if(!dontJoin) { personJoinQuery += "\tJOIN " + owner() + "Person " + tmpTableName + "\n" + "\t\tON " + real + "." + personField + " = " + tmpTableName + ".ID\n"; } String fqName = tmpTableName + ".DistinguishedName"; query += fqName + makeAs(tmpTableName + "_DN"); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { sumQuery += ",\n\t" + tmpTableName + "_DN AS " + tmpTableName + "_DN "; sumGroupByQuery += tmpTableName + "_DN ,"; } addQuery = false; } //if(Util.isSame(token2, "evnum") && Util.isSame(token, "file")) { // throw new Exception("You can find file based on file.evnum (find file where file.evenum = blah) but cannot find file.evnum"); //} if(Util.isSame(token2, "evnum") && Util.isSame(token, "lumi")) { throw new Exception("You can find lumi based on lumi.evnum (find lumi where lumi.evenum = blah) but cannot find lumi.evnum"); } if(Util.isSame(token2, "parent") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileParentAdded) dontJoin = true; fileParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "child") && Util.isSame(token, "file")) { boolean dontJoin = false; if(fileChildAdded) dontJoin = true; fileChildAdded = true; //System.out.println("childJoinQuery " + childJoinQuery+ " dontJoin " + dontJoin); if(!dontJoin) childJoinQuery += handleChild(tmpTableName, "Files", "FileParentage"); String fqName = tmpTableName + ".LogicalFileName"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "procds")) { boolean dontJoin = false; if(procDsParentAdded) dontJoin = true; procDsParentAdded = true; if(!dontJoin) parentJoinQuery += handleParent(tmpTableName, "ProcessedDataset", "ProcDSParent"); String fqName = tmpTableName + ".Name"; query += fqName + makeAs(fqName); if(iLumi) groupByQuery += fqName + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(fqName)) + " "; if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } addQuery = false; } if(Util.isSame(token2, "parent") && Util.isSame(token, "dataset")) { //System.out.println("line 8"); allKws = addUniqueInList(allKws, "Block"); boolean dontJoin = false; if(datasetParentAdded) dontJoin = true; datasetParentAdded = true; if(!dontJoin) pathParentWhereQuery += handlePathParent(); String fqName = "Block.Path AS Dataset_Parent"; query += fqName; if(iLumi) groupByQuery += "Block.Path ,"; if(sumPresent || countPresent) { sumQuery += ",\n\t Dataset_Parent AS Dataset_Parent "; sumGroupByQuery += " Dataset_Parent ,"; } addQuery = false; } if(Util.isSame(token, "dataset")) { allKws = addUniqueInList(allKws, "ProcessedDataset"); } Vertex vCombined = u.getMappedVertex(aKw); if(vCombined == null) { if(addQuery) { String mapVal = km.getMappedValue(aKw, true); //if(mapVal.equals(aKw)) throw new Exception("The keyword " + aKw + " not yet implemented in Query Builder" ); query += mapVal + makeAs(mapVal); if(iLumi) groupByQuery += mapVal + ","; if(sumPresent || countPresent) { String toSelect = makeSumSelect(makeAs(mapVal)); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } else { allKws = addUniqueInList(allKws, u.getRealFromVertex(vCombined)); if(addQuery) { String tmp = makeQueryFromDefaults(vCombined); query += tmp; if(iLumi) groupByQuery += makeGroupQueryFromDefaults(vCombined); if(sumPresent || countPresent) { String toSelect = makeSumSelect(tmp); if(toSelect.length() != 0) { sumQuery += ",\n\t" + toSelect + " AS " + toSelect + " "; sumGroupByQuery += toSelect + ","; } } } } } }
diff --git a/user/src/com/google/gwt/user/client/Cookies.java b/user/src/com/google/gwt/user/client/Cookies.java index 81ab03e82..1ab8492d1 100644 --- a/user/src/com/google/gwt/user/client/Cookies.java +++ b/user/src/com/google/gwt/user/client/Cookies.java @@ -1,167 +1,175 @@ /* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.user.client; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Provides access to browser cookies stored on the client. Because of browser * restrictions, you will only be able to access cookies associated with the * current page's domain. */ public class Cookies { /** * Cached copy of cookies. */ static HashMap<String, String> cachedCookies = null; /** * Raw cookie string stored to allow cached cookies to be invalidated on * write. */ // Used only in JSNI. static String rawCookies; /** * Gets the cookie associated with the given name. * * @param name the name of the cookie to be retrieved * @return the cookie's value, or <code>null</code> if the cookie doesn't exist */ public static String getCookie(String name) { Map<String, String> cookiesMap = ensureCookies(); return cookiesMap.get(name); } /** * Gets the names of all cookies in this page's domain. * * @return the names of all cookies */ public static Collection<String> getCookieNames() { return ensureCookies().keySet(); } /** * Removes the cookie associated with the given name. * * @param name the name of the cookie to be removed */ public static native void removeCookie(String name) /*-{ $doc.cookie = name + "=;expires=Fri, 02-Jan-1970 00:00:00 GMT"; }-*/; /** * Sets a cookie. The cookie will expire when the current browser session is * ended. * * @param name the cookie's name * @param value the cookie's value */ public static void setCookie(String name, String value) { setCookieImpl(name, value, 0, null, null, false); } /** * Sets a cookie. * * @param name the cookie's name * @param value the cookie's value * @param expires when the cookie expires */ public static void setCookie(String name, String value, Date expires) { setCookie(name, value, expires, null, null, false); } /** * Sets a cookie. * * @param name the cookie's name * @param value the cookie's value * @param expires when the cookie expires * @param domain the domain to be associated with this cookie * @param path the path to be associated with this cookie * @param secure <code>true</code> to make this a secure cookie (that is, * only accessible over an SSL connection) */ public static void setCookie(String name, String value, Date expires, String domain, String path, boolean secure) { setCookieImpl(name, value, (expires == null) ? 0 : expires.getTime(), domain, path, secure); } static native void loadCookies(HashMap<String, String> m) /*-{ var docCookie = $doc.cookie; if (docCookie && docCookie != '') { var crumbs = docCookie.split('; '); for (var i = 0; i < crumbs.length; ++i) { var name, value; var eqIdx = crumbs[i].indexOf('='); if (eqIdx == -1) { name = crumbs[i]; value = ''; } else { name = crumbs[i].substring(0, eqIdx); value = crumbs[i].substring(eqIdx + 1); } - name = decodeURIComponent(name); - value = decodeURIComponent(value); + try { + name = decodeURIComponent(name); + } catch (e) { + // ignore error, keep undecoded name + } + try { + value = decodeURIComponent(value); + } catch (e) { + // ignore error, keep undecoded value + } [email protected]::put(Ljava/lang/Object;Ljava/lang/Object;)(name,value); } } }-*/; private static HashMap<String, String> ensureCookies() { if (cachedCookies == null || needsRefresh()) { cachedCookies = new HashMap<String, String>(); loadCookies(cachedCookies); } return cachedCookies; } private static native boolean needsRefresh() /*-{ var docCookie = $doc.cookie; // Check to see if cached cookies need to be invalidated. if (docCookie != @com.google.gwt.user.client.Cookies::rawCookies) { @com.google.gwt.user.client.Cookies::rawCookies = docCookie; return true; } else { return false; } }-*/; private static native void setCookieImpl(String name, String value, double expires, String domain, String path, boolean secure) /*-{ var c = encodeURIComponent(name) + '=' + encodeURIComponent(value); if ( expires ) c += ';expires=' + (new Date(expires)).toGMTString(); if (domain) c += ';domain=' + domain; if (path) c += ';path=' + path; if (secure) c += ';secure'; $doc.cookie = c; }-*/; private Cookies() { } }
true
true
static native void loadCookies(HashMap<String, String> m) /*-{ var docCookie = $doc.cookie; if (docCookie && docCookie != '') { var crumbs = docCookie.split('; '); for (var i = 0; i < crumbs.length; ++i) { var name, value; var eqIdx = crumbs[i].indexOf('='); if (eqIdx == -1) { name = crumbs[i]; value = ''; } else { name = crumbs[i].substring(0, eqIdx); value = crumbs[i].substring(eqIdx + 1); } name = decodeURIComponent(name); value = decodeURIComponent(value); [email protected]::put(Ljava/lang/Object;Ljava/lang/Object;)(name,value); } } }-*/;
static native void loadCookies(HashMap<String, String> m) /*-{ var docCookie = $doc.cookie; if (docCookie && docCookie != '') { var crumbs = docCookie.split('; '); for (var i = 0; i < crumbs.length; ++i) { var name, value; var eqIdx = crumbs[i].indexOf('='); if (eqIdx == -1) { name = crumbs[i]; value = ''; } else { name = crumbs[i].substring(0, eqIdx); value = crumbs[i].substring(eqIdx + 1); } try { name = decodeURIComponent(name); } catch (e) { // ignore error, keep undecoded name } try { value = decodeURIComponent(value); } catch (e) { // ignore error, keep undecoded value } [email protected]::put(Ljava/lang/Object;Ljava/lang/Object;)(name,value); } } }-*/;
diff --git a/java/client/src/test/java/com/cloudera/kitten/TestKittenDistributedShell.java b/java/client/src/test/java/com/cloudera/kitten/TestKittenDistributedShell.java index 3644a38..0a50ffb 100644 --- a/java/client/src/test/java/com/cloudera/kitten/TestKittenDistributedShell.java +++ b/java/client/src/test/java/com/cloudera/kitten/TestKittenDistributedShell.java @@ -1,86 +1,86 @@ /** * Copyright (c) 2012, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package com.cloudera.kitten; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.server.MiniYARNCluster; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.cloudera.kitten.client.KittenClient; import com.cloudera.kitten.util.LocalDataHelper; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; public class TestKittenDistributedShell { private static final Log LOG = LogFactory.getLog(TestKittenDistributedShell.class); protected static MiniYARNCluster yarnCluster = null; protected static Configuration conf = new Configuration(); @BeforeClass public static void setup() throws InterruptedException, IOException { LOG.info("Starting up YARN cluster"); conf.setInt("yarn.scheduler.fifo.minimum-allocation-mb", 128); if (yarnCluster == null) { yarnCluster = new MiniYARNCluster(TestKittenDistributedShell.class.getName(), 1, 1, 1); yarnCluster.init(conf); yarnCluster.start(); } try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.info("setup thread sleep interrupted. message=" + e.getMessage()); } } @AfterClass public static void tearDown() throws IOException { if (yarnCluster != null) { yarnCluster.stop(); yarnCluster = null; } } @Test public void testKittenShell() throws Exception { - String config = "/lua/distshell.lua"; + String config = "lua/distshell.lua"; // For the outputs File tmpFile = File.createTempFile("distshell", ".txt"); tmpFile.deleteOnExit(); KittenClient client = new KittenClient( ImmutableMap.<String, Object>of( "TEST_FILE", tmpFile.getAbsolutePath(), "PWD", (new File(".")).getAbsolutePath())); conf.set(LocalDataHelper.APP_BASE_DIR, "file:///tmp/"); client.setConf(conf); assertEquals(0, client.run(new String[] { config, "distshell" })); assertEquals(12, Files.readLines(tmpFile, Charsets.UTF_8).size()); } }
true
true
public void testKittenShell() throws Exception { String config = "/lua/distshell.lua"; // For the outputs File tmpFile = File.createTempFile("distshell", ".txt"); tmpFile.deleteOnExit(); KittenClient client = new KittenClient( ImmutableMap.<String, Object>of( "TEST_FILE", tmpFile.getAbsolutePath(), "PWD", (new File(".")).getAbsolutePath())); conf.set(LocalDataHelper.APP_BASE_DIR, "file:///tmp/"); client.setConf(conf); assertEquals(0, client.run(new String[] { config, "distshell" })); assertEquals(12, Files.readLines(tmpFile, Charsets.UTF_8).size()); }
public void testKittenShell() throws Exception { String config = "lua/distshell.lua"; // For the outputs File tmpFile = File.createTempFile("distshell", ".txt"); tmpFile.deleteOnExit(); KittenClient client = new KittenClient( ImmutableMap.<String, Object>of( "TEST_FILE", tmpFile.getAbsolutePath(), "PWD", (new File(".")).getAbsolutePath())); conf.set(LocalDataHelper.APP_BASE_DIR, "file:///tmp/"); client.setConf(conf); assertEquals(0, client.run(new String[] { config, "distshell" })); assertEquals(12, Files.readLines(tmpFile, Charsets.UTF_8).size()); }
diff --git a/scm-webapp/src/main/java/sonia/scm/web/security/DefaultAdministrationContext.java b/scm-webapp/src/main/java/sonia/scm/web/security/DefaultAdministrationContext.java index 57434346d..34517fab7 100644 --- a/scm-webapp/src/main/java/sonia/scm/web/security/DefaultAdministrationContext.java +++ b/scm-webapp/src/main/java/sonia/scm/web/security/DefaultAdministrationContext.java @@ -1,294 +1,294 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.web.security; //~--- non-JDK imports -------------------------------------------------------- import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.support.SubjectThreadState; import org.apache.shiro.util.ThreadContext; import org.apache.shiro.util.ThreadState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.SCMContext; import sonia.scm.group.GroupNames; import sonia.scm.security.Role; import sonia.scm.security.ScmRealm; import sonia.scm.user.User; import sonia.scm.util.AssertUtil; //~--- JDK imports ------------------------------------------------------------ import java.net.URL; import javax.xml.bind.JAXB; /** * * @author Sebastian Sdorra */ @Singleton public class DefaultAdministrationContext implements AdministrationContext { /** Field description */ public static final String SYSTEM_ACCOUNT = "/sonia/scm/web/security/system-account.xml"; /** the logger for DefaultAdministrationContext */ private static final Logger logger = LoggerFactory.getLogger(DefaultAdministrationContext.class); //~--- constructors --------------------------------------------------------- /** * Constructs ... * * * @param injector * @param userSessionProvider * @param contextHolder * @param securityManager */ @Inject public DefaultAdministrationContext(Injector injector, org.apache.shiro.mgt.SecurityManager securityManager) { this.injector = injector; this.securityManager = securityManager; URL url = DefaultAdministrationContext.class.getResource(SYSTEM_ACCOUNT); if (url == null) { throw new RuntimeException("could not find resource for system account"); } User adminUser = JAXB.unmarshal(url, User.class); principalCollection = createAdminCollection(adminUser); } //~--- methods -------------------------------------------------------------- /** * Method description * * * @param action */ @Override public void runAsAdmin(PrivilegedAction action) { AssertUtil.assertIsNotNull(action); if (ThreadContext.getSecurityManager() != null) { Subject subject = SecurityUtils.getSubject(); if (subject.hasRole(Role.ADMIN)) { logger.debug( "user is already an admin, we need no system account session, execute action {}", action.getClass().getName()); action.run(); } else { doRunAsInWebSessionContext(action); } } else { doRunAsInNonWebSessionContext(action); } } /** * Method description * * * @param actionClass */ @Override public void runAsAdmin(Class<? extends PrivilegedAction> actionClass) { PrivilegedAction action = injector.getInstance(actionClass); runAsAdmin(action); } /** * Method description * * * @param adminUser * * @return */ private PrincipalCollection createAdminCollection(User adminUser) { SimplePrincipalCollection collection = new SimplePrincipalCollection(); collection.add(adminUser.getId(), ScmRealm.NAME); collection.add(adminUser, ScmRealm.NAME); collection.add(new GroupNames(), ScmRealm.NAME); return collection; } /** * Method description * * * @param action */ private void doRunAsInNonWebSessionContext(PrivilegedAction action) { if (logger.isTraceEnabled()) { logger.trace("bind shiro security manager to current thread"); } try { SecurityUtils.setSecurityManager(securityManager); //J- Subject subject = new Subject.Builder(securityManager) .authenticated(true) .principals(principalCollection) .buildSubject(); //J+ ThreadState state = new SubjectThreadState(subject); state.bind(); try { if (logger.isInfoEnabled()) { logger.info("execute action {} in administration context", action.getClass().getName()); } action.run(); } finally { state.clear(); } } finally { SecurityUtils.setSecurityManager(null); } } /** * Method description * * * @param action */ private void doRunAsInWebSessionContext(PrivilegedAction action) { Subject subject = SecurityUtils.getSubject(); String principal = (String) subject.getPrincipal(); if (logger.isInfoEnabled()) { String username = null; if (subject.isAuthenticated()) { username = principal; } else { username = SCMContext.USER_ANONYMOUS; } logger.info("user {} executes {} as admin", username, action.getClass().getName()); } subject.runAs(principalCollection); try { action.run(); } finally { PrincipalCollection collection = subject.releaseRunAs(); if (logger.isDebugEnabled()) { - logger.debug("release runas for user {}", - collection.getPrimaryPrincipal()); + logger.debug("release runas for user {}/{}", + principal, collection.getPrimaryPrincipal()); } if (!subject.getPrincipal().equals(principal)) { logger.error("release runas failed, {} is not equal with {}, logout.", subject.getPrincipal(), principal); subject.logout(); } } } //~--- fields --------------------------------------------------------------- /** Field description */ private Injector injector; /** Field description */ private PrincipalCollection principalCollection; /** Field description */ private org.apache.shiro.mgt.SecurityManager securityManager; }
true
true
private void doRunAsInWebSessionContext(PrivilegedAction action) { Subject subject = SecurityUtils.getSubject(); String principal = (String) subject.getPrincipal(); if (logger.isInfoEnabled()) { String username = null; if (subject.isAuthenticated()) { username = principal; } else { username = SCMContext.USER_ANONYMOUS; } logger.info("user {} executes {} as admin", username, action.getClass().getName()); } subject.runAs(principalCollection); try { action.run(); } finally { PrincipalCollection collection = subject.releaseRunAs(); if (logger.isDebugEnabled()) { logger.debug("release runas for user {}", collection.getPrimaryPrincipal()); } if (!subject.getPrincipal().equals(principal)) { logger.error("release runas failed, {} is not equal with {}, logout.", subject.getPrincipal(), principal); subject.logout(); } } }
private void doRunAsInWebSessionContext(PrivilegedAction action) { Subject subject = SecurityUtils.getSubject(); String principal = (String) subject.getPrincipal(); if (logger.isInfoEnabled()) { String username = null; if (subject.isAuthenticated()) { username = principal; } else { username = SCMContext.USER_ANONYMOUS; } logger.info("user {} executes {} as admin", username, action.getClass().getName()); } subject.runAs(principalCollection); try { action.run(); } finally { PrincipalCollection collection = subject.releaseRunAs(); if (logger.isDebugEnabled()) { logger.debug("release runas for user {}/{}", principal, collection.getPrimaryPrincipal()); } if (!subject.getPrincipal().equals(principal)) { logger.error("release runas failed, {} is not equal with {}, logout.", subject.getPrincipal(), principal); subject.logout(); } } }
diff --git a/src/frontend/org/voltdb/utils/PersistentBinaryDeque.java b/src/frontend/org/voltdb/utils/PersistentBinaryDeque.java index 5b2012bc7..dc1627f88 100644 --- a/src/frontend/org/voltdb/utils/PersistentBinaryDeque.java +++ b/src/frontend/org/voltdb/utils/PersistentBinaryDeque.java @@ -1,730 +1,730 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.utils; import java.io.EOFException; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayDeque; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import java.util.Iterator; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.DBBPool.BBContainer; /** * A deque that specializes in providing persistence of binary objects to disk. Any object placed * in the deque will be persisted to disk asynchronously. Objects placed in the queue can * be persisted synchronously by invoking sync. The files backing this deque all start with a nonce * provided at construction time followed by a segment index that is stored in the filename. Files grow to * a maximum size of 64 megabytes and then a new segment is created. The index starts at 0. Segments are deleted * once all objects from the segment have been polled and all the containers returned by poll have been discarded. * Push is implemented by creating new segments at the head of the queue containing the objects to be pushed. * */ public class PersistentBinaryDeque implements BinaryDeque { /** * Processors also log using this facility. */ private static final VoltLogger exportLog = new VoltLogger("EXPORT"); private final File m_path; private final String m_nonce; private java.util.concurrent.atomic.AtomicLong m_sizeInBytes = new java.util.concurrent.atomic.AtomicLong(0); /** * Objects placed in the deque are stored in file segments that are up to 64 megabytes. * Segments only support appending objects. A segment will throw an IOException if an attempt * to insert an object that exceeds the remaining space is made. A segment can be used * for reading and writing, but not both at the same time. * */ private class DequeSegment { //Avoid unecessary sync with this flag private boolean m_syncedSinceLastEdit = true; private final File m_file; private RandomAccessFile m_ras; private FileChannel m_fc; //Index of the next object to read, not an offset into the file //The offset is maintained by the ByteBuffer. Used to determine if there is another object private int m_objectReadIndex = 0; //ID of this segment private final Long m_index; private static final int m_chunkSize = (1024 * 1024) * 64; //How many entries that have been polled have from this file have been discarded. //Once this == the number of entries the segment can close and delete itself private int m_discardsUntilDeletion = 0; public DequeSegment(Long index, File file) { m_index = index; m_file = file; } private final ByteBuffer m_bufferForNumEntries = ByteBuffer.allocateDirect(4); private int getNumEntries() throws IOException { if (m_fc == null) { open(); } if (m_fc.size() > 0) { m_bufferForNumEntries.clear(); while (m_bufferForNumEntries.hasRemaining()) { int read = m_fc.read(m_bufferForNumEntries, 0); if (read == -1) { throw new EOFException(); } } m_bufferForNumEntries.flip(); return m_bufferForNumEntries.getInt(); } else { return 0; } } private void initNumEntries() throws IOException { m_bufferForNumEntries.clear(); m_bufferForNumEntries.putInt(0).flip(); while (m_bufferForNumEntries.hasRemaining()) { m_fc.write(m_bufferForNumEntries, 0); } m_syncedSinceLastEdit = false; } private void incrementNumEntries() throws IOException { //First read the existing amount m_bufferForNumEntries.clear(); while (m_bufferForNumEntries.hasRemaining()) { int read = m_fc.read(m_bufferForNumEntries, 0); if (read == -1) { throw new EOFException(); } } m_bufferForNumEntries.flip(); //Then write the incremented value int numEntries = m_bufferForNumEntries.getInt(); m_bufferForNumEntries.flip(); m_bufferForNumEntries.putInt(++numEntries).flip(); while (m_bufferForNumEntries.hasRemaining()) { m_fc.write(m_bufferForNumEntries, 0); } m_syncedSinceLastEdit = false; //For when this buffer is eventually finished and starts being polled //Stored on disk and in memory m_discardsUntilDeletion++; } /** * Bytes of space available for inserting more entries * @return */ private int remaining() throws IOException { //Subtract 4 for the length prefix return (int)(m_chunkSize - m_fc.position()) - 4; } private void open() throws IOException { if (!m_file.exists()) { m_syncedSinceLastEdit = false; } if (m_ras != null) { throw new IOException(m_file + " was already opened"); } m_ras = new RandomAccessFile( m_file, "rw"); m_fc = m_ras.getChannel(); m_fc.position(4); if (m_fc.size() >= 4) { m_discardsUntilDeletion = getNumEntries(); } } private void closeAndDelete() throws IOException { close(); m_sizeInBytes.addAndGet(-sizeInBytes()); m_file.delete(); } private void close() throws IOException { if (m_fc != null) { m_fc.close(); m_ras = null; m_fc = null; } } private void sync() throws IOException { if (!m_syncedSinceLastEdit) { m_fc.force(true); } m_syncedSinceLastEdit = true; } private BBContainer poll() throws IOException { if (m_fc == null) { open(); } //No more entries to read if (m_objectReadIndex >= getNumEntries()) { return null; } m_objectReadIndex++; //If this is the last object to read from this segment //increment the poll segment index so that the next poll //selects the correct segment if (m_objectReadIndex >= getNumEntries()) { m_currentPollSegmentIndex++; } //Get the length prefix and then read the object m_bufferForNumEntries.clear(); while (m_bufferForNumEntries.hasRemaining()) { int read = m_fc.read(m_bufferForNumEntries); if (read == -1) { throw new EOFException(); } } m_bufferForNumEntries.flip(); int length = m_bufferForNumEntries.getInt(); if (length < 1) { throw new IOException("Read an invalid length"); } ByteBuffer resultBuffer = ByteBuffer.allocate(length); while (resultBuffer.hasRemaining()) { int read = m_fc.read(resultBuffer); if (read == -1) { throw new EOFException(); } } resultBuffer.flip(); return new BBContainer( resultBuffer, 0L) { private boolean discarded = false; private final Throwable t = new Throwable(); @Override public void discard() { if (!discarded) { discarded = true; m_discardsUntilDeletion--; if (m_discardsUntilDeletion == 0) { m_finishedSegments.remove(m_index); try { closeAndDelete(); } catch (IOException e) { exportLog.error(e); } } } else { exportLog.error("An export buffer was discarded multiple times"); } } @Override public void finalize() { if (!discarded && !m_closed) { exportLog.error(m_file + " had a buffer that was finalized without being discarded"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); exportLog.error(sw.toString()); discard(); } } }; } private void offer(BBContainer objects[]) throws IOException { int length = 0; for (BBContainer obj : objects ) { length += obj.b.remaining(); } if (remaining() < length) { throw new IOException(m_file + " has insufficient space"); } m_bufferForNumEntries.clear(); m_bufferForNumEntries.putInt(length).flip(); while (m_bufferForNumEntries.hasRemaining()) { m_fc.write(m_bufferForNumEntries); } int objectIndex = 0; for (BBContainer obj : objects ) { boolean success = false; try { while (obj.b.hasRemaining()) { m_fc.write(obj.b); } obj.discard(); success = true; objectIndex++; } finally { if (!success) { for (int ii = objectIndex; ii < objects.length; ii++) { objects[ii].discard(); } } } } m_sizeInBytes.addAndGet(4 + length); incrementNumEntries(); } //A white lie, don't include the object count prefix //so that the size is 0 when there is no user data private long sizeInBytes() { return m_file.length() - 4; } } //Segments that are no longer being written to and can be polled //These segments are "immutable". They will not be modified until deletion private final TreeMap<Long, DequeSegment> m_finishedSegments = new TreeMap<Long, DequeSegment>(); //The current segment being written to private DequeSegment m_writeSegment = null; //Index of the segment being polled private Long m_currentPollSegmentIndex = 0L; private volatile boolean m_closed = false; /** * Create a persistent binary deque with the specified nonce and storage back at the specified path. * Existing files will * @param nonce * @param path * @throws IOException */ public PersistentBinaryDeque(final String nonce, final File path) throws IOException { m_path = path; m_nonce = nonce; if (!path.exists() || !path.canRead() || !path.canWrite() || !path.canExecute() || !path.isDirectory()) { throw new IOException(path + " is not usable ( !exists || !readable " + "|| !writable || !executable || !directory)"); } //Parse the files in the directory by name to find files //that are part of this deque path.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); if (name.startsWith(nonce) && name.endsWith(".pbd")) { if (pathname.length() == 4) { //Doesn't have any objects, just the object count pathname.delete(); return false; } Long index = Long.valueOf(name.substring( nonce.length() + 1, name.length() - 4)); DequeSegment ds = new DequeSegment( index, pathname); m_finishedSegments.put( index, ds); m_sizeInBytes.addAndGet(ds.sizeInBytes()); } return false; } }); Long lastKey = null; for (Long key : m_finishedSegments.keySet()) { if (lastKey == null) { lastKey = key; } else { if (lastKey + 1 != key) { throw new IOException("Missing " + nonce + " pbd segments between " + lastKey + " and " + key + " in directory " + path + ". The data files found in the export overflow directory were inconsistent."); } lastKey = key; } } //Find the first and last segment for polling and writing (after) Long writeSegmentIndex = 0L; try { m_currentPollSegmentIndex = m_finishedSegments.firstKey(); writeSegmentIndex = m_finishedSegments.lastKey() + 1; } catch (NoSuchElementException e) {} m_writeSegment = new DequeSegment( writeSegmentIndex, new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd")); m_writeSegment.open(); m_writeSegment.initNumEntries(); } @Override public synchronized void offer(BBContainer[] objects) throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } int needed = 0; for (BBContainer b : objects) { needed += b.b.remaining(); } if (needed > DequeSegment.m_chunkSize - 4) { throw new IOException("Maxiumum object size is " + (DequeSegment.m_chunkSize - 4)); } if (m_writeSegment.remaining() < needed) { openNewWriteSegment(); } m_writeSegment.offer(objects); } @Override public synchronized void push(BBContainer[][] objects) throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } if (!m_finishedSegments.isEmpty()) { assert(m_finishedSegments.firstKey().equals(m_currentPollSegmentIndex)); } ArrayDeque<ArrayDeque<BBContainer[]>> segments = new ArrayDeque<ArrayDeque<BBContainer[]>>(); ArrayDeque<BBContainer[]> currentSegment = new ArrayDeque<BBContainer[]>(); //Take the objects that were provided and separate them into deques of objects //that will fit in a single write segment int available = DequeSegment.m_chunkSize - 4; for (BBContainer object[] : objects) { int needed = 4; for (BBContainer obj : object) { needed += obj.b.remaining(); } if (available - needed < 0) { if (needed > DequeSegment.m_chunkSize - 4) { throw new IOException("Maximum object size is " + (DequeSegment.m_chunkSize - 4)); } segments.offer( currentSegment ); currentSegment = new ArrayDeque<BBContainer[]>(); available = DequeSegment.m_chunkSize - 4; } available -= needed; currentSegment.add(object); } segments.add(currentSegment); assert(segments.size() > 0); //Calculate the index for the first segment to push at the front //This will be the index before the first segment available for read or //before the write segment if there are no finished segments Long nextIndex = 0L; if (m_finishedSegments.size() > 0) { nextIndex = m_finishedSegments.firstKey() - 1; } else { nextIndex = m_writeSegment.m_index - 1; } while (segments.peek() != null) { ArrayDeque<BBContainer[]> currentSegmentContents = segments.poll(); DequeSegment writeSegment = new DequeSegment( nextIndex, new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd")); m_currentPollSegmentIndex = nextIndex; writeSegment.open(); writeSegment.initNumEntries(); nextIndex--; while (currentSegmentContents.peek() != null) { writeSegment.offer(currentSegmentContents.pollFirst()); } writeSegment.m_fc.position(4); m_finishedSegments.put(writeSegment.m_index, writeSegment); } } private void openNewWriteSegment() throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } m_writeSegment.m_fc.position(4); m_finishedSegments.put(m_writeSegment.m_index, m_writeSegment); Long nextIndex = m_writeSegment.m_index + 1; m_writeSegment = new DequeSegment( nextIndex, new VoltFile(m_path, m_nonce + "." + nextIndex + ".pbd")); m_writeSegment.open(); m_writeSegment.initNumEntries(); } @Override public synchronized BBContainer poll() throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } DequeSegment segment = m_finishedSegments.get(m_currentPollSegmentIndex); if (segment == null) { assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex)); //See if we can steal the write segment, otherwise return null if (m_writeSegment.getNumEntries() > 0) { openNewWriteSegment(); return poll(); } else { return null; } } return segment.poll(); } @Override public synchronized void sync() throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } m_writeSegment.sync(); for (DequeSegment segment : m_finishedSegments.values()) { segment.sync(); } } @Override public synchronized void close() throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } if (m_writeSegment.getNumEntries() > 0) { m_finishedSegments.put(m_writeSegment.m_index, m_writeSegment); } else { m_writeSegment.closeAndDelete(); } m_writeSegment = null; for (DequeSegment segment : m_finishedSegments.values()) { segment.close(); } m_closed = true; } @Override public synchronized boolean isEmpty() throws IOException { if (m_writeSegment == null) { throw new IOException("Closed"); } DequeSegment segment = m_finishedSegments.get(m_currentPollSegmentIndex); if (segment == null) { assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex)); //See if we can steal the write segment, otherwise return null if (m_writeSegment.getNumEntries() > 0) { return false; } else { return true; } } return segment.m_objectReadIndex >= segment.getNumEntries(); } @Override public long sizeInBytes() { return m_sizeInBytes.get(); } @Override public synchronized void closeAndDelete() throws IOException { m_writeSegment.closeAndDelete(); for (DequeSegment ds : m_finishedSegments.values()) { ds.closeAndDelete(); } } @Override - public void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { + public synchronized void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { if (m_finishedSegments.isEmpty()) { exportLog.debug("PBD " + m_nonce + " has no finished segments"); return; } //+16 because I am not sure if the max chunk size is enforced right ByteBuffer readBuffer = ByteBuffer.allocateDirect(DequeSegment.m_chunkSize + 16); /* * Iterator all the objects in all the segments and pass them to the truncator * When it finds the truncation point */ Long lastSegmentIndex = null; for (Map.Entry<Long, DequeSegment> entry : m_finishedSegments.entrySet()) { readBuffer.clear(); DequeSegment segment = entry.getValue(); long segmentIndex = entry.getKey(); File segmentFile = segment.m_file; RandomAccessFile ras = new RandomAccessFile(segmentFile, "rw"); FileChannel fc = ras.getChannel(); try { /* * Read the entire segment into memory */ while (readBuffer.hasRemaining()) { int read = fc.read(readBuffer); if (read == -1) { break; } } readBuffer.flip(); //Get the number of objects and then iterator over them int numObjects = readBuffer.getInt(); exportLog.debug("PBD " + m_nonce + " has " + numObjects + " objects to parse and truncate"); for (int ii = 0; ii < numObjects; ii++) { final int nextObjectLength = readBuffer.getInt(); //Copy the next object into a separate heap byte buffer //do the old limit stashing trick to avoid buffer overflow ByteBuffer nextObject = ByteBuffer.allocate(nextObjectLength); final int oldLimit = readBuffer.limit(); readBuffer.limit(readBuffer.position() + nextObjectLength); nextObject.put(readBuffer).flip(); //Put back the original limit readBuffer.limit(oldLimit); //Handoff the object to the truncator and await a decision ByteBuffer retval = truncator.parse(nextObject); if (retval == null) { //Nothing to do, leave the object alone and move to the next continue; } else { long startSize = fc.size(); //If the returned bytebuffer is empty, remove the object and truncate the file if (retval.remaining() == 0) { if (ii == 0) { /* * If truncation is occuring at the first object * Whammo! Delete the file. Do it by setting the lastSegmentIndex * to 1 previous. We may end up with an empty finished segment * set. */ lastSegmentIndex = segmentIndex - 1; } else { //Don't forget to update the number of entries in the file ByteBuffer numObjectsBuffer = ByteBuffer.allocate(4); numObjectsBuffer.putInt(0, ii); fc.position(0); while (numObjectsBuffer.hasRemaining()) { fc.write(numObjectsBuffer); } fc.truncate(readBuffer.position() - (nextObjectLength + 4)); } } else { readBuffer.position(readBuffer.position() - (nextObjectLength + 4)); readBuffer.putInt(retval.remaining()); readBuffer.put(retval); readBuffer.flip(); readBuffer.putInt(0, ii + 1); /* * SHOULD REALLY make a copy of the original and then swap them with renaming */ fc.position(0); fc.truncate(0); while (readBuffer.hasRemaining()) { fc.write(readBuffer); } } long endSize = fc.size(); m_sizeInBytes.addAndGet(endSize - startSize); //Set last segment and break the loop over this segment if (lastSegmentIndex == null) { lastSegmentIndex = segmentIndex; } break; } } //If this is set the just processed segment was the last one if (lastSegmentIndex != null) { break; } } finally { fc.close(); } } /* * If it was found that no truncation is necessary, lastSegmentIndex will be null. * Return and the parseAndTruncate is a noop. */ if (lastSegmentIndex == null) { return; } /* * Now truncate all the segments after the truncation point */ Iterator<Map.Entry<Long, DequeSegment>> iterator = m_finishedSegments.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Long, DequeSegment> entry = iterator.next(); if (entry.getKey() <= lastSegmentIndex) { continue; } DequeSegment ds = entry.getValue(); iterator.remove(); ds.closeAndDelete(); } //The write segment may have the wrong index, delete it m_writeSegment.closeAndDelete(); /* * Reset the poll and write segments */ //Find the first and last segment for polling and writing (after) m_currentPollSegmentIndex = 0L; Long writeSegmentIndex = 0L; try { m_currentPollSegmentIndex = m_finishedSegments.firstKey(); writeSegmentIndex = m_finishedSegments.lastKey() + 1; } catch (NoSuchElementException e) {} m_writeSegment = new DequeSegment( writeSegmentIndex, new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd")); m_writeSegment.open(); m_writeSegment.initNumEntries(); if (m_finishedSegments.isEmpty()) { assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex)); } } }
true
true
public void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { if (m_finishedSegments.isEmpty()) { exportLog.debug("PBD " + m_nonce + " has no finished segments"); return; } //+16 because I am not sure if the max chunk size is enforced right ByteBuffer readBuffer = ByteBuffer.allocateDirect(DequeSegment.m_chunkSize + 16); /* * Iterator all the objects in all the segments and pass them to the truncator * When it finds the truncation point */ Long lastSegmentIndex = null; for (Map.Entry<Long, DequeSegment> entry : m_finishedSegments.entrySet()) { readBuffer.clear(); DequeSegment segment = entry.getValue(); long segmentIndex = entry.getKey(); File segmentFile = segment.m_file; RandomAccessFile ras = new RandomAccessFile(segmentFile, "rw"); FileChannel fc = ras.getChannel(); try { /* * Read the entire segment into memory */ while (readBuffer.hasRemaining()) { int read = fc.read(readBuffer); if (read == -1) { break; } } readBuffer.flip(); //Get the number of objects and then iterator over them int numObjects = readBuffer.getInt(); exportLog.debug("PBD " + m_nonce + " has " + numObjects + " objects to parse and truncate"); for (int ii = 0; ii < numObjects; ii++) { final int nextObjectLength = readBuffer.getInt(); //Copy the next object into a separate heap byte buffer //do the old limit stashing trick to avoid buffer overflow ByteBuffer nextObject = ByteBuffer.allocate(nextObjectLength); final int oldLimit = readBuffer.limit(); readBuffer.limit(readBuffer.position() + nextObjectLength); nextObject.put(readBuffer).flip(); //Put back the original limit readBuffer.limit(oldLimit); //Handoff the object to the truncator and await a decision ByteBuffer retval = truncator.parse(nextObject); if (retval == null) { //Nothing to do, leave the object alone and move to the next continue; } else { long startSize = fc.size(); //If the returned bytebuffer is empty, remove the object and truncate the file if (retval.remaining() == 0) { if (ii == 0) { /* * If truncation is occuring at the first object * Whammo! Delete the file. Do it by setting the lastSegmentIndex * to 1 previous. We may end up with an empty finished segment * set. */ lastSegmentIndex = segmentIndex - 1; } else { //Don't forget to update the number of entries in the file ByteBuffer numObjectsBuffer = ByteBuffer.allocate(4); numObjectsBuffer.putInt(0, ii); fc.position(0); while (numObjectsBuffer.hasRemaining()) { fc.write(numObjectsBuffer); } fc.truncate(readBuffer.position() - (nextObjectLength + 4)); } } else { readBuffer.position(readBuffer.position() - (nextObjectLength + 4)); readBuffer.putInt(retval.remaining()); readBuffer.put(retval); readBuffer.flip(); readBuffer.putInt(0, ii + 1); /* * SHOULD REALLY make a copy of the original and then swap them with renaming */ fc.position(0); fc.truncate(0); while (readBuffer.hasRemaining()) { fc.write(readBuffer); } } long endSize = fc.size(); m_sizeInBytes.addAndGet(endSize - startSize); //Set last segment and break the loop over this segment if (lastSegmentIndex == null) { lastSegmentIndex = segmentIndex; } break; } } //If this is set the just processed segment was the last one if (lastSegmentIndex != null) { break; } } finally { fc.close(); } } /* * If it was found that no truncation is necessary, lastSegmentIndex will be null. * Return and the parseAndTruncate is a noop. */ if (lastSegmentIndex == null) { return; } /* * Now truncate all the segments after the truncation point */ Iterator<Map.Entry<Long, DequeSegment>> iterator = m_finishedSegments.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Long, DequeSegment> entry = iterator.next(); if (entry.getKey() <= lastSegmentIndex) { continue; } DequeSegment ds = entry.getValue(); iterator.remove(); ds.closeAndDelete(); } //The write segment may have the wrong index, delete it m_writeSegment.closeAndDelete(); /* * Reset the poll and write segments */ //Find the first and last segment for polling and writing (after) m_currentPollSegmentIndex = 0L; Long writeSegmentIndex = 0L; try { m_currentPollSegmentIndex = m_finishedSegments.firstKey(); writeSegmentIndex = m_finishedSegments.lastKey() + 1; } catch (NoSuchElementException e) {} m_writeSegment = new DequeSegment( writeSegmentIndex, new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd")); m_writeSegment.open(); m_writeSegment.initNumEntries(); if (m_finishedSegments.isEmpty()) { assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex)); } }
public synchronized void parseAndTruncate(BinaryDequeTruncator truncator) throws IOException { if (m_finishedSegments.isEmpty()) { exportLog.debug("PBD " + m_nonce + " has no finished segments"); return; } //+16 because I am not sure if the max chunk size is enforced right ByteBuffer readBuffer = ByteBuffer.allocateDirect(DequeSegment.m_chunkSize + 16); /* * Iterator all the objects in all the segments and pass them to the truncator * When it finds the truncation point */ Long lastSegmentIndex = null; for (Map.Entry<Long, DequeSegment> entry : m_finishedSegments.entrySet()) { readBuffer.clear(); DequeSegment segment = entry.getValue(); long segmentIndex = entry.getKey(); File segmentFile = segment.m_file; RandomAccessFile ras = new RandomAccessFile(segmentFile, "rw"); FileChannel fc = ras.getChannel(); try { /* * Read the entire segment into memory */ while (readBuffer.hasRemaining()) { int read = fc.read(readBuffer); if (read == -1) { break; } } readBuffer.flip(); //Get the number of objects and then iterator over them int numObjects = readBuffer.getInt(); exportLog.debug("PBD " + m_nonce + " has " + numObjects + " objects to parse and truncate"); for (int ii = 0; ii < numObjects; ii++) { final int nextObjectLength = readBuffer.getInt(); //Copy the next object into a separate heap byte buffer //do the old limit stashing trick to avoid buffer overflow ByteBuffer nextObject = ByteBuffer.allocate(nextObjectLength); final int oldLimit = readBuffer.limit(); readBuffer.limit(readBuffer.position() + nextObjectLength); nextObject.put(readBuffer).flip(); //Put back the original limit readBuffer.limit(oldLimit); //Handoff the object to the truncator and await a decision ByteBuffer retval = truncator.parse(nextObject); if (retval == null) { //Nothing to do, leave the object alone and move to the next continue; } else { long startSize = fc.size(); //If the returned bytebuffer is empty, remove the object and truncate the file if (retval.remaining() == 0) { if (ii == 0) { /* * If truncation is occuring at the first object * Whammo! Delete the file. Do it by setting the lastSegmentIndex * to 1 previous. We may end up with an empty finished segment * set. */ lastSegmentIndex = segmentIndex - 1; } else { //Don't forget to update the number of entries in the file ByteBuffer numObjectsBuffer = ByteBuffer.allocate(4); numObjectsBuffer.putInt(0, ii); fc.position(0); while (numObjectsBuffer.hasRemaining()) { fc.write(numObjectsBuffer); } fc.truncate(readBuffer.position() - (nextObjectLength + 4)); } } else { readBuffer.position(readBuffer.position() - (nextObjectLength + 4)); readBuffer.putInt(retval.remaining()); readBuffer.put(retval); readBuffer.flip(); readBuffer.putInt(0, ii + 1); /* * SHOULD REALLY make a copy of the original and then swap them with renaming */ fc.position(0); fc.truncate(0); while (readBuffer.hasRemaining()) { fc.write(readBuffer); } } long endSize = fc.size(); m_sizeInBytes.addAndGet(endSize - startSize); //Set last segment and break the loop over this segment if (lastSegmentIndex == null) { lastSegmentIndex = segmentIndex; } break; } } //If this is set the just processed segment was the last one if (lastSegmentIndex != null) { break; } } finally { fc.close(); } } /* * If it was found that no truncation is necessary, lastSegmentIndex will be null. * Return and the parseAndTruncate is a noop. */ if (lastSegmentIndex == null) { return; } /* * Now truncate all the segments after the truncation point */ Iterator<Map.Entry<Long, DequeSegment>> iterator = m_finishedSegments.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Long, DequeSegment> entry = iterator.next(); if (entry.getKey() <= lastSegmentIndex) { continue; } DequeSegment ds = entry.getValue(); iterator.remove(); ds.closeAndDelete(); } //The write segment may have the wrong index, delete it m_writeSegment.closeAndDelete(); /* * Reset the poll and write segments */ //Find the first and last segment for polling and writing (after) m_currentPollSegmentIndex = 0L; Long writeSegmentIndex = 0L; try { m_currentPollSegmentIndex = m_finishedSegments.firstKey(); writeSegmentIndex = m_finishedSegments.lastKey() + 1; } catch (NoSuchElementException e) {} m_writeSegment = new DequeSegment( writeSegmentIndex, new VoltFile(m_path, m_nonce + "." + writeSegmentIndex + ".pbd")); m_writeSegment.open(); m_writeSegment.initNumEntries(); if (m_finishedSegments.isEmpty()) { assert(m_writeSegment.m_index.equals(m_currentPollSegmentIndex)); } }
diff --git a/src/main/java/net/pms/dlna/SubSelFile.java b/src/main/java/net/pms/dlna/SubSelFile.java index f10b23012..4b560ec36 100644 --- a/src/main/java/net/pms/dlna/SubSelFile.java +++ b/src/main/java/net/pms/dlna/SubSelFile.java @@ -1,57 +1,54 @@ package net.pms.dlna; import java.io.IOException; import java.util.Map; import net.pms.dlna.virtual.VirtualFolder; import net.pms.formats.v2.SubtitleType; import net.pms.util.FileUtil; import net.pms.util.OpenSubtitle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SubSelFile extends VirtualFolder { private static final Logger LOGGER = LoggerFactory.getLogger(SubSelFile.class); private RealFile rf; public SubSelFile(DLNAResource r) { this((RealFile) r); } public SubSelFile(RealFile file) { super(file.getDisplayName(), file.getThumbnailURL()); rf = file; } @Override public void discoverChildren() { Map<String, Object> data; try { data = OpenSubtitle.findSubs(rf.getFile()); } catch (IOException e) { return; } if (data == null || data.isEmpty()) { return; } for (String key : data.keySet()) { LOGGER.debug("Add play subtitle child " + key + " rf " + rf); DLNAMediaSubtitle sub = rf.getMediaSubtitle(); if (sub == null) { sub = new DLNAMediaSubtitle(); } String lang = OpenSubtitle.getLang(key); String name = OpenSubtitle.getName(key); - if (name.endsWith(".srt")) { - name = FileUtil.getFileNameWithoutExtension(name); - } sub.setType(SubtitleType.SUBRIP); sub.setId(1); sub.setLang(lang); sub.setLiveSub((String) data.get(key), OpenSubtitle.subFile(name + "_" + lang)); RealFile nrf = new RealFile(rf.getFile(), name); nrf.setMediaSubtitle(sub); nrf.setSrtFile(true); addChild(nrf); } } }
true
true
public void discoverChildren() { Map<String, Object> data; try { data = OpenSubtitle.findSubs(rf.getFile()); } catch (IOException e) { return; } if (data == null || data.isEmpty()) { return; } for (String key : data.keySet()) { LOGGER.debug("Add play subtitle child " + key + " rf " + rf); DLNAMediaSubtitle sub = rf.getMediaSubtitle(); if (sub == null) { sub = new DLNAMediaSubtitle(); } String lang = OpenSubtitle.getLang(key); String name = OpenSubtitle.getName(key); if (name.endsWith(".srt")) { name = FileUtil.getFileNameWithoutExtension(name); } sub.setType(SubtitleType.SUBRIP); sub.setId(1); sub.setLang(lang); sub.setLiveSub((String) data.get(key), OpenSubtitle.subFile(name + "_" + lang)); RealFile nrf = new RealFile(rf.getFile(), name); nrf.setMediaSubtitle(sub); nrf.setSrtFile(true); addChild(nrf); } }
public void discoverChildren() { Map<String, Object> data; try { data = OpenSubtitle.findSubs(rf.getFile()); } catch (IOException e) { return; } if (data == null || data.isEmpty()) { return; } for (String key : data.keySet()) { LOGGER.debug("Add play subtitle child " + key + " rf " + rf); DLNAMediaSubtitle sub = rf.getMediaSubtitle(); if (sub == null) { sub = new DLNAMediaSubtitle(); } String lang = OpenSubtitle.getLang(key); String name = OpenSubtitle.getName(key); sub.setType(SubtitleType.SUBRIP); sub.setId(1); sub.setLang(lang); sub.setLiveSub((String) data.get(key), OpenSubtitle.subFile(name + "_" + lang)); RealFile nrf = new RealFile(rf.getFile(), name); nrf.setMediaSubtitle(sub); nrf.setSrtFile(true); addChild(nrf); } }
diff --git a/src/games/Block.java b/src/games/Block.java index 7b77f68..831b835 100644 --- a/src/games/Block.java +++ b/src/games/Block.java @@ -1,23 +1,23 @@ package games; import java.util.Random; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class Block extends Image{ Image sprite = null; Random r = new Random(); int xVel; int yVel; int x; int y; Block() throws SlickException{ - sprite = new Image("resrouces/plane.png"); + sprite = new Image("resources/plane.png"); xVel = r.nextInt(10); yVel = r.nextInt(10); x = r.nextInt(640); y = r.nextInt(480); } }
true
true
Block() throws SlickException{ sprite = new Image("resrouces/plane.png"); xVel = r.nextInt(10); yVel = r.nextInt(10); x = r.nextInt(640); y = r.nextInt(480); }
Block() throws SlickException{ sprite = new Image("resources/plane.png"); xVel = r.nextInt(10); yVel = r.nextInt(10); x = r.nextInt(640); y = r.nextInt(480); }
diff --git a/src/org/ktln2/android/callstat/CallStatAdapter.java b/src/org/ktln2/android/callstat/CallStatAdapter.java index dde5817..b1e7fe2 100644 --- a/src/org/ktln2/android/callstat/CallStatAdapter.java +++ b/src/org/ktln2/android/callstat/CallStatAdapter.java @@ -1,158 +1,158 @@ package org.ktln2.android.callstat; import android.content.Context; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.ImageView; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.text.SpannableString; import android.text.style.StyleSpan; import android.graphics.Typeface; import java.util.Comparator; /* * This adapter bind the data to the list view. * * There is only a problem: from the same data you can calculate several * different list ordering and visualization. * * The common point is the layout of the cell: a contact information * and a value side by side. */ public class CallStatAdapter extends ArrayAdapter<CallStat> { public final static int CALL_STAT_ADAPTER_ORDERING_TOTAL_DURATION = 0; public final static int CALL_STAT_ADAPTER_ORDERING_TOTAL_CALLS = 1; public final static int CALL_STAT_ADAPTER_ORDERING_MAX_DURATION = 2; public final static int CALL_STAT_ADAPTER_ORDERING_MIN_DURATION = 3; public final static int CALL_STAT_ADAPTER_ORDERING_AVG_DURATION = 4; // the only role of this class is to maintain // the expensive information about list item // without quering everytime the layout private class Holder { public TextView numberView; public TextView contactView; public TextView contactTotalCallsView; public TextView contactTotalDurationView; public TextView contactAvgDurationView; public TextView contactMaxDurationView; public TextView contactMinDurationView; public ImageView photoView; } Context mContext; StatisticsMap mMap; /* * From default load the data by max duration. */ public CallStatAdapter(Context context, StatisticsMap data) { super( context, R.layout.list_duration_item, data.getCallStatOrderedByMaxDuration() ); mContext = context; mMap = data; } public View getView(int position, View view, ViewGroup viewGroup) { Holder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - view = inflater.inflate(R.layout.list_duration_item, null); + view = inflater.inflate(R.layout.list_duration_item, viewGroup, false); holder = new Holder(); holder.numberView = (TextView)view.findViewById(R.id.number); holder.contactView = (TextView)view.findViewById(R.id.contact); holder.contactTotalCallsView = (TextView)view.findViewById(R.id.contact_total_calls); holder.contactAvgDurationView = (TextView)view.findViewById(R.id.contact_avg_duration); holder.contactMaxDurationView = (TextView)view.findViewById(R.id.contact_max_duration); holder.contactMinDurationView = (TextView)view.findViewById(R.id.contact_min_duration); holder.photoView = (ImageView)view.findViewById(R.id.photo); view.setTag(holder); } else { holder = (Holder)view.getTag(); } CallStat entry = getItem(position); String phonenumber = entry.getKey(); float percent = new Float(entry.getTotalDuration())*100/new Float(mMap.getTotalDuration()); holder.numberView.setText(phonenumber); // show contact name holder.contactView.setText(entry.getContactName()); // fill various statistical data String text = new String(entry.getTotalCalls() + " calls for " + DateUtils.formatElapsedTimeNG(entry.getTotalDuration())); SpannableString ss = new SpannableString(text); ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(), 0); holder.contactTotalCallsView.setText(ss); holder.contactAvgDurationView.setText("Average call: " + DateUtils.formatElapsedTimeNG(entry.getAverageDuration())); holder.contactMaxDurationView.setText("Max call: " + DateUtils.formatElapsedTimeNG(entry.getMaxDuration())); holder.contactMinDurationView.setText("Min call: " + DateUtils.formatElapsedTimeNG(entry.getMinDuration())); // show contact photo holder.photoView.setImageBitmap(entry.getContactPhoto()); return view; } /* * Tell to the adapter to reorder its data with respect to * the quantity passed as argument. */ public void order(int type) { Comparator<CallStat> comparator = null; switch(type) { case CALL_STAT_ADAPTER_ORDERING_TOTAL_DURATION: comparator = new Comparator<CallStat>() { public int compare(CallStat a, CallStat b) { return (int)(-a.getTotalDuration() + b.getTotalDuration()); } }; break; case CALL_STAT_ADAPTER_ORDERING_AVG_DURATION: comparator = new Comparator<CallStat>() { public int compare(CallStat a, CallStat b) { return (int)(-a.getAverageDuration() + b.getAverageDuration()); } }; break; case CALL_STAT_ADAPTER_ORDERING_MAX_DURATION: comparator = new Comparator<CallStat>() { public int compare(CallStat a, CallStat b) { return (int)(-a.getMaxDuration() + b.getMaxDuration()); } }; break; case CALL_STAT_ADAPTER_ORDERING_MIN_DURATION: comparator = new Comparator<CallStat>() { public int compare(CallStat a, CallStat b) { return (int)(-a.getMinDuration() + b.getMinDuration()); } }; break; default: case CALL_STAT_ADAPTER_ORDERING_TOTAL_CALLS: comparator = new Comparator<CallStat>() { public int compare(CallStat a, CallStat b) { return (int)(-a.getTotalCalls() + b.getTotalCalls()); } }; break; } sort(comparator); } }
true
true
public View getView(int position, View view, ViewGroup viewGroup) { Holder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.list_duration_item, null); holder = new Holder(); holder.numberView = (TextView)view.findViewById(R.id.number); holder.contactView = (TextView)view.findViewById(R.id.contact); holder.contactTotalCallsView = (TextView)view.findViewById(R.id.contact_total_calls); holder.contactAvgDurationView = (TextView)view.findViewById(R.id.contact_avg_duration); holder.contactMaxDurationView = (TextView)view.findViewById(R.id.contact_max_duration); holder.contactMinDurationView = (TextView)view.findViewById(R.id.contact_min_duration); holder.photoView = (ImageView)view.findViewById(R.id.photo); view.setTag(holder); } else { holder = (Holder)view.getTag(); } CallStat entry = getItem(position); String phonenumber = entry.getKey(); float percent = new Float(entry.getTotalDuration())*100/new Float(mMap.getTotalDuration()); holder.numberView.setText(phonenumber); // show contact name holder.contactView.setText(entry.getContactName()); // fill various statistical data String text = new String(entry.getTotalCalls() + " calls for " + DateUtils.formatElapsedTimeNG(entry.getTotalDuration())); SpannableString ss = new SpannableString(text); ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(), 0); holder.contactTotalCallsView.setText(ss); holder.contactAvgDurationView.setText("Average call: " + DateUtils.formatElapsedTimeNG(entry.getAverageDuration())); holder.contactMaxDurationView.setText("Max call: " + DateUtils.formatElapsedTimeNG(entry.getMaxDuration())); holder.contactMinDurationView.setText("Min call: " + DateUtils.formatElapsedTimeNG(entry.getMinDuration())); // show contact photo holder.photoView.setImageBitmap(entry.getContactPhoto()); return view; }
public View getView(int position, View view, ViewGroup viewGroup) { Holder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.list_duration_item, viewGroup, false); holder = new Holder(); holder.numberView = (TextView)view.findViewById(R.id.number); holder.contactView = (TextView)view.findViewById(R.id.contact); holder.contactTotalCallsView = (TextView)view.findViewById(R.id.contact_total_calls); holder.contactAvgDurationView = (TextView)view.findViewById(R.id.contact_avg_duration); holder.contactMaxDurationView = (TextView)view.findViewById(R.id.contact_max_duration); holder.contactMinDurationView = (TextView)view.findViewById(R.id.contact_min_duration); holder.photoView = (ImageView)view.findViewById(R.id.photo); view.setTag(holder); } else { holder = (Holder)view.getTag(); } CallStat entry = getItem(position); String phonenumber = entry.getKey(); float percent = new Float(entry.getTotalDuration())*100/new Float(mMap.getTotalDuration()); holder.numberView.setText(phonenumber); // show contact name holder.contactView.setText(entry.getContactName()); // fill various statistical data String text = new String(entry.getTotalCalls() + " calls for " + DateUtils.formatElapsedTimeNG(entry.getTotalDuration())); SpannableString ss = new SpannableString(text); ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(), 0); holder.contactTotalCallsView.setText(ss); holder.contactAvgDurationView.setText("Average call: " + DateUtils.formatElapsedTimeNG(entry.getAverageDuration())); holder.contactMaxDurationView.setText("Max call: " + DateUtils.formatElapsedTimeNG(entry.getMaxDuration())); holder.contactMinDurationView.setText("Min call: " + DateUtils.formatElapsedTimeNG(entry.getMinDuration())); // show contact photo holder.photoView.setImageBitmap(entry.getContactPhoto()); return view; }
diff --git a/software/examples/java/ExampleSimple.java b/software/examples/java/ExampleSimple.java index ec9ee7e..53bd1d7 100644 --- a/software/examples/java/ExampleSimple.java +++ b/software/examples/java/ExampleSimple.java @@ -1,27 +1,27 @@ import com.tinkerforge.BrickletGPS; import com.tinkerforge.IPConnection; public class ExampleSimple { private static final String host = "localhost"; private static final int port = 4223; private static final String UID = "ABC"; // Change to your UID // Note: To make the example code cleaner we do not handle exceptions. Exceptions you // might normally want to catch are described in the commnents below public static void main(String args[]) throws Exception { IPConnection ipcon = new IPConnection(); // Create IP connection BrickletGPS gps = new BrickletGPS(UID, ipcon); // Create device object ipcon.connect(host, port); // Connect to brickd // Don't use device before ipcon is connected - // Get GPS coordinates + // Get current coordinates BrickletGPS.Coordinates coords = gps.getCoordinates(); // Can throw com.tinkerforge.TimeoutException System.out.println("Latitude: " + coords.latitude/1000000.0 + "° " + coords.ns); System.out.println("Longitude: " + coords.longitude/1000000.0 + "° " + coords.ew); System.console().readLine("Press key to exit\n"); ipcon.disconnect(); } }
true
true
public static void main(String args[]) throws Exception { IPConnection ipcon = new IPConnection(); // Create IP connection BrickletGPS gps = new BrickletGPS(UID, ipcon); // Create device object ipcon.connect(host, port); // Connect to brickd // Don't use device before ipcon is connected // Get GPS coordinates BrickletGPS.Coordinates coords = gps.getCoordinates(); // Can throw com.tinkerforge.TimeoutException System.out.println("Latitude: " + coords.latitude/1000000.0 + "° " + coords.ns); System.out.println("Longitude: " + coords.longitude/1000000.0 + "° " + coords.ew); System.console().readLine("Press key to exit\n"); ipcon.disconnect(); }
public static void main(String args[]) throws Exception { IPConnection ipcon = new IPConnection(); // Create IP connection BrickletGPS gps = new BrickletGPS(UID, ipcon); // Create device object ipcon.connect(host, port); // Connect to brickd // Don't use device before ipcon is connected // Get current coordinates BrickletGPS.Coordinates coords = gps.getCoordinates(); // Can throw com.tinkerforge.TimeoutException System.out.println("Latitude: " + coords.latitude/1000000.0 + "° " + coords.ns); System.out.println("Longitude: " + coords.longitude/1000000.0 + "° " + coords.ew); System.console().readLine("Press key to exit\n"); ipcon.disconnect(); }
diff --git a/src/main/java/org/codehaus/mojo/mail/MailMojo.java b/src/main/java/org/codehaus/mojo/mail/MailMojo.java index 3ef2075..01d5fc7 100644 --- a/src/main/java/org/codehaus/mojo/mail/MailMojo.java +++ b/src/main/java/org/codehaus/mojo/mail/MailMojo.java @@ -1,326 +1,326 @@ package org.codehaus.mojo.mail; /* * Copyright 2011 Markus W Mahlberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * Goal which sends a mail to recipients * * @goal mail * @phase deploy */ public class MailMojo extends AbstractMojo { // Sadly, one can't extend enums, so we have to wrap it ourselves private enum RecipientType { TO("To",Message.RecipientType.TO), CC("CC",Message.RecipientType.CC), BCC("BCC",Message.RecipientType.BCC); private final String description_; private final Message.RecipientType rectype_; private RecipientType(String desc, Message.RecipientType rt) { this.description_ = desc; this.rectype_ = rt; } String getDescription() { return this.description_; } Message.RecipientType getType() { return this.rectype_; } } /** * Sender * @parameter default-value="maven2@localhost" * @required */ private String from; /** * To-Adresses * @parameter * @required */ private List<String> recipients; /** * CC-Adresses * @parameter */ private List<String> ccRecipients; /** * BCC-Adresses * @parameter */ private List<String> bccRecipients; /** * Subject * @parameter expression="${mail.subject}" default-value="${project.name} deployed" */ private String subject; /** * Body * @parameter expression="${mail.body}" default-value="${project.name} was successfully deployed" * @required */ private String body; /** * Attachements * @parameter */ private List<String> attachments; /** * SMTP Host * @parameter expression="${mail.smtp.host}" default-value="localhost" * @required */ private String smtphost; /** * SMTP Port * The port which will be used to connect to the SMTP server * @parameter expression="${mail.smtp.port}" default-value="25" */ private Integer smtpport; /** * SMTP User * @parameter expression="${mail.smtp.user}" */ private String smtpuser; /** * SMTP Password * @parameter expression="${mail.smtp.user}" */ private String smtppassword; private MimeMessage message; private static Map<String, String> propsToMap(Properties props) { HashMap<String, String> hmap = new HashMap<String,String>(); Enumeration<Object> e = props.keys(); while (e.hasMoreElements()) { String s = (String)e.nextElement(); hmap.put(s, props.getProperty(s)); } return hmap; } private void addRecipents(List<String> recipients, RecipientType rt) throws MojoExecutionException { if (recipients == null) { return; } getLog().info(rt.getDescription() + ": " + recipients); Iterator<String> iterator = recipients.iterator(); while (iterator.hasNext()) { try { message.addRecipient(rt.getType(), new InternetAddress(iterator.next(), true)); getLog().debug("Added " + rt.getType()); } catch (AddressException e) { throw new MojoExecutionException( "Reason was an AddressException", e); } catch (MessagingException e) { throw new MojoExecutionException( "Reason was a MessagingException", e); } catch (Exception e) { throw new MojoExecutionException("Unknown Reason", e); } } } private void addAttachements(MimeMultipart parent) throws MojoExecutionException { Iterator<String> it = attachments.iterator(); while (it.hasNext()) { File attachment = new File(it.next()); getLog().info("\t...\"" + attachment.getPath() + "\""); /* * Traversing directories is not yet implemented I strongly doubt * that it should be, since this is most likely going to produce * quite some mailtraffic */ if (attachment.isDirectory()) { throw new MojoExecutionException( "Attachement can not be a directory (yet)"); } DataSource src = new FileDataSource(attachment); BodyPart msgPart = new MimeBodyPart(); try { msgPart.setDataHandler(new DataHandler(src)); msgPart.setFileName(attachment.getName()); // Don't know whether using FileDataSource.getContentType() is // really a good idea, // but so far it works. msgPart.setHeader("Content-Type", src.getContentType()); msgPart.setHeader("Content-ID", attachment.getName()); msgPart.setDisposition(Part.ATTACHMENT); } catch (MessagingException e) { getLog().error( "Could not create attachment from file \"" + attachment.getName() + "\""); throw new MojoExecutionException("Cought MessagingException", e); } try { parent.addBodyPart(msgPart); } catch (MessagingException e) { getLog().error( "Could not attach \"" + attachment.getName() + "\" to message"); throw new MojoExecutionException("Cought MessagingException", e); } } } public void execute() throws MojoExecutionException { Properties props = new Properties(); getLog().debug("Sending Mail via: " + smtphost); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", smtpport); props.put("mail.smtp.starttls.enable", "true"); Session s = Session.getInstance(props, null); message = new MimeMessage(s); try { message.setFrom(new InternetAddress(from)); } catch (AddressException e) { throw new MojoExecutionException("Cought AddressException!", e); } catch (MessagingException e) { throw new MojoExecutionException("Cought MessagingException!", e); } catch (Exception e) { getLog().error("Could not set " + from + " as FromAddress"); throw new MojoExecutionException( "Something is SERIOUSLY going wrong: ", e); } if (recipients == null) { throw new MojoExecutionException( "There must be at last one recipient"); } getLog().info("Preparing mail from " + from + " via " + smtphost); - addRecipients(recipients, RecipientType.TO); + addRecipents(recipients, RecipientType.TO); if (ccRecipients != null) { - this.addRecipients(ccRecipients, RecipientType.CC); + addRecipents(ccRecipients, RecipientType.CC); } if (bccRecipients != null) { - this.addRecipients(bccRecipients, RecipientType.BCC); + addRecipents(bccRecipients, RecipientType.BCC); } BodyPart msgBodyPart = new MimeBodyPart(); try { msgBodyPart.setContent(body, "text/plain; charset=utf-8"); msgBodyPart.setDisposition(Part.INLINE); } catch (MessagingException e) { getLog().error("Could not set body to \"" + body + "\""); throw new MojoExecutionException("Cought MessagingException: ", e); } MimeMultipart multipart = new MimeMultipart(); try { multipart.addBodyPart(msgBodyPart); } catch (MessagingException e) { getLog().error("Could not attach body to MultipartMessage"); throw new MojoExecutionException("Cought MessagingException: ", e); } if (attachments != null) { getLog().info("Attaching..."); this.addAttachements(multipart); } else { getLog().info("No attachments"); } try { message.setSubject(subject, "UTF-8"); message.setHeader("Content-Transfer-Encoding", "8bit"); message.setContent(multipart); getLog().info("Mail sucessfully sent"); if (smtpuser != null && smtppassword != null) { Transport transport = s.getTransport("smtp"); transport.connect(smtpuser, smtppassword); } Transport.send(message); } catch (MessagingException e) { getLog().info("Cought MessagingException: " + e.toString()); throw new MojoExecutionException(e.toString()); } } }
false
true
public void execute() throws MojoExecutionException { Properties props = new Properties(); getLog().debug("Sending Mail via: " + smtphost); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", smtpport); props.put("mail.smtp.starttls.enable", "true"); Session s = Session.getInstance(props, null); message = new MimeMessage(s); try { message.setFrom(new InternetAddress(from)); } catch (AddressException e) { throw new MojoExecutionException("Cought AddressException!", e); } catch (MessagingException e) { throw new MojoExecutionException("Cought MessagingException!", e); } catch (Exception e) { getLog().error("Could not set " + from + " as FromAddress"); throw new MojoExecutionException( "Something is SERIOUSLY going wrong: ", e); } if (recipients == null) { throw new MojoExecutionException( "There must be at last one recipient"); } getLog().info("Preparing mail from " + from + " via " + smtphost); addRecipients(recipients, RecipientType.TO); if (ccRecipients != null) { this.addRecipients(ccRecipients, RecipientType.CC); } if (bccRecipients != null) { this.addRecipients(bccRecipients, RecipientType.BCC); } BodyPart msgBodyPart = new MimeBodyPart(); try { msgBodyPart.setContent(body, "text/plain; charset=utf-8"); msgBodyPart.setDisposition(Part.INLINE); } catch (MessagingException e) { getLog().error("Could not set body to \"" + body + "\""); throw new MojoExecutionException("Cought MessagingException: ", e); } MimeMultipart multipart = new MimeMultipart(); try { multipart.addBodyPart(msgBodyPart); } catch (MessagingException e) { getLog().error("Could not attach body to MultipartMessage"); throw new MojoExecutionException("Cought MessagingException: ", e); } if (attachments != null) { getLog().info("Attaching..."); this.addAttachements(multipart); } else { getLog().info("No attachments"); } try { message.setSubject(subject, "UTF-8"); message.setHeader("Content-Transfer-Encoding", "8bit"); message.setContent(multipart); getLog().info("Mail sucessfully sent"); if (smtpuser != null && smtppassword != null) { Transport transport = s.getTransport("smtp"); transport.connect(smtpuser, smtppassword); } Transport.send(message); } catch (MessagingException e) { getLog().info("Cought MessagingException: " + e.toString()); throw new MojoExecutionException(e.toString()); } }
public void execute() throws MojoExecutionException { Properties props = new Properties(); getLog().debug("Sending Mail via: " + smtphost); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", smtpport); props.put("mail.smtp.starttls.enable", "true"); Session s = Session.getInstance(props, null); message = new MimeMessage(s); try { message.setFrom(new InternetAddress(from)); } catch (AddressException e) { throw new MojoExecutionException("Cought AddressException!", e); } catch (MessagingException e) { throw new MojoExecutionException("Cought MessagingException!", e); } catch (Exception e) { getLog().error("Could not set " + from + " as FromAddress"); throw new MojoExecutionException( "Something is SERIOUSLY going wrong: ", e); } if (recipients == null) { throw new MojoExecutionException( "There must be at last one recipient"); } getLog().info("Preparing mail from " + from + " via " + smtphost); addRecipents(recipients, RecipientType.TO); if (ccRecipients != null) { addRecipents(ccRecipients, RecipientType.CC); } if (bccRecipients != null) { addRecipents(bccRecipients, RecipientType.BCC); } BodyPart msgBodyPart = new MimeBodyPart(); try { msgBodyPart.setContent(body, "text/plain; charset=utf-8"); msgBodyPart.setDisposition(Part.INLINE); } catch (MessagingException e) { getLog().error("Could not set body to \"" + body + "\""); throw new MojoExecutionException("Cought MessagingException: ", e); } MimeMultipart multipart = new MimeMultipart(); try { multipart.addBodyPart(msgBodyPart); } catch (MessagingException e) { getLog().error("Could not attach body to MultipartMessage"); throw new MojoExecutionException("Cought MessagingException: ", e); } if (attachments != null) { getLog().info("Attaching..."); this.addAttachements(multipart); } else { getLog().info("No attachments"); } try { message.setSubject(subject, "UTF-8"); message.setHeader("Content-Transfer-Encoding", "8bit"); message.setContent(multipart); getLog().info("Mail sucessfully sent"); if (smtpuser != null && smtppassword != null) { Transport transport = s.getTransport("smtp"); transport.connect(smtpuser, smtppassword); } Transport.send(message); } catch (MessagingException e) { getLog().info("Cought MessagingException: " + e.toString()); throw new MojoExecutionException(e.toString()); } }
diff --git a/loci/ome/notebook/ClickableList.java b/loci/ome/notebook/ClickableList.java index 486ebcca5..9438dd01f 100644 --- a/loci/ome/notebook/ClickableList.java +++ b/loci/ome/notebook/ClickableList.java @@ -1,305 +1,305 @@ package loci.ome.notebook; import java.util.Vector; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import javax.swing.JList; import javax.swing.DefaultListModel; import javax.swing.JTextArea; import javax.swing.JOptionPane; import javax.swing.DefaultListSelectionModel; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.event.DocumentListener; import javax.swing.event.DocumentEvent; import org.openmicroscopy.xml.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Document; public class ClickableList extends JList implements MouseListener, ActionListener, DocumentListener { protected JPopupMenu jPop; protected MetadataPane.TablePanel tableP; protected JTextArea textArea; protected DefaultListModel myModel; protected NotePanel noteP; public ClickableList (DefaultListModel thisModel, NotePanel nP) { super(thisModel); DefaultListSelectionModel selectModel = new DefaultListSelectionModel(); selectModel.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); setSelectionModel(selectModel); myModel = thisModel; addMouseListener(this); jPop = new JPopupMenu(); tableP = nP.tableP; textArea = nP.textArea; noteP = nP; } public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3 || e.getButton() == MouseEvent.BUTTON2) { jPop = new JPopupMenu("Add/Remove Notes"); JMenuItem addItem = new JMenuItem("Add a new note"); addItem.addActionListener(this); addItem.setActionCommand("add"); JMenuItem delItem = new JMenuItem("Delete selected note"); delItem.addActionListener(this); delItem.setActionCommand("remove"); jPop.add(addItem); jPop.add(delItem); jPop.show(this, e.getX(), e.getY()); } } public void setValue(String text) { if ( ((String) getSelectedValue()) != null && text != null) { Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); Vector childList = DOMUtil.getChildElements(tableP.el.getAttribute("XMLName") + "Annotation", currentCA); Element childEle = null; for(int i = 0;i<childList.size();i++) { Element thisEle = (Element) childList.get(i); if(thisEle.getAttribute("Name").equals((String) getSelectedValue())) childEle = thisEle; } childEle.setAttribute("Value", text); } } // -- Event API Overridden Methods -- //abstract methods we must override but have no use for public void mouseReleased(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if ("add".equals(cmd)) { String newName = (String)JOptionPane.showInputDialog( getTopLevelAncestor(), "Please create a name for the new\n" + tableP.name + " Note...\n", "Create a New Note", JOptionPane.PLAIN_MESSAGE, null, null, "NewName"); //If a string was returned, say so. if ((newName != null) && (newName.length() > 0)) { CustomAttributesNode caNode = null; Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); if (currentCA != null) caNode = new CustomAttributesNode(currentCA); else { Element cloneEle = DOMUtil.createChild(tableP.tPanel.oNode.getDOMElement(),"CustomAttributes"); caNode = new CustomAttributesNode(cloneEle); } String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE == null) childE = DOMUtil.createChild(omeE, "SemanticTypeDefinitions"); Element stdE = childE; - Boolean alreadyPresent = false; + boolean alreadyPresent = false; NodeList stdChildren = childE.getChildNodes(); for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) alreadyPresent = true; } if(!alreadyPresent) { childE = DOMUtil.createChild(stdE, "SemanticType"); childE.setAttribute("Name", newXMLName); childE.setAttribute("AppliesTo", tableP.tPanel.name.substring(0,1)); Element stE = childE; childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Name"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Value"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "NoteFor"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "reference"); childE.setAttribute("RefersTo", tableP.el.getAttribute("XMLName")); } AttributeNode newNode = new AttributeNode(caNode, newXMLName); newNode.setAttribute("NoteFor", tableP.id); newNode.setAttribute("Name", newName); myModel.addElement(newName); noteP.setNameLabel(true); tableP.setNumNotes(noteP.getNumNotes()); setSelectedIndex(myModel.getSize() -1); ensureIndexIsVisible(getSelectedIndex()); } } if ("remove".equals(cmd)) { if ( ((String) getSelectedValue()) != null) { int prevIndex = getSelectedIndex(); Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); Vector childList = DOMUtil.getChildElements(tableP.el.getAttribute("XMLName") + "Annotation", currentCA); Element childEle = null; for(int i = 0;i<childList.size();i++) { Element thisEle = (Element) childList.get(i); if(thisEle.getAttribute("Name").equals((String) getSelectedValue())) childEle = thisEle; } currentCA.removeChild((Node) childEle); NodeList caChildren = currentCA.getChildNodes(); if ( caChildren != null) { if ( caChildren.getLength() == 0) { tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); } } else tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); Document thisDoc = null; try { thisDoc = tableP.tPanel.ome.getOMEDocument(true); } catch (Exception exc) { exc.printStackTrace(); } Element foundE = DOMUtil.findElement(tableP.el.getAttribute("XMLName") + "Annotation", thisDoc); if (foundE == null) { String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE != null) { Element stdE = childE; NodeList stdChildren = childE.getChildNodes(); Element stE = null; for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) stE = tempE; } if (stE != null) stdE.removeChild( (Node) stE ); if ( stdChildren != null) { if ( stdChildren.getLength() == 0) { omeE.removeChild( (Node) stdE); } } else omeE.removeChild( (Node) stdE); } } myModel.removeElementAt(getSelectedIndex()); if (myModel.size() == 0) { noteP.setNameLabel(false); noteP.setNotesLabel(false); } tableP.setNumNotes(noteP.getNumNotes()); if (myModel.size() == 1) setSelectedIndex(0); else { if (prevIndex >= myModel.size() - 1) setSelectedIndex(prevIndex - 1); else setSelectedIndex(prevIndex); } ensureIndexIsVisible(getSelectedIndex()); } else { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Because there is no name selected, you\n" + "cannot delete the selected note.", "No Selection Found", JOptionPane.WARNING_MESSAGE); } } } public void insertUpdate(DocumentEvent e) { String result = null; try { result = e.getDocument().getText(0, e.getDocument().getLength()); } catch (Exception exc) { exc.printStackTrace(); } if (myModel.size() != 0 && getSelectedIndex() != -1) { if (result.equals("")) { noteP.setNotesLabel(false); } else noteP.setNotesLabel(true); } setValue(result); } public void removeUpdate(DocumentEvent e) { String result = null; try { result = e.getDocument().getText(0, e.getDocument().getLength()); } catch (Exception exc) { exc.printStackTrace(); } if (myModel.size() != 0 && getSelectedIndex() != -1) { if (result.equals("")) { noteP.setNotesLabel(false); } else noteP.setNotesLabel(true); } setValue(result); } public void changedUpdate(DocumentEvent e) { String result = null; try { result = e.getDocument().getText(0, e.getDocument().getLength()); } catch (Exception exc) { exc.printStackTrace(); } if (myModel.size() != 0 && getSelectedIndex() != -1) { if (result.equals("")) { noteP.setNotesLabel(false); } else noteP.setNotesLabel(true); } setValue(result); } }
true
true
public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if ("add".equals(cmd)) { String newName = (String)JOptionPane.showInputDialog( getTopLevelAncestor(), "Please create a name for the new\n" + tableP.name + " Note...\n", "Create a New Note", JOptionPane.PLAIN_MESSAGE, null, null, "NewName"); //If a string was returned, say so. if ((newName != null) && (newName.length() > 0)) { CustomAttributesNode caNode = null; Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); if (currentCA != null) caNode = new CustomAttributesNode(currentCA); else { Element cloneEle = DOMUtil.createChild(tableP.tPanel.oNode.getDOMElement(),"CustomAttributes"); caNode = new CustomAttributesNode(cloneEle); } String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE == null) childE = DOMUtil.createChild(omeE, "SemanticTypeDefinitions"); Element stdE = childE; Boolean alreadyPresent = false; NodeList stdChildren = childE.getChildNodes(); for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) alreadyPresent = true; } if(!alreadyPresent) { childE = DOMUtil.createChild(stdE, "SemanticType"); childE.setAttribute("Name", newXMLName); childE.setAttribute("AppliesTo", tableP.tPanel.name.substring(0,1)); Element stE = childE; childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Name"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Value"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "NoteFor"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "reference"); childE.setAttribute("RefersTo", tableP.el.getAttribute("XMLName")); } AttributeNode newNode = new AttributeNode(caNode, newXMLName); newNode.setAttribute("NoteFor", tableP.id); newNode.setAttribute("Name", newName); myModel.addElement(newName); noteP.setNameLabel(true); tableP.setNumNotes(noteP.getNumNotes()); setSelectedIndex(myModel.getSize() -1); ensureIndexIsVisible(getSelectedIndex()); } } if ("remove".equals(cmd)) { if ( ((String) getSelectedValue()) != null) { int prevIndex = getSelectedIndex(); Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); Vector childList = DOMUtil.getChildElements(tableP.el.getAttribute("XMLName") + "Annotation", currentCA); Element childEle = null; for(int i = 0;i<childList.size();i++) { Element thisEle = (Element) childList.get(i); if(thisEle.getAttribute("Name").equals((String) getSelectedValue())) childEle = thisEle; } currentCA.removeChild((Node) childEle); NodeList caChildren = currentCA.getChildNodes(); if ( caChildren != null) { if ( caChildren.getLength() == 0) { tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); } } else tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); Document thisDoc = null; try { thisDoc = tableP.tPanel.ome.getOMEDocument(true); } catch (Exception exc) { exc.printStackTrace(); } Element foundE = DOMUtil.findElement(tableP.el.getAttribute("XMLName") + "Annotation", thisDoc); if (foundE == null) { String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE != null) { Element stdE = childE; NodeList stdChildren = childE.getChildNodes(); Element stE = null; for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) stE = tempE; } if (stE != null) stdE.removeChild( (Node) stE ); if ( stdChildren != null) { if ( stdChildren.getLength() == 0) { omeE.removeChild( (Node) stdE); } } else omeE.removeChild( (Node) stdE); } } myModel.removeElementAt(getSelectedIndex()); if (myModel.size() == 0) { noteP.setNameLabel(false); noteP.setNotesLabel(false); } tableP.setNumNotes(noteP.getNumNotes()); if (myModel.size() == 1) setSelectedIndex(0); else { if (prevIndex >= myModel.size() - 1) setSelectedIndex(prevIndex - 1); else setSelectedIndex(prevIndex); } ensureIndexIsVisible(getSelectedIndex()); } else { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Because there is no name selected, you\n" + "cannot delete the selected note.", "No Selection Found", JOptionPane.WARNING_MESSAGE); } } }
public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if ("add".equals(cmd)) { String newName = (String)JOptionPane.showInputDialog( getTopLevelAncestor(), "Please create a name for the new\n" + tableP.name + " Note...\n", "Create a New Note", JOptionPane.PLAIN_MESSAGE, null, null, "NewName"); //If a string was returned, say so. if ((newName != null) && (newName.length() > 0)) { CustomAttributesNode caNode = null; Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); if (currentCA != null) caNode = new CustomAttributesNode(currentCA); else { Element cloneEle = DOMUtil.createChild(tableP.tPanel.oNode.getDOMElement(),"CustomAttributes"); caNode = new CustomAttributesNode(cloneEle); } String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE == null) childE = DOMUtil.createChild(omeE, "SemanticTypeDefinitions"); Element stdE = childE; boolean alreadyPresent = false; NodeList stdChildren = childE.getChildNodes(); for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) alreadyPresent = true; } if(!alreadyPresent) { childE = DOMUtil.createChild(stdE, "SemanticType"); childE.setAttribute("Name", newXMLName); childE.setAttribute("AppliesTo", tableP.tPanel.name.substring(0,1)); Element stE = childE; childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Name"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "Value"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "string"); childE = DOMUtil.createChild(stE, "Element"); childE.setAttribute("Name", "NoteFor"); childE.setAttribute("DBLocation", ""); childE.setAttribute("DataType", "reference"); childE.setAttribute("RefersTo", tableP.el.getAttribute("XMLName")); } AttributeNode newNode = new AttributeNode(caNode, newXMLName); newNode.setAttribute("NoteFor", tableP.id); newNode.setAttribute("Name", newName); myModel.addElement(newName); noteP.setNameLabel(true); tableP.setNumNotes(noteP.getNumNotes()); setSelectedIndex(myModel.getSize() -1); ensureIndexIsVisible(getSelectedIndex()); } } if ("remove".equals(cmd)) { if ( ((String) getSelectedValue()) != null) { int prevIndex = getSelectedIndex(); Element currentCA = DOMUtil.getChildElement("CustomAttributes", tableP.tPanel.oNode.getDOMElement()); Vector childList = DOMUtil.getChildElements(tableP.el.getAttribute("XMLName") + "Annotation", currentCA); Element childEle = null; for(int i = 0;i<childList.size();i++) { Element thisEle = (Element) childList.get(i); if(thisEle.getAttribute("Name").equals((String) getSelectedValue())) childEle = thisEle; } currentCA.removeChild((Node) childEle); NodeList caChildren = currentCA.getChildNodes(); if ( caChildren != null) { if ( caChildren.getLength() == 0) { tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); } } else tableP.tPanel.oNode.getDOMElement().removeChild( (Node) currentCA); Document thisDoc = null; try { thisDoc = tableP.tPanel.ome.getOMEDocument(true); } catch (Exception exc) { exc.printStackTrace(); } Element foundE = DOMUtil.findElement(tableP.el.getAttribute("XMLName") + "Annotation", thisDoc); if (foundE == null) { String newXMLName = tableP.el.getAttribute("XMLName") + "Annotation"; Element omeE = tableP.tPanel.ome.getDOMElement(); NodeList omeChildren = omeE.getChildNodes(); Element childE = null; for(int i = 0;i < omeChildren.getLength();i++) { Element tempE = (Element) omeChildren.item(i); if (tempE.getTagName().equals("SemanticTypeDefinitions")) childE = tempE; } if (childE != null) { Element stdE = childE; NodeList stdChildren = childE.getChildNodes(); Element stE = null; for(int i = 0;i < stdChildren.getLength();i++) { Element tempE = (Element) stdChildren.item(i); if (tempE.getTagName().equals("SemanticType") && tempE.getAttribute("Name").equals(newXMLName) ) stE = tempE; } if (stE != null) stdE.removeChild( (Node) stE ); if ( stdChildren != null) { if ( stdChildren.getLength() == 0) { omeE.removeChild( (Node) stdE); } } else omeE.removeChild( (Node) stdE); } } myModel.removeElementAt(getSelectedIndex()); if (myModel.size() == 0) { noteP.setNameLabel(false); noteP.setNotesLabel(false); } tableP.setNumNotes(noteP.getNumNotes()); if (myModel.size() == 1) setSelectedIndex(0); else { if (prevIndex >= myModel.size() - 1) setSelectedIndex(prevIndex - 1); else setSelectedIndex(prevIndex); } ensureIndexIsVisible(getSelectedIndex()); } else { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Because there is no name selected, you\n" + "cannot delete the selected note.", "No Selection Found", JOptionPane.WARNING_MESSAGE); } } }
diff --git a/source/net/sourceforge/fullsync/schedule/SchedulerImpl.java b/source/net/sourceforge/fullsync/schedule/SchedulerImpl.java index 3c5b244..b2b83be 100644 --- a/source/net/sourceforge/fullsync/schedule/SchedulerImpl.java +++ b/source/net/sourceforge/fullsync/schedule/SchedulerImpl.java @@ -1,131 +1,134 @@ /* * Created on 16.10.2004 */ package net.sourceforge.fullsync.schedule; import java.util.ArrayList; /** * @author <a href="mailto:[email protected]">Jan Kopcsek</a> */ public class SchedulerImpl implements Scheduler, Runnable { private ScheduleTaskSource scheduleSource; private Thread worker; private boolean running; private boolean enabled; private ArrayList schedulerListeners; public SchedulerImpl() { this( null ); } public SchedulerImpl( ScheduleTaskSource source ) { scheduleSource = source; schedulerListeners = new ArrayList(); } public void setSource( ScheduleTaskSource source ) { scheduleSource = source; } public ScheduleTaskSource getSource() { return scheduleSource; } public void addSchedulerChangeListener(SchedulerChangeListener listener) { schedulerListeners.add(listener); } public void removeSchedulerChangeListener(SchedulerChangeListener listener) { schedulerListeners.remove(listener); } protected void fireSchedulerChangedEvent() { for (int i = 0; i < schedulerListeners.size(); i++) { ((SchedulerChangeListener)schedulerListeners.get(i)).schedulerStatusChanged(enabled); } } public boolean isRunning() { return running; } public boolean isEnabled() { return enabled; } public void start() { if( enabled ) return; enabled = true; if( worker == null || !worker.isAlive() ) { worker = new Thread( this, "Scheduler" ); worker.setDaemon( true ); worker.start(); } fireSchedulerChangedEvent(); } public void stop() { if( !enabled || worker == null ) return; enabled = false; if( running ) { worker.interrupt(); } try { worker.join(); } catch( InterruptedException e ) { } finally { worker = null; } fireSchedulerChangedEvent(); } public void refresh() { if( worker != null ) worker.interrupt(); } public void run() { running = true; while( enabled ) { long now = System.currentTimeMillis(); ScheduleTask task = scheduleSource.getNextScheduleTask(); if( task == null ) { // TODO log sth here ? enabled = false; break; } long nextTime = task.getExecutionTime(); try { if( nextTime >= now ) Thread.sleep( nextTime-now ); task.run(); } catch( InterruptedException ie ) { } } running = false; - enabled = false; - fireSchedulerChangedEvent(); + if( enabled ) + { + enabled = false; + fireSchedulerChangedEvent(); + } } }
true
true
public void run() { running = true; while( enabled ) { long now = System.currentTimeMillis(); ScheduleTask task = scheduleSource.getNextScheduleTask(); if( task == null ) { // TODO log sth here ? enabled = false; break; } long nextTime = task.getExecutionTime(); try { if( nextTime >= now ) Thread.sleep( nextTime-now ); task.run(); } catch( InterruptedException ie ) { } } running = false; enabled = false; fireSchedulerChangedEvent(); }
public void run() { running = true; while( enabled ) { long now = System.currentTimeMillis(); ScheduleTask task = scheduleSource.getNextScheduleTask(); if( task == null ) { // TODO log sth here ? enabled = false; break; } long nextTime = task.getExecutionTime(); try { if( nextTime >= now ) Thread.sleep( nextTime-now ); task.run(); } catch( InterruptedException ie ) { } } running = false; if( enabled ) { enabled = false; fireSchedulerChangedEvent(); } }
diff --git a/assembly/src/release/example/src/StompExample.java b/assembly/src/release/example/src/StompExample.java index 89e93626f..4e06e4f2b 100644 --- a/assembly/src/release/example/src/StompExample.java +++ b/assembly/src/release/example/src/StompExample.java @@ -1,63 +1,59 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.activemq.transport.stomp.Stomp; import org.apache.activemq.transport.stomp.StompConnection; import org.apache.activemq.transport.stomp.StompFrame; import org.apache.activemq.transport.stomp.Stomp.Headers.Subscribe; /** * * This example demonstrates Stomp Java API * * @version $Revision$ * */ public class StompExample { public static void main(String args[]) throws Exception { StompConnection connection = new StompConnection(); connection.open("localhost", 61613); connection.connect("system", "manager"); - StompFrame connect = connection.receive(); - if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) { - throw new Exception ("Not connected"); - } connection.begin("tx1"); connection.send("/queue/test", "message1"); connection.send("/queue/test", "message2"); connection.commit("tx1"); connection.subscribe("/queue/test", Subscribe.AckModeValues.CLIENT); connection.begin("tx2"); StompFrame message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); connection.commit("tx2"); connection.disconnect(); } }
true
true
public static void main(String args[]) throws Exception { StompConnection connection = new StompConnection(); connection.open("localhost", 61613); connection.connect("system", "manager"); StompFrame connect = connection.receive(); if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) { throw new Exception ("Not connected"); } connection.begin("tx1"); connection.send("/queue/test", "message1"); connection.send("/queue/test", "message2"); connection.commit("tx1"); connection.subscribe("/queue/test", Subscribe.AckModeValues.CLIENT); connection.begin("tx2"); StompFrame message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); connection.commit("tx2"); connection.disconnect(); }
public static void main(String args[]) throws Exception { StompConnection connection = new StompConnection(); connection.open("localhost", 61613); connection.connect("system", "manager"); connection.begin("tx1"); connection.send("/queue/test", "message1"); connection.send("/queue/test", "message2"); connection.commit("tx1"); connection.subscribe("/queue/test", Subscribe.AckModeValues.CLIENT); connection.begin("tx2"); StompFrame message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); message = connection.receive(); System.out.println(message.getBody()); connection.ack(message, "tx2"); connection.commit("tx2"); connection.disconnect(); }
diff --git a/src/main/java/nuroko/module/TrainingOp.java b/src/main/java/nuroko/module/TrainingOp.java index 351ad51..cc2ed0a 100644 --- a/src/main/java/nuroko/module/TrainingOp.java +++ b/src/main/java/nuroko/module/TrainingOp.java @@ -1,50 +1,50 @@ package nuroko.module; import mikera.vectorz.Op; public class TrainingOp extends AOperationComponent { private final Op op; public TrainingOp(int length, Op op) { super(length); this.op = op; } @Override public void thinkInternal() { // identity function while thinking normally output.set(input); } @Override public void thinkInternalTraining() { // apply op only when training output.set(input); op.applyTo(output); } @Override public void trainGradientInternal(double factor) { double[] ov=output.getArray(); double[] og=outputGradient.getArray(); - double[] ig=outputGradient.getArray(); + double[] ig=inputGradient.getArray(); for (int i=0; i<length; i++) { ig[i]=op.derivativeForOutput(ov[i])*og[i]; } } @Override public boolean hasDifferentTrainingThinking() { return true; } @Override public TrainingOp clone() { return new TrainingOp(length,op); } @Override public String toString() { return length+":"+length+" "+op.toString(); } }
true
true
public void trainGradientInternal(double factor) { double[] ov=output.getArray(); double[] og=outputGradient.getArray(); double[] ig=outputGradient.getArray(); for (int i=0; i<length; i++) { ig[i]=op.derivativeForOutput(ov[i])*og[i]; } }
public void trainGradientInternal(double factor) { double[] ov=output.getArray(); double[] og=outputGradient.getArray(); double[] ig=inputGradient.getArray(); for (int i=0; i<length; i++) { ig[i]=op.derivativeForOutput(ov[i])*og[i]; } }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/validators/EndpointProjectFieldController.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/validators/EndpointProjectFieldController.java index 132e17c6d..894e49fba 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/validators/EndpointProjectFieldController.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.artifact.endpoint/src/org/wso2/developerstudio/eclipse/artifact/endpoint/validators/EndpointProjectFieldController.java @@ -1,232 +1,229 @@ /* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.artifact.endpoint.validators; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNode; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.wso2.developerstudio.eclipse.artifact.endpoint.model.EndpointModel; import org.wso2.developerstudio.eclipse.artifact.endpoint.utils.EpArtifactConstants; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact; import org.wso2.developerstudio.eclipse.platform.core.exception.FieldValidationException; import org.wso2.developerstudio.eclipse.platform.core.model.AbstractFieldController; import org.wso2.developerstudio.eclipse.platform.core.model.AbstractListDataProvider.ListData; import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel; import org.wso2.developerstudio.eclipse.platform.ui.validator.CommonFieldValidator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.FactoryConfigurationError; public class EndpointProjectFieldController extends AbstractFieldController { IProject project =null; public void validate(String modelProperty, Object value, ProjectDataModel model) throws FieldValidationException { EndpointModel epModel = (EndpointModel) model; String templateName = new String(); if(epModel!=null && epModel.getSelectedTemplate()!=null){ templateName = epModel.getSelectedTemplate().getName(); } boolean isAddressEP = EpArtifactConstants.ADDRESS_EP.equals(templateName); boolean isWSDlEP = EpArtifactConstants.WSDL_EP.equals(templateName); boolean isHttpEP = EpArtifactConstants.HTTP_EP.equals(templateName); if (modelProperty.equals("ep.name")) { CommonFieldValidator.validateArtifactName(value); if (value != null) { String resource = value.toString(); EndpointModel endpointModel = (EndpointModel) model; if (endpointModel != null) { IContainer resLocation = endpointModel.getEndpointSaveLocation(); if (resLocation != null) { IProject project = resLocation.getProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile()); List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts(); for (ESBArtifact artifact : allArtifacts) { if (resource.equals(artifact.getName())) { throw new FieldValidationException(""); } } } catch (Exception e) { throw new FieldValidationException("Artifact name already exsits"); } } } } } else if (modelProperty.equals("import.file")) { CommonFieldValidator.validateImportFile(value); } else if (modelProperty.equals("save.file")) { IResource resource = (IResource)value; if(resource==null || !resource.exists()) throw new FieldValidationException("Specified project or path doesn't exist"); - }else if (modelProperty.equals("ep.type")) { - EndpointModel endpointModel = (EndpointModel) model; - project = endpointModel.getEndpointSaveLocation().getProject(); }else if (modelProperty.equals("templ.address.ep.uri") && isAddressEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("Address url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "Address url"); } } else if (modelProperty.equals("templ.http.ep.uritemplate") && isHttpEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("URI Template cannot be empty"); } //Identified as irrelevant //else{ // CommonFieldValidator.isValidUrl(value.toString().trim(), "URI Template"); //} } else if (modelProperty.equals("templ.wsdl.ep.uri") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "WSDL url"); } } else if (modelProperty.equals("templ.wsdl.ep.service") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL service cannot be empty"); } } else if (modelProperty.equals("templ.wsdl.ep.port") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL port cannot be empty"); } } else if(modelProperty.equals("registry.browser")){ if(epModel.isSaveAsDynamic()){ if(null==value || value.toString().trim().isEmpty()){ throw new FieldValidationException("Registry path cannot be empty"); } } } } public boolean isEnableField(String modelProperty, ProjectDataModel model) { boolean enableField = super.isEnableField(modelProperty, model); if (modelProperty.equals("reg.path")) { enableField = ((EndpointModel) model).isSaveAsDynamic(); } else if (modelProperty.equals("reg.path")) { enableField = ((EndpointModel) model).isSaveAsDynamic(); } else if (modelProperty.equals("import.file")) { enableField = true; } else if(modelProperty.equals("registry.browser")) { enableField = ((EndpointModel) model).isSaveAsDynamic(); } return enableField; } public List<String> getUpdateFields(String modelProperty, ProjectDataModel model) { List<String> updateFields = super.getUpdateFields(modelProperty, model); if (modelProperty.equals("dynamic.ep")) { updateFields.add("reg.path"); updateFields.add("registry.browser"); updateFields.add("save.file"); } else if (modelProperty.equals("import.file")) { updateFields.add("available.eps"); } else if (modelProperty.equals("create.esb.prj")) { updateFields.add("save.file"); } else if (modelProperty.equals("ep.type")) { Map<String, List<String>> templateFieldProperties = getTemplateFieldProperties(); for (List<String> fields : templateFieldProperties.values()) { updateFields.addAll(fields); } } else if (modelProperty.equals("reg.path")) { updateFields.add("registry.browser"); } else if (modelProperty.equals("save.file")){ updateFields.add("templ.target.availabletemplates"); }else if (modelProperty.equals("templ.target.availabletemplates")){ updateFields.add("templ.target.template"); } return updateFields; } public boolean isVisibleField(String modelProperty, ProjectDataModel model) { boolean visibleField = super.isVisibleField(modelProperty, model); if (modelProperty.startsWith("templ.")) { Map<String, List<String>> templateFieldProperties = getTemplateFieldProperties(); List<String> list = templateFieldProperties.get(((EndpointModel) model).getSelectedTemplate() .getId()); for (String control : list) { visibleField = false; } if (list.contains(modelProperty)) { visibleField = true; } else { visibleField = false; } } if (modelProperty.equals("available.eps")) { List<OMElement> availableEPList = ((EndpointModel) model).getAvailableEPList(); visibleField = (availableEPList != null && availableEPList.size() > 0); } return visibleField; } private Map<String, List<String>> getTemplateFieldProperties() { Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put("org.wso2.developerstudio.eclipse.esb.template.ep2", Arrays.asList(new String[] {})); map.put("org.wso2.developerstudio.eclipse.esb.template.ep1", Arrays .asList(new String[] { "templ.address.ep.uri" })); map.put("org.wso2.developerstudio.eclipse.esb.template.ep5", Arrays .asList(new String[] { "templ.wsdl.ep.uri", "templ.wsdl.ep.service", "templ.wsdl.ep.port" })); map.put("org.wso2.developerstudio.eclipse.esb.template.ep3", Arrays.asList(new String[] {})); map.put("org.wso2.developerstudio.eclipse.esb.template.ep4", Arrays.asList(new String[] {})); map.put("org.wso2.developerstudio.eclipse.esb.template.ep7", Arrays .asList(new String[] { "templ.template.ep.uri", "templ.target.template","templ.target.availabletemplates"})); map.put("org.wso2.developerstudio.eclipse.esb.template.ep8", Arrays .asList(new String[] { "templ.http.ep.uritemplate", "templ.http.ep.method"})); return map; } public boolean isReadOnlyField(String modelProperty, ProjectDataModel model) { boolean readOnlyField = super.isReadOnlyField(modelProperty, model); if (modelProperty.equals("save.file")) { readOnlyField = true; } else if (modelProperty.equals("registry.browser")) { readOnlyField = true; } return readOnlyField; } }
true
true
public void validate(String modelProperty, Object value, ProjectDataModel model) throws FieldValidationException { EndpointModel epModel = (EndpointModel) model; String templateName = new String(); if(epModel!=null && epModel.getSelectedTemplate()!=null){ templateName = epModel.getSelectedTemplate().getName(); } boolean isAddressEP = EpArtifactConstants.ADDRESS_EP.equals(templateName); boolean isWSDlEP = EpArtifactConstants.WSDL_EP.equals(templateName); boolean isHttpEP = EpArtifactConstants.HTTP_EP.equals(templateName); if (modelProperty.equals("ep.name")) { CommonFieldValidator.validateArtifactName(value); if (value != null) { String resource = value.toString(); EndpointModel endpointModel = (EndpointModel) model; if (endpointModel != null) { IContainer resLocation = endpointModel.getEndpointSaveLocation(); if (resLocation != null) { IProject project = resLocation.getProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile()); List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts(); for (ESBArtifact artifact : allArtifacts) { if (resource.equals(artifact.getName())) { throw new FieldValidationException(""); } } } catch (Exception e) { throw new FieldValidationException("Artifact name already exsits"); } } } } } else if (modelProperty.equals("import.file")) { CommonFieldValidator.validateImportFile(value); } else if (modelProperty.equals("save.file")) { IResource resource = (IResource)value; if(resource==null || !resource.exists()) throw new FieldValidationException("Specified project or path doesn't exist"); }else if (modelProperty.equals("ep.type")) { EndpointModel endpointModel = (EndpointModel) model; project = endpointModel.getEndpointSaveLocation().getProject(); }else if (modelProperty.equals("templ.address.ep.uri") && isAddressEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("Address url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "Address url"); } } else if (modelProperty.equals("templ.http.ep.uritemplate") && isHttpEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("URI Template cannot be empty"); } //Identified as irrelevant //else{ // CommonFieldValidator.isValidUrl(value.toString().trim(), "URI Template"); //} } else if (modelProperty.equals("templ.wsdl.ep.uri") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "WSDL url"); } } else if (modelProperty.equals("templ.wsdl.ep.service") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL service cannot be empty"); } } else if (modelProperty.equals("templ.wsdl.ep.port") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL port cannot be empty"); } } else if(modelProperty.equals("registry.browser")){ if(epModel.isSaveAsDynamic()){ if(null==value || value.toString().trim().isEmpty()){ throw new FieldValidationException("Registry path cannot be empty"); } } } }
public void validate(String modelProperty, Object value, ProjectDataModel model) throws FieldValidationException { EndpointModel epModel = (EndpointModel) model; String templateName = new String(); if(epModel!=null && epModel.getSelectedTemplate()!=null){ templateName = epModel.getSelectedTemplate().getName(); } boolean isAddressEP = EpArtifactConstants.ADDRESS_EP.equals(templateName); boolean isWSDlEP = EpArtifactConstants.WSDL_EP.equals(templateName); boolean isHttpEP = EpArtifactConstants.HTTP_EP.equals(templateName); if (modelProperty.equals("ep.name")) { CommonFieldValidator.validateArtifactName(value); if (value != null) { String resource = value.toString(); EndpointModel endpointModel = (EndpointModel) model; if (endpointModel != null) { IContainer resLocation = endpointModel.getEndpointSaveLocation(); if (resLocation != null) { IProject project = resLocation.getProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile()); List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts(); for (ESBArtifact artifact : allArtifacts) { if (resource.equals(artifact.getName())) { throw new FieldValidationException(""); } } } catch (Exception e) { throw new FieldValidationException("Artifact name already exsits"); } } } } } else if (modelProperty.equals("import.file")) { CommonFieldValidator.validateImportFile(value); } else if (modelProperty.equals("save.file")) { IResource resource = (IResource)value; if(resource==null || !resource.exists()) throw new FieldValidationException("Specified project or path doesn't exist"); }else if (modelProperty.equals("templ.address.ep.uri") && isAddressEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("Address url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "Address url"); } } else if (modelProperty.equals("templ.http.ep.uritemplate") && isHttpEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("URI Template cannot be empty"); } //Identified as irrelevant //else{ // CommonFieldValidator.isValidUrl(value.toString().trim(), "URI Template"); //} } else if (modelProperty.equals("templ.wsdl.ep.uri") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL url cannot be empty"); } else{ CommonFieldValidator.isValidUrl(value.toString().trim(), "WSDL url"); } } else if (modelProperty.equals("templ.wsdl.ep.service") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL service cannot be empty"); } } else if (modelProperty.equals("templ.wsdl.ep.port") && isWSDlEP) { if (value == null || value.toString().trim().isEmpty()) { throw new FieldValidationException("WSDL port cannot be empty"); } } else if(modelProperty.equals("registry.browser")){ if(epModel.isSaveAsDynamic()){ if(null==value || value.toString().trim().isEmpty()){ throw new FieldValidationException("Registry path cannot be empty"); } } } }
diff --git a/src/AudioIndexer.java b/src/AudioIndexer.java index a64411f..3d69379 100644 --- a/src/AudioIndexer.java +++ b/src/AudioIndexer.java @@ -1,185 +1,186 @@ import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.DataLine.Info; public class AudioIndexer { public static void main(String[]args) { AudioIndexer ai = new AudioIndexer(); } @SuppressWarnings("unchecked") public AudioIndexer() { String[] filenames = new String[12]; filenames[0] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo1/vdo1.wav"; filenames[1] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo2/vdo2.wav"; filenames[2] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo3/vdo3.wav"; filenames[3] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo4/vdo4.wav"; filenames[4] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo5/vdo5.wav"; filenames[5] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo6/vdo6.wav"; filenames[6] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo7/vdo7.wav"; filenames[7] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo8/vdo8.wav"; filenames[8] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo9/vdo9.wav"; filenames[9] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo10/vdo10.wav"; filenames[10] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo11/vdo11.wav"; filenames[11] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo12/vdo12.wav"; try { AudioFormat audioFormat; AudioInputStream audioInputStream = null; Info info; SourceDataLine dataLine; int bufferSize; int readBytes = 0; byte[] audioBuffer; FileWriter fw = new FileWriter("audioindex.txt"); BufferedWriter bw = new BufferedWriter(fw); FileInputStream inputStream; for (int i = 0; i < 12; i++) { File file = new File(filenames[i]); bw.write("" + i + " "); int audiolen = (int)file.length(); bufferSize = (int) Math.round((double) audiolen * 42.0 / 30000.0); int oneFrameSize = audiolen/720; + System.out.println("index: " + i); System.out.println("oneFrameSize: " + oneFrameSize); System.out.println("audiolen: " + audiolen); System.out.println("bufferSize: " + bufferSize); audioBuffer = new byte[audiolen]; inputStream = new FileInputStream(file); InputStream bufferedIn = new BufferedInputStream(inputStream); audioInputStream = AudioSystem.getAudioInputStream(bufferedIn); // Obtain the information about the AudioInputStream audioFormat = audioInputStream.getFormat(); //System.out.println(audioFormat); info = new Info(SourceDataLine.class, audioFormat); // opens the audio channel dataLine = null; try { dataLine = (SourceDataLine) AudioSystem.getLine(info); dataLine.open(audioFormat, bufferSize); } catch (LineUnavailableException e1) { System.out.println(e1); //throw new PlayWaveException(e1); } readBytes = audioInputStream.read(audioBuffer, 0, audioBuffer.length); int temp[] = new int[oneFrameSize]; int index = 0; int count = 0; int tempMax = 0; for (int audioByte = 0; audioByte < audioBuffer.length;) { //for (int channel = 0; channel < nbChannels; channel++) //{ // Do the byte to sample conversion. int low = (int) audioBuffer[audioByte]; audioByte++; if (audioByte < audioBuffer.length) { int high = (int) audioBuffer[audioByte]; audioByte++; int sample = (high << 8) + (low & 0x00ff); temp[count] = sample; //bw.write("" + sample + " "); } //System.out.println(sample); //toReturn[index] = sample; //} count++; - if ((audioByte) % oneFrameSize == 0) { + if ((audioByte) % oneFrameSize == 0 || (audioByte + 1) % oneFrameSize == 0) { count = 0; int maxVal = maxValue(temp); if (maxVal > tempMax) tempMax = maxVal; //System.out.println(maxVal); bw.write("" + maxVal/1024 + " "); } index++; } System.out.println(tempMax); bw.write("\n"); } bw.close(); } catch (UnsupportedAudioFileException e1) { System.out.println(e1); } catch (IOException e1) { System.out.println(e1); } catch (Exception e) { e.printStackTrace(); } } public int maxValue(int[] chars) { int max = chars[0]; for (int ktr = 0; ktr < chars.length; ktr++) { if (chars[ktr] > max) { max = chars[ktr]; } } return max; } public int averageValue(int[] nums) { int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; } return sum / nums.length; } public int[] getUnscaledAmplitude(byte[] eightBitByteArray) { int[] toReturn = new int[eightBitByteArray.length / 2]; int index = 0; for (int audioByte = 0; audioByte < eightBitByteArray.length;) { //for (int channel = 0; channel < nbChannels; channel++) //{ // Do the byte to sample conversion. int low = (int) eightBitByteArray[audioByte]; audioByte++; int high = (int) eightBitByteArray[audioByte]; audioByte++; int sample = (high << 8) + (low & 0x00ff); //System.out.println(sample); toReturn[index] = sample; //} index++; } return toReturn; } }
false
true
public AudioIndexer() { String[] filenames = new String[12]; filenames[0] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo1/vdo1.wav"; filenames[1] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo2/vdo2.wav"; filenames[2] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo3/vdo3.wav"; filenames[3] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo4/vdo4.wav"; filenames[4] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo5/vdo5.wav"; filenames[5] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo6/vdo6.wav"; filenames[6] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo7/vdo7.wav"; filenames[7] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo8/vdo8.wav"; filenames[8] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo9/vdo9.wav"; filenames[9] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo10/vdo10.wav"; filenames[10] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo11/vdo11.wav"; filenames[11] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo12/vdo12.wav"; try { AudioFormat audioFormat; AudioInputStream audioInputStream = null; Info info; SourceDataLine dataLine; int bufferSize; int readBytes = 0; byte[] audioBuffer; FileWriter fw = new FileWriter("audioindex.txt"); BufferedWriter bw = new BufferedWriter(fw); FileInputStream inputStream; for (int i = 0; i < 12; i++) { File file = new File(filenames[i]); bw.write("" + i + " "); int audiolen = (int)file.length(); bufferSize = (int) Math.round((double) audiolen * 42.0 / 30000.0); int oneFrameSize = audiolen/720; System.out.println("oneFrameSize: " + oneFrameSize); System.out.println("audiolen: " + audiolen); System.out.println("bufferSize: " + bufferSize); audioBuffer = new byte[audiolen]; inputStream = new FileInputStream(file); InputStream bufferedIn = new BufferedInputStream(inputStream); audioInputStream = AudioSystem.getAudioInputStream(bufferedIn); // Obtain the information about the AudioInputStream audioFormat = audioInputStream.getFormat(); //System.out.println(audioFormat); info = new Info(SourceDataLine.class, audioFormat); // opens the audio channel dataLine = null; try { dataLine = (SourceDataLine) AudioSystem.getLine(info); dataLine.open(audioFormat, bufferSize); } catch (LineUnavailableException e1) { System.out.println(e1); //throw new PlayWaveException(e1); } readBytes = audioInputStream.read(audioBuffer, 0, audioBuffer.length); int temp[] = new int[oneFrameSize]; int index = 0; int count = 0; int tempMax = 0; for (int audioByte = 0; audioByte < audioBuffer.length;) { //for (int channel = 0; channel < nbChannels; channel++) //{ // Do the byte to sample conversion. int low = (int) audioBuffer[audioByte]; audioByte++; if (audioByte < audioBuffer.length) { int high = (int) audioBuffer[audioByte]; audioByte++; int sample = (high << 8) + (low & 0x00ff); temp[count] = sample; //bw.write("" + sample + " "); } //System.out.println(sample); //toReturn[index] = sample; //} count++; if ((audioByte) % oneFrameSize == 0) { count = 0; int maxVal = maxValue(temp); if (maxVal > tempMax) tempMax = maxVal; //System.out.println(maxVal); bw.write("" + maxVal/1024 + " "); } index++; } System.out.println(tempMax); bw.write("\n"); } bw.close(); } catch (UnsupportedAudioFileException e1) { System.out.println(e1); } catch (IOException e1) { System.out.println(e1); } catch (Exception e) { e.printStackTrace(); } }
public AudioIndexer() { String[] filenames = new String[12]; filenames[0] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo1/vdo1.wav"; filenames[1] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo2/vdo2.wav"; filenames[2] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo3/vdo3.wav"; filenames[3] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo4/vdo4.wav"; filenames[4] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo5/vdo5.wav"; filenames[5] = "C:/Users/Cauchy/Documents/CSCI576/project/vdo6/vdo6.wav"; filenames[6] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo7/vdo7.wav"; filenames[7] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo8/vdo8.wav"; filenames[8] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo9/vdo9.wav"; filenames[9] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo10/vdo10.wav"; filenames[10] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo11/vdo11.wav"; filenames[11] = "C:/Users/Cauchy/Documents/CSCI576/Project/vdo12/vdo12.wav"; try { AudioFormat audioFormat; AudioInputStream audioInputStream = null; Info info; SourceDataLine dataLine; int bufferSize; int readBytes = 0; byte[] audioBuffer; FileWriter fw = new FileWriter("audioindex.txt"); BufferedWriter bw = new BufferedWriter(fw); FileInputStream inputStream; for (int i = 0; i < 12; i++) { File file = new File(filenames[i]); bw.write("" + i + " "); int audiolen = (int)file.length(); bufferSize = (int) Math.round((double) audiolen * 42.0 / 30000.0); int oneFrameSize = audiolen/720; System.out.println("index: " + i); System.out.println("oneFrameSize: " + oneFrameSize); System.out.println("audiolen: " + audiolen); System.out.println("bufferSize: " + bufferSize); audioBuffer = new byte[audiolen]; inputStream = new FileInputStream(file); InputStream bufferedIn = new BufferedInputStream(inputStream); audioInputStream = AudioSystem.getAudioInputStream(bufferedIn); // Obtain the information about the AudioInputStream audioFormat = audioInputStream.getFormat(); //System.out.println(audioFormat); info = new Info(SourceDataLine.class, audioFormat); // opens the audio channel dataLine = null; try { dataLine = (SourceDataLine) AudioSystem.getLine(info); dataLine.open(audioFormat, bufferSize); } catch (LineUnavailableException e1) { System.out.println(e1); //throw new PlayWaveException(e1); } readBytes = audioInputStream.read(audioBuffer, 0, audioBuffer.length); int temp[] = new int[oneFrameSize]; int index = 0; int count = 0; int tempMax = 0; for (int audioByte = 0; audioByte < audioBuffer.length;) { //for (int channel = 0; channel < nbChannels; channel++) //{ // Do the byte to sample conversion. int low = (int) audioBuffer[audioByte]; audioByte++; if (audioByte < audioBuffer.length) { int high = (int) audioBuffer[audioByte]; audioByte++; int sample = (high << 8) + (low & 0x00ff); temp[count] = sample; //bw.write("" + sample + " "); } //System.out.println(sample); //toReturn[index] = sample; //} count++; if ((audioByte) % oneFrameSize == 0 || (audioByte + 1) % oneFrameSize == 0) { count = 0; int maxVal = maxValue(temp); if (maxVal > tempMax) tempMax = maxVal; //System.out.println(maxVal); bw.write("" + maxVal/1024 + " "); } index++; } System.out.println(tempMax); bw.write("\n"); } bw.close(); } catch (UnsupportedAudioFileException e1) { System.out.println(e1); } catch (IOException e1) { System.out.println(e1); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/com/android/mms/ui/ConversationHeaderView.java b/src/com/android/mms/ui/ConversationHeaderView.java index 4bd0c75..054637c 100644 --- a/src/com/android/mms/ui/ConversationHeaderView.java +++ b/src/com/android/mms/ui/ConversationHeaderView.java @@ -1,248 +1,248 @@ /* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import java.util.List; import com.android.mms.R; import com.android.mms.data.Contact; import com.android.mms.data.ContactList; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Handler; import android.provider.ContactsContract.Intents; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.text.style.TextAppearanceSpan; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.QuickContactBadge; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /** * This class manages the view for given conversation. */ public class ConversationHeaderView extends RelativeLayout implements Contact.UpdateListener { private static final String TAG = "ConversationHeaderView"; private static final boolean DEBUG = false; private TextView mSubjectView; private TextView mFromView; private TextView mDateView; private View mAttachmentView; private View mErrorIndicator; private ImageView mPresenceView; private QuickContactBadge mAvatarView; static private Drawable sDefaultContactImage; // For posting UI update Runnables from other threads: private Handler mHandler = new Handler(); private ConversationHeader mConversationHeader; private static final StyleSpan STYLE_BOLD = new StyleSpan(Typeface.BOLD); public ConversationHeaderView(Context context) { super(context); } public ConversationHeaderView(Context context, AttributeSet attrs) { super(context, attrs); if (sDefaultContactImage == null) { sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture); } } @Override protected void onFinishInflate() { super.onFinishInflate(); mFromView = (TextView) findViewById(R.id.from); mSubjectView = (TextView) findViewById(R.id.subject); mDateView = (TextView) findViewById(R.id.date); mAttachmentView = findViewById(R.id.attachment); mErrorIndicator = findViewById(R.id.error); mPresenceView = (ImageView) findViewById(R.id.presence); mAvatarView = (QuickContactBadge) findViewById(R.id.avatar); } public void setPresenceIcon(int iconId) { if (iconId == 0) { mPresenceView.setVisibility(View.GONE); } else { mPresenceView.setImageResource(iconId); mPresenceView.setVisibility(View.VISIBLE); } } public ConversationHeader getConversationHeader() { return mConversationHeader; } private void setConversationHeader(ConversationHeader header) { mConversationHeader = header; } /** * Only used for header binding. */ public void bind(String title, String explain) { mFromView.setText(title); mSubjectView.setText(explain); } private CharSequence formatMessage(ConversationHeader ch) { final int size = android.R.style.TextAppearance_Small; final int color = android.R.styleable.Theme_textColorSecondary; String from = ch.getFrom(); SpannableStringBuilder buf = new SpannableStringBuilder(from); if (ch.getMessageCount() > 1) { buf.append(" (" + ch.getMessageCount() + ") "); } int before = buf.length(); if (ch.hasDraft()) { buf.append(" "); buf.append(mContext.getResources().getString(R.string.has_draft)); buf.setSpan(new TextAppearanceSpan(mContext, size, color), before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); buf.setSpan(new ForegroundColorSpan( mContext.getResources().getColor(R.drawable.text_color_red)), before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } // Unread messages are shown in bold if (!ch.isRead()) { buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } return buf; } private void updateAvatarView() { ConversationHeader ch = mConversationHeader; Drawable avatarDrawable; if (ch.getContacts().size() == 1) { Contact contact = ch.getContacts().get(0); avatarDrawable = contact.getAvatar(sDefaultContactImage); if (contact.existsInDatabase()) { mAvatarView.assignContactUri(contact.getUri()); } else { mAvatarView.assignContactFromPhone(contact.getNumber(), true); } } else { // TODO get a multiple recipients asset (or do something else) avatarDrawable = sDefaultContactImage; mAvatarView.assignContactUri(null); } mAvatarView.setImageDrawable(avatarDrawable); mAvatarView.setVisibility(View.VISIBLE); } private void updateFromView() { ConversationHeader ch = mConversationHeader; ch.updateRecipients(); mFromView.setText(formatMessage(ch)); setPresenceIcon(ch.getContacts().getPresenceResId()); updateAvatarView(); } public void onUpdate(Contact updated) { mHandler.post(new Runnable() { public void run() { updateFromView(); } }); } public final void bind(Context context, final ConversationHeader ch) { //if (DEBUG) Log.v(TAG, "bind()"); setConversationHeader(ch); - int bgcolor = ch.isRead()? - mContext.getResources().getColor(R.color.read_bgcolor) : - mContext.getResources().getColor(R.color.unread_bgcolor); + Drawable background = ch.isRead()? + mContext.getResources().getDrawable(R.drawable.conversation_item_background_read) : + mContext.getResources().getDrawable(R.drawable.conversation_item_background_unread); - setBackgroundColor(bgcolor); + setBackgroundDrawable(background); LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams(); boolean hasError = ch.hasError(); // When there's an error icon, the attachment icon is left of the error icon. // When there is not an error icon, the attachment icon is left of the date text. // As far as I know, there's no way to specify that relationship in xml. if (hasError) { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error); } else { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date); } boolean hasAttachment = ch.hasAttachment(); mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE); // Date mDateView.setText(ch.getDate()); // From. mFromView.setText(formatMessage(ch)); // Register for updates in changes of any of the contacts in this conversation. ContactList contacts = ch.getContacts(); if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this); contacts.addListeners(this); setPresenceIcon(contacts.getPresenceResId()); // Subject mSubjectView.setText(ch.getSubject()); LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams(); // We have to make the subject left of whatever optional items are shown on the right. subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment : (hasError ? R.id.error : R.id.date)); // Transmission error indicator. mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE); updateAvatarView(); } public final void unbind() { if (DEBUG) Log.v(TAG, "unbind: contacts.removeListeners " + this); // Unregister contact update callbacks. mConversationHeader.getContacts().removeListeners(this); } }
false
true
public final void bind(Context context, final ConversationHeader ch) { //if (DEBUG) Log.v(TAG, "bind()"); setConversationHeader(ch); int bgcolor = ch.isRead()? mContext.getResources().getColor(R.color.read_bgcolor) : mContext.getResources().getColor(R.color.unread_bgcolor); setBackgroundColor(bgcolor); LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams(); boolean hasError = ch.hasError(); // When there's an error icon, the attachment icon is left of the error icon. // When there is not an error icon, the attachment icon is left of the date text. // As far as I know, there's no way to specify that relationship in xml. if (hasError) { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error); } else { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date); } boolean hasAttachment = ch.hasAttachment(); mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE); // Date mDateView.setText(ch.getDate()); // From. mFromView.setText(formatMessage(ch)); // Register for updates in changes of any of the contacts in this conversation. ContactList contacts = ch.getContacts(); if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this); contacts.addListeners(this); setPresenceIcon(contacts.getPresenceResId()); // Subject mSubjectView.setText(ch.getSubject()); LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams(); // We have to make the subject left of whatever optional items are shown on the right. subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment : (hasError ? R.id.error : R.id.date)); // Transmission error indicator. mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE); updateAvatarView(); }
public final void bind(Context context, final ConversationHeader ch) { //if (DEBUG) Log.v(TAG, "bind()"); setConversationHeader(ch); Drawable background = ch.isRead()? mContext.getResources().getDrawable(R.drawable.conversation_item_background_read) : mContext.getResources().getDrawable(R.drawable.conversation_item_background_unread); setBackgroundDrawable(background); LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams(); boolean hasError = ch.hasError(); // When there's an error icon, the attachment icon is left of the error icon. // When there is not an error icon, the attachment icon is left of the date text. // As far as I know, there's no way to specify that relationship in xml. if (hasError) { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error); } else { attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date); } boolean hasAttachment = ch.hasAttachment(); mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE); // Date mDateView.setText(ch.getDate()); // From. mFromView.setText(formatMessage(ch)); // Register for updates in changes of any of the contacts in this conversation. ContactList contacts = ch.getContacts(); if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this); contacts.addListeners(this); setPresenceIcon(contacts.getPresenceResId()); // Subject mSubjectView.setText(ch.getSubject()); LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams(); // We have to make the subject left of whatever optional items are shown on the right. subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment : (hasError ? R.id.error : R.id.date)); // Transmission error indicator. mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE); updateAvatarView(); }
diff --git a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java index 817a3895..851fbd7b 100644 --- a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java +++ b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java @@ -1,254 +1,254 @@ /* * Copyright 2010 The myBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.spring; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.support.JdbcAccessor; import org.springframework.util.Assert; /** * Helper class that simplifies data access via the MyBatis * {@link org.apache.ibatis.session.SqlSession} API, converting checked SQLExceptions into unchecked * DataAccessExceptions, following the <code>org.springframework.dao</code> exception hierarchy. * Uses the same {@link org.springframework.jdbc.support.SQLExceptionTranslator} mechanism as * {@link org.springframework.jdbc.core.JdbcTemplate}. * * The main method of this class executes a callback that implements a data access action. * Furthermore, this class provides numerous convenience methods that mirror * {@link org.apache.ibatis.session.SqlSession}'s execution methods. * * It is generally recommended to use the convenience methods on this template for plain * query/insert/update/delete operations. However, for more complex operations like batch updates, a * custom SqlSessionCallback must be implemented, usually as anonymous inner class. For example: * * <pre class="code"> * getSqlSessionTemplate().execute(new SqlSessionCallback&lt;Object&gt;() { * public Object doInSqlSession(SqlSession sqlSession) throws SQLException { * sqlSession.getMapper(MyMapper.class).update(parameterObject); * sqlSession.update(&quot;MyMapper.update&quot;, otherParameterObject); * return null; * } * }, ExecutorType.BATCH); * </pre> * * The template needs a SqlSessionFactory to create SqlSessions, passed in via the * "sqlSessionFactory" property. A Spring context typically uses a {@link SqlSessionFactoryBean} to * build the SqlSessionFactory. The template can additionally be configured with a DataSource for * fetching Connections, although this is not necessary since a DataSource is specified for the * SqlSessionFactory itself (through configured Environment). * * @see #execute * @see #setSqlSessionFactory(org.apache.ibatis.session.SqlSessionFactory) * @see SqlSessionFactoryBean#setDataSource * @see org.apache.ibatis.session.SqlSessionFactory#getConfiguration() * @see org.apache.ibatis.session.SqlSession * @see org.mybatis.spring.SqlSessionOperations * @version $Id$ */ @SuppressWarnings({ "unchecked" }) public class SqlSessionTemplate extends JdbcAccessor implements SqlSessionOperations { private SqlSessionFactory sqlSessionFactory; public SqlSessionTemplate() {} public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { setSqlSessionFactory(sqlSessionFactory); } /** * Sets the SqlSessionFactory this template will use when creating SqlSessions. */ public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } /** * Returns either the DataSource explicitly set for this template of the one specified by the SqlSessionFactory's Environment. * * @see org.apache.ibatis.mapping.Environment */ @Override public DataSource getDataSource() { DataSource ds = super.getDataSource(); return (ds != null ? ds : this.sqlSessionFactory.getConfiguration().getEnvironment().getDataSource()); } @Override public void afterPropertiesSet() { if (this.sqlSessionFactory == null) { throw new IllegalArgumentException("Property 'sqlSessionFactory' is required"); } super.afterPropertiesSet(); } public <T> T execute(SqlSessionCallback<T> action) throws DataAccessException { return execute(action, this.sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } /** * Execute the given data access action on a Executor. * * @param action callback object that specifies the data access action * @param executorType SIMPLE, REUSE, BATCH * @return a result object returned by the action, or <code>null</code> * @throws DataAccessException in case of errors */ public <T> T execute(SqlSessionCallback<T> action, ExecutorType executorType) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Assert.notNull(this.sqlSessionFactory, "No SqlSessionFactory specified"); SqlSession sqlSession = SqlSessionUtils.getSqlSession(this.sqlSessionFactory, getDataSource(), executorType); try { return action.doInSqlSession(sqlSession); } catch (Throwable t) { throw wrapException(t); } finally { SqlSessionUtils.closeSqlSession(sqlSession, this.sqlSessionFactory); } } public Object selectOne(String statement) { return selectOne(statement, null); } public Object selectOne(final String statement, final Object parameter) { return execute(new SqlSessionCallback<Object>() { public Object doInSqlSession(SqlSession sqlSession) { return sqlSession.selectOne(statement, parameter); } }); } public <T> List<T> selectList(String statement) { return selectList(statement, null); } public <T> List<T> selectList(String statement, Object parameter) { return selectList(statement, parameter, RowBounds.DEFAULT); } public <T> List<T> selectList(final String statement, final Object parameter, final RowBounds rowBounds) { return execute(new SqlSessionCallback<List<T>>() { public List<T> doInSqlSession(SqlSession sqlSession) { return sqlSession.selectList(statement, parameter, rowBounds); } }); } public void select(String statement, Object parameter, ResultHandler handler) { select(statement, parameter, RowBounds.DEFAULT, handler); } public void select(final String statement, final Object parameter, final RowBounds rowBounds, final ResultHandler handler) { execute(new SqlSessionCallback<Object>() { public Object doInSqlSession(SqlSession sqlSession) { sqlSession.select(statement, parameter, rowBounds, handler); return null; } }); } public int insert(String statement) { return insert(statement, null); } public int insert(final String statement, final Object parameter) { return execute(new SqlSessionCallback<Integer>() { public Integer doInSqlSession(SqlSession sqlSession) { return sqlSession.insert(statement, parameter); } }); } public int update(String statement) { return update(statement, null); } public int update(final String statement, final Object parameter) { return execute(new SqlSessionCallback<Integer>() { public Integer doInSqlSession(SqlSession sqlSession) { return sqlSession.update(statement, parameter); } }); } public int delete(String statement) { return delete(statement, null); } public int delete(final String statement, final Object parameter) { return execute(new SqlSessionCallback<Integer>() { public Integer doInSqlSession(SqlSession sqlSession) { return sqlSession.delete(statement, parameter); } }); } public <T> T getMapper(final Class<T> type) { return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return execute(new SqlSessionCallback<Object>() { public Object doInSqlSession(SqlSession sqlSession) throws SQLException { try { return method.invoke(sqlSession.getMapper(type), args); } catch (java.lang.reflect.InvocationTargetException e) { - throw wrapException(e); + throw wrapException(e.getCause()); } catch (Exception e) { throw new MyBatisSystemException("SqlSession operation", e); } } }); } }); } public DataAccessException wrapException(Throwable t) { if (t instanceof PersistenceException) { if (t.getCause() instanceof SQLException) { return getExceptionTranslator().translate("SqlSession operation", null, (SQLException) t.getCause()); } else { return new MyBatisSystemException("SqlSession operation", t); } } else if (t instanceof DataAccessException) { return (DataAccessException) t; } else { return new MyBatisSystemException("SqlSession operation", t); } } }
true
true
public <T> T getMapper(final Class<T> type) { return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return execute(new SqlSessionCallback<Object>() { public Object doInSqlSession(SqlSession sqlSession) throws SQLException { try { return method.invoke(sqlSession.getMapper(type), args); } catch (java.lang.reflect.InvocationTargetException e) { throw wrapException(e); } catch (Exception e) { throw new MyBatisSystemException("SqlSession operation", e); } } }); } }); }
public <T> T getMapper(final Class<T> type) { return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return execute(new SqlSessionCallback<Object>() { public Object doInSqlSession(SqlSession sqlSession) throws SQLException { try { return method.invoke(sqlSession.getMapper(type), args); } catch (java.lang.reflect.InvocationTargetException e) { throw wrapException(e.getCause()); } catch (Exception e) { throw new MyBatisSystemException("SqlSession operation", e); } } }); } }); }
diff --git a/sikuli-ide/src/main/java/edu/mit/csail/uid/sikuli_test/UnitTestRunner.java b/sikuli-ide/src/main/java/edu/mit/csail/uid/sikuli_test/UnitTestRunner.java index d3e313d0..b7ca8156 100644 --- a/sikuli-ide/src/main/java/edu/mit/csail/uid/sikuli_test/UnitTestRunner.java +++ b/sikuli-ide/src/main/java/edu/mit/csail/uid/sikuli_test/UnitTestRunner.java @@ -1,522 +1,521 @@ package edu.mit.csail.uid.sikuli_test; import edu.mit.csail.uid.SikuliIDE; import java.util.Vector; import java.util.HashMap; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.runner.BaseTestRunner; import junit.runner.FailureDetailView; import junit.runner.SimpleTestCollector; import junit.runner.TestCollector; import junit.runner.TestRunListener; import junit.runner.StandardTestSuiteLoader; import junit.runner.TestSuiteLoader; import edu.mit.csail.uid.Debug; import java.io.PrintStream; import java.io.File; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.python.util.PythonInterpreter; import org.python.core.*; public class UnitTestRunner extends BaseTestRunner implements TestRunContext{ private static final int GAP= 4; private JFrame minFrame; private JPanel mainPane, minPane; private JToolBar toolbar; private JButton fRun; private ProgressBar fProgressIndicator; private CounterPanel fCounterPanel; private JTabbedPane fTestViewTab; private FailureDetailView fFailureView; private JScrollPane tracePane; private Vector fTestRunViews= new Vector(); // view associated with tab in tabbed pane private DefaultListModel fFailures; private Thread fRunner; private TestResult fTestResult; //private HashMap<String, Integer> _lineNoOfTest; public JComponent getTracePane(){ return tracePane; } public JPanel getPanel(){ return mainPane; } public JFrame getMinFrame(){ return minFrame; } private JToolBar initToolbar(){ JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); fRun = createRunButton(); toolbar.add(fRun); return toolbar; } protected JButton createRunButton() { JButton run= new JButton("Run"); run.setEnabled(true); run.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { runSuite(); } } ); return run; } protected CounterPanel createCounterPanel() { return new CounterPanel(); } protected JTabbedPane createTestRunViews() { JTabbedPane pane= new JTabbedPane(); FailureRunView lv= new FailureRunView(this); fTestRunViews.addElement(lv); lv.addTab(pane); TestHierarchyRunView tv= new TestHierarchyRunView(this); fTestRunViews.addElement(tv); tv.addTab(pane); pane.addChangeListener( new ChangeListener() { public void stateChanged(ChangeEvent e) { testViewChanged(); } } ); return pane; } public void testViewChanged() { TestRunView view= (TestRunView)fTestRunViews.elementAt(fTestViewTab.getSelectedIndex()); view.activate(); } private void initComponents(){ toolbar = initToolbar(); /* if (inMac()) fProgressIndicator= new MacProgressBar(fStatusLine); else */ fProgressIndicator= new ProgressBar(); fCounterPanel= createCounterPanel(); fFailures= new DefaultListModel(); fTestViewTab= createTestRunViews(); fFailureView= createFailureDetailView(); tracePane= new JScrollPane(fFailureView.getComponent(), ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); initMinFrame(); } private void initMinFrame(){ minFrame = new JFrame("Sikuli Test"); minFrame.setAlwaysOnTop(true); minFrame.setSize(255, 85); minFrame.getRootPane().putClientProperty("Window.alpha", new Float(0.7f)); /* Container con = minFrame.getContentPane(); con.add(minPane); minFrame.doLayout(); minFrame.setVisible(true); */ } private static final String FAILUREDETAILVIEW_KEY= "FailureViewClass"; protected FailureDetailView createFailureDetailView() { String className= BaseTestRunner.getPreference(FAILUREDETAILVIEW_KEY); if (className != null) { Class viewClass= null; try { viewClass= Class.forName(className); return (FailureDetailView)viewClass.newInstance(); } catch(Exception e) { JOptionPane.showMessageDialog(mainPane, "Could not create Failure DetailView - using default view"); } } return new DefaultFailureDetailView(); } public UnitTestRunner(){ mainPane = new JPanel(new GridBagLayout()); minPane = new JPanel(new GridBagLayout()); initComponents(); addGrid(mainPane, toolbar, 0, 0, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(mainPane, new JSeparator(), 0, 1, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(mainPane, fCounterPanel, 0, 2, 2, GridBagConstraints.NONE, 0.0, GridBagConstraints.WEST); addGrid(mainPane, fProgressIndicator, 0, 3, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(mainPane, new JSeparator(), 0, 5, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(mainPane, new JLabel("Results:"), 0, 6, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(mainPane, fTestViewTab, 0, 7, 2, GridBagConstraints.BOTH, 1.0, GridBagConstraints.WEST); //_lineNoOfTest = new HashMap<String, Integer>(); } void addMinComponentsToPane(JPanel pane){ addGrid(pane, toolbar, 0, 0, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); addGrid(pane, fCounterPanel, 0, 2, 2, GridBagConstraints.NONE, 0.0, GridBagConstraints.WEST); addGrid(pane, fProgressIndicator, 0, 3, 2, GridBagConstraints.HORIZONTAL, 1.0, GridBagConstraints.WEST); } private void addGrid(JPanel p, Component co, int x, int y, int w, int fill, double wx, int anchor) { GridBagConstraints c= new GridBagConstraints(); c.gridx= x; c.gridy= y; c.gridwidth= w; c.anchor= anchor; c.weightx= wx; c.fill= fill; if(fill == GridBagConstraints.BOTH || fill == GridBagConstraints.VERTICAL) c.weighty= 1.0; c.insets= new Insets(y == 0 ? 10 : 0, GAP, GAP, GAP); p.add(co, c); } public ListModel getFailures() { return fFailures; } public void handleTestSelected(Test test){ moveCursorToTest(test); showFailureDetail(test); } private void moveCursorToTest(Test test){ if( test instanceof TestCase ){ String func = ((TestCase)test).getName(); try{ SikuliIDE.getInstance().jumpTo(func); } catch(BadLocationException e){ e.printStackTrace(); } } } private void showFailureDetail(Test test) { if (test != null) { ListModel failures= getFailures(); for (int i= 0; i < failures.getSize(); i++) { TestFailure failure= (TestFailure)failures.getElementAt(i); if (failure.failedTest() == test) { fFailureView.showFailure(failure); return; } } } fFailureView.clear(); } synchronized public void runSuite() { SikuliIDE ide = SikuliIDE.getInstance(); if (fRunner != null) { fTestResult.stop(); showIDE(true); } else { try{ showIDE(false); reset(); String filename = ide.getCurrentFilename(); String path = ide.getCurrentBundlePath(); Test suite = genTestSuite(filename, path); doRun(suite); } catch(IOException e){ e.printStackTrace(); showIDE(true); } } } private void showInfo(String message) { //fStatusLine.showInfo(message); System.out.println(message); } private void postInfo(final String message) { SwingUtilities.invokeLater( new Runnable() { public void run() { showInfo(message); } } ); } protected void reset() { fCounterPanel.reset(); fProgressIndicator.reset(); fFailureView.clear(); fFailures.clear(); } private void setButtonLabel(final JButton button, final String label) { SwingUtilities.invokeLater( new Runnable() { public void run() { button.setText(label); } } ); } protected void runFinished(final Test testSuite) { SwingUtilities.invokeLater( new Runnable() { public void run() { for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements(); ) { TestRunView v= (TestRunView) e.nextElement(); v.runFinished(testSuite, fTestResult); } } } ); } public static final int SUCCESS_EXIT= 0; public static final int FAILURE_EXIT= 1; public static final int EXCEPTION_EXIT= 2; public TestSuiteLoader getLoader() { return new StandardTestSuiteLoader(); } private void revealFailure(Test test) { for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements(); ) { TestRunView v= (TestRunView) e.nextElement(); v.revealFailure(test); } } private void appendFailure(Test test, Throwable t) { fFailures.addElement(new TestFailure(test, t)); if (fFailures.size() == 1) revealFailure(test); } public void testFailed(final int status, final Test test, final Throwable t) { SwingUtilities.invokeLater( new Runnable() { public void run() { switch (status) { case TestRunListener.STATUS_ERROR: fCounterPanel.setErrorValue(fTestResult.errorCount()); appendFailure(test, t); break; case TestRunListener.STATUS_FAILURE: fCounterPanel.setFailureValue(fTestResult.failureCount()); appendFailure(test, t); break; } } } ); } public void testStarted(String testName) { Debug.log(8,"test started: " + testName); } public void testEnded(String testName) { Debug.log(8,"test ended: " + testName); synchUI(); SwingUtilities.invokeLater( new Runnable() { public void run() { if (fTestResult != null) { fCounterPanel.setRunValue(fTestResult.runCount()); fProgressIndicator.step(fTestResult.runCount(), fTestResult.wasSuccessful()); } } } ); } private void synchUI() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() {} } ); } catch (Exception e) { } } protected TestResult createTestResult() { return new TestResult(); } private void doRun(final Test testSuite) { setButtonLabel(fRun, "Stop"); fRunner= new Thread("TestRunner-Thread") { public void run() { UnitTestRunner.this.start(testSuite); postInfo("Running..."); long startTime= System.currentTimeMillis(); testSuite.run(fTestResult); if (fTestResult.shouldStop()) { postInfo("Stopped"); } else { long endTime= System.currentTimeMillis(); long runTime= endTime-startTime; postInfo("Finished: " + elapsedTimeAsString(runTime) + " seconds"); } runFinished(testSuite); setButtonLabel(fRun, "Run"); showIDE(true); fRunner= null; System.gc(); } }; // make sure that the test result is created before we start the // test runner thread so that listeners can register for it. fTestResult= createTestResult(); fTestResult.addListener(UnitTestRunner.this); aboutToStart(testSuite); fRunner.start(); } private void showIDE(boolean show){ SikuliIDE.getInstance().setVisible(show); if(show){ addMinComponentsToPane(mainPane); } else{ addMinComponentsToPane(minPane); Container con = minFrame.getContentPane(); con.add(minPane); minFrame.doLayout(); } minFrame.setVisible(!show); } protected void aboutToStart(final Test testSuite) { for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements(); ) { TestRunView v= (TestRunView) e.nextElement(); v.aboutToStart(testSuite, fTestResult); } } private void start(final Test test) { SwingUtilities.invokeLater( new Runnable() { public void run() { int total= test.countTestCases(); fProgressIndicator.start(total); fCounterPanel.setTotal(total); } } ); } private String genTestClassName(String filename){ String fname = new File(filename).getName(); int dot = fname.indexOf("."); return fname.substring(0, dot); } private Test genTestSuite(String filename, String bundlePath) throws IOException{ String className = genTestClassName(filename); TestSuite ret = new TestSuite(className); PythonInterpreter interp = new PythonInterpreter(); String testCode = "import junit\n"+ "from junit.framework.Assert import *\n"+ - "from python.edu.mit.csail.uid.Sikuli import *\n"+ - "from python.edu.mit.csail.uid.SikuliTest import *\n"+ + "from sikuli.Sikuli import *\n"+ "class "+className+" (junit.framework.TestCase):\n"+ - " def __init__(self, name):\n"+ - " junit.framework.TestCase.__init__(self,name)\n"+ - " self.theTestFunction = getattr(self,name)\n"+ - " setBundlePath('"+bundlePath+"')\n"+ - " def runTest(self):\n"+ - " self.theTestFunction()\n"; + "\tdef __init__(self, name):\n"+ + "\t\tjunit.framework.TestCase.__init__(self,name)\n"+ + "\t\tself.theTestFunction = getattr(self,name)\n"+ + "\t\tsetBundlePath('"+bundlePath+"')\n"+ + "\tdef runTest(self):\n"+ + "\t\tself.theTestFunction()\n"; BufferedReader in = new BufferedReader(new FileReader(filename)); String line; //int lineNo = 0; //Pattern patDef = Pattern.compile("def\\s+(\\w+)\\s*\\("); while( (line = in.readLine()) != null ){ // lineNo++; - testCode += " " + line + "\n"; + testCode += "\t" + line + "\n"; /* Matcher matcher = patDef.matcher(line); if(matcher.find()){ String func = matcher.group(1); Debug.log("Parsed " + lineNo + ": " + func); _lineNoOfTest.put( func, lineNo ); } */ } interp.exec(testCode); PyList tests = (PyList)interp.eval( "["+className+"(f) for f in dir("+className+") if f.startswith(\"test\")]"); while( tests.size() > 0 ){ PyObject t = tests.pop(); Test t2 = (Test)(t).__tojava__(TestCase.class); ret.addTest( t2 ); } return ret; } protected void runFailed(String message) { System.err.println(message); fRunner= null; } }
false
true
private Test genTestSuite(String filename, String bundlePath) throws IOException{ String className = genTestClassName(filename); TestSuite ret = new TestSuite(className); PythonInterpreter interp = new PythonInterpreter(); String testCode = "import junit\n"+ "from junit.framework.Assert import *\n"+ "from python.edu.mit.csail.uid.Sikuli import *\n"+ "from python.edu.mit.csail.uid.SikuliTest import *\n"+ "class "+className+" (junit.framework.TestCase):\n"+ " def __init__(self, name):\n"+ " junit.framework.TestCase.__init__(self,name)\n"+ " self.theTestFunction = getattr(self,name)\n"+ " setBundlePath('"+bundlePath+"')\n"+ " def runTest(self):\n"+ " self.theTestFunction()\n"; BufferedReader in = new BufferedReader(new FileReader(filename)); String line; //int lineNo = 0; //Pattern patDef = Pattern.compile("def\\s+(\\w+)\\s*\\("); while( (line = in.readLine()) != null ){ // lineNo++; testCode += " " + line + "\n"; /* Matcher matcher = patDef.matcher(line); if(matcher.find()){ String func = matcher.group(1); Debug.log("Parsed " + lineNo + ": " + func); _lineNoOfTest.put( func, lineNo ); } */ } interp.exec(testCode); PyList tests = (PyList)interp.eval( "["+className+"(f) for f in dir("+className+") if f.startswith(\"test\")]"); while( tests.size() > 0 ){ PyObject t = tests.pop(); Test t2 = (Test)(t).__tojava__(TestCase.class); ret.addTest( t2 ); } return ret; }
private Test genTestSuite(String filename, String bundlePath) throws IOException{ String className = genTestClassName(filename); TestSuite ret = new TestSuite(className); PythonInterpreter interp = new PythonInterpreter(); String testCode = "import junit\n"+ "from junit.framework.Assert import *\n"+ "from sikuli.Sikuli import *\n"+ "class "+className+" (junit.framework.TestCase):\n"+ "\tdef __init__(self, name):\n"+ "\t\tjunit.framework.TestCase.__init__(self,name)\n"+ "\t\tself.theTestFunction = getattr(self,name)\n"+ "\t\tsetBundlePath('"+bundlePath+"')\n"+ "\tdef runTest(self):\n"+ "\t\tself.theTestFunction()\n"; BufferedReader in = new BufferedReader(new FileReader(filename)); String line; //int lineNo = 0; //Pattern patDef = Pattern.compile("def\\s+(\\w+)\\s*\\("); while( (line = in.readLine()) != null ){ // lineNo++; testCode += "\t" + line + "\n"; /* Matcher matcher = patDef.matcher(line); if(matcher.find()){ String func = matcher.group(1); Debug.log("Parsed " + lineNo + ": " + func); _lineNoOfTest.put( func, lineNo ); } */ } interp.exec(testCode); PyList tests = (PyList)interp.eval( "["+className+"(f) for f in dir("+className+") if f.startswith(\"test\")]"); while( tests.size() > 0 ){ PyObject t = tests.pop(); Test t2 = (Test)(t).__tojava__(TestCase.class); ret.addTest( t2 ); } return ret; }
diff --git a/src/test/java/com/tacitknowledge/util/migration/builders/MockBuilder.java b/src/test/java/com/tacitknowledge/util/migration/builders/MockBuilder.java index a7cb74d..8ae191e 100644 --- a/src/test/java/com/tacitknowledge/util/migration/builders/MockBuilder.java +++ b/src/test/java/com/tacitknowledge/util/migration/builders/MockBuilder.java @@ -1,76 +1,76 @@ /* Copyright 2004 Tacit Knowledge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tacitknowledge.util.migration.builders; import com.tacitknowledge.util.migration.MigrationException; import com.tacitknowledge.util.migration.MigrationRunnerStrategy; import com.tacitknowledge.util.migration.PatchInfoStore; import org.apache.commons.lang.ArrayUtils; import org.easymock.MockControl; import org.easymock.classextension.IMocksControl; import java.util.Properties; import java.util.Set; import static org.easymock.EasyMock.endsWith; import static org.easymock.EasyMock.expect; import static org.easymock.classextension.EasyMock.createStrictControl; /** * MockBuilder to retrieve simple objects used in different tests * * @author Oscar Gonzalez ([email protected]) */ public class MockBuilder { public static PatchInfoStore getPatchInfoStore(int patchLevel) throws MigrationException { return getPatchInfoStore(patchLevel, null); } public static PatchInfoStore getPatchInfoStore(int patchLevel, Set<Integer> patchesApplied) throws MigrationException { IMocksControl patchInfoStoreControl = createStrictControl(); PatchInfoStore patchInfoStoreMock = patchInfoStoreControl.createMock(PatchInfoStore.class); expect( patchInfoStoreMock.getPatchLevel()).andReturn(patchLevel).anyTimes(); expect(patchInfoStoreMock.getPatchesApplied()).andReturn(patchesApplied); patchInfoStoreControl.replay(); return patchInfoStoreMock; } public static Properties getPropertiesWithSystemConfiguration( String system, String strategy ){ Properties properties = new Properties(); - properties.setProperty(system + ".jdbc.database.type", "hsqldb"); +// properties.setProperty(system + ".jdbc.database.type", "hsqldb"); properties.setProperty(system + ".patch.path", "systemPath"); properties.setProperty(system + ".jdbc.driver", "jdbcDriver"); properties.setProperty(system + ".jdbc.url", "jdbcUrl"); properties.setProperty(system + ".jdbc.username", "jdbcUsername"); properties.setProperty(system + ".jdbc.password", "jdbcPassword"); properties.setProperty(system + ".jdbc.dialect", "hsqldb"); properties.setProperty("migration.strategy", strategy); return properties; } public static Properties getPropertiesWithDistributedSystemConfiguration( String system, String strategy, String subsystems ){ Properties properties = getPropertiesWithSystemConfiguration(system,strategy); properties.setProperty(system + ".context", system); properties.setProperty(system + ".controlled.systems", subsystems ); return properties; } }
true
true
public static Properties getPropertiesWithSystemConfiguration( String system, String strategy ){ Properties properties = new Properties(); properties.setProperty(system + ".jdbc.database.type", "hsqldb"); properties.setProperty(system + ".patch.path", "systemPath"); properties.setProperty(system + ".jdbc.driver", "jdbcDriver"); properties.setProperty(system + ".jdbc.url", "jdbcUrl"); properties.setProperty(system + ".jdbc.username", "jdbcUsername"); properties.setProperty(system + ".jdbc.password", "jdbcPassword"); properties.setProperty(system + ".jdbc.dialect", "hsqldb"); properties.setProperty("migration.strategy", strategy); return properties; }
public static Properties getPropertiesWithSystemConfiguration( String system, String strategy ){ Properties properties = new Properties(); // properties.setProperty(system + ".jdbc.database.type", "hsqldb"); properties.setProperty(system + ".patch.path", "systemPath"); properties.setProperty(system + ".jdbc.driver", "jdbcDriver"); properties.setProperty(system + ".jdbc.url", "jdbcUrl"); properties.setProperty(system + ".jdbc.username", "jdbcUsername"); properties.setProperty(system + ".jdbc.password", "jdbcPassword"); properties.setProperty(system + ".jdbc.dialect", "hsqldb"); properties.setProperty("migration.strategy", strategy); return properties; }
diff --git a/frontend/client/src/autotest/afe/HostSelector.java b/frontend/client/src/autotest/afe/HostSelector.java index 9fed6e8b..d6208d3a 100644 --- a/frontend/client/src/autotest/afe/HostSelector.java +++ b/frontend/client/src/autotest/afe/HostSelector.java @@ -1,303 +1,303 @@ package autotest.afe; import autotest.common.JSONArrayList; import autotest.common.table.ArrayDataSource; import autotest.common.table.DataSource; import autotest.common.table.SelectionManager; import autotest.common.table.TableDecorator; import autotest.common.table.DataSource.DefaultDataCallback; import autotest.common.table.DynamicTable.DynamicTableListener; import autotest.common.table.SelectionManager.SelectionListener; import autotest.common.ui.NotifyManager; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * A widget to facilitate selection of a group of hosts for running a job. The * widget displays two side-by-side tables; the left table is a normal * {@link HostTable} displaying available, unselected hosts, and the right table * displays selected hosts. Click on a host in either table moves it to the * other (i.e. selects or deselects a host). The widget provides several * convenience controls (such as one to remove all selected hosts) and a special * section for adding meta-host entries. */ public class HostSelector { public static final int TABLE_SIZE = 10; public static final String META_PREFIX = "Any "; public static final String ONE_TIME = "(one-time host)"; static class HostSelection { public List<String> hosts = new ArrayList<String>(); public List<String> metaHosts = new ArrayList<String>(); public List<String> oneTimeHosts = new ArrayList<String>(); } protected ArrayDataSource<JSONObject> selectedHostData = new ArrayDataSource<JSONObject>("hostname"); protected HostTable availableTable = new HostTable(new HostDataSource()); protected HostTableDecorator availableDecorator = new HostTableDecorator(availableTable, TABLE_SIZE); protected HostTable selectedTable = new HostTable(selectedHostData); protected TableDecorator selectedDecorator = new TableDecorator(selectedTable); protected SelectionManager availableSelection = new SelectionManager(availableTable, false); public HostSelector() { selectedTable.setClickable(true); selectedTable.setRowsPerPage(TABLE_SIZE); selectedDecorator.addPaginators(); availableTable.setClickable(true); availableDecorator.lockedFilter.setSelectedChoice("No"); availableDecorator.aclFilter.setActive(true); availableTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { availableSelection.toggleSelected(row); availableSelection.refreshSelection(); } public void onTableRefreshed() { availableSelection.refreshSelection(); } }); availableSelection.addListener(new SelectionListener() { public void onAdd(Collection<JSONObject> objects) { for (JSONObject row : objects) { selectRow(row); } selectionRefresh(); } public void onRemove(Collection<JSONObject> objects) { for (JSONObject row : objects) { deselectRow(row); } selectionRefresh(); } }); selectedTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { - if (isMetaEntry(row)) { + if (isMetaEntry(row) || isOneTimeHost(row)) { deselectRow(row); selectionRefresh(); } else availableSelection.deselectObject(row); } public void onTableRefreshed() {} }); RootPanel.get("create_available_table").add(availableDecorator); RootPanel.get("create_selected_table").add(selectedDecorator); Button addVisibleButton = new Button("Select visible"); addVisibleButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addVisible(); } }); Button addFilteredButton = new Button("Select all"); addFilteredButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addAllFiltered(); } }); Button removeAllButton = new Button("Select none"); removeAllButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { deselectAll(); } }); Panel availableControls = new HorizontalPanel(); availableControls.add(addVisibleButton); availableControls.add(addFilteredButton); availableControls.add(removeAllButton); RootPanel.get("create_available_controls").add(availableControls); final ListBox metaLabelSelect = new ListBox(); populateLabels(metaLabelSelect); final TextBox metaNumber = new TextBox(); metaNumber.setVisibleLength(4); final Button metaButton = new Button("Add"); metaButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { int selected = metaLabelSelect.getSelectedIndex(); String labelName = metaLabelSelect.getItemText(selected); String label = AfeUtils.decodeLabelName(labelName); String number = metaNumber.getText(); try { Integer.parseInt(number); } catch (NumberFormatException exc) { String error = "Invalid number " + number; NotifyManager.getInstance().showError(error); return; } selectMetaHost(label, number); selectionRefresh(); } }); RootPanel.get("create_meta_select").add(metaLabelSelect); RootPanel.get("create_meta_number").add(metaNumber); RootPanel.get("create_meta_button").add(metaButton); final TextBox oneTimeHostField = new TextBox(); final Button oneTimeHostButton = new Button("Add"); oneTimeHostButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { String hostname = oneTimeHostField.getText(); JSONObject oneTimeObject = new JSONObject(); oneTimeObject.put("hostname", new JSONString(hostname)); oneTimeObject.put("platform", new JSONString(ONE_TIME)); selectRow(oneTimeObject); selectionRefresh(); } }); RootPanel.get("create_one_time_field").add(oneTimeHostField); RootPanel.get("create_one_time_button").add(oneTimeHostButton); } protected void selectMetaHost(String label, String number) { JSONObject metaObject = new JSONObject(); metaObject.put("hostname", new JSONString(META_PREFIX + number)); metaObject.put("platform", new JSONString(label)); metaObject.put("labels", new JSONArray()); metaObject.put("status", new JSONString("")); metaObject.put("locked", new JSONNumber(0)); selectRow(metaObject); } protected void selectRow(JSONObject row) { selectedHostData.addItem(row); } protected void deselectRow(JSONObject row) { selectedHostData.removeItem(row); } protected void addVisible() { List<JSONObject> rowsToAdd = new ArrayList<JSONObject>(); for (int i = 0; i < availableTable.getRowCount(); i++) { rowsToAdd.add(availableTable.getRow(i)); } availableSelection.selectObjects(rowsToAdd); } protected void addAllFiltered() { DataSource availableDataSource = availableTable.getDataSource(); availableDataSource.getPage(null, null, null, new DefaultDataCallback() { @Override public void handlePage(JSONArray data) { availableSelection.selectObjects( new JSONArrayList<JSONObject>(data)); } }); } protected void deselectAll() { availableSelection.deselectAll(); // get rid of leftover meta-host entries selectedHostData.clear(); selectionRefresh(); } protected void populateLabels(ListBox list) { String[] labelNames = AfeUtils.getLabelStrings(); for(int i = 0; i < labelNames.length; i++) { list.addItem(labelNames[i]); } } protected String getHostname(JSONObject row) { return row.get("hostname").isString().stringValue(); } protected boolean isMetaEntry(JSONObject row) { return getHostname(row).startsWith(META_PREFIX); } protected int getMetaNumber(JSONObject row) { return Integer.parseInt(getHostname(row).substring(META_PREFIX.length())); } protected boolean isOneTimeHost(JSONObject row) { JSONString platform = row.get("platform").isString(); if (platform == null) { return false; } return platform.stringValue().equals(ONE_TIME); } /** * Retrieve the set of selected hosts. */ public HostSelection getSelectedHosts() { HostSelection selection = new HostSelection(); List<JSONObject> selectionArray = selectedHostData.getItems(); for(JSONObject row : selectionArray ) { if (isMetaEntry(row)) { int count = getMetaNumber(row); String platform = row.get("platform").isString().stringValue(); for(int counter = 0; counter < count; counter++) { selection.metaHosts.add(platform); } } else { String hostname = getHostname(row); if (isOneTimeHost(row)) { selection.oneTimeHosts.add(hostname); } else { selection.hosts.add(hostname); } } } return selection; } /** * Reset the widget (deselect all hosts). */ public void reset() { deselectAll(); selectionRefresh(); } /** * Refresh as necessary for selection change, but don't make any RPCs. */ protected void selectionRefresh() { selectedTable.refresh(); availableSelection.refreshSelection(); } public void refresh() { availableTable.refresh(); selectionRefresh(); } }
true
true
public HostSelector() { selectedTable.setClickable(true); selectedTable.setRowsPerPage(TABLE_SIZE); selectedDecorator.addPaginators(); availableTable.setClickable(true); availableDecorator.lockedFilter.setSelectedChoice("No"); availableDecorator.aclFilter.setActive(true); availableTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { availableSelection.toggleSelected(row); availableSelection.refreshSelection(); } public void onTableRefreshed() { availableSelection.refreshSelection(); } }); availableSelection.addListener(new SelectionListener() { public void onAdd(Collection<JSONObject> objects) { for (JSONObject row : objects) { selectRow(row); } selectionRefresh(); } public void onRemove(Collection<JSONObject> objects) { for (JSONObject row : objects) { deselectRow(row); } selectionRefresh(); } }); selectedTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { if (isMetaEntry(row)) { deselectRow(row); selectionRefresh(); } else availableSelection.deselectObject(row); } public void onTableRefreshed() {} }); RootPanel.get("create_available_table").add(availableDecorator); RootPanel.get("create_selected_table").add(selectedDecorator); Button addVisibleButton = new Button("Select visible"); addVisibleButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addVisible(); } }); Button addFilteredButton = new Button("Select all"); addFilteredButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addAllFiltered(); } }); Button removeAllButton = new Button("Select none"); removeAllButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { deselectAll(); } }); Panel availableControls = new HorizontalPanel(); availableControls.add(addVisibleButton); availableControls.add(addFilteredButton); availableControls.add(removeAllButton); RootPanel.get("create_available_controls").add(availableControls); final ListBox metaLabelSelect = new ListBox(); populateLabels(metaLabelSelect); final TextBox metaNumber = new TextBox(); metaNumber.setVisibleLength(4); final Button metaButton = new Button("Add"); metaButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { int selected = metaLabelSelect.getSelectedIndex(); String labelName = metaLabelSelect.getItemText(selected); String label = AfeUtils.decodeLabelName(labelName); String number = metaNumber.getText(); try { Integer.parseInt(number); } catch (NumberFormatException exc) { String error = "Invalid number " + number; NotifyManager.getInstance().showError(error); return; } selectMetaHost(label, number); selectionRefresh(); } }); RootPanel.get("create_meta_select").add(metaLabelSelect); RootPanel.get("create_meta_number").add(metaNumber); RootPanel.get("create_meta_button").add(metaButton); final TextBox oneTimeHostField = new TextBox(); final Button oneTimeHostButton = new Button("Add"); oneTimeHostButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { String hostname = oneTimeHostField.getText(); JSONObject oneTimeObject = new JSONObject(); oneTimeObject.put("hostname", new JSONString(hostname)); oneTimeObject.put("platform", new JSONString(ONE_TIME)); selectRow(oneTimeObject); selectionRefresh(); } }); RootPanel.get("create_one_time_field").add(oneTimeHostField); RootPanel.get("create_one_time_button").add(oneTimeHostButton); }
public HostSelector() { selectedTable.setClickable(true); selectedTable.setRowsPerPage(TABLE_SIZE); selectedDecorator.addPaginators(); availableTable.setClickable(true); availableDecorator.lockedFilter.setSelectedChoice("No"); availableDecorator.aclFilter.setActive(true); availableTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { availableSelection.toggleSelected(row); availableSelection.refreshSelection(); } public void onTableRefreshed() { availableSelection.refreshSelection(); } }); availableSelection.addListener(new SelectionListener() { public void onAdd(Collection<JSONObject> objects) { for (JSONObject row : objects) { selectRow(row); } selectionRefresh(); } public void onRemove(Collection<JSONObject> objects) { for (JSONObject row : objects) { deselectRow(row); } selectionRefresh(); } }); selectedTable.addListener(new DynamicTableListener() { public void onRowClicked(int rowIndex, JSONObject row) { if (isMetaEntry(row) || isOneTimeHost(row)) { deselectRow(row); selectionRefresh(); } else availableSelection.deselectObject(row); } public void onTableRefreshed() {} }); RootPanel.get("create_available_table").add(availableDecorator); RootPanel.get("create_selected_table").add(selectedDecorator); Button addVisibleButton = new Button("Select visible"); addVisibleButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addVisible(); } }); Button addFilteredButton = new Button("Select all"); addFilteredButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { addAllFiltered(); } }); Button removeAllButton = new Button("Select none"); removeAllButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { deselectAll(); } }); Panel availableControls = new HorizontalPanel(); availableControls.add(addVisibleButton); availableControls.add(addFilteredButton); availableControls.add(removeAllButton); RootPanel.get("create_available_controls").add(availableControls); final ListBox metaLabelSelect = new ListBox(); populateLabels(metaLabelSelect); final TextBox metaNumber = new TextBox(); metaNumber.setVisibleLength(4); final Button metaButton = new Button("Add"); metaButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { int selected = metaLabelSelect.getSelectedIndex(); String labelName = metaLabelSelect.getItemText(selected); String label = AfeUtils.decodeLabelName(labelName); String number = metaNumber.getText(); try { Integer.parseInt(number); } catch (NumberFormatException exc) { String error = "Invalid number " + number; NotifyManager.getInstance().showError(error); return; } selectMetaHost(label, number); selectionRefresh(); } }); RootPanel.get("create_meta_select").add(metaLabelSelect); RootPanel.get("create_meta_number").add(metaNumber); RootPanel.get("create_meta_button").add(metaButton); final TextBox oneTimeHostField = new TextBox(); final Button oneTimeHostButton = new Button("Add"); oneTimeHostButton.addClickListener(new ClickListener() { public void onClick(Widget sender) { String hostname = oneTimeHostField.getText(); JSONObject oneTimeObject = new JSONObject(); oneTimeObject.put("hostname", new JSONString(hostname)); oneTimeObject.put("platform", new JSONString(ONE_TIME)); selectRow(oneTimeObject); selectionRefresh(); } }); RootPanel.get("create_one_time_field").add(oneTimeHostField); RootPanel.get("create_one_time_button").add(oneTimeHostButton); }
diff --git a/CallerFlashlight/src/main/java/com/spirosbond/callerflashlight/PrefsActivity.java b/CallerFlashlight/src/main/java/com/spirosbond/callerflashlight/PrefsActivity.java index 94c9896..0f7120b 100644 --- a/CallerFlashlight/src/main/java/com/spirosbond/callerflashlight/PrefsActivity.java +++ b/CallerFlashlight/src/main/java/com/spirosbond/callerflashlight/PrefsActivity.java @@ -1,134 +1,134 @@ package com.spirosbond.callerflashlight; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.util.Log; /** * Created by spiros on 8/5/13. */ public class PrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener { private static final String TAG = PrefsActivity.class.getSimpleName(); ListPreference lp; CallerFlashlight callerFlashlight; CheckBoxPreference screenOfPreference; private boolean dismissed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); callerFlashlight = (CallerFlashlight) this.getApplication(); addPreferencesFromResource(R.xml.prefs); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) getActionBar().setDisplayHomeAsUpEnabled(true); PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); lp = (ListPreference) findPreference("type_list"); lp.setValue(String.valueOf(callerFlashlight.getType())); setTypeSum(callerFlashlight.getType()); screenOfPreference = (CheckBoxPreference) findPreference("screen_off"); screenOfPreference.setOnPreferenceClickListener(this); setScreenOffSum(callerFlashlight.isScreenOffPref()); } private void setScreenOffSum(boolean isChecked) { if (isChecked) { screenOfPreference.setSummary(getResources().getString(R.string.screen_off_ticked_sum)); } else { screenOfPreference.setSummary(getResources().getString(R.string.screen_off_sum)); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { if (CallerFlashlight.LOG) Log.d(TAG, "onSharedPreferenceChanged: " + s); if (s.equals("type_list")) { // lp = (ListPreference) findPreference("type_list"); setTypeSum(Integer.valueOf(sharedPreferences.getString("type_list", ""))); } } public void setTypeSum(int type) { // lp = (ListPreference) findPreference("type_list"); if (CallerFlashlight.LOG) Log.d(TAG, "setTypeSum"); // int type = callerFlashlight.getType(); if (type == 1) { if (CallerFlashlight.LOG) Log.d(TAG, "sum type 1"); lp.setSummary(getResources().getString(R.string.type_list_1)); } else if (type == 2) { if (CallerFlashlight.LOG) Log.d(TAG, "sum type 2"); lp.setSummary(getResources().getString(R.string.type_list_2)); } else if (type == 3) { if (CallerFlashlight.LOG) Log.d(TAG, "sum type 3"); lp.setSummary(getResources().getString(R.string.type_list_3)); } } @Override public boolean onPreferenceClick(Preference preference) { dismissed = true; if ("screen_off".equals(preference.getKey())) { if (!callerFlashlight.isScreenOffPref()) { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=false"); new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.warning)) .setMessage(getResources().getString(R.string.warning_screenoff)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.enable_anyway, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(true); setScreenOffSum(true); screenOfPreference.setChecked(true); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); screenOfPreference.setChecked(false); } - }).setOnDismissListener(new DialogInterface.OnDismissListener() { + }).setCancelable(false)/*.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (dismissed) { if (CallerFlashlight.LOG) Log.d(TAG, "onDismiss"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); } } - }).show(); + })*/.show(); return true; } else { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=true"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); return false; } } return false; } }
false
true
public boolean onPreferenceClick(Preference preference) { dismissed = true; if ("screen_off".equals(preference.getKey())) { if (!callerFlashlight.isScreenOffPref()) { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=false"); new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.warning)) .setMessage(getResources().getString(R.string.warning_screenoff)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.enable_anyway, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(true); setScreenOffSum(true); screenOfPreference.setChecked(true); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); screenOfPreference.setChecked(false); } }).setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (dismissed) { if (CallerFlashlight.LOG) Log.d(TAG, "onDismiss"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); } } }).show(); return true; } else { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=true"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); return false; } } return false; }
public boolean onPreferenceClick(Preference preference) { dismissed = true; if ("screen_off".equals(preference.getKey())) { if (!callerFlashlight.isScreenOffPref()) { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=false"); new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.warning)) .setMessage(getResources().getString(R.string.warning_screenoff)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.enable_anyway, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(true); setScreenOffSum(true); screenOfPreference.setChecked(true); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (CallerFlashlight.LOG) Log.d(TAG, "whichButton: " + whichButton); dismissed = false; callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); screenOfPreference.setChecked(false); } }).setCancelable(false)/*.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (dismissed) { if (CallerFlashlight.LOG) Log.d(TAG, "onDismiss"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); } } })*/.show(); return true; } else { if (CallerFlashlight.LOG) Log.d(TAG, "callerFlashlight.isScreenOffPref()=true"); screenOfPreference.setChecked(false); callerFlashlight.setScreenOffPref(false); setScreenOffSum(false); return false; } } return false; }
diff --git a/LauncherV4/src/it/planetgeeks/mclauncher/frames/LauncherFrame.java b/LauncherV4/src/it/planetgeeks/mclauncher/frames/LauncherFrame.java index 00d729c..0e33e77 100644 --- a/LauncherV4/src/it/planetgeeks/mclauncher/frames/LauncherFrame.java +++ b/LauncherV4/src/it/planetgeeks/mclauncher/frames/LauncherFrame.java @@ -1,256 +1,256 @@ package it.planetgeeks.mclauncher.frames; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import it.planetgeeks.mclauncher.Launcher; import it.planetgeeks.mclauncher.frames.panels.LoginPanel; import it.planetgeeks.mclauncher.frames.panels.MainPanel; import it.planetgeeks.mclauncher.frames.utils.CustomMouseListener; import it.planetgeeks.mclauncher.utils.LanguageUtils; import javax.swing.ButtonGroup; import javax.swing.GroupLayout; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import javax.swing.LayoutStyle; import javax.swing.WindowConstants; public class LauncherFrame extends JFrame { private static final long serialVersionUID = 1L; public LauncherFrame() { dim = new Dimension(); dim.width = 840; dim.height = 530; initComponents(); } private void initComponents() { setTitle(LanguageUtils.getTranslated("launcher.title")); this.setMinimumSize(dim); loginPanel = new LoginPanel(); mainPanel = new MainPanel(); menuBar = new JMenuBar(); menu1 = new JMenu(); menu2 = new JMenu(); menu3 = new JMenu(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); menuBar.add(menu1); menuBar.add(menu2); menuBar.add(menu3); setJMenuBar(menuBar); setMenu(); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(loginPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(mainPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(mainPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(loginPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))); pack(); } private void setMenu() { menu1.setText(LanguageUtils.getTranslated("lancher.bar.file")); menu2.setText(LanguageUtils.getTranslated("launcher.bar.options")); menu3.setText(LanguageUtils.getTranslated("launcher.bar.info")); Object items1[][] = { { "Esci", KeyEvent.VK_E, KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK), "normal" } }; menuItemCreation(menu1, items1); menu1.setMnemonic(KeyEvent.VK_F); menu1.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.closeLauncher(); } }); Object items2[][] = { { LanguageUtils.getTranslated("launcher.bar.options.manageMem"), KeyEvent.VK_M, KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.options.showConsole"), KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK), "check" }, { "separator" }, { LanguageUtils.getTranslated("launcher.bar.options.advanced"), KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu2, items2); menu2.setMnemonic(KeyEvent.VK_O); menu2.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openMemoryEditor(0, null); } }); menu2.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseConsole(); } }); menu2.getItem(3).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseOptionsFrame(); } }); menu2.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { ((JCheckBoxMenuItem) menu2.getItem(1)).setSelected(Launcher.isConsoleOpened()); ((JCheckBoxMenuItem) menu2.getItem(4)).setSelected(Launcher.isAdvOptionsOpened()); } }); String langs[] = LanguageUtils.getNames(); Object items[][] = new String[langs.length][4]; for (int i = 0; i < langs.length; i++) { items[i][0] = langs[i]; items[i][1] = null; items[i][2] = null; items[i][3] = "check"; } JMenu menuLanguage = new JMenu(LanguageUtils.getTranslated("launcher.bar.options.language")); menuLanguage.setMnemonic(KeyEvent.VK_L); menuItemCreation(menuLanguage, items); for (int i = 0; i < langs.length; i++) { temp = i; menuLanguage.getItem(i).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { LanguageUtils.setLanguage(temp); } }); temp = 0; } menuLanguage.getItem(LanguageUtils.getCurrentLangIndex()).setSelected(true); menu2.add(menuLanguage, 2); Object items3[][] = { { LanguageUtils.getTranslated("launcher.bar.info.website"), KeyEvent.VK_W, KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.info.info"), KeyEvent.VK_I, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu3, items3); menu3.setMnemonic(KeyEvent.VK_QUOTE); menu3.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseInfoFrame(); } }); menu3.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { - ((JCheckBoxMenuItem) menu2.getItem(1)).setSelected(Launcher.isInfoOpened()); + ((JCheckBoxMenuItem) menu3.getItem(1)).setSelected(Launcher.isInfoOpened()); } }); } private void menuItemCreation(JMenu menu, Object data[][]) { ButtonGroup bg = new ButtonGroup(); JMenuItem item = null; for (int i = 0; i < data.length; i++) { if (data[i].length > 1) { if (data[i][3].equals("normal")) { item = new JMenuItem(); } else if (data[i][3].equals("radio")) { item = new JRadioButtonMenuItem(); bg.add(item); } else if (data[i][3].equals("check")) { item = new JCheckBoxMenuItem(); } } else { item = new JMenuItem(); } String data0 = (String) data[i][0]; if (data0.equals("separator")) menu.addSeparator(); else { String text = data0; Integer mnemonic = data[i][1] != null ? (Integer) data[i][1] : KeyEvent.VK_UNDEFINED; KeyStroke accelerator = data[i][2] != null ? (KeyStroke) data[i][2] : null; item.setText(text); item.setMnemonic(mnemonic); item.setAccelerator(accelerator); menu.add(item); } } } private Dimension dim; private JMenu menu1; private JMenu menu2; private JMenu menu3; private JMenuBar menuBar; public MainPanel mainPanel; public LoginPanel loginPanel; private int temp; }
true
true
private void setMenu() { menu1.setText(LanguageUtils.getTranslated("lancher.bar.file")); menu2.setText(LanguageUtils.getTranslated("launcher.bar.options")); menu3.setText(LanguageUtils.getTranslated("launcher.bar.info")); Object items1[][] = { { "Esci", KeyEvent.VK_E, KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK), "normal" } }; menuItemCreation(menu1, items1); menu1.setMnemonic(KeyEvent.VK_F); menu1.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.closeLauncher(); } }); Object items2[][] = { { LanguageUtils.getTranslated("launcher.bar.options.manageMem"), KeyEvent.VK_M, KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.options.showConsole"), KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK), "check" }, { "separator" }, { LanguageUtils.getTranslated("launcher.bar.options.advanced"), KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu2, items2); menu2.setMnemonic(KeyEvent.VK_O); menu2.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openMemoryEditor(0, null); } }); menu2.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseConsole(); } }); menu2.getItem(3).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseOptionsFrame(); } }); menu2.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { ((JCheckBoxMenuItem) menu2.getItem(1)).setSelected(Launcher.isConsoleOpened()); ((JCheckBoxMenuItem) menu2.getItem(4)).setSelected(Launcher.isAdvOptionsOpened()); } }); String langs[] = LanguageUtils.getNames(); Object items[][] = new String[langs.length][4]; for (int i = 0; i < langs.length; i++) { items[i][0] = langs[i]; items[i][1] = null; items[i][2] = null; items[i][3] = "check"; } JMenu menuLanguage = new JMenu(LanguageUtils.getTranslated("launcher.bar.options.language")); menuLanguage.setMnemonic(KeyEvent.VK_L); menuItemCreation(menuLanguage, items); for (int i = 0; i < langs.length; i++) { temp = i; menuLanguage.getItem(i).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { LanguageUtils.setLanguage(temp); } }); temp = 0; } menuLanguage.getItem(LanguageUtils.getCurrentLangIndex()).setSelected(true); menu2.add(menuLanguage, 2); Object items3[][] = { { LanguageUtils.getTranslated("launcher.bar.info.website"), KeyEvent.VK_W, KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.info.info"), KeyEvent.VK_I, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu3, items3); menu3.setMnemonic(KeyEvent.VK_QUOTE); menu3.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseInfoFrame(); } }); menu3.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { ((JCheckBoxMenuItem) menu2.getItem(1)).setSelected(Launcher.isInfoOpened()); } }); }
private void setMenu() { menu1.setText(LanguageUtils.getTranslated("lancher.bar.file")); menu2.setText(LanguageUtils.getTranslated("launcher.bar.options")); menu3.setText(LanguageUtils.getTranslated("launcher.bar.info")); Object items1[][] = { { "Esci", KeyEvent.VK_E, KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK), "normal" } }; menuItemCreation(menu1, items1); menu1.setMnemonic(KeyEvent.VK_F); menu1.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.closeLauncher(); } }); Object items2[][] = { { LanguageUtils.getTranslated("launcher.bar.options.manageMem"), KeyEvent.VK_M, KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.options.showConsole"), KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK), "check" }, { "separator" }, { LanguageUtils.getTranslated("launcher.bar.options.advanced"), KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu2, items2); menu2.setMnemonic(KeyEvent.VK_O); menu2.getItem(0).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openMemoryEditor(0, null); } }); menu2.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseConsole(); } }); menu2.getItem(3).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseOptionsFrame(); } }); menu2.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { ((JCheckBoxMenuItem) menu2.getItem(1)).setSelected(Launcher.isConsoleOpened()); ((JCheckBoxMenuItem) menu2.getItem(4)).setSelected(Launcher.isAdvOptionsOpened()); } }); String langs[] = LanguageUtils.getNames(); Object items[][] = new String[langs.length][4]; for (int i = 0; i < langs.length; i++) { items[i][0] = langs[i]; items[i][1] = null; items[i][2] = null; items[i][3] = "check"; } JMenu menuLanguage = new JMenu(LanguageUtils.getTranslated("launcher.bar.options.language")); menuLanguage.setMnemonic(KeyEvent.VK_L); menuItemCreation(menuLanguage, items); for (int i = 0; i < langs.length; i++) { temp = i; menuLanguage.getItem(i).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { LanguageUtils.setLanguage(temp); } }); temp = 0; } menuLanguage.getItem(LanguageUtils.getCurrentLangIndex()).setSelected(true); menu2.add(menuLanguage, 2); Object items3[][] = { { LanguageUtils.getTranslated("launcher.bar.info.website"), KeyEvent.VK_W, KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK), "normal" }, { LanguageUtils.getTranslated("launcher.bar.info.info"), KeyEvent.VK_I, KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK), "check" } }; menuItemCreation(menu3, items3); menu3.setMnemonic(KeyEvent.VK_QUOTE); menu3.getItem(1).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Launcher.openOrCloseInfoFrame(); } }); menu3.addMouseListener(new CustomMouseListener() { @Override public void mousePressed(MouseEvent e) { ((JCheckBoxMenuItem) menu3.getItem(1)).setSelected(Launcher.isInfoOpened()); } }); }
diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java index ef82637..2e90964 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java @@ -1,381 +1,381 @@ package com.earth2me.essentials; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.craftbukkit.block.CraftSign; import org.bukkit.event.block.*; import org.bukkit.inventory.ItemStack; public class EssentialsBlockListener extends BlockListener { private final Essentials ess; private static final Logger logger = Logger.getLogger("Minecraft"); public final static ArrayList<Material> protectedBlocks = new ArrayList<Material>(4); static { protectedBlocks.add(Material.CHEST); protectedBlocks.add(Material.BURNING_FURNACE); protectedBlocks.add(Material.FURNACE); protectedBlocks.add(Material.DISPENSER); } public EssentialsBlockListener(Essentials ess) { this.ess = ess; } @Override public void onBlockBreak(BlockBreakEvent event) { if (event.isCancelled()) return; if (ess.getSettings().areSignsDisabled()) return; User user = ess.getUser(event.getPlayer()); if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override")) { if (isBlockProtected(event.getBlock(), user)) { event.setCancelled(true); user.sendMessage(Util.format("noDestroyPermission", event.getBlock().getType().toString().toLowerCase())); return; } } if (checkProtectionSign(event.getBlock(), user) != NOSIGN && checkProtectionSign(event.getBlock(), user) != OWNER) { event.setCancelled(true); user.sendMessage(Util.format("noDestroyPermission", event.getBlock().getType().toString().toLowerCase())); } } @Override public void onSignChange(SignChangeEvent event) { if (event.isCancelled()) return; if (ess.getSettings().areSignsDisabled()) return; User user = ess.getUser(event.getPlayer()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); try { if (event.getLine(0).equalsIgnoreCase("[Protection]")) { Block block = event.getBlock(); if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user)) event.setLine(0, "§1[Protection]"); else event.setLine(0, "§4[Protection]"); event.setLine(3, username); return; } if (event.getLine(0).equalsIgnoreCase("[Disposal]")) { if (user.isAuthorized("essentials.signs.disposal.create")) event.setLine(0, "§1[Disposal]"); else event.setLine(0, "§4[Disposal]"); return; } if (event.getLine(0).equalsIgnoreCase("[Heal]")) { event.setLine(0, "§4[Heal]"); if (user.isAuthorized("essentials.signs.heal.create")) { if (!event.getLine(1).isEmpty()) { String[] l1 = event.getLine(1).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if (q1 < 1 || (!m1 && (int)q1 < 1)) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } event.setLine(0, "§1[Heal]"); } return; } if (event.getLine(0).equalsIgnoreCase("[Free]")) { event.setLine(0, "§4[Free]"); ItemDb.get(event.getLine(1)); if (user.isAuthorized("essentials.signs.free.create")) event.setLine(0, "§1[Free]"); return; } if (event.getLine(0).equalsIgnoreCase("[Mail]")) { if (user.isAuthorized("essentials.signs.mail.create")) event.setLine(0, "§1[Mail]"); else event.setLine(0, "§4[Mail]"); return; } if (event.getLine(0).equalsIgnoreCase("[Balance]")) { if (user.isAuthorized("essentials.signs.balance.create")) event.setLine(0, "§1[Balance]"); else event.setLine(0, "§4[Balance]"); return; } if (event.getLine(0).equalsIgnoreCase("[Warp]")) { event.setLine(0, "§4[Warp]"); if (user.isAuthorized("essentials.signs.warp.create")) { if (!event.getLine(3).isEmpty()) { String[] l1 = event.getLine(3).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if ((int)q1 < 1) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(3, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } if (event.getLine(1).isEmpty()) { - event.setLine(1, "§dWarp name here!"); + event.setLine(1, "§dWarp name!"); return; } else { Essentials.getWarps().getWarp(event.getLine(1)); if (event.getLine(2).equalsIgnoreCase("Everyone")) { event.setLine(2, "§2Everyone"); } event.setLine(0, "§1[Warp]"); } } return; } } catch (Throwable ex) { user.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, ex.getMessage(), ex); } } } @Override public void onBlockPlace(BlockPlaceEvent event) { if (event.isCancelled()) return; Block signBlock = event.getBlockAgainst(); if (signBlock.getType() == Material.WALL_SIGN || signBlock.getType() == Material.SIGN_POST) { Sign sign = new CraftSign(signBlock); if (sign.getLine(0).matches("§1\\[[a-zA-Z]+\\]")) { event.setCancelled(true); return; } } final User user = ess.getUser(event.getPlayer()); // Do not rely on getItemInHand(); // http://leaky.bukkit.org/issues/663 final ItemStack is = new ItemStack(event.getBlockPlaced().getType(), 1, (short)0, event.getBlockPlaced().getData()); switch(is.getType()) { case WOODEN_DOOR: is.setType(Material.WOOD_DOOR); is.setDurability((short)0); break; case IRON_DOOR_BLOCK: is.setType(Material.IRON_DOOR); is.setDurability((short)0); break; case SIGN_POST: case WALL_SIGN: is.setType(Material.SIGN); is.setDurability((short)0); break; case CROPS: is.setType(Material.SEEDS); is.setDurability((short)0); break; case CAKE_BLOCK: is.setType(Material.CAKE); is.setDurability((short)0); break; case BED_BLOCK: is.setType(Material.BED); is.setDurability((short)0); break; case REDSTONE_WIRE: is.setType(Material.REDSTONE); is.setDurability((short)0); break; case REDSTONE_TORCH_OFF: case REDSTONE_TORCH_ON: is.setType(Material.REDSTONE_TORCH_ON); is.setDurability((short)0); break; case DIODE_BLOCK_OFF: case DIODE_BLOCK_ON: is.setType(Material.DIODE); is.setDurability((short)0); break; case DOUBLE_STEP: is.setType(Material.STEP); break; case TORCH: case RAILS: case LADDER: case WOOD_STAIRS: case COBBLESTONE_STAIRS: case LEVER: case STONE_BUTTON: case FURNACE: case DISPENSER: case PUMPKIN: case JACK_O_LANTERN: case WOOD_PLATE: case STONE_PLATE: is.setDurability((short)0); break; } boolean unlimitedForUser = user.hasUnlimited(is); if (unlimitedForUser) { ess.getScheduler().scheduleSyncDelayedTask(ess, new Runnable() { public void run() { user.getInventory().addItem(is); user.updateInventory(); } }); } } public boolean hasAdjacentChest(Block block) { Block[] faces = getAdjacentBlocks(block); for (Block b : faces) { if (protectedBlocks.contains(b.getType())) { return true; } } return false; } private static final int NOT_ALLOWED = 0; private static final int ALLOWED = 1; private static final int NOSIGN = 2; private static final int OWNER = 3; private int checkProtectionSign(Block block, User user) { String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) { Sign sign = new CraftSign(block); if (sign.getLine(0).equalsIgnoreCase("§1[Protection]") && !user.isAuthorized("essentials.signs.protection.override")) { for (int i = 1; i <= 2; i++) { String line = sign.getLine(i); if (line.startsWith("(") && line.endsWith(")")) { line = line.substring(1, line.length() - 1); if (user.inGroup(line)) { return ALLOWED; } } else if (line.equalsIgnoreCase(username)) { return ALLOWED; } } if (sign.getLine(3).equalsIgnoreCase(username)) { return OWNER; } return NOT_ALLOWED; } } return NOSIGN; } private static Block[] getAdjacentBlocks(Block block) { return new Block[] { block.getFace(BlockFace.NORTH), block.getFace(BlockFace.SOUTH), block.getFace(BlockFace.EAST), block.getFace(BlockFace.WEST), block.getFace(BlockFace.DOWN), block.getFace(BlockFace.UP) }; } public boolean isBlockProtected(Block block, User user) { Block[] faces = getAdjacentBlocks(block); boolean protect = false; for (Block b : faces) { int check = checkProtectionSign(b, user); if (check == NOT_ALLOWED) { protect = true; } if (check == ALLOWED || check == OWNER) { return false; } if (protectedBlocks.contains(b.getType())) { Block[] faceChest = getAdjacentBlocks(b); for (Block a : faceChest) { check = checkProtectionSign(a, user); if (check == NOT_ALLOWED) { protect = true; } if (check == ALLOWED || check == OWNER) { return false; } } } } return protect; } public static boolean isBlockProtected(Block block) { Block[] faces = getAdjacentBlocks(block); for (Block b : faces) { if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN) { Sign sign = new CraftSign(b); if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) { return true; } } if (protectedBlocks.contains(b.getType())) { Block[] faceChest = getAdjacentBlocks(b); for (Block a : faceChest) { if (a.getType() == Material.SIGN_POST || a.getType() == Material.WALL_SIGN) { Sign sign = new CraftSign(a); if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) { return true; } } } } } return false; } }
true
true
public void onSignChange(SignChangeEvent event) { if (event.isCancelled()) return; if (ess.getSettings().areSignsDisabled()) return; User user = ess.getUser(event.getPlayer()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); try { if (event.getLine(0).equalsIgnoreCase("[Protection]")) { Block block = event.getBlock(); if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user)) event.setLine(0, "§1[Protection]"); else event.setLine(0, "§4[Protection]"); event.setLine(3, username); return; } if (event.getLine(0).equalsIgnoreCase("[Disposal]")) { if (user.isAuthorized("essentials.signs.disposal.create")) event.setLine(0, "§1[Disposal]"); else event.setLine(0, "§4[Disposal]"); return; } if (event.getLine(0).equalsIgnoreCase("[Heal]")) { event.setLine(0, "§4[Heal]"); if (user.isAuthorized("essentials.signs.heal.create")) { if (!event.getLine(1).isEmpty()) { String[] l1 = event.getLine(1).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if (q1 < 1 || (!m1 && (int)q1 < 1)) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } event.setLine(0, "§1[Heal]"); } return; } if (event.getLine(0).equalsIgnoreCase("[Free]")) { event.setLine(0, "§4[Free]"); ItemDb.get(event.getLine(1)); if (user.isAuthorized("essentials.signs.free.create")) event.setLine(0, "§1[Free]"); return; } if (event.getLine(0).equalsIgnoreCase("[Mail]")) { if (user.isAuthorized("essentials.signs.mail.create")) event.setLine(0, "§1[Mail]"); else event.setLine(0, "§4[Mail]"); return; } if (event.getLine(0).equalsIgnoreCase("[Balance]")) { if (user.isAuthorized("essentials.signs.balance.create")) event.setLine(0, "§1[Balance]"); else event.setLine(0, "§4[Balance]"); return; } if (event.getLine(0).equalsIgnoreCase("[Warp]")) { event.setLine(0, "§4[Warp]"); if (user.isAuthorized("essentials.signs.warp.create")) { if (!event.getLine(3).isEmpty()) { String[] l1 = event.getLine(3).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if ((int)q1 < 1) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(3, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } if (event.getLine(1).isEmpty()) { event.setLine(1, "§dWarp name here!"); return; } else { Essentials.getWarps().getWarp(event.getLine(1)); if (event.getLine(2).equalsIgnoreCase("Everyone")) { event.setLine(2, "§2Everyone"); } event.setLine(0, "§1[Warp]"); } } return; } } catch (Throwable ex) { user.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, ex.getMessage(), ex); } } }
public void onSignChange(SignChangeEvent event) { if (event.isCancelled()) return; if (ess.getSettings().areSignsDisabled()) return; User user = ess.getUser(event.getPlayer()); String username = user.getName().substring(0, user.getName().length() > 14 ? 14 : user.getName().length()); try { if (event.getLine(0).equalsIgnoreCase("[Protection]")) { Block block = event.getBlock(); if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user)) event.setLine(0, "§1[Protection]"); else event.setLine(0, "§4[Protection]"); event.setLine(3, username); return; } if (event.getLine(0).equalsIgnoreCase("[Disposal]")) { if (user.isAuthorized("essentials.signs.disposal.create")) event.setLine(0, "§1[Disposal]"); else event.setLine(0, "§4[Disposal]"); return; } if (event.getLine(0).equalsIgnoreCase("[Heal]")) { event.setLine(0, "§4[Heal]"); if (user.isAuthorized("essentials.signs.heal.create")) { if (!event.getLine(1).isEmpty()) { String[] l1 = event.getLine(1).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if (q1 < 1 || (!m1 && (int)q1 < 1)) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(1, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } event.setLine(0, "§1[Heal]"); } return; } if (event.getLine(0).equalsIgnoreCase("[Free]")) { event.setLine(0, "§4[Free]"); ItemDb.get(event.getLine(1)); if (user.isAuthorized("essentials.signs.free.create")) event.setLine(0, "§1[Free]"); return; } if (event.getLine(0).equalsIgnoreCase("[Mail]")) { if (user.isAuthorized("essentials.signs.mail.create")) event.setLine(0, "§1[Mail]"); else event.setLine(0, "§4[Mail]"); return; } if (event.getLine(0).equalsIgnoreCase("[Balance]")) { if (user.isAuthorized("essentials.signs.balance.create")) event.setLine(0, "§1[Balance]"); else event.setLine(0, "§4[Balance]"); return; } if (event.getLine(0).equalsIgnoreCase("[Warp]")) { event.setLine(0, "§4[Warp]"); if (user.isAuthorized("essentials.signs.warp.create")) { if (!event.getLine(3).isEmpty()) { String[] l1 = event.getLine(3).split("[ :-]+", 2); boolean m1 = l1[0].matches("^[^0-9][\\.0-9]+"); double q1 = Double.parseDouble(m1 ? l1[0].substring(1) : l1[0]); if ((int)q1 < 1) throw new Exception(Util.i18n("moreThanZero")); if (!m1) ItemDb.get(l1[1]); event.setLine(3, (m1 ? Util.formatCurrency(q1) : (int)q1 + " " + l1[1])); } if (event.getLine(1).isEmpty()) { event.setLine(1, "§dWarp name!"); return; } else { Essentials.getWarps().getWarp(event.getLine(1)); if (event.getLine(2).equalsIgnoreCase("Everyone")) { event.setLine(2, "§2Everyone"); } event.setLine(0, "§1[Warp]"); } } return; } } catch (Throwable ex) { user.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, ex.getMessage(), ex); } } }
diff --git a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java index 090dfad2a..4b946aee9 100644 --- a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java +++ b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java @@ -1,2091 +1,2091 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.impl.xs.traversers; import java.io.IOException; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.xs.SchemaGrammar; import org.apache.xerces.impl.xs.SchemaNamespaceSupport; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XMLSchemaException; import org.apache.xerces.impl.xs.XMLSchemaLoader; import org.apache.xerces.impl.xs.XSComplexTypeDecl; import org.apache.xerces.impl.xs.XSDDescription; import org.apache.xerces.impl.xs.XSDeclarationPool; import org.apache.xerces.impl.xs.XSElementDecl; import org.apache.xerces.impl.xs.XSGrammarBucket; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.impl.xs.XSParticleDecl; import org.apache.xerces.impl.xs.dom.ElementNSImpl; import org.apache.xerces.impl.xs.opti.ElementImpl; import org.apache.xerces.impl.xs.opti.SchemaParsingConfig; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * The purpose of this class is to co-ordinate the construction of a * grammar object corresponding to a schema. To do this, it must be * prepared to parse several schema documents (for instance if the * schema document originally referred to contains <include> or * <redefined> information items). If any of the schemas imports a * schema, other grammars may be constructed as a side-effect. * * @author Neil Graham, IBM * @author Pavani Mukthipudi, Sun Microsystems * @version $Id$ */ public class XSDHandler { /** Feature identifier: allow java encodings */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: continue after fatal error */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; /** Feature identifier: allow java encodings */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; protected static final boolean DEBUG_NODE_POOL = false; // Data // different sorts of declarations; should make lookup and // traverser calling more efficient/less bulky. final static int ATTRIBUTE_TYPE = 1; final static int ATTRIBUTEGROUP_TYPE = 2; final static int ELEMENT_TYPE = 3; final static int GROUP_TYPE = 4; final static int IDENTITYCONSTRAINT_TYPE = 5; final static int NOTATION_TYPE = 6; final static int TYPEDECL_TYPE = 7; // this string gets appended to redefined names; it's purpose is to be // as unlikely as possible to cause collisions. public final static String REDEF_IDENTIFIER = "_fn3dktizrknc9pi"; // //protected data that can be accessable by any traverser // stores <notation> decl protected Hashtable fNotationRegistry = new Hashtable(); protected XSDeclarationPool fDeclPool = null; // are java encodings allowed? private boolean fAllowJavaEncodings = false; // enforcing strict uri? private boolean fStrictURI = false; // These tables correspond to the symbol spaces defined in the // spec. // They are keyed with a QName (that is, String("URI,localpart) and // their values are nodes corresponding to the given name's decl. // By asking the node for its ownerDocument and looking in // XSDocumentInfoRegistry we can easily get the corresponding // XSDocumentInfo object. private Hashtable fUnparsedAttributeRegistry = new Hashtable(); private Hashtable fUnparsedAttributeGroupRegistry = new Hashtable(); private Hashtable fUnparsedElementRegistry = new Hashtable(); private Hashtable fUnparsedGroupRegistry = new Hashtable(); private Hashtable fUnparsedIdentityConstraintRegistry = new Hashtable(); private Hashtable fUnparsedNotationRegistry = new Hashtable(); private Hashtable fUnparsedTypeRegistry = new Hashtable(); // this is keyed with a documentNode (or the schemaRoot nodes // contained in the XSDocumentInfo objects) and its value is the // XSDocumentInfo object corresponding to that document. // Basically, the function of this registry is to be a link // between the nodes we fetch from calls to the fUnparsed* // arrays and the XSDocumentInfos they live in. private Hashtable fXSDocumentInfoRegistry = new Hashtable(); // this hashtable is keyed on by XSDocumentInfo objects. Its values // are Vectors containing the XSDocumentInfo objects <include>d, // <import>ed or <redefine>d by the key XSDocumentInfo. private Hashtable fDependencyMap = new Hashtable(); // this hashtable is keyed on by a target namespace. Its values // are Vectors containing namespaces imported by schema documents // with the key target namespace. // if an imprted schema has absent namespace, the value "null" is stored. private Hashtable fImportMap = new Hashtable(); // all namespaces that imports other namespaces // if the importing schema has absent namespace, empty string is stored. // (because the key of a hashtable can't be null.) private Vector fAllTNSs = new Vector(); // stores instance document mappings between namespaces and schema hints private Hashtable fLocationPairs = null; // convenience methods private String null2EmptyString(String ns) { return ns == null ? XMLSymbols.EMPTY_STRING : ns; } private String emptyString2Null(String ns) { return ns == XMLSymbols.EMPTY_STRING ? null : ns; } // This vector stores strings which are combinations of the // publicId and systemId of the inputSource corresponding to a // schema document. This combination is used so that the user's // EntityResolver can provide a consistent way of identifying a // schema document that is included in multiple other schemas. private Hashtable fTraversed = new Hashtable(); // this hashtable contains a mapping from Document to its systemId // this is useful to resolve a uri relative to the referring document private Hashtable fDoc2SystemId = new Hashtable(); // the primary XSDocumentInfo we were called to parse private XSDocumentInfo fRoot = null; // This hashtable's job is to act as a link between the document // node at the root of the parsed schema's tree and its // XSDocumentInfo object. private Hashtable fDoc2XSDocumentMap = new Hashtable(); // map between <redefine> elements and the XSDocumentInfo // objects that correspond to the documents being redefined. private Hashtable fRedefine2XSDMap = new Hashtable(); // map between <redefine> elements and the namespace support private Hashtable fRedefine2NSSupport = new Hashtable(); // these objects store a mapping between the names of redefining // groups/attributeGroups and the groups/AttributeGroups which // they redefine by restriction (implicitly). It is up to the // Group and AttributeGroup traversers to check these restrictions for // validity. private Hashtable fRedefinedRestrictedAttributeGroupRegistry = new Hashtable(); private Hashtable fRedefinedRestrictedGroupRegistry = new Hashtable(); // a variable storing whether the last schema document // processed (by getSchema) was a duplicate. private boolean fLastSchemaWasDuplicate; // the XMLErrorReporter private XMLErrorReporter fErrorReporter; private XMLEntityResolver fEntityResolver; // the XSAttributeChecker private XSAttributeChecker fAttributeChecker; // the symbol table private SymbolTable fSymbolTable; // the GrammarResolver private XSGrammarBucket fGrammarBucket; // the Grammar description private XSDDescription fSchemaGrammarDescription; // the Grammar Pool private XMLGrammarPool fGrammarPool; //************ Traversers ********** XSDAttributeGroupTraverser fAttributeGroupTraverser; XSDAttributeTraverser fAttributeTraverser; XSDComplexTypeTraverser fComplexTypeTraverser; XSDElementTraverser fElementTraverser; XSDGroupTraverser fGroupTraverser; XSDKeyrefTraverser fKeyrefTraverser; XSDNotationTraverser fNotationTraverser; XSDSimpleTypeTraverser fSimpleTypeTraverser; XSDUniqueOrKeyTraverser fUniqueOrKeyTraverser; XSDWildcardTraverser fWildCardTraverser; //DOMParser fSchemaParser; SchemaParsingConfig fSchemaParser; // these data members are needed for the deferred traversal // of local elements. // the initial size of the array to store deferred local elements private static final int INIT_STACK_SIZE = 30; // the incremental size of the array to store deferred local elements private static final int INC_STACK_SIZE = 10; // current position of the array (# of deferred local elements) private int fLocalElemStackPos = 0; private XSParticleDecl[] fParticle = new XSParticleDecl[INIT_STACK_SIZE]; private Element[] fLocalElementDecl = new Element[INIT_STACK_SIZE]; private int[] fAllContext = new int[INIT_STACK_SIZE]; private XSComplexTypeDecl[] fEnclosingCT = new XSComplexTypeDecl[INIT_STACK_SIZE]; private String [][] fLocalElemNamespaceContext = new String [INIT_STACK_SIZE][1]; // these data members are needed for the deferred traversal // of keyrefs. // the initial size of the array to store deferred keyrefs private static final int INIT_KEYREF_STACK = 2; // the incremental size of the array to store deferred keyrefs private static final int INC_KEYREF_STACK_AMOUNT = 2; // current position of the array (# of deferred keyrefs) private int fKeyrefStackPos = 0; private Element [] fKeyrefs = new Element[INIT_KEYREF_STACK]; private XSElementDecl [] fKeyrefElems = new XSElementDecl [INIT_KEYREF_STACK]; private String [][] fKeyrefNamespaceContext = new String[INIT_KEYREF_STACK][1]; // Constructors // it should be possible to use the same XSDHandler to parse // multiple schema documents; this will allow one to be // constructed. public XSDHandler (XSGrammarBucket gBucket) { fGrammarBucket = gBucket; // Note: don't use SchemaConfiguration internally // we will get stack overflaw because // XMLSchemaValidator will be instantiating XSDHandler... fSchemaGrammarDescription = new XSDDescription(); } // end constructor // This method initiates the parse of a schema. It will likely be // called from the Validator and it will make the // resulting grammar available; it returns a reference to this object just // in case. An ErrorHandler, EntityResolver, XSGrammarBucket and SymbolTable must // already have been set; the last thing this method does is reset // this object (i.e., clean the registries, etc.). public SchemaGrammar parseSchema(XMLInputSource is, XSDDescription desc, Hashtable locationPairs) throws IOException { fLocationPairs = locationPairs; // first try to find it in the bucket/pool, return if one is found SchemaGrammar grammar = findGrammar(desc); if (grammar != null) return grammar; if (fSchemaParser != null) { fSchemaParser.resetNodePool(); } short referType = desc.getContextType(); String schemaNamespace = desc.getTargetNamespace(); // handle empty string URI as null if (schemaNamespace != null) { schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); } // before parsing a schema, need to clear registries associated with // parsing schemas prepareForParse(); // first phase: construct trees. Document schemaRoot = getSchema(schemaNamespace, is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); if (schemaRoot == null) { // something went wrong right off the hop return null; } if ( schemaNamespace == null && referType == XSDDescription.CONTEXT_PREPARSE) { Element schemaElem = DOMUtil.getRoot(schemaRoot); schemaNamespace = DOMUtil.getAttrValue(schemaElem, SchemaSymbols.ATT_TARGETNAMESPACE); if(schemaNamespace != null && schemaNamespace.length() > 0) { schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); desc.setTargetNamespace(schemaNamespace); String schemaId = XMLEntityManager.expandSystemId(desc.getLiteralSystemId(), desc.getBaseSystemId(), false); XSDKey key = new XSDKey(schemaId, referType, schemaNamespace); fTraversed.put(key, schemaRoot ); if (schemaId != null) { fDoc2SystemId.put(schemaRoot, schemaId ); } } } // before constructing trees and traversing a schema, need to reset // all traversers and clear all registries prepareForTraverse(); fRoot = constructTrees(schemaRoot, is.getSystemId(), desc); if (fRoot == null) { return null; } // second phase: fill global registries. buildGlobalNameRegistries(); // third phase: call traversers traverseSchemas(); // fourth phase: handle local element decls traverseLocalElements(); // fifth phase: handle Keyrefs resolveKeyRefs(); // sixth phase: validate attribute of non-schema namespaces // REVISIT: skip this for now. we really don't want to do it. //fAttributeChecker.checkNonSchemaAttributes(fGrammarBucket); // seventh phase: store imported grammars // for all grammars with <import>s for (int i = fAllTNSs.size() - 1; i >= 0; i--) { // get its target namespace String tns = (String)fAllTNSs.elementAt(i); // get all namespaces it imports Vector ins = (Vector)fImportMap.get(tns); // get the grammar SchemaGrammar sg = fGrammarBucket.getGrammar(emptyString2Null(tns)); if (sg == null) continue; SchemaGrammar isg; // for imported namespace int count = 0; for (int j = 0; j < ins.size(); j++) { // get imported grammar isg = fGrammarBucket.getGrammar((String)ins.elementAt(j)); // reuse the same vector if (isg != null) ins.setElementAt(isg, count++); } ins.setSize(count); // set the imported grammars sg.setImportedGrammars(ins); } // and return. return fGrammarBucket.getGrammar(fRoot.fTargetNamespace); } // end parseSchema /** * First try to find a grammar in the bucket, if failed, consult the * grammar pool. If a grammar is found in the pool, then add it (and all * imported ones) into the bucket. */ protected SchemaGrammar findGrammar(XSDDescription desc) { SchemaGrammar sg = fGrammarBucket.getGrammar(desc.getTargetNamespace()); if (sg == null) { if (fGrammarPool != null) { sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc); if (sg != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(sg, true)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? reportSchemaWarning("GrammarConflict", null, null); sg = null; } } } } return sg; } // may wish to have setter methods for ErrorHandler, // EntityResolver... private static final String[][] NS_ERROR_CODES = { {"src-include.2.1", "src-include.2.1"}, {"src-redefine.3.1", "src-redefine.3.1"}, {"src-import.3.1", "src-import.3.2"}, null, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"} }; private static final String[] ELE_ERROR_CODES = { "src-include.1", "src-redefine.2", "src-import.2", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4" }; // This method does several things: // It constructs an instance of an XSDocumentInfo object using the // schemaRoot node. Then, for each <include>, // <redefine>, and <import> children, it attempts to resolve the // requested schema document, initiates a DOM parse, and calls // itself recursively on that document's root. It also records in // the DependencyMap object what XSDocumentInfo objects its XSDocumentInfo // depends on. // It also makes sure the targetNamespace of the schema it was // called to parse is correct. protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree //sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo)); - sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo)); + sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaDoc)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // if this namespace has been imported by this document, // ignore the <import> statement if (currSchemaInfo.isAllowedNS(schemaNamespace)) continue; // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace exists (or being // built), ignore this one (don't traverse it). if (findGrammar(fSchemaGrammarDescription) != null) continue; newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; // store the namespace decls of the redefine element if (localName.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport)); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) { reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); } // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees // This method builds registries for all globally-referenceable // names. A registry will be built for each symbol space defined // by the spec. It is also this method's job to rename redefined // components, and to record which components redefine others (so // that implicit redefinitions of groups and attributeGroups can be handled). protected void buildGlobalNameRegistries() { /* Starting with fRoot, we examine each child of the schema * element. Skipping all imports and includes, we record the names * of all other global components (and children of <redefine>). We * also put <redefine> names in a registry that we look through in * case something needs renaming. Once we're done with a schema we * set its Document node to hidden so that we don't try to traverse * it again; then we look to its Dependency map entry. We keep a * stack of schemas that we haven't yet finished processing; this * is a depth-first traversal. */ Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Document currDoc = currSchemaDoc.fSchemaDoc; if (DOMUtil.isHidden(currDoc)) { // must have processed this already! continue; } Element currRoot = DOMUtil.getRoot(currDoc); // process this schema's global decls boolean dependenciesCanOccur = true; for (Element globalComp = DOMUtil.getFirstChildElement(currRoot); globalComp != null; globalComp = DOMUtil.getNextSiblingElement(globalComp)) { // this loop makes sure the <schema> element ordering is // also valid. if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_ANNOTATION)) { //skip it; traverse it later continue; } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_INCLUDE) || DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_IMPORT)) { if (!dependenciesCanOccur) { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } // we've dealt with this; mark as traversed DOMUtil.setHidden(globalComp); } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { if (!dependenciesCanOccur) { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } for (Element redefineComp = DOMUtil.getFirstChildElement(globalComp); redefineComp != null; redefineComp = DOMUtil.getNextSiblingElement(redefineComp)) { String lName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME); if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null ? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; String componentType = DOMUtil.getLocalName(redefineComp); if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_ATTRIBUTEGROUP, lName, targetLName); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME) + REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_COMPLEXTYPE, lName, targetLName); } else { // must be simpleType renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_SIMPLETYPE, lName, targetLName); } } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_GROUP, lName, targetLName); } } // end march through <redefine> children // and now set as traversed //DOMUtil.setHidden(globalComp); } else { dependenciesCanOccur = false; String lName = DOMUtil.getAttrValue(globalComp, SchemaSymbols.ATT_NAME); if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; String componentType = DOMUtil.getLocalName(globalComp); if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { checkForDuplicateNames(qName, fUnparsedAttributeRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, globalComp, currSchemaDoc); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { checkForDuplicateNames(qName, fUnparsedElementRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { checkForDuplicateNames(qName, fUnparsedNotationRegistry, globalComp, currSchemaDoc); } } } // end for // now we're done with this one! DOMUtil.setHidden(currDoc); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end buildGlobalNameRegistries // Beginning at the first schema processing was requested for // (fRoot), this method // examines each child (global schema information item) of each // schema document (and of each <redefine> element) // corresponding to an XSDocumentInfo object. If the // readOnly field on that node has not been set, it calls an // appropriate traverser to traverse it. Once all global decls in // an XSDocumentInfo object have been traversed, it marks that object // as traversed (or hidden) in order to avoid infinite loops. It completes // when it has visited all XSDocumentInfo objects in the // DependencyMap and marked them as traversed. protected void traverseSchemas() { // the process here is very similar to that in // buildGlobalRegistries, except we can't set our schemas as // hidden for a second time; so make them all visible again // first! setSchemasVisible(fRoot); Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Document currDoc = currSchemaDoc.fSchemaDoc; SchemaGrammar currSG = fGrammarBucket.getGrammar(currSchemaDoc.fTargetNamespace); if (DOMUtil.isHidden(currDoc)) { // must have processed this already! continue; } Element currRoot = DOMUtil.getRoot(currDoc); // traverse this schema's global decls for (Element globalComp = DOMUtil.getFirstVisibleChildElement(currRoot); globalComp != null; globalComp = DOMUtil.getNextVisibleSiblingElement(globalComp)) { // We'll always want to set this as hidden! DOMUtil.setHidden(globalComp); String componentType = DOMUtil.getLocalName(globalComp); // includes and imports will not show up here! if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { // use the namespace decls for the redefine, instead of for the parent <schema> currSchemaDoc.backupNSSupport((SchemaNamespaceSupport)fRedefine2NSSupport.get(globalComp)); for (Element redefinedComp = DOMUtil.getFirstVisibleChildElement(globalComp); redefinedComp != null; redefinedComp = DOMUtil.getNextVisibleSiblingElement(redefinedComp)) { String redefinedComponentType = DOMUtil.getLocalName(redefinedComp); DOMUtil.setHidden(redefinedComp); if (redefinedComponentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: according to 3.13.2 the PSVI needs the parent's attributes; // thus this should be done in buildGlobalNameRegistries not here... fElementTraverser.traverseAnnotationDecl(redefinedComp, null, true, currSchemaDoc); } else { reportSchemaError("src-redefine", new Object [] {componentType}, redefinedComp); } } // end march through <redefine> children currSchemaDoc.restoreNSSupport(); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { fAttributeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { fElementTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { fNotationTraverser.traverse(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: according to 3.13.2 the PSVI needs the parent's attributes; // thus this should be done in buildGlobalNameRegistries not here... fElementTraverser.traverseAnnotationDecl(globalComp, null, true, currSchemaDoc); } else { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } } // end for // now we're done with this one! DOMUtil.setHidden(currDoc); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end traverseSchemas // store whether we have reported an error about that no grammar // is found for the given namespace uri private Vector fReportedTNS = null; // check whether we need to report an error against the given uri. // if we have reported an error, then we don't need to report again; // otherwise we reported the error, and remember this fact. private final boolean needReportTNSError(String uri) { if (fReportedTNS == null) fReportedTNS = new Vector(); else if (fReportedTNS.contains(uri)) return false; fReportedTNS.addElement(uri); return true; } private static final String[] COMP_TYPE = { null, // index 0 "attribute declaration", "attribute group", "element declaration", "group", "identity constraint", "notation", "type definition", }; private static final String[] CIRCULAR_CODES = { "Internal-Error", "Internal-Error", "src-attribute_group.3", "e-props-correct.6", "mg-props-correct.2", "Internal-Error", "Internal-Error", "st-props-correct.2", //or ct-props-correct.3 }; // since it is forbidden for traversers to talk to each other // directly (except wen a traverser encounters a local declaration), // this provides a generic means for a traverser to call // for the traversal of some declaration. An XSDocumentInfo is // required because the XSDocumentInfo that the traverser is traversing // may bear no relation to the one the handler is operating on. // This method will: // 1. See if a global definition matching declToTraverse exists; // 2. if so, determine if there is a path from currSchema to the // schema document where declToTraverse lives (i.e., do a lookup // in DependencyMap); // 3. depending on declType (which will be relevant to step 1 as // well), call the appropriate traverser with the appropriate // XSDocumentInfo object. // This method returns whatever the traverser it called returned; // this will be an Object of some kind // that lives in the Grammar. protected Object getGlobalDecl(XSDocumentInfo currSchema, int declType, QName declToTraverse, Element elmNode) { if (DEBUG_NODE_POOL) { System.out.println("TRAVERSE_GL: "+declToTraverse.toString()); } // from the schema spec, all built-in types are present in all schemas, // so if the requested component is a type, and could be found in the // default schema grammar, we should return that type. // otherwise (since we would support user-defined schema grammar) we'll // use the normal way to get the decl if (declToTraverse.uri != null && declToTraverse.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { if (declType == TYPEDECL_TYPE) { Object retObj = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(declToTraverse.localpart); if (retObj != null) return retObj; } } // now check whether this document can access the requsted namespace if (!currSchema.isAllowedNS(declToTraverse.uri)) { // cannot get to this schema from the one containing the requesting decl if (currSchema.needReportTNSError(declToTraverse.uri)) { String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2"; reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode); } return null; } // check whether there is grammar for the requested namespace SchemaGrammar sGrammar = fGrammarBucket.getGrammar(declToTraverse.uri); if (sGrammar == null) { if (needReportTNSError(declToTraverse.uri)) reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // if there is such grammar, check whether the requested component is in the grammar Object retObj = null; switch (declType) { case ATTRIBUTE_TYPE : retObj = sGrammar.getGlobalAttributeDecl(declToTraverse.localpart); break; case ATTRIBUTEGROUP_TYPE : retObj = sGrammar.getGlobalAttributeGroupDecl(declToTraverse.localpart); break; case ELEMENT_TYPE : retObj = sGrammar.getGlobalElementDecl(declToTraverse.localpart); break; case GROUP_TYPE : retObj = sGrammar.getGlobalGroupDecl(declToTraverse.localpart); break; case IDENTITYCONSTRAINT_TYPE : retObj = sGrammar.getIDConstraintDecl(declToTraverse.localpart); break; case NOTATION_TYPE : retObj = sGrammar.getGlobalNotationDecl(declToTraverse.localpart); break; case TYPEDECL_TYPE : retObj = sGrammar.getGlobalTypeDecl(declToTraverse.localpart); break; } // if the component is parsed, return it if (retObj != null) return retObj; XSDocumentInfo schemaWithDecl = null; Element decl = null; // the component is not parsed, try to find a DOM element for it String declKey = declToTraverse.uri == null? ","+declToTraverse.localpart: declToTraverse.uri+","+declToTraverse.localpart; switch (declType) { case ATTRIBUTE_TYPE : decl = (Element)fUnparsedAttributeRegistry.get(declKey); break; case ATTRIBUTEGROUP_TYPE : decl = (Element)fUnparsedAttributeGroupRegistry.get(declKey); break; case ELEMENT_TYPE : decl = (Element)fUnparsedElementRegistry.get(declKey); break; case GROUP_TYPE : decl = (Element)fUnparsedGroupRegistry.get(declKey); break; case IDENTITYCONSTRAINT_TYPE : decl = (Element)fUnparsedIdentityConstraintRegistry.get(declKey); break; case NOTATION_TYPE : decl = (Element)fUnparsedNotationRegistry.get(declKey); break; case TYPEDECL_TYPE : decl = (Element)fUnparsedTypeRegistry.get(declKey); break; default: reportSchemaError("Internal-Error", new Object [] {"XSDHandler asked to locate component of type " + declType + "; it does not recognize this type!"}, elmNode); } // no DOM element found, so the component can't be located if (decl == null) { reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // get the schema doc containing the component to be parsed // it should always return non-null value, but since null-checking // comes for free, let's be safe and check again schemaWithDecl = findXSDocumentForDecl(currSchema, decl); if (schemaWithDecl == null) { // cannot get to this schema from the one containing the requesting decl String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2"; reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode); return null; } // a component is hidden, meaning either it's traversed, or being traversed. // but we didn't find it in the grammar, so it's the latter case, and // a circular reference. error! if (DOMUtil.isHidden(decl)) { String code = CIRCULAR_CODES[declType]; if (declType == TYPEDECL_TYPE) { if (SchemaSymbols.ELT_COMPLEXTYPE.equals(DOMUtil.getLocalName(decl))) code = "ct-props-correct.3"; } // decl must not be null if we're here... reportSchemaError(code, new Object [] {declToTraverse.prefix+":"+declToTraverse.localpart}, elmNode); return null; } // hide the element node before traversing it DOMUtil.setHidden(decl); SchemaNamespaceSupport nsSupport = null; // if the parent is <redefine> use the namespace delcs for it. Element parent = DOMUtil.getParent(decl); if (DOMUtil.getLocalName(parent).equals(SchemaSymbols.ELT_REDEFINE)) nsSupport = (SchemaNamespaceSupport)fRedefine2NSSupport.get(parent); // back up the current SchemaNamespaceSupport, because we need to provide // a fresh one to the traverseGlobal methods. schemaWithDecl.backupNSSupport(nsSupport); // traverse the referenced global component switch (declType) { case ATTRIBUTE_TYPE : retObj = fAttributeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ATTRIBUTEGROUP_TYPE : retObj = fAttributeGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ELEMENT_TYPE : retObj = fElementTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case GROUP_TYPE : retObj = fGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case IDENTITYCONSTRAINT_TYPE : // identity constraints should have been parsed already... // we should never get here retObj = null; break; case NOTATION_TYPE : retObj = fNotationTraverser.traverse(decl, schemaWithDecl, sGrammar); break; case TYPEDECL_TYPE : if (DOMUtil.getLocalName(decl).equals(SchemaSymbols.ELT_COMPLEXTYPE)) retObj = fComplexTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); else retObj = fSimpleTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); } // restore the previous SchemaNamespaceSupport, so that the caller can get // proper namespace binding. schemaWithDecl.restoreNSSupport(); return retObj; } // getGlobalDecl(XSDocumentInfo, int, QName): Object // This method determines whether there is a group // (attributeGroup) which the given one has redefined by // restriction. If so, it returns it; else it returns null. // @param type: whether what's been redefined is an // attributeGroup or a group; // @param name: the QName of the component doing the redefining. // @param currSchema: schema doc in which the redefining component lives. // @return: Object representing decl redefined if present, null // otherwise. Object getGrpOrAttrGrpRedefinedByRestriction(int type, QName name, XSDocumentInfo currSchema, Element elmNode) { String realName = name.uri != null?name.uri+","+name.localpart: ","+name.localpart; String nameToFind = null; switch (type) { case ATTRIBUTEGROUP_TYPE: nameToFind = (String)fRedefinedRestrictedAttributeGroupRegistry.get(realName); break; case GROUP_TYPE: nameToFind = (String)fRedefinedRestrictedGroupRegistry.get(realName); break; default: return null; } if (nameToFind == null) return null; int commaPos = nameToFind.indexOf(","); QName qNameToFind = new QName(XMLSymbols.EMPTY_STRING, nameToFind.substring(commaPos+1), nameToFind.substring(commaPos), (commaPos == 0)? null : nameToFind.substring(0, commaPos)); Object retObj = getGlobalDecl(currSchema, type, qNameToFind, elmNode); if(retObj == null) { switch (type) { case ATTRIBUTEGROUP_TYPE: reportSchemaError("src-redefine.7.2.1", new Object []{name.localpart}, elmNode); break; case GROUP_TYPE: reportSchemaError("src-redefine.6.2.1", new Object []{name.localpart}, elmNode); break; } return null; } return retObj; } // getGrpOrAttrGrpRedefinedByRestriction(int, QName, XSDocumentInfo): Object // Since ID constraints can occur in local elements, unless we // wish to completely traverse all our DOM trees looking for ID // constraints while we're building our global name registries, // which seems terribly inefficient, we need to resolve keyrefs // after all parsing is complete. This we can simply do by running through // fIdentityConstraintRegistry and calling traverseKeyRef on all // of the KeyRef nodes. This unfortunately removes this knowledge // from the elementTraverser class (which must ignore keyrefs), // but there seems to be no efficient way around this... protected void resolveKeyRefs() { for (int i=0; i<fKeyrefStackPos; i++) { Document keyrefDoc = DOMUtil.getDocument(fKeyrefs[i]); XSDocumentInfo keyrefSchemaDoc = (XSDocumentInfo)fDoc2XSDocumentMap.get(keyrefDoc); keyrefSchemaDoc.fNamespaceSupport.makeGlobal(); keyrefSchemaDoc.fNamespaceSupport.setEffectiveContext( fKeyrefNamespaceContext[i] ); SchemaGrammar keyrefGrammar = fGrammarBucket.getGrammar(keyrefSchemaDoc.fTargetNamespace); // need to set <keyref> to hidden before traversing it, // because it has global scope DOMUtil.setHidden(fKeyrefs[i]); fKeyrefTraverser.traverse(fKeyrefs[i], fKeyrefElems[i], keyrefSchemaDoc, keyrefGrammar); } } // end resolveKeyRefs // an accessor method. Just makes sure callers // who want the Identity constraint registry vaguely know what they're about. protected Hashtable getIDRegistry() { return fUnparsedIdentityConstraintRegistry; } // This method squirrels away <keyref> declarations--along with the element // decls and namespace bindings they might find handy. protected void storeKeyRef (Element keyrefToStore, XSDocumentInfo schemaDoc, XSElementDecl currElemDecl) { String keyrefName = DOMUtil.getAttrValue(keyrefToStore, SchemaSymbols.ATT_NAME); if (keyrefName.length() != 0) { String keyrefQName = schemaDoc.fTargetNamespace == null? "," + keyrefName: schemaDoc.fTargetNamespace+","+keyrefName; checkForDuplicateNames(keyrefQName, fUnparsedIdentityConstraintRegistry, keyrefToStore, schemaDoc); } // now set up all the registries we'll need... // check array sizes if (fKeyrefStackPos == fKeyrefs.length) { Element [] elemArray = new Element [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefs, 0, elemArray, 0, fKeyrefStackPos); fKeyrefs = elemArray; XSElementDecl [] declArray = new XSElementDecl [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefElems, 0, declArray, 0, fKeyrefStackPos); fKeyrefElems = declArray; String[][] stringArray = new String [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT][]; System.arraycopy(fKeyrefNamespaceContext, 0, stringArray, 0, fKeyrefStackPos); fKeyrefNamespaceContext = stringArray; } fKeyrefs[fKeyrefStackPos] = keyrefToStore; fKeyrefElems[fKeyrefStackPos] = currElemDecl; fKeyrefNamespaceContext[fKeyrefStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); } // storeKeyref (Element, XSDocumentInfo, XSElementDecl): void private static final String[] DOC_ERROR_CODES = { "src-include.0", "src-redefine.0", "src-import.0", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4" }; // This method is responsible for schema resolution. If it finds // a schema document that the XMLEntityResolver resolves to with // the given namespace and hint, it returns it. It returns true // if this is the first time it's seen this document, false // otherwise. schemaDoc is null if and only if no schema document // was resolved to. private Document getSchema(XSDDescription desc, boolean mustResolve, Element referElement) { XMLInputSource schemaSource=null; try { schemaSource = XMLSchemaLoader.resolveDocument(desc, fLocationPairs, fEntityResolver); } catch (IOException ex) { if (mustResolve) { reportSchemaError(DOC_ERROR_CODES[desc.getContextType()], new Object[]{desc.getLocationHints()[0]}, referElement); } else { reportSchemaWarning(DOC_ERROR_CODES[desc.getContextType()], new Object[]{desc.getLocationHints()[0]}, referElement); } } return getSchema(desc.getTargetNamespace(), schemaSource, mustResolve, desc.getContextType(), referElement); } // getSchema(String, String, String, boolean, short): Document private Document getSchema(String schemaNamespace, XMLInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { boolean hasInput = true; // contents of this method will depend on the system we adopt for entity resolution--i.e., XMLEntityHandler, EntityHandler, etc. Document schemaDoc = null; try { // when the system id and byte stream and character stream // of the input source are all null, it's // impossible to find the schema document. so we skip in // this case. otherwise we'll receive some NPE or // file not found errors. but schemaHint=="" is perfectly // legal for import. if (schemaSource != null && (schemaSource.getSystemId() != null || schemaSource.getByteStream() != null || schemaSource.getCharacterStream() != null)) { // When the system id of the input source is used, first try to // expand it, and check whether the same document has been // parsed before. If so, return the document corresponding to // that system id. String schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); XSDKey key = new XSDKey(schemaId, referType, schemaNamespace); if ((schemaDoc = (Document)fTraversed.get(key)) != null) { fLastSchemaWasDuplicate = true; return schemaDoc; } // If this is the first schema this Handler has // parsed, it has to construct a DOMParser if (fSchemaParser == null) { //fSchemaParser = new DOMParser(); fSchemaParser = new SchemaParsingConfig(); resetSchemaParserErrorHandler(); } fSchemaParser.parse(schemaSource); schemaDoc = fSchemaParser.getDocument(); // now we need to store the mapping information from system id // to the document. also from the document to the system id. fTraversed.put(key, schemaDoc ); if (schemaId != null) fDoc2SystemId.put(schemaDoc, schemaId ); fLastSchemaWasDuplicate = false; return schemaDoc; } else { hasInput = false; } } catch (IOException ex) { } // either an error occured (exception), or empty input source was // returned, we need to report an error or a warning if (mustResolve) { reportSchemaError(DOC_ERROR_CODES[referType], new Object[]{schemaSource.getSystemId()}, referElement); } else if (hasInput) { reportSchemaWarning(DOC_ERROR_CODES[referType], new Object[]{schemaSource.getSystemId()}, referElement); } fLastSchemaWasDuplicate = false; return null; } // getSchema(String, XMLInputSource, boolean, boolean): Document // initialize all the traversers. // this should only need to be called once during the construction // of this object; it creates the traversers that will be used to // construct schemaGrammars. private void createTraversers() { fAttributeChecker = new XSAttributeChecker(this); fAttributeGroupTraverser = new XSDAttributeGroupTraverser(this, fAttributeChecker); fAttributeTraverser = new XSDAttributeTraverser(this, fAttributeChecker); fComplexTypeTraverser = new XSDComplexTypeTraverser(this, fAttributeChecker); fElementTraverser = new XSDElementTraverser(this, fAttributeChecker); fGroupTraverser = new XSDGroupTraverser(this, fAttributeChecker); fKeyrefTraverser = new XSDKeyrefTraverser(this, fAttributeChecker); fNotationTraverser = new XSDNotationTraverser(this, fAttributeChecker); fSimpleTypeTraverser = new XSDSimpleTypeTraverser(this, fAttributeChecker); fUniqueOrKeyTraverser = new XSDUniqueOrKeyTraverser(this, fAttributeChecker); fWildCardTraverser = new XSDWildcardTraverser(this, fAttributeChecker); } // createTraversers() // before parsing a schema, need to clear registries associated with // parsing schemas void prepareForParse() { fTraversed.clear(); fDoc2SystemId.clear(); fLastSchemaWasDuplicate = false; } // before traversing a schema's parse tree, need to reset all traversers and // clear all registries void prepareForTraverse() { fUnparsedAttributeRegistry.clear(); fUnparsedAttributeGroupRegistry.clear(); fUnparsedElementRegistry.clear(); fUnparsedGroupRegistry.clear(); fUnparsedIdentityConstraintRegistry.clear(); fUnparsedNotationRegistry.clear(); fUnparsedTypeRegistry.clear(); fXSDocumentInfoRegistry.clear(); fDependencyMap.clear(); fDoc2XSDocumentMap.clear(); fRedefine2XSDMap.clear(); fRedefine2NSSupport.clear(); fAllTNSs.removeAllElements(); fImportMap.clear(); fRoot = null; // clear local element stack for (int i = 0; i < fLocalElemStackPos; i++) { fParticle[i] = null; fLocalElementDecl[i] = null; fLocalElemNamespaceContext[i] = null; } fLocalElemStackPos = 0; // and do same for keyrefs. for (int i = 0; i < fKeyrefStackPos; i++) { fKeyrefs[i] = null; fKeyrefElems[i] = null; fKeyrefNamespaceContext[i] = null; } fKeyrefStackPos = 0; // create traversers if necessary if (fAttributeChecker == null) { createTraversers(); } // reset traversers fAttributeChecker.reset(fSymbolTable); fAttributeGroupTraverser.reset(fSymbolTable); fAttributeTraverser.reset(fSymbolTable); fComplexTypeTraverser.reset(fSymbolTable); fElementTraverser.reset(fSymbolTable); fGroupTraverser.reset(fSymbolTable); fKeyrefTraverser.reset(fSymbolTable); fNotationTraverser.reset(fSymbolTable); fSimpleTypeTraverser.reset(fSymbolTable); fUniqueOrKeyTraverser.reset(fSymbolTable); fWildCardTraverser.reset(fSymbolTable); fRedefinedRestrictedAttributeGroupRegistry.clear(); fRedefinedRestrictedGroupRegistry.clear(); } public void setDeclPool (XSDeclarationPool declPool){ fDeclPool = declPool; } // this method reset properties that might change between parses. // and process the jaxp schemaSource property public void reset(XMLErrorReporter errorReporter, XMLEntityResolver entityResolver, SymbolTable symbolTable, XMLGrammarPool grammarPool, boolean allowJavaEncodings, boolean strictURI) { fErrorReporter = errorReporter; fEntityResolver = entityResolver; fSymbolTable = symbolTable; fGrammarPool = grammarPool; fAllowJavaEncodings = allowJavaEncodings; fStrictURI = strictURI; resetSchemaParserErrorHandler(); } // reset(ErrorReporter, EntityResolver, SymbolTable, XMLGrammarPool) void resetSchemaParserErrorHandler() { if (fSchemaParser != null) { try { XMLErrorHandler currErrorHandler = fErrorReporter.getErrorHandler(); // Setting a parser property can be much more expensive // than checking its value. Don't set the ERROR_HANDLER // property unless it's actually changed. if (currErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) { fSchemaParser.setProperty(ERROR_HANDLER, currErrorHandler); } } catch (Exception e) { } // make sure the following are set correctly: // continue-after-fatal-error // allow-java-encodings // standard-uri-conformant try { fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); } catch (Exception e) { } try { fSchemaParser.setFeature(ALLOW_JAVA_ENCODINGS, fAllowJavaEncodings); } catch (Exception e) { } try { fSchemaParser.setFeature(STANDARD_URI_CONFORMANT_FEATURE, fStrictURI); } catch (Exception e) { } try { if (fEntityResolver != fSchemaParser.getProperty(ENTITY_RESOLVER)) { fSchemaParser.setProperty(ENTITY_RESOLVER, fEntityResolver); } } catch (Exception e) { } } } // resetSchemaParserErrorHandler() /** * Traverse all the deferred local elements. This method should be called * by traverseSchemas after we've done with all the global declarations. */ void traverseLocalElements() { fElementTraverser.fDeferTraversingLocalElements = false; for (int i = 0; i < fLocalElemStackPos; i++) { Element currElem = fLocalElementDecl[i]; XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem)); SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fEnclosingCT[i]); } } // the purpose of this method is to keep up-to-date structures // we'll need for the feferred traversal of local elements. void fillInLocalElemInfo(Element elmDecl, XSDocumentInfo schemaDoc, int allContextFlags, XSComplexTypeDecl enclosingCT, XSParticleDecl particle) { // if the stack is full, increase the size if (fParticle.length == fLocalElemStackPos) { // increase size XSParticleDecl[] newStackP = new XSParticleDecl[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fParticle, 0, newStackP, 0, fLocalElemStackPos); fParticle = newStackP; Element[] newStackE = new Element[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fLocalElementDecl, 0, newStackE, 0, fLocalElemStackPos); fLocalElementDecl = newStackE; int[] newStackI = new int[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fAllContext, 0, newStackI, 0, fLocalElemStackPos); fAllContext = newStackI; XSComplexTypeDecl[] newStackC = new XSComplexTypeDecl[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fEnclosingCT, 0, newStackC, 0, fLocalElemStackPos); fEnclosingCT = newStackC; String [][] newStackN = new String [fLocalElemStackPos+INC_STACK_SIZE][]; System.arraycopy(fLocalElemNamespaceContext, 0, newStackN, 0, fLocalElemStackPos); fLocalElemNamespaceContext = newStackN; } fParticle[fLocalElemStackPos] = particle; fLocalElementDecl[fLocalElemStackPos] = elmDecl; fAllContext[fLocalElemStackPos] = allContextFlags; fEnclosingCT[fLocalElemStackPos] = enclosingCT; fLocalElemNamespaceContext[fLocalElemStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); } // end fillInLocalElemInfo(...) /** This method makes sure that * if this component is being redefined that it lives in the * right schema. It then renames the component correctly. If it * detects a collision--a duplicate definition--then it complains. * Note that redefines must be handled carefully: if there * is a collision, it may be because we're redefining something we know about * or because we've found the thing we're redefining. */ void checkForDuplicateNames(String qName, Hashtable registry, Element currComp, XSDocumentInfo currSchema) { Object objElem = null; // REVISIT: when we add derivation checking, we'll have to make // sure that ID constraint collisions don't necessarily result in error messages. if ((objElem = registry.get(qName)) == null) { // just add it in! registry.put(qName, currComp); } else { Element collidingElem = (Element)objElem; if (collidingElem == currComp) return; Element elemParent = null; XSDocumentInfo redefinedSchema = null; // case where we've collided with a redefining element // (the parent of the colliding element is a redefine) boolean collidedWithRedefine = true; if ((DOMUtil.getLocalName((elemParent = DOMUtil.getParent(collidingElem))).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = (XSDocumentInfo)(fRedefine2XSDMap.get(elemParent)); // case where we're a redefining element. } else if ((DOMUtil.getLocalName(DOMUtil.getParent(currComp)).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = (XSDocumentInfo)(fDoc2XSDocumentMap.get(DOMUtil.getDocument(collidingElem))); collidedWithRedefine = false; } if (redefinedSchema != null) { //redefinition involved somehow // If both components belong to the same document then // report an error and return. if (fDoc2XSDocumentMap.get(DOMUtil.getDocument(collidingElem)) == currSchema) { reportSchemaError("sch-props-correct.2", new Object[]{qName}, currComp); return; } String newName = qName.substring(qName.lastIndexOf(',')+1)+REDEF_IDENTIFIER; if (redefinedSchema == currSchema) { // object comp. okay here // now have to do some renaming... currComp.setAttribute(SchemaSymbols.ATT_NAME, newName); if (currSchema.fTargetNamespace == null) registry.put(","+newName, currComp); else registry.put(currSchema.fTargetNamespace+","+newName, currComp); // and take care of nested redefines by calling recursively: if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema); } else { // we may be redefining the wrong schema if (collidedWithRedefine) { if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema); } else { // error that redefined element in wrong schema reportSchemaError("src-redefine.1", new Object [] {qName}, currComp); } } } else { // we've just got a flat-out collision reportSchemaError("sch-props-correct.2", new Object []{qName}, currComp); } } } // checkForDuplicateNames(String, Hashtable, Element, XSDocumentInfo):void // the purpose of this method is to take the component of the // specified type and rename references to itself so that they // refer to the object being redefined. It takes special care of // <group>s and <attributeGroup>s to ensure that information // relating to implicit restrictions is preserved for those // traversers. private void renameRedefiningComponents(XSDocumentInfo currSchema, Element child, String componentType, String oldName, String newName) { if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { String grandKidName = grandKid.getLocalName(); if (grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); grandKidName = grandKid.getLocalName(); } if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else if (!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) { reportSchemaError("src-redefine.5", null, child); } else { Object[] attrs = fAttributeChecker.checkAttributes(grandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5", null, child); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) grandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else grandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } fAttributeChecker.returnAttrArray(attrs, currSchema); } } } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { if (grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); } if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { // have to go one more level down; let another pass worry whether complexType is valid. Element greatGrandKid = DOMUtil.getFirstChildElement(grandKid); if (greatGrandKid == null) { reportSchemaError("src-redefine.5", null, grandKid); } else { String greatGrandKidName = greatGrandKid.getLocalName(); if (greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { greatGrandKid = DOMUtil.getNextSiblingElement(greatGrandKid); greatGrandKidName = greatGrandKid.getLocalName(); } if (greatGrandKid == null) { reportSchemaError("src-redefine.5", null, grandKid); } else if (!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) && !greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) { reportSchemaError("src-redefine.5", null, greatGrandKid); } else { Object[] attrs = fAttributeChecker.checkAttributes(greatGrandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5", null, greatGrandKid); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } } } } } } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int attGroupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (attGroupRefsCount > 1) { reportSchemaError("src-redefine.7.1", new Object []{new Integer(attGroupRefsCount)}, child); } else if (attGroupRefsCount == 1) { // return true; } else if (currSchema.fTargetNamespace == null) fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int groupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (groupRefsCount > 1) { reportSchemaError("src-redefine.6.1.1", new Object []{new Integer(groupRefsCount)}, child); } else if (groupRefsCount == 1) { // return true; } else { if (currSchema.fTargetNamespace == null) fRedefinedRestrictedGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } } else { reportSchemaError("Internal-Error", new Object [] {"could not handle this particular <redefine>; please submit your schemas and instance document in a bug report!"}, child); } // if we get here then we must have reported an error and failed somewhere... // return false; } // renameRedefiningComponents(XSDocumentInfo, Element, String, String, String):void // this method takes a name of the form a:b, determines the URI mapped // to by a in the current SchemaNamespaceSupport object, and returns this // information in the form (nsURI,b) suitable for lookups in the global // decl Hashtables. // REVISIT: should have it return QName, instead of String. this would // save lots of string concatenation time. we can use // QName#equals() to compare two QNames, and use QName directly // as a key to the SymbolHash. // And when the DV's are ready to return compiled values from // validate() method, we should just call QNameDV.validate() // in this method. private String findQName(String name, XSDocumentInfo schemaDoc) { SchemaNamespaceSupport currNSMap = schemaDoc.fNamespaceSupport; int colonPtr = name.indexOf(':'); String prefix = XMLSymbols.EMPTY_STRING; if (colonPtr > 0) prefix = name.substring(0, colonPtr); String uri = currNSMap.getURI(fSymbolTable.addSymbol(prefix)); String localpart = (colonPtr == 0)?name:name.substring(colonPtr+1); if (prefix == XMLSymbols.EMPTY_STRING && uri == null && schemaDoc.fIsChameleonSchema) uri = schemaDoc.fTargetNamespace; if (uri == null) return ","+localpart; return uri+","+localpart; } // findQName(String, XSDocumentInfo): String // This function looks among the children of curr for an element of type elementSought. // If it finds one, it evaluates whether its ref attribute contains a reference // to originalQName. If it does, it returns 1 + the value returned by // calls to itself on all other children. In all other cases it returns 0 plus // the sum of the values returned by calls to itself on curr's children. // It also resets the value of ref so that it will refer to the renamed type from the schema // being redefined. private int changeRedefineGroup(String originalQName, String elementSought, String newName, Element curr, XSDocumentInfo schemaDoc) { int result = 0; for (Element child = DOMUtil.getFirstChildElement(curr); child != null; child = DOMUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (!name.equals(elementSought)) result += changeRedefineGroup(originalQName, elementSought, newName, child, schemaDoc); else { String ref = child.getAttribute( SchemaSymbols.ATT_REF ); if (ref.length() != 0) { String processedRef = findQName(ref, schemaDoc); if (originalQName.equals(processedRef)) { String prefix = XMLSymbols.EMPTY_STRING; int colonptr = ref.indexOf(":"); if (colonptr > 0) { prefix = ref.substring(0,colonptr); child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName); } else child.setAttribute(SchemaSymbols.ATT_REF, newName); result++; if (elementSought.equals(SchemaSymbols.ELT_GROUP)) { String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS ); String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS ); if (!((maxOccurs.length() == 0 || maxOccurs.equals("1")) && (minOccurs.length() == 0 || minOccurs.equals("1")))) { reportSchemaError("src-redefine.6.1.2", new Object [] {ref}, child); } } } } // if ref was null some other stage of processing will flag the error } } return result; } // changeRedefineGroup // this method returns the XSDocumentInfo object that contains the // component corresponding to decl. If components from this // document cannot be referred to from those of currSchema, this // method returns null; it's up to the caller to throw an error. // @param: currSchema: the XSDocumentInfo object containing the // decl ref'ing us. // @param: decl: the declaration being ref'd. private XSDocumentInfo findXSDocumentForDecl(XSDocumentInfo currSchema, Element decl) { if (DEBUG_NODE_POOL) { System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaDoc).hashCode()); } Document declDoc = DOMUtil.getDocument(decl); Object temp = fDoc2XSDocumentMap.get(declDoc); if (temp == null) { // something went badly wrong; we don't know this doc? return null; } XSDocumentInfo declDocInfo = (XSDocumentInfo)temp; return declDocInfo; /********* Logic here is unnecessary after schema WG's recent decision to allow schema components from one document to refer to components of any other, so long as there's some include/import/redefine path amongst them. If they rver reverse this decision the code's right here though... - neilg // now look in fDependencyMap to see if this is reachable if(((Vector)fDependencyMap.get(currSchema)).contains(declDocInfo)) { return declDocInfo; } // obviously the requesting doc didn't include, redefine or // import the one containing decl... return null; **********/ } // findXSDocumentForDecl(XSDocumentInfo, Element): XSDocumentInfo // returns whether more than <annotation>s occur in children of elem private boolean nonAnnotationContent(Element elem) { for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; } return false; } // nonAnnotationContent(Element): boolean private void setSchemasVisible(XSDocumentInfo startSchema) { if (DOMUtil.isHidden(startSchema.fSchemaDoc)) { // make it visible DOMUtil.setVisible(startSchema.fSchemaDoc); Vector dependingSchemas = (Vector)fDependencyMap.get(startSchema); for (int i = 0; i < dependingSchemas.size(); i++) { setSchemasVisible((XSDocumentInfo)dependingSchemas.elementAt(i)); } } // if it's visible already than so must be its children } // setSchemasVisible(XSDocumentInfo): void private SimpleLocator xl = new SimpleLocator(); /** * Extract location information from an Element node, and create a * new SimpleLocator object from such information. Returning null means * no information can be retrieved from the element. */ public SimpleLocator element2Locator(Element e) { if (!(e instanceof ElementNSImpl || e instanceof ElementImpl)) return null; SimpleLocator l = new SimpleLocator(); return element2Locator(e, l) ? l : null; } /** * Extract location information from an Element node, store such * information in the passed-in SimpleLocator object, then return * true. Returning false means can't extract or store such information. */ public boolean element2Locator(Element e, SimpleLocator l) { if (l == null) return false; if (e instanceof ElementImpl) { ElementImpl ele = (ElementImpl)e; // get system id from document object Document doc = ele.getOwnerDocument(); String sid = (String)fDoc2SystemId.get(doc); // line/column numbers are stored in the element node int line = ele.getLineNumber(); int column = ele.getColumnNumber(); l.setValues(sid, sid, line, column); return true; } if (e instanceof ElementNSImpl) { ElementNSImpl ele = (ElementNSImpl)e; // get system id from document object Document doc = ele.getOwnerDocument(); String sid = (String)fDoc2SystemId.get(doc); // line/column numbers are stored in the element node int line = ele.getLineNumber(); int column = ele.getColumnNumber(); l.setValues(sid, sid, line, column); return true; } return false; } void reportSchemaError(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } } void reportSchemaWarning(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } } /** * used to identify a reference to a schema document * if the same document is referenced twice with the same key, then * we only need to parse it once. * * When 2 XSDKey's are compared, the following table can be used to * determine whether they are equal: * inc red imp pre ins * inc N/L ? N/L N/L N/L * red ? N/L ? ? ? * imp N/L ? N/P N/P N/P * pre N/L ? N/P N/P N/P * ins N/L ? N/P N/P N/P * * Where: N/L: duplicate when they have the same namespace and location. * ? : not clear from the spec. * REVISIT: to simplify the process, also considering * it's very rare, we treat them as not duplicate. * N/P: not possible. imp/pre/ins are referenced by namespace. * when the first time we encounter a schema document for a * namespace, we create a grammar and store it in the grammar * bucket. when we see another reference to the same namespace, * we first check whether a grammar with the same namespace is * already in the bucket, which is true in this case, so we * won't create another XSDKey. * * Conclusion from the table: two XSDKey's are duplicate only when all of * the following are true: * 1. They are both "redefine", or neither is "redefine" (which implies * that they are both "include"); * 2. They have the same namespace and location. */ private static class XSDKey { String systemId; short referType; // for inclue/redefine, this is the enclosing namespace // for import/preparse/instance, this is the target namespace String referNS; XSDKey(String systemId, short referType, String referNS) { this.systemId = systemId; this.referType = referType; this.referNS = referNS; } public int hashCode() { // according to the description at the beginning of this class, // we use the hashcode of the namespace as the hashcoe of this key. return referNS == null ? 0 : referNS.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof XSDKey)) { return false; } XSDKey key = (XSDKey)obj; // condition 1: both are redefine if (referType == XSDDescription.CONTEXT_REDEFINE || key.referType == XSDDescription.CONTEXT_REDEFINE) { if (referType != key.referType) return false; } // condition 2: same namespace and same locatoin if (referNS != key.referNS || (systemId == null && key.systemId != null) || systemId != null && !systemId.equals(key.systemId)) { return false; } return true; } } } // XSDHandler
true
true
protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree //sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo)); sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // if this namespace has been imported by this document, // ignore the <import> statement if (currSchemaInfo.isAllowedNS(schemaNamespace)) continue; // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace exists (or being // built), ignore this one (don't traverse it). if (findGrammar(fSchemaGrammarDescription) != null) continue; newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; // store the namespace decls of the redefine element if (localName.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport)); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) { reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); } // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees
protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree //sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo)); sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaDoc)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // if this namespace has been imported by this document, // ignore the <import> statement if (currSchemaInfo.isAllowedNS(schemaNamespace)) continue; // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace exists (or being // built), ignore this one (don't traverse it). if (findGrammar(fSchemaGrammarDescription) != null) continue; newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; // store the namespace decls of the redefine element if (localName.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport)); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) { reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); } // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees
diff --git a/code/src/group/pals/android/lib/ui/filechooser/utils/E.java b/code/src/group/pals/android/lib/ui/filechooser/utils/E.java index 34a6243..812c68d 100644 --- a/code/src/group/pals/android/lib/ui/filechooser/utils/E.java +++ b/code/src/group/pals/android/lib/ui/filechooser/utils/E.java @@ -1,53 +1,53 @@ /* * Copyright 2012 Hai Bison * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package group.pals.android.lib.ui.filechooser.utils; import group.pals.android.lib.ui.filechooser.utils.ui.Dlg; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; /** * Something funny :-) * * @author Hai Bison * */ public class E { /** * Shows it! * * @param context * {@link Context} */ public static void show(Context context) { String msg = null; try { msg = String.format("Hi :-)\n\n" + "%s v%s\n" + "…by Hai Bison\n\n" + "http://www.haibison.com\n\n" - + "Hope you enjoy this library.", "android-filechooser", "4.6 beta"); + + "Hope you enjoy this library.", "android-filechooser", "4.6"); } catch (Exception e) { msg = "Oops… You've found a broken Easter egg, try again later :-("; } AlertDialog dlg = Dlg.newDlg(context); dlg.setButton(DialogInterface.BUTTON_NEGATIVE, null, (DialogInterface.OnClickListener) null); dlg.setTitle("…"); dlg.setMessage(msg); dlg.show(); }// show() }
true
true
public static void show(Context context) { String msg = null; try { msg = String.format("Hi :-)\n\n" + "%s v%s\n" + "…by Hai Bison\n\n" + "http://www.haibison.com\n\n" + "Hope you enjoy this library.", "android-filechooser", "4.6 beta"); } catch (Exception e) { msg = "Oops… You've found a broken Easter egg, try again later :-("; } AlertDialog dlg = Dlg.newDlg(context); dlg.setButton(DialogInterface.BUTTON_NEGATIVE, null, (DialogInterface.OnClickListener) null); dlg.setTitle("…"); dlg.setMessage(msg); dlg.show(); }// show()
public static void show(Context context) { String msg = null; try { msg = String.format("Hi :-)\n\n" + "%s v%s\n" + "…by Hai Bison\n\n" + "http://www.haibison.com\n\n" + "Hope you enjoy this library.", "android-filechooser", "4.6"); } catch (Exception e) { msg = "Oops… You've found a broken Easter egg, try again later :-("; } AlertDialog dlg = Dlg.newDlg(context); dlg.setButton(DialogInterface.BUTTON_NEGATIVE, null, (DialogInterface.OnClickListener) null); dlg.setTitle("…"); dlg.setMessage(msg); dlg.show(); }// show()
diff --git a/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java b/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java index b432b344..e360f457 100644 --- a/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java +++ b/extensions/grapher/src/com/google/inject/grapher/graphviz/GraphvizRenderer.java @@ -1,229 +1,229 @@ /** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.grapher.graphviz; import com.google.common.base.Join; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.grapher.ImplementationNode; import com.google.inject.grapher.NodeAliasFactory; import com.google.inject.grapher.Renderer; import java.io.PrintWriter; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * {@link Renderer} implementation that writes out a Graphviz DOT file of the * graph. Bound in {@link GraphvizModule}. * <p> * Specify the {@link PrintWriter} to output to with * {@link #setOut(PrintWriter)}. * * @author [email protected] (Pete Hopkins) */ public class GraphvizRenderer implements Renderer, NodeAliasFactory<String> { private final List<GraphvizNode> nodes = Lists.newArrayList(); private final List<GraphvizEdge> edges = Lists.newArrayList(); private final Map<String, String> aliases = Maps.newHashMap(); private PrintWriter out; private String rankdir = "TB"; public GraphvizRenderer setOut(PrintWriter out) { this.out = out; return this; } public GraphvizRenderer setRankdir(String rankdir) { this.rankdir = rankdir; return this; } public void addNode(GraphvizNode node) { nodes.add(node); } public void addEdge(GraphvizEdge edge) { edges.add(edge); } public void newAlias(String fromId, String toId) { aliases.put(fromId, toId); } protected String resolveAlias(String id) { while (aliases.containsKey(id)) { id = aliases.get(id); } return id; } public void render() { start(); for (GraphvizNode node : nodes) { renderNode(node); } for (GraphvizEdge edge : edges) { renderEdge(edge); } finish(); out.flush(); } protected Map<String, String> getGraphAttributes() { Map<String, String> attrs = Maps.newHashMap(); attrs.put("rankdir", rankdir); return attrs; } protected void start() { out.println("digraph injector {"); Map<String, String> attrs = getGraphAttributes(); out.println("graph " + getAttrString(attrs) + ";"); } protected void finish() { out.println("}"); } protected void renderNode(GraphvizNode node) { Map<String, String> attrs = getNodeAttributes(node); out.println(node.getNodeId() + " " + getAttrString(attrs)); } protected Map<String, String> getNodeAttributes(GraphvizNode node) { Map<String, String> attrs = Maps.newHashMap(); attrs.put("label", getNodeLabel(node)); // remove most of the margin because the table has internal padding attrs.put("margin", "0.02,0"); attrs.put("shape", node.getShape().toString()); attrs.put("style", node.getStyle().toString()); return attrs; } /** * Creates the "label" for a node. This is a string of HTML that defines a * table with a heading at the top and (in the case of * {@link ImplementationNode}s) rows for each of the member fields. */ protected String getNodeLabel(GraphvizNode node) { String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0"; StringBuilder html = new StringBuilder(); html.append("<"); html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\""); html.append(cellborder).append("\" border=\"0\">"); html.append("<tr>").append("<td align=\"left\" port=\"header\" "); html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">"); String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles()); if (subtitle.length() != 0) { - html.append("<font align=\"left\" color=\"").append(node.getHeaderTextColor()); + html.append("<font color=\"").append(node.getHeaderTextColor()); html.append("\" point-size=\"10\">"); html.append(subtitle).append("<br align=\"left\"/>").append("</font>"); } html.append("<font color=\"" + node.getHeaderTextColor() + "\">"); html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>"); html.append("</font>").append("</td>").append("</tr>"); for (Map.Entry<String, String> field : node.getFields().entrySet()) { html.append("<tr>"); html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">"); html.append(htmlEscape(field.getValue())); html.append("</td>").append("</tr>"); } html.append("</table>"); html.append(">"); return html.toString(); } protected void renderEdge(GraphvizEdge edge) { Map<String, String> attrs = getEdgeAttributes(edge); String tailId = getEdgeEndPoint(resolveAlias(edge.getTailNodeId()), edge.getTailPortId(), edge.getTailCompassPoint()); String headId = getEdgeEndPoint(resolveAlias(edge.getHeadNodeId()), edge.getHeadPortId(), edge.getHeadCompassPoint()); out.println(tailId + " -> " + headId + " " + getAttrString(attrs)); } protected Map<String, String> getEdgeAttributes(GraphvizEdge edge) { Map<String, String> attrs = Maps.newHashMap(); attrs.put("arrowhead", getArrowString(edge.getArrowHead())); attrs.put("arrowtail", getArrowString(edge.getArrowTail())); attrs.put("style", edge.getStyle().toString()); return attrs; } private String getAttrString(Map<String, String> attrs) { List<String> attrList = Lists.newArrayList(); for (Entry<String, String> attr : attrs.entrySet()) { String value = attr.getValue(); if (value != null) { attrList.add(attr.getKey() + "=" + value); } } return "[" + Join.join(", ", attrList) + "]"; } /** * Turns a {@link List} of {@link ArrowType}s into a {@link String} that * represents combining them. With Graphviz, that just means concatenating * them. */ protected String getArrowString(List<ArrowType> arrows) { return Join.join("", arrows); } protected String getEdgeEndPoint(String nodeId, String portId, CompassPoint compassPoint) { List<String> portStrings = Lists.newArrayList(nodeId); if (portId != null) { portStrings.add(portId); } if (compassPoint != null) { portStrings.add(compassPoint.toString()); } return Join.join(":", portStrings); } protected String htmlEscape(String str) { return str.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } }
true
true
protected String getNodeLabel(GraphvizNode node) { String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0"; StringBuilder html = new StringBuilder(); html.append("<"); html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\""); html.append(cellborder).append("\" border=\"0\">"); html.append("<tr>").append("<td align=\"left\" port=\"header\" "); html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">"); String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles()); if (subtitle.length() != 0) { html.append("<font align=\"left\" color=\"").append(node.getHeaderTextColor()); html.append("\" point-size=\"10\">"); html.append(subtitle).append("<br align=\"left\"/>").append("</font>"); } html.append("<font color=\"" + node.getHeaderTextColor() + "\">"); html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>"); html.append("</font>").append("</td>").append("</tr>"); for (Map.Entry<String, String> field : node.getFields().entrySet()) { html.append("<tr>"); html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">"); html.append(htmlEscape(field.getValue())); html.append("</td>").append("</tr>"); } html.append("</table>"); html.append(">"); return html.toString(); }
protected String getNodeLabel(GraphvizNode node) { String cellborder = node.getStyle() == NodeStyle.INVISIBLE ? "1" : "0"; StringBuilder html = new StringBuilder(); html.append("<"); html.append("<table cellspacing=\"0\" cellpadding=\"5\" cellborder=\""); html.append(cellborder).append("\" border=\"0\">"); html.append("<tr>").append("<td align=\"left\" port=\"header\" "); html.append("bgcolor=\"" + node.getHeaderBackgroundColor() + "\">"); String subtitle = Join.join("<br align=\"left\"/>", node.getSubtitles()); if (subtitle.length() != 0) { html.append("<font color=\"").append(node.getHeaderTextColor()); html.append("\" point-size=\"10\">"); html.append(subtitle).append("<br align=\"left\"/>").append("</font>"); } html.append("<font color=\"" + node.getHeaderTextColor() + "\">"); html.append(htmlEscape(node.getTitle())).append("<br align=\"left\"/>"); html.append("</font>").append("</td>").append("</tr>"); for (Map.Entry<String, String> field : node.getFields().entrySet()) { html.append("<tr>"); html.append("<td align=\"left\" port=\"").append(field.getKey()).append("\">"); html.append(htmlEscape(field.getValue())); html.append("</td>").append("</tr>"); } html.append("</table>"); html.append(">"); return html.toString(); }
diff --git a/pcpl.core/src/eplic/core/handlers/SampleHandler.java b/pcpl.core/src/eplic/core/handlers/SampleHandler.java index d54fa0d..4c628a3 100644 --- a/pcpl.core/src/eplic/core/handlers/SampleHandler.java +++ b/pcpl.core/src/eplic/core/handlers/SampleHandler.java @@ -1,99 +1,99 @@ package eplic.core.handlers; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import eplic.core.breakpoint.BreakpointManager; import eplic.core.eventHandler.EventCenter; import eplic.core.mode.NormalMode; import eplic.core.mode.RecordMode; import eplic.core.mode.TraceMode; import eplic.core.ui.pcplDialog; /** * Our sample handler extends AbstractHandler, an IHandler base class. * @see org.eclipse.core.commands.IHandler * @see org.eclipse.core.commands.AbstractHandler */ public class SampleHandler extends AbstractHandler { /** * The constructor. */ private pcplDialog _dialog; public SampleHandler() { initDialog(); } private void initDialog() { _dialog = new pcplDialog(Display.getDefault().getActiveShell()); } /** * the command has been executed, so extract extract the needed information * from the application context. */ public Object execute(ExecutionEvent event) throws ExecutionException { /*IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Hello, Eclipse world");*/ //_dialog.setInput(EventCenter.getInstance().getModeList()); //_dialog.run(); if(EventCenter.getInstance().getModeType() == 0){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Plugin is started"); BreakpointManager.getInstance().removeAllBreakpoint(); BreakpointManager.getInstance().setAllBreakpoint(); NormalMode nm = new NormalMode(); EventCenter.getInstance().setNorMode(nm); System.out.print("BreakPoint Setup \n"); System.out.print("change Mode Type 1\n"); } else if(EventCenter.getInstance().getModeType() == 1){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Now, Do something you want to trace"); RecordMode rm = new RecordMode(); EventCenter.getInstance().setRecMode(rm); System.out.print("change Mode Type 2\n"); } else if(EventCenter.getInstance().getModeType() == 2){//record mode //EventCenter.getInstance().setMode(EventCenter.getInstance().getNorMode()); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Change to TraceMode"); TraceMode tm = new TraceMode(); - EventCenter.getInstance().setRecMode(tm); + EventCenter.getInstance().setTraMode(tm); System.out.print("change Mode Type 3\n"); } else if(EventCenter.getInstance().getModeType() == 3){ //normal mode EventCenter.getInstance().reset(); BreakpointManager.getInstance().reset(); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Reset"); } else{ System.err.print("mode error"); } return null; } }
true
true
public Object execute(ExecutionEvent event) throws ExecutionException { /*IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Hello, Eclipse world");*/ //_dialog.setInput(EventCenter.getInstance().getModeList()); //_dialog.run(); if(EventCenter.getInstance().getModeType() == 0){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Plugin is started"); BreakpointManager.getInstance().removeAllBreakpoint(); BreakpointManager.getInstance().setAllBreakpoint(); NormalMode nm = new NormalMode(); EventCenter.getInstance().setNorMode(nm); System.out.print("BreakPoint Setup \n"); System.out.print("change Mode Type 1\n"); } else if(EventCenter.getInstance().getModeType() == 1){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Now, Do something you want to trace"); RecordMode rm = new RecordMode(); EventCenter.getInstance().setRecMode(rm); System.out.print("change Mode Type 2\n"); } else if(EventCenter.getInstance().getModeType() == 2){//record mode //EventCenter.getInstance().setMode(EventCenter.getInstance().getNorMode()); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Change to TraceMode"); TraceMode tm = new TraceMode(); EventCenter.getInstance().setRecMode(tm); System.out.print("change Mode Type 3\n"); } else if(EventCenter.getInstance().getModeType() == 3){ //normal mode EventCenter.getInstance().reset(); BreakpointManager.getInstance().reset(); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Reset"); } else{ System.err.print("mode error"); } return null; }
public Object execute(ExecutionEvent event) throws ExecutionException { /*IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Hello, Eclipse world");*/ //_dialog.setInput(EventCenter.getInstance().getModeList()); //_dialog.run(); if(EventCenter.getInstance().getModeType() == 0){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Plugin is started"); BreakpointManager.getInstance().removeAllBreakpoint(); BreakpointManager.getInstance().setAllBreakpoint(); NormalMode nm = new NormalMode(); EventCenter.getInstance().setNorMode(nm); System.out.print("BreakPoint Setup \n"); System.out.print("change Mode Type 1\n"); } else if(EventCenter.getInstance().getModeType() == 1){ //normal mode IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Now, Do something you want to trace"); RecordMode rm = new RecordMode(); EventCenter.getInstance().setRecMode(rm); System.out.print("change Mode Type 2\n"); } else if(EventCenter.getInstance().getModeType() == 2){//record mode //EventCenter.getInstance().setMode(EventCenter.getInstance().getNorMode()); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "Change to TraceMode"); TraceMode tm = new TraceMode(); EventCenter.getInstance().setTraMode(tm); System.out.print("change Mode Type 3\n"); } else if(EventCenter.getInstance().getModeType() == 3){ //normal mode EventCenter.getInstance().reset(); BreakpointManager.getInstance().reset(); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openInformation( window.getShell(), "Core", "EPLIC Reset"); } else{ System.err.print("mode error"); } return null; }
diff --git a/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java b/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java index 0fb7c9f2..291b2a79 100644 --- a/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java +++ b/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java @@ -1,189 +1,184 @@ /** * PackageDependenciesTest.java */ package com.eteks.sweethome3d.junit; import java.io.IOException; import jdepend.framework.DependencyConstraint; import jdepend.framework.JDepend; import jdepend.framework.JavaPackage; import jdepend.framework.PackageFilter; import junit.framework.TestCase; /** * Tests if dependencies between Sweet Home 3D packages are met. * @author Emmanuel Puybaret */ public class PackageDependenciesTest extends TestCase { /** * Tests that the package dependencies constraint is met for the analyzed packages. */ public void testPackageDependencies() throws IOException { PackageFilter packageFilter = new PackageFilter(); // Ignore Java packages and Swing sub packages packageFilter.addPackage("java.*"); packageFilter.addPackage("javax.swing.*"); // Ignore JUnit tests packageFilter.addPackage("com.eteks.sweethome3d.junit"); JDepend jdepend = new JDepend(packageFilter); jdepend.addDirectory("classes"); DependencyConstraint constraint = new DependencyConstraint(); // Sweet Home 3D packages JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model"); JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools"); JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin"); JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller"); JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing"); JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d"); JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io"); JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d"); JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet"); // Swing components packages JavaPackage swing = constraint.addPackage("javax.swing"); JavaPackage imageio = constraint.addPackage("javax.imageio"); // Java 3D JavaPackage java3d = constraint.addPackage("javax.media.j3d"); JavaPackage vecmath = constraint.addPackage("javax.vecmath"); JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders"); JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d"); JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry"); JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image"); JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe"); JavaPackage sun3dExpSwing = constraint.addPackage("com.sun.j3d.exp.swing.JCanvas3D"); JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds"); // XML JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers"); JavaPackage xmlSax = constraint.addPackage("org.xml.sax"); JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers"); // JMF JavaPackage jmf = constraint.addPackage("javax.media"); JavaPackage jmfControl = constraint.addPackage("javax.media.control"); JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink"); JavaPackage jmfFormat = constraint.addPackage("javax.media.format"); JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol"); // SunFlow JavaPackage sunflow = constraint.addPackage("org.sunflow"); JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core"); JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light"); JavaPackage sunflowCorePrimitive = constraint.addPackage("org.sunflow.core.primitive"); JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image"); JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math"); JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system"); JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui"); // iText for PDF JavaPackage iText = constraint.addPackage("com.lowagie.text"); JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf"); // FreeHEP Vector Graphics for SVG JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util"); JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg"); // Batik for SVG path parsing JavaPackage orgApacheBatikParser = constraint.addPackage("org.apache.batik.parser"); // Java JNLP JavaPackage jnlp = constraint.addPackage("javax.jnlp"); - // Print attributes - JavaPackage javaxPrintAttribute = constraint.addPackage("javax.print.attribute"); - JavaPackage sunPrint = constraint.addPackage("sun.print"); // Mac OS X specific interfaces JavaPackage eawt = constraint.addPackage("com.applet.eawt"); JavaPackage eio = constraint.addPackage("com.applet.eio"); // Describe dependencies : model don't have any dependency on // other packages, IO and View/Controller packages ignore each other // and Swing components and Java 3D use is isolated in sweetHome3DSwing sweetHome3DTools.dependsUpon(sweetHome3DModel); sweetHome3DTools.dependsUpon(eio); sweetHome3DPlugin.dependsUpon(sweetHome3DModel); sweetHome3DPlugin.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DModel); sweetHome3DViewController.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DPlugin); sweetHome3DJava3D.dependsUpon(sweetHome3DModel); sweetHome3DJava3D.dependsUpon(sweetHome3DTools); sweetHome3DJava3D.dependsUpon(sweetHome3DViewController); sweetHome3DJava3D.dependsUpon(java3d); sweetHome3DJava3D.dependsUpon(vecmath); sweetHome3DJava3D.dependsUpon(sun3dLoaders); sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d); sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry); sweetHome3DJava3D.dependsUpon(sun3dUtilsImage); sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse); sweetHome3DJava3D.dependsUpon(loader3ds); sweetHome3DJava3D.dependsUpon(imageio); sweetHome3DJava3D.dependsUpon(sunflow); sweetHome3DJava3D.dependsUpon(sunflowCore); sweetHome3DJava3D.dependsUpon(sunflowCoreLight); sweetHome3DJava3D.dependsUpon(sunflowCorePrimitive); sweetHome3DJava3D.dependsUpon(sunflowImage); sweetHome3DJava3D.dependsUpon(sunflowMath); sweetHome3DJava3D.dependsUpon(sunflowSystem); sweetHome3DJava3D.dependsUpon(sunflowSystemUI); sweetHome3DJava3D.dependsUpon(xmlParsers); sweetHome3DJava3D.dependsUpon(xmlSax); sweetHome3DJava3D.dependsUpon(xmlSaxHelpers); sweetHome3DJava3D.dependsUpon(orgApacheBatikParser); sweetHome3DSwing.dependsUpon(sweetHome3DModel); sweetHome3DSwing.dependsUpon(sweetHome3DTools); sweetHome3DSwing.dependsUpon(sweetHome3DPlugin); sweetHome3DSwing.dependsUpon(sweetHome3DViewController); sweetHome3DSwing.dependsUpon(sweetHome3DJava3D); sweetHome3DSwing.dependsUpon(swing); sweetHome3DSwing.dependsUpon(imageio); sweetHome3DSwing.dependsUpon(java3d); sweetHome3DSwing.dependsUpon(vecmath); sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry); sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse); sweetHome3DSwing.dependsUpon(sun3dExpSwing); sweetHome3DSwing.dependsUpon(jmf); sweetHome3DSwing.dependsUpon(jmfControl); sweetHome3DSwing.dependsUpon(jmfDataSink); sweetHome3DSwing.dependsUpon(jmfFormat); sweetHome3DSwing.dependsUpon(jmfProtocol); sweetHome3DSwing.dependsUpon(iText); sweetHome3DSwing.dependsUpon(iTextPdf); sweetHome3DSwing.dependsUpon(vectorGraphicsUtil); sweetHome3DSwing.dependsUpon(vectorGraphicsSvg); sweetHome3DSwing.dependsUpon(jnlp); - sweetHome3DSwing.dependsUpon(javaxPrintAttribute); - sweetHome3DSwing.dependsUpon(sunPrint); sweetHome3DIO.dependsUpon(sweetHome3DModel); sweetHome3DIO.dependsUpon(sweetHome3DTools); sweetHome3DIO.dependsUpon(eio); // Describe application and applet assembly packages sweetHome3DApplication.dependsUpon(sweetHome3DModel); sweetHome3DApplication.dependsUpon(sweetHome3DTools); sweetHome3DApplication.dependsUpon(sweetHome3DPlugin); sweetHome3DApplication.dependsUpon(sweetHome3DViewController); sweetHome3DApplication.dependsUpon(sweetHome3DJava3D); sweetHome3DApplication.dependsUpon(sweetHome3DSwing); sweetHome3DApplication.dependsUpon(sweetHome3DIO); sweetHome3DApplication.dependsUpon(swing); sweetHome3DApplication.dependsUpon(imageio); sweetHome3DApplication.dependsUpon(java3d); sweetHome3DApplication.dependsUpon(eawt); sweetHome3DApplication.dependsUpon(jnlp); sweetHome3DApplet.dependsUpon(sweetHome3DModel); sweetHome3DApplet.dependsUpon(sweetHome3DTools); sweetHome3DApplet.dependsUpon(sweetHome3DPlugin); sweetHome3DApplet.dependsUpon(sweetHome3DViewController); sweetHome3DApplet.dependsUpon(sweetHome3DJava3D); sweetHome3DApplet.dependsUpon(sweetHome3DSwing); sweetHome3DApplet.dependsUpon(sweetHome3DIO); sweetHome3DApplet.dependsUpon(swing); sweetHome3DApplet.dependsUpon(java3d); sweetHome3DApplet.dependsUpon(jnlp); jdepend.analyze(); assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint)); } }
false
true
public void testPackageDependencies() throws IOException { PackageFilter packageFilter = new PackageFilter(); // Ignore Java packages and Swing sub packages packageFilter.addPackage("java.*"); packageFilter.addPackage("javax.swing.*"); // Ignore JUnit tests packageFilter.addPackage("com.eteks.sweethome3d.junit"); JDepend jdepend = new JDepend(packageFilter); jdepend.addDirectory("classes"); DependencyConstraint constraint = new DependencyConstraint(); // Sweet Home 3D packages JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model"); JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools"); JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin"); JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller"); JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing"); JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d"); JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io"); JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d"); JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet"); // Swing components packages JavaPackage swing = constraint.addPackage("javax.swing"); JavaPackage imageio = constraint.addPackage("javax.imageio"); // Java 3D JavaPackage java3d = constraint.addPackage("javax.media.j3d"); JavaPackage vecmath = constraint.addPackage("javax.vecmath"); JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders"); JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d"); JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry"); JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image"); JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe"); JavaPackage sun3dExpSwing = constraint.addPackage("com.sun.j3d.exp.swing.JCanvas3D"); JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds"); // XML JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers"); JavaPackage xmlSax = constraint.addPackage("org.xml.sax"); JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers"); // JMF JavaPackage jmf = constraint.addPackage("javax.media"); JavaPackage jmfControl = constraint.addPackage("javax.media.control"); JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink"); JavaPackage jmfFormat = constraint.addPackage("javax.media.format"); JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol"); // SunFlow JavaPackage sunflow = constraint.addPackage("org.sunflow"); JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core"); JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light"); JavaPackage sunflowCorePrimitive = constraint.addPackage("org.sunflow.core.primitive"); JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image"); JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math"); JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system"); JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui"); // iText for PDF JavaPackage iText = constraint.addPackage("com.lowagie.text"); JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf"); // FreeHEP Vector Graphics for SVG JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util"); JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg"); // Batik for SVG path parsing JavaPackage orgApacheBatikParser = constraint.addPackage("org.apache.batik.parser"); // Java JNLP JavaPackage jnlp = constraint.addPackage("javax.jnlp"); // Print attributes JavaPackage javaxPrintAttribute = constraint.addPackage("javax.print.attribute"); JavaPackage sunPrint = constraint.addPackage("sun.print"); // Mac OS X specific interfaces JavaPackage eawt = constraint.addPackage("com.applet.eawt"); JavaPackage eio = constraint.addPackage("com.applet.eio"); // Describe dependencies : model don't have any dependency on // other packages, IO and View/Controller packages ignore each other // and Swing components and Java 3D use is isolated in sweetHome3DSwing sweetHome3DTools.dependsUpon(sweetHome3DModel); sweetHome3DTools.dependsUpon(eio); sweetHome3DPlugin.dependsUpon(sweetHome3DModel); sweetHome3DPlugin.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DModel); sweetHome3DViewController.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DPlugin); sweetHome3DJava3D.dependsUpon(sweetHome3DModel); sweetHome3DJava3D.dependsUpon(sweetHome3DTools); sweetHome3DJava3D.dependsUpon(sweetHome3DViewController); sweetHome3DJava3D.dependsUpon(java3d); sweetHome3DJava3D.dependsUpon(vecmath); sweetHome3DJava3D.dependsUpon(sun3dLoaders); sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d); sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry); sweetHome3DJava3D.dependsUpon(sun3dUtilsImage); sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse); sweetHome3DJava3D.dependsUpon(loader3ds); sweetHome3DJava3D.dependsUpon(imageio); sweetHome3DJava3D.dependsUpon(sunflow); sweetHome3DJava3D.dependsUpon(sunflowCore); sweetHome3DJava3D.dependsUpon(sunflowCoreLight); sweetHome3DJava3D.dependsUpon(sunflowCorePrimitive); sweetHome3DJava3D.dependsUpon(sunflowImage); sweetHome3DJava3D.dependsUpon(sunflowMath); sweetHome3DJava3D.dependsUpon(sunflowSystem); sweetHome3DJava3D.dependsUpon(sunflowSystemUI); sweetHome3DJava3D.dependsUpon(xmlParsers); sweetHome3DJava3D.dependsUpon(xmlSax); sweetHome3DJava3D.dependsUpon(xmlSaxHelpers); sweetHome3DJava3D.dependsUpon(orgApacheBatikParser); sweetHome3DSwing.dependsUpon(sweetHome3DModel); sweetHome3DSwing.dependsUpon(sweetHome3DTools); sweetHome3DSwing.dependsUpon(sweetHome3DPlugin); sweetHome3DSwing.dependsUpon(sweetHome3DViewController); sweetHome3DSwing.dependsUpon(sweetHome3DJava3D); sweetHome3DSwing.dependsUpon(swing); sweetHome3DSwing.dependsUpon(imageio); sweetHome3DSwing.dependsUpon(java3d); sweetHome3DSwing.dependsUpon(vecmath); sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry); sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse); sweetHome3DSwing.dependsUpon(sun3dExpSwing); sweetHome3DSwing.dependsUpon(jmf); sweetHome3DSwing.dependsUpon(jmfControl); sweetHome3DSwing.dependsUpon(jmfDataSink); sweetHome3DSwing.dependsUpon(jmfFormat); sweetHome3DSwing.dependsUpon(jmfProtocol); sweetHome3DSwing.dependsUpon(iText); sweetHome3DSwing.dependsUpon(iTextPdf); sweetHome3DSwing.dependsUpon(vectorGraphicsUtil); sweetHome3DSwing.dependsUpon(vectorGraphicsSvg); sweetHome3DSwing.dependsUpon(jnlp); sweetHome3DSwing.dependsUpon(javaxPrintAttribute); sweetHome3DSwing.dependsUpon(sunPrint); sweetHome3DIO.dependsUpon(sweetHome3DModel); sweetHome3DIO.dependsUpon(sweetHome3DTools); sweetHome3DIO.dependsUpon(eio); // Describe application and applet assembly packages sweetHome3DApplication.dependsUpon(sweetHome3DModel); sweetHome3DApplication.dependsUpon(sweetHome3DTools); sweetHome3DApplication.dependsUpon(sweetHome3DPlugin); sweetHome3DApplication.dependsUpon(sweetHome3DViewController); sweetHome3DApplication.dependsUpon(sweetHome3DJava3D); sweetHome3DApplication.dependsUpon(sweetHome3DSwing); sweetHome3DApplication.dependsUpon(sweetHome3DIO); sweetHome3DApplication.dependsUpon(swing); sweetHome3DApplication.dependsUpon(imageio); sweetHome3DApplication.dependsUpon(java3d); sweetHome3DApplication.dependsUpon(eawt); sweetHome3DApplication.dependsUpon(jnlp); sweetHome3DApplet.dependsUpon(sweetHome3DModel); sweetHome3DApplet.dependsUpon(sweetHome3DTools); sweetHome3DApplet.dependsUpon(sweetHome3DPlugin); sweetHome3DApplet.dependsUpon(sweetHome3DViewController); sweetHome3DApplet.dependsUpon(sweetHome3DJava3D); sweetHome3DApplet.dependsUpon(sweetHome3DSwing); sweetHome3DApplet.dependsUpon(sweetHome3DIO); sweetHome3DApplet.dependsUpon(swing); sweetHome3DApplet.dependsUpon(java3d); sweetHome3DApplet.dependsUpon(jnlp); jdepend.analyze(); assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint)); }
public void testPackageDependencies() throws IOException { PackageFilter packageFilter = new PackageFilter(); // Ignore Java packages and Swing sub packages packageFilter.addPackage("java.*"); packageFilter.addPackage("javax.swing.*"); // Ignore JUnit tests packageFilter.addPackage("com.eteks.sweethome3d.junit"); JDepend jdepend = new JDepend(packageFilter); jdepend.addDirectory("classes"); DependencyConstraint constraint = new DependencyConstraint(); // Sweet Home 3D packages JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model"); JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools"); JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin"); JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller"); JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing"); JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d"); JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io"); JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d"); JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet"); // Swing components packages JavaPackage swing = constraint.addPackage("javax.swing"); JavaPackage imageio = constraint.addPackage("javax.imageio"); // Java 3D JavaPackage java3d = constraint.addPackage("javax.media.j3d"); JavaPackage vecmath = constraint.addPackage("javax.vecmath"); JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders"); JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d"); JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry"); JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image"); JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe"); JavaPackage sun3dExpSwing = constraint.addPackage("com.sun.j3d.exp.swing.JCanvas3D"); JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds"); // XML JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers"); JavaPackage xmlSax = constraint.addPackage("org.xml.sax"); JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers"); // JMF JavaPackage jmf = constraint.addPackage("javax.media"); JavaPackage jmfControl = constraint.addPackage("javax.media.control"); JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink"); JavaPackage jmfFormat = constraint.addPackage("javax.media.format"); JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol"); // SunFlow JavaPackage sunflow = constraint.addPackage("org.sunflow"); JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core"); JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light"); JavaPackage sunflowCorePrimitive = constraint.addPackage("org.sunflow.core.primitive"); JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image"); JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math"); JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system"); JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui"); // iText for PDF JavaPackage iText = constraint.addPackage("com.lowagie.text"); JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf"); // FreeHEP Vector Graphics for SVG JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util"); JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg"); // Batik for SVG path parsing JavaPackage orgApacheBatikParser = constraint.addPackage("org.apache.batik.parser"); // Java JNLP JavaPackage jnlp = constraint.addPackage("javax.jnlp"); // Mac OS X specific interfaces JavaPackage eawt = constraint.addPackage("com.applet.eawt"); JavaPackage eio = constraint.addPackage("com.applet.eio"); // Describe dependencies : model don't have any dependency on // other packages, IO and View/Controller packages ignore each other // and Swing components and Java 3D use is isolated in sweetHome3DSwing sweetHome3DTools.dependsUpon(sweetHome3DModel); sweetHome3DTools.dependsUpon(eio); sweetHome3DPlugin.dependsUpon(sweetHome3DModel); sweetHome3DPlugin.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DModel); sweetHome3DViewController.dependsUpon(sweetHome3DTools); sweetHome3DViewController.dependsUpon(sweetHome3DPlugin); sweetHome3DJava3D.dependsUpon(sweetHome3DModel); sweetHome3DJava3D.dependsUpon(sweetHome3DTools); sweetHome3DJava3D.dependsUpon(sweetHome3DViewController); sweetHome3DJava3D.dependsUpon(java3d); sweetHome3DJava3D.dependsUpon(vecmath); sweetHome3DJava3D.dependsUpon(sun3dLoaders); sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d); sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry); sweetHome3DJava3D.dependsUpon(sun3dUtilsImage); sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse); sweetHome3DJava3D.dependsUpon(loader3ds); sweetHome3DJava3D.dependsUpon(imageio); sweetHome3DJava3D.dependsUpon(sunflow); sweetHome3DJava3D.dependsUpon(sunflowCore); sweetHome3DJava3D.dependsUpon(sunflowCoreLight); sweetHome3DJava3D.dependsUpon(sunflowCorePrimitive); sweetHome3DJava3D.dependsUpon(sunflowImage); sweetHome3DJava3D.dependsUpon(sunflowMath); sweetHome3DJava3D.dependsUpon(sunflowSystem); sweetHome3DJava3D.dependsUpon(sunflowSystemUI); sweetHome3DJava3D.dependsUpon(xmlParsers); sweetHome3DJava3D.dependsUpon(xmlSax); sweetHome3DJava3D.dependsUpon(xmlSaxHelpers); sweetHome3DJava3D.dependsUpon(orgApacheBatikParser); sweetHome3DSwing.dependsUpon(sweetHome3DModel); sweetHome3DSwing.dependsUpon(sweetHome3DTools); sweetHome3DSwing.dependsUpon(sweetHome3DPlugin); sweetHome3DSwing.dependsUpon(sweetHome3DViewController); sweetHome3DSwing.dependsUpon(sweetHome3DJava3D); sweetHome3DSwing.dependsUpon(swing); sweetHome3DSwing.dependsUpon(imageio); sweetHome3DSwing.dependsUpon(java3d); sweetHome3DSwing.dependsUpon(vecmath); sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry); sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse); sweetHome3DSwing.dependsUpon(sun3dExpSwing); sweetHome3DSwing.dependsUpon(jmf); sweetHome3DSwing.dependsUpon(jmfControl); sweetHome3DSwing.dependsUpon(jmfDataSink); sweetHome3DSwing.dependsUpon(jmfFormat); sweetHome3DSwing.dependsUpon(jmfProtocol); sweetHome3DSwing.dependsUpon(iText); sweetHome3DSwing.dependsUpon(iTextPdf); sweetHome3DSwing.dependsUpon(vectorGraphicsUtil); sweetHome3DSwing.dependsUpon(vectorGraphicsSvg); sweetHome3DSwing.dependsUpon(jnlp); sweetHome3DIO.dependsUpon(sweetHome3DModel); sweetHome3DIO.dependsUpon(sweetHome3DTools); sweetHome3DIO.dependsUpon(eio); // Describe application and applet assembly packages sweetHome3DApplication.dependsUpon(sweetHome3DModel); sweetHome3DApplication.dependsUpon(sweetHome3DTools); sweetHome3DApplication.dependsUpon(sweetHome3DPlugin); sweetHome3DApplication.dependsUpon(sweetHome3DViewController); sweetHome3DApplication.dependsUpon(sweetHome3DJava3D); sweetHome3DApplication.dependsUpon(sweetHome3DSwing); sweetHome3DApplication.dependsUpon(sweetHome3DIO); sweetHome3DApplication.dependsUpon(swing); sweetHome3DApplication.dependsUpon(imageio); sweetHome3DApplication.dependsUpon(java3d); sweetHome3DApplication.dependsUpon(eawt); sweetHome3DApplication.dependsUpon(jnlp); sweetHome3DApplet.dependsUpon(sweetHome3DModel); sweetHome3DApplet.dependsUpon(sweetHome3DTools); sweetHome3DApplet.dependsUpon(sweetHome3DPlugin); sweetHome3DApplet.dependsUpon(sweetHome3DViewController); sweetHome3DApplet.dependsUpon(sweetHome3DJava3D); sweetHome3DApplet.dependsUpon(sweetHome3DSwing); sweetHome3DApplet.dependsUpon(sweetHome3DIO); sweetHome3DApplet.dependsUpon(swing); sweetHome3DApplet.dependsUpon(java3d); sweetHome3DApplet.dependsUpon(jnlp); jdepend.analyze(); assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint)); }
diff --git a/src/com/android/voicedialer/VoiceDialerActivity.java b/src/com/android/voicedialer/VoiceDialerActivity.java index ea80e2c..824934e 100644 --- a/src/com/android/voicedialer/VoiceDialerActivity.java +++ b/src/com/android/voicedialer/VoiceDialerActivity.java @@ -1,1176 +1,1177 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.voicedialer; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.SystemProperties; import android.os.Vibrator; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; /** * TODO: get rid of the anonymous classes * * This class is the user interface of the VoiceDialer application. * It begins in the INITIALIZING state. * * INITIALIZING : * This transitions out on events from TTS and the BluetoothHeadset * once TTS initialized and SCO channel set up: * * prompt the user "speak now" * * transition to the SPEAKING_GREETING state * * SPEAKING_GREETING: * This transitions out only on events from TTS or the fallback runnable * once the greeting utterance completes: * * begin listening for the command using the {@link CommandRecognizerEngine} * * transition to the WAITING_FOR_COMMAND state * * WAITING_FOR_COMMAND : * This transitions out only on events from the recognizer * on RecognitionFailure or RecognitionError: * * begin speaking "try again." * * transition to state SPEAKING_TRY_AGAIN * on RecognitionSuccess: * single result: * * begin speaking the sentence describing the intent * * transition to the SPEAKING_CHOSEN_ACTION * multiple results: * * begin speaking each of the choices in order * * transition to the SPEAKING_CHOICES state * * SPEAKING_TRY_AGAIN: * This transitions out only on events from TTS or the fallback runnable * once the try again utterance completes: * * begin listening for the command using the {@link CommandRecognizerEngine} * * transition to the LISTENING_FOR_COMMAND state * * SPEAKING_CHOSEN_ACTION: * This transitions out only on events from TTS or the fallback runnable * once the utterance completes: * * dispatch the intent that was chosen * * transition to the EXITING state * * finish the activity * * SPEAKING_CHOICES: * This transitions out only on events from TTS or the fallback runnable * once the utterance completes: * * begin listening for the user's choice using the * {@link PhoneTypeChoiceRecognizerEngine} * * transition to the WAITING_FOR_CHOICE state. * * WAITING_FOR_CHOICE: * This transitions out only on events from the recognizer * on RecognitionFailure or RecognitionError: * * begin speaking the "invalid choice" message, along with the list * of choices * * transition to the SPEAKING_CHOICES state * on RecognitionSuccess: * if the result is "try again", prompt the user to say a command, begin * listening for the command, and transition back to the WAITING_FOR_COMMAND * state. * if the result is "exit", then being speaking the "goodbye" message and * transition to the SPEAKING_GOODBYE state. * if the result is a valid choice, begin speaking the action chosen,initiate * the command the user has choose and exit. * if not a valid choice, speak the "invalid choice" message, begin * speaking the choices in order again, transition to the * SPEAKING_CHOICES * * SPEAKING_GOODBYE: * This transitions out only on events from TTS or the fallback runnable * after a time out, finish the activity. * */ public class VoiceDialerActivity extends Activity { private static final String TAG = "VoiceDialerActivity"; private static final String MICROPHONE_EXTRA = "microphone"; private static final String CONTACTS_EXTRA = "contacts"; private static final String SPEAK_NOW_UTTERANCE = "speak_now"; private static final String TRY_AGAIN_UTTERANCE = "try_again"; private static final String CHOSEN_ACTION_UTTERANCE = "chose_action"; private static final String GOODBYE_UTTERANCE = "goodbye"; private static final String CHOICES_UTTERANCE = "choices"; private static final int FIRST_UTTERANCE_DELAY = 300; private static final int MAX_TTS_DELAY = 6000; private static final int EXIT_DELAY = 2000; private static final int BLUETOOTH_SAMPLE_RATE = 8000; private static final int REGULAR_SAMPLE_RATE = 11025; private static final int INITIALIZING = 0; private static final int SPEAKING_GREETING = 1; private static final int WAITING_FOR_COMMAND = 2; private static final int SPEAKING_TRY_AGAIN = 3; private static final int SPEAKING_CHOICES = 4; private static final int WAITING_FOR_CHOICE = 5; private static final int WAITING_FOR_DIALOG_CHOICE = 6; private static final int SPEAKING_CHOSEN_ACTION = 7; private static final int SPEAKING_GOODBYE = 8; private static final int EXITING = 9; private static final CommandRecognizerEngine mCommandEngine = new CommandRecognizerEngine(); private static final PhoneTypeChoiceRecognizerEngine mPhoneTypeChoiceEngine = new PhoneTypeChoiceRecognizerEngine(); private CommandRecognizerClient mCommandClient; private ChoiceRecognizerClient mChoiceClient; private ToneGenerator mToneGenerator; private Handler mHandler; private Thread mRecognizerThread = null; private AudioManager mAudioManager; private BluetoothHeadset mBluetoothHeadset; private BluetoothDevice mBluetoothDevice; private BluetoothAdapter mAdapter; private TextToSpeech mTts; private HashMap<String, String> mTtsParams; private VoiceDialerBroadcastReceiver mReceiver; private boolean mWaitingForTts; private boolean mWaitingForScoConnection; private Intent[] mAvailableChoices; private Intent mChosenAction; private int mBluetoothVoiceVolume; private int mState; private AlertDialog mAlertDialog; private Runnable mFallbackRunnable; private boolean mUsingBluetooth = false; private int mSampleRate; private WakeLock mWakeLock; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // TODO: All of this state management and holding of // connections to the TTS engine and recognizer really // belongs in a service. The activity can be stopped or deleted // and recreated for lots of reasons. // It's way too late in the ICS release cycle for a change // like this now though. // MHibdon Sept 20 2011 mHandler = new Handler(); mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE); mToneGenerator = new ToneGenerator(AudioManager.STREAM_RING, ToneGenerator.MAX_VOLUME); acquireWakeLock(this); mState = INITIALIZING; mChosenAction = null; mAudioManager.requestAudioFocus( null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); // set this flag so this activity will stay in front of the keyguard int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; getWindow().addFlags(flags); // open main window setTheme(android.R.style.Theme_Dialog); setTitle(R.string.title); setContentView(R.layout.voice_dialing); findViewById(R.id.microphone_view).setVisibility(View.INVISIBLE); findViewById(R.id.retry_view).setVisibility(View.INVISIBLE); findViewById(R.id.microphone_loading_view).setVisibility(View.VISIBLE); if (RecognizerLogger.isEnabled(this)) { ((TextView) findViewById(R.id.substate)).setText(R.string.logging_enabled); } // Get handle to BluetoothHeadset object IntentFilter audioStateFilter; audioStateFilter = new IntentFilter(); audioStateFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); audioStateFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); mReceiver = new VoiceDialerBroadcastReceiver(); registerReceiver(mReceiver, audioStateFilter); mCommandEngine.setContactsFile(newFile(getArg(CONTACTS_EXTRA))); mCommandEngine.setMinimizeResults(true); mCommandEngine.setAllowOpenEntries(false); mCommandClient = new CommandRecognizerClient(); mChoiceClient = new ChoiceRecognizerClient(); mAdapter = BluetoothAdapter.getDefaultAdapter(); if (BluetoothHeadset.isBluetoothVoiceDialingEnabled(this) && mAdapter != null) { if (!mAdapter.getProfileProxy(this, mBluetoothHeadsetServiceListener, BluetoothProfile.HEADSET)) { Log.e(TAG, "Getting Headset Proxy failed"); } } else { mUsingBluetooth = false; if (false) Log.d(TAG, "bluetooth unavailable"); mSampleRate = REGULAR_SAMPLE_RATE; mCommandEngine.setMinimizeResults(false); mCommandEngine.setAllowOpenEntries(true); // we're not using bluetooth apparently, just start listening. listenForCommand(); } } class ErrorRunnable implements Runnable { private int mErrorMsg; public ErrorRunnable(int errorMsg) { mErrorMsg = errorMsg; } public void run() { // put up an error and exit mHandler.removeCallbacks(mMicFlasher); ((TextView)findViewById(R.id.state)).setText(R.string.failure); ((TextView)findViewById(R.id.substate)).setText(mErrorMsg); ((TextView)findViewById(R.id.substate)).setText( R.string.headset_connection_lost); findViewById(R.id.microphone_view).setVisibility(View.INVISIBLE); findViewById(R.id.retry_view).setVisibility(View.VISIBLE); if (!mUsingBluetooth) { playSound(ToneGenerator.TONE_PROP_NACK); } } } class OnTtsCompletionRunnable implements Runnable { private boolean mFallback; OnTtsCompletionRunnable(boolean fallback) { mFallback = fallback; } public void run() { if (mFallback) { Log.e(TAG, "utterance completion not delivered, using fallback"); } Log.d(TAG, "onTtsCompletionRunnable"); if (mState == SPEAKING_GREETING || mState == SPEAKING_TRY_AGAIN) { listenForCommand(); } else if (mState == SPEAKING_CHOICES) { listenForChoice(); } else if (mState == SPEAKING_GOODBYE) { mState = EXITING; finish(); } else if (mState == SPEAKING_CHOSEN_ACTION) { mState = EXITING; startActivityHelp(mChosenAction); finish(); } } } class GreetingRunnable implements Runnable { public void run() { mState = SPEAKING_GREETING; mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, SPEAK_NOW_UTTERANCE); mTts.speak(getString(R.string.speak_now_tts), TextToSpeech.QUEUE_FLUSH, mTtsParams); // Normally, we will begin listening for the command after the // utterance completes. As a fallback in case the utterance // does not complete, post a delayed runnable to fire // the intent. mFallbackRunnable = new OnTtsCompletionRunnable(true); mHandler.postDelayed(mFallbackRunnable, MAX_TTS_DELAY); } } class TtsInitListener implements TextToSpeech.OnInitListener { public void onInit(int status) { // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR. if (false) Log.d(TAG, "onInit for tts"); if (status != TextToSpeech.SUCCESS) { // Initialization failed. Log.e(TAG, "Could not initialize TextToSpeech."); mHandler.post(new ErrorRunnable(R.string.recognition_error)); exitActivity(); return; } if (mTts == null) { Log.e(TAG, "null tts"); mHandler.post(new ErrorRunnable(R.string.recognition_error)); exitActivity(); return; } mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener()); // The TTS engine has been successfully initialized. mWaitingForTts = false; // TTS over bluetooth is really loud, // Limit volume to -18dB. Stream volume range represents approximately 50dB // (See AudioSystem.cpp linearToLog()) so the number of steps corresponding // to 18dB is 18 / (50 / maxSteps). mBluetoothVoiceVolume = mAudioManager.getStreamVolume( AudioManager.STREAM_BLUETOOTH_SCO); int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_BLUETOOTH_SCO); int volume = maxVolume - ((18 / (50/maxVolume)) + 1); if (mBluetoothVoiceVolume > volume) { mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, volume, 0); } if (mWaitingForScoConnection) { // the bluetooth connection is not up yet, still waiting. } else { // we now have SCO connection and TTS, so we can start. mHandler.postDelayed(new GreetingRunnable(), FIRST_UTTERANCE_DELAY); } } } class OnUtteranceCompletedListener implements TextToSpeech.OnUtteranceCompletedListener { public void onUtteranceCompleted(String utteranceId) { if (false) Log.d(TAG, "onUtteranceCompleted " + utteranceId); // since the utterance has completed, we no longer need the fallback. mHandler.removeCallbacks(mFallbackRunnable); mFallbackRunnable = null; mHandler.post(new OnTtsCompletionRunnable(false)); } } private void updateBluetoothParameters(boolean connected) { if (connected) { if (false) Log.d(TAG, "using bluetooth"); mUsingBluetooth = true; mBluetoothHeadset.startVoiceRecognition(mBluetoothDevice); mSampleRate = BLUETOOTH_SAMPLE_RATE; mCommandEngine.setMinimizeResults(true); mCommandEngine.setAllowOpenEntries(false); // we can't start recognizing until we get connected to the BluetoothHeadset // and have a connected audio state. We will listen for these // states to change. mWaitingForScoConnection = true; // initialize the text to speech system mWaitingForTts = true; mTts = new TextToSpeech(VoiceDialerActivity.this, new TtsInitListener()); mTtsParams = new HashMap<String, String>(); mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_VOICE_CALL)); // we need to wait for the TTS system and the SCO connection // before we can start listening. } else { if (false) Log.d(TAG, "not using bluetooth"); mUsingBluetooth = false; mSampleRate = REGULAR_SAMPLE_RATE; mCommandEngine.setMinimizeResults(false); mCommandEngine.setAllowOpenEntries(true); // we're not using bluetooth apparently, just start listening. listenForCommand(); } } private BluetoothProfile.ServiceListener mBluetoothHeadsetServiceListener = new BluetoothProfile.ServiceListener() { public void onServiceConnected(int profile, BluetoothProfile proxy) { if (false) Log.d(TAG, "onServiceConnected"); mBluetoothHeadset = (BluetoothHeadset) proxy; List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices(); if (deviceList.size() > 0) { mBluetoothDevice = deviceList.get(0); int state = mBluetoothHeadset.getConnectionState(mBluetoothDevice); if (false) Log.d(TAG, "headset status " + state); // We are already connnected to a headset if (state == BluetoothHeadset.STATE_CONNECTED) { updateBluetoothParameters(true); return; } } updateBluetoothParameters(false); } public void onServiceDisconnected(int profile) { mBluetoothHeadset = null; } }; private class VoiceDialerBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); if (false) Log.d(TAG, "HEADSET STATE -> " + state); if (state == BluetoothProfile.STATE_CONNECTED) { if (device == null) { return; } mBluetoothDevice = device; updateBluetoothParameters(true); } else if (state == BluetoothProfile.STATE_DISCONNECTED) { mBluetoothDevice = null; updateBluetoothParameters(false); } } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); int prevState = intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1); if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED && mWaitingForScoConnection) { // SCO channel has just become available. mWaitingForScoConnection = false; if (mWaitingForTts) { // still waiting for the TTS to be set up. } else { // we now have SCO connection and TTS, so we can start. mHandler.postDelayed(new GreetingRunnable(), FIRST_UTTERANCE_DELAY); } } else if (prevState == BluetoothHeadset.STATE_AUDIO_CONNECTED) { if (!mWaitingForScoConnection) { // apparently our connection to the headset has dropped. // we won't be able to continue voicedialing. if (false) Log.d(TAG, "lost sco connection"); mHandler.post(new ErrorRunnable( R.string.headset_connection_lost)); exitActivity(); } } } } } private void askToTryAgain() { // get work off UAPI thread mHandler.post(new Runnable() { public void run() { if (mAlertDialog != null) { mAlertDialog.dismiss(); } mHandler.removeCallbacks(mMicFlasher); ((TextView)findViewById(R.id.state)).setText(R.string.please_try_again); findViewById(R.id.state).setVisibility(View.VISIBLE); findViewById(R.id.microphone_view).setVisibility(View.INVISIBLE); findViewById(R.id.retry_view).setVisibility(View.VISIBLE); if (mUsingBluetooth) { mState = SPEAKING_TRY_AGAIN; mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, TRY_AGAIN_UTTERANCE); mTts.speak(getString(R.string.no_results_tts), TextToSpeech.QUEUE_FLUSH, mTtsParams); // Normally, the we will start listening after the // utterance completes. As a fallback in case the utterance // does not complete, post a delayed runnable to fire // the intent. mFallbackRunnable = new OnTtsCompletionRunnable(true); mHandler.postDelayed(mFallbackRunnable, MAX_TTS_DELAY); } else { try { Thread.sleep(playSound(ToneGenerator.TONE_PROP_NACK)); } catch (InterruptedException e) { } // we are not using tts, so we just start listening again. listenForCommand(); } } }); } private void performChoice() { if (mUsingBluetooth) { String sentenceSpoken = spaceOutDigits( mChosenAction.getStringExtra( RecognizerEngine.SENTENCE_EXTRA)); mState = SPEAKING_CHOSEN_ACTION; mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, CHOSEN_ACTION_UTTERANCE); mTts.speak(sentenceSpoken, TextToSpeech.QUEUE_FLUSH, mTtsParams); // Normally, the intent will be dispatched after the // utterance completes. As a fallback in case the utterance // does not complete, post a delayed runnable to fire // the intent. mFallbackRunnable = new OnTtsCompletionRunnable(true); mHandler.postDelayed(mFallbackRunnable, MAX_TTS_DELAY); } else { // just dispatch the intent startActivityHelp(mChosenAction); finish(); } } private void waitForChoice() { if (mUsingBluetooth) { // We are running in bluetooth mode, and we have // multiple matches. Speak the choices and let // the user choose. // We will not start listening until the utterance // of the choice list completes. speakChoices(); // Normally, listening will begin after the // utterance completes. As a fallback in case the utterance // does not complete, post a delayed runnable to begin // listening. mFallbackRunnable = new OnTtsCompletionRunnable(true); mHandler.postDelayed(mFallbackRunnable, MAX_TTS_DELAY); } else { // We are not running in bluetooth mode, so all // we need to do is wait for the user to select // a choice from the alert dialog. We will wait // indefinitely for this. mState = WAITING_FOR_DIALOG_CHOICE; } } private class CommandRecognizerClient implements RecognizerClient { static final int MIN_VOLUME_TO_SKIP = 2; /** * Called by the {@link RecognizerEngine} when the microphone is started. */ public void onMicrophoneStart(InputStream mic) { if (false) Log.d(TAG, "onMicrophoneStart"); if (!mUsingBluetooth) { playSound(ToneGenerator.TONE_PROP_BEEP); int ringVolume = mAudioManager.getStreamVolume( AudioManager.STREAM_RING); Log.d(TAG, "ringVolume " + ringVolume); if (ringVolume >= MIN_VOLUME_TO_SKIP) { // now we're playing a sound, and corrupting the input sample. // So we need to pull that junk off of the input stream so that the // recognizer won't see it. try { skipBeep(mic); } catch (java.io.IOException e) { Log.e(TAG, "IOException " + e); } } else { if (false) Log.d(TAG, "no tone"); } } mHandler.post(new Runnable() { public void run() { findViewById(R.id.retry_view).setVisibility(View.INVISIBLE); findViewById(R.id.microphone_loading_view).setVisibility( View.INVISIBLE); ((TextView)findViewById(R.id.state)).setText(R.string.listening); mHandler.post(mMicFlasher); } }); } /** * Beep detection */ private static final int START_WINDOW_MS = 500; // Beep detection window duration in ms private static final int SINE_FREQ = 400; // base sine frequency on beep private static final int NUM_PERIODS_BLOCK = 10; // number of sine periods in one energy averaging block private static final int THRESHOLD = 8; // absolute pseudo energy threshold private static final int START = 0; // beep detection start private static final int RISING = 1; // beep rising edge start private static final int TOP = 2; // beep constant energy detected void skipBeep(InputStream is) throws IOException { int sampleCount = ((mSampleRate / SINE_FREQ) * NUM_PERIODS_BLOCK); int blockSize = 2 * sampleCount; // energy averaging block if (is == null || blockSize == 0) { return; } byte[] buf = new byte[blockSize]; int maxBytes = 2 * ((START_WINDOW_MS * mSampleRate) / 1000); maxBytes = ((maxBytes-1) / blockSize + 1) * blockSize; int count = 0; int state = START; // detection state long prevE = 0; // previous pseudo energy long peak = 0; int threshold = THRESHOLD*sampleCount; // absolute energy threshold Log.d(TAG, "blockSize " + blockSize); while (count < maxBytes) { int cnt = 0; while (cnt < blockSize) { int n = is.read(buf, cnt, blockSize-cnt); if (n < 0) { throw new java.io.IOException(); } cnt += n; } // compute pseudo energy cnt = blockSize; long sumx = 0; long sumxx = 0; while (cnt >= 2) { short smp = (short)((buf[cnt - 1] << 8) + (buf[cnt - 2] & 0xFF)); sumx += smp; sumxx += smp*smp; cnt -= 2; } long energy = (sumxx*sampleCount - sumx*sumx)/(sampleCount*sampleCount); Log.d(TAG, "sumx " + sumx + " sumxx " + sumxx + " ee " + energy); switch (state) { case START: if (energy > threshold && energy > (prevE * 2) && prevE != 0) { // rising edge if energy doubled and > abs threshold state = RISING; if (false) Log.d(TAG, "start RISING: " + count +" time: "+ (((1000*count)/2)/mSampleRate)); } break; case RISING: if (energy < threshold || energy < (prevE / 2)){ // energy fell back below half of previous, back to start if (false) Log.d(TAG, "back to START: " + count +" time: "+ (((1000*count)/2)/mSampleRate)); peak = 0; state = START; } else if (energy > (prevE / 2) && energy < (prevE * 2)) { // Start of constant energy if (false) Log.d(TAG, "start TOP: " + count +" time: "+ (((1000*count)/2)/mSampleRate)); if (peak < energy) { peak = energy; } state = TOP; } break; case TOP: if (energy < threshold || energy < (peak / 2)) { // e went to less than half of the peak if (false) Log.d(TAG, "end TOP: " + count +" time: "+ (((1000*count)/2)/mSampleRate)); return; } break; } prevE = energy; count += blockSize; } if (false) Log.d(TAG, "no beep detected, timed out"); } /** * Called by the {@link RecognizerEngine} if the recognizer fails. */ public void onRecognitionFailure(final String msg) { if (false) Log.d(TAG, "onRecognitionFailure " + msg); // we had zero results. Just try again. askToTryAgain(); } /** * Called by the {@link RecognizerEngine} on an internal error. */ public void onRecognitionError(final String msg) { if (false) Log.d(TAG, "onRecognitionError " + msg); mHandler.post(new ErrorRunnable(R.string.recognition_error)); exitActivity(); } /** * Called by the {@link RecognizerEngine} when is succeeds. If there is * only one item, then the Intent is dispatched immediately. * If there are more, then an AlertDialog is displayed and the user is * prompted to select. * @param intents a list of Intents corresponding to the sentences. */ public void onRecognitionSuccess(final Intent[] intents) { if (false) Log.d(TAG, "CommandRecognizerClient onRecognitionSuccess " + intents.length); if (mState != WAITING_FOR_COMMAND) { if (false) Log.d(TAG, "not waiting for command, ignoring"); return; } // store the intents in a member variable so that we can access it // later when the user chooses which action to perform. mAvailableChoices = intents; mHandler.post(new Runnable() { public void run() { if (!mUsingBluetooth) { playSound(ToneGenerator.TONE_PROP_ACK); } mHandler.removeCallbacks(mMicFlasher); String[] sentences = new String[intents.length]; for (int i = 0; i < intents.length; i++) { sentences[i] = intents[i].getStringExtra( RecognizerEngine.SENTENCE_EXTRA); } if (intents.length == 0) { onRecognitionFailure("zero intents"); return; } if (intents.length > 0) { // see if we the response was "exit" or "cancel". String value = intents[0].getStringExtra( RecognizerEngine.SEMANTIC_EXTRA); if (false) Log.d(TAG, "value " + value); if ("X".equals(value)) { exitActivity(); return; } } if (mUsingBluetooth && (intents.length == 1 || !Intent.ACTION_CALL_PRIVILEGED.equals( intents[0].getAction()))) { // When we're running in bluetooth mode, we expect // that the user is not looking at the screen and cannot // interact with the device in any way besides voice // commands. In this case we need to minimize how many // interactions the user has to perform in order to call // someone. // So if there is only one match, instead of making the // user confirm, we just assume it's correct, speak // the choice over TTS, and then dispatch it. // If there are multiple matches for some intent type // besides "call", it's too difficult for the user to // explain which one they meant, so we just take the highest // confidence match and dispatch that. // Speak the sentence for the action we are about // to dispatch so that the user knows what is happening. mChosenAction = intents[0]; performChoice(); return; } else { // Either we are not running in bluetooth mode, // or we had multiple matches. Either way, we need // the user to confirm the choice. // Put up a dialog from which the user can select // his/her choice. DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { if (false) { Log.d(TAG, "cancelListener.onCancel"); } dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "clickListener.onClick " + which); } startActivityHelp(intents[which]); dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener negativeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "negativeListener.onClick " + which); } dialog.dismiss(); finish(); } }; mAlertDialog = - new AlertDialog.Builder(VoiceDialerActivity.this) + new AlertDialog.Builder(VoiceDialerActivity.this, + AlertDialog.THEME_HOLO_DARK) .setTitle(R.string.title) .setItems(sentences, clickListener) .setOnCancelListener(cancelListener) .setNegativeButton(android.R.string.cancel, negativeListener) .show(); waitForChoice(); } } }); } } private class ChoiceRecognizerClient implements RecognizerClient { public void onRecognitionSuccess(final Intent[] intents) { if (false) Log.d(TAG, "ChoiceRecognizerClient onRecognitionSuccess"); if (mState != WAITING_FOR_CHOICE) { if (false) Log.d(TAG, "not waiting for choice, ignoring"); return; } if (mAlertDialog != null) { mAlertDialog.dismiss(); } // disregard all but the first intent. if (intents.length > 0) { String value = intents[0].getStringExtra( RecognizerEngine.SEMANTIC_EXTRA); if (false) Log.d(TAG, "value " + value); if ("R".equals(value)) { if (mUsingBluetooth) { mHandler.post(new GreetingRunnable()); } else { listenForCommand(); } } else if ("X".equals(value)) { exitActivity(); } else { // it's a phone type response mChosenAction = null; for (int i = 0; i < mAvailableChoices.length; i++) { if (value.equalsIgnoreCase( mAvailableChoices[i].getStringExtra( CommandRecognizerEngine.PHONE_TYPE_EXTRA))) { mChosenAction = mAvailableChoices[i]; } } if (mChosenAction != null) { performChoice(); } else { // invalid choice if (false) Log.d(TAG, "invalid choice" + value); if (mUsingBluetooth) { mTtsParams.remove(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID); mTts.speak(getString(R.string.invalid_choice_tts), TextToSpeech.QUEUE_FLUSH, mTtsParams); } waitForChoice(); } } } } public void onRecognitionFailure(String msg) { if (false) Log.d(TAG, "ChoiceRecognizerClient onRecognitionFailure"); exitActivity(); } public void onRecognitionError(String err) { if (false) Log.d(TAG, "ChoiceRecognizerClient onRecognitionError"); mHandler.post(new ErrorRunnable(R.string.recognition_error)); exitActivity(); } public void onMicrophoneStart(InputStream mic) { if (false) Log.d(TAG, "ChoiceRecognizerClient onMicrophoneStart"); } } private void speakChoices() { if (false) Log.d(TAG, "speakChoices"); mState = SPEAKING_CHOICES; String sentenceSpoken = spaceOutDigits( mAvailableChoices[0].getStringExtra( RecognizerEngine.SENTENCE_EXTRA)); // When we have multiple choices, they will be of the form // "call jack jones at home", "call jack jones on mobile". // Speak the entire first sentence, then the last word from each // of the remaining sentences. This will come out to something // like "call jack jones at home mobile or work". StringBuilder builder = new StringBuilder(); builder.append(sentenceSpoken); int count = mAvailableChoices.length; for (int i=1; i < count; i++) { if (i == count-1) { builder.append(" or "); } else { builder.append(" "); } String tmpSentence = mAvailableChoices[i].getStringExtra( RecognizerEngine.SENTENCE_EXTRA); String[] words = tmpSentence.trim().split(" "); builder.append(words[words.length-1]); } mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, CHOICES_UTTERANCE); mTts.speak(builder.toString(), TextToSpeech.QUEUE_ADD, mTtsParams); } private static String spaceOutDigits(String sentenceDisplay) { // if we have a sentence of the form "dial 123 456 7890", // we need to insert a space between each digit, otherwise // the TTS engine will say "dial one hundred twenty three...." // When there already is a space, we also insert a comma, // so that it pauses between sections. For the displayable // sentence "dial 123 456 7890" it will speak // "dial 1 2 3, 4 5 6, 7 8 9 0" char buffer[] = sentenceDisplay.toCharArray(); StringBuilder builder = new StringBuilder(); boolean buildingNumber = false; int l = sentenceDisplay.length(); for (int index = 0; index < l; index++) { char c = buffer[index]; if (Character.isDigit(c)) { if (buildingNumber) { builder.append(" "); } buildingNumber = true; builder.append(c); } else if (c == ' ') { if (buildingNumber) { builder.append(","); } else { builder.append(" "); } } else { buildingNumber = false; builder.append(c); } } return builder.toString(); } private void startActivityHelp(Intent intent) { startActivity(intent); } private void listenForCommand() { if (false) Log.d(TAG, "" + "Command(): MICROPHONE_EXTRA: "+getArg(MICROPHONE_EXTRA)+ ", CONTACTS_EXTRA: "+getArg(CONTACTS_EXTRA)); mState = WAITING_FOR_COMMAND; mRecognizerThread = new Thread() { public void run() { mCommandEngine.recognize(mCommandClient, VoiceDialerActivity.this, newFile(getArg(MICROPHONE_EXTRA)), mSampleRate); } }; mRecognizerThread.start(); } private void listenForChoice() { if (false) Log.d(TAG, "listenForChoice(): MICROPHONE_EXTRA: " + getArg(MICROPHONE_EXTRA)); mState = WAITING_FOR_CHOICE; mRecognizerThread = new Thread() { public void run() { mPhoneTypeChoiceEngine.recognize(mChoiceClient, VoiceDialerActivity.this, newFile(getArg(MICROPHONE_EXTRA)), mSampleRate); } }; mRecognizerThread.start(); } private void exitActivity() { synchronized(this) { if (mState != EXITING) { if (false) Log.d(TAG, "exitActivity"); mState = SPEAKING_GOODBYE; if (mUsingBluetooth) { mTtsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, GOODBYE_UTTERANCE); mTts.speak(getString(R.string.goodbye_tts), TextToSpeech.QUEUE_FLUSH, mTtsParams); // Normally, the activity will finish() after the // utterance completes. As a fallback in case the utterance // does not complete, post a delayed runnable finish the // activity. mFallbackRunnable = new OnTtsCompletionRunnable(true); mHandler.postDelayed(mFallbackRunnable, MAX_TTS_DELAY); } else { mHandler.postDelayed(new Runnable() { public void run() { finish(); } }, EXIT_DELAY); } } } } private String getArg(String name) { if (name == null) return null; String arg = getIntent().getStringExtra(name); if (arg != null) return arg; arg = SystemProperties.get("app.voicedialer." + name); return arg != null && arg.length() > 0 ? arg : null; } private static File newFile(String name) { return name != null ? new File(name) : null; } private int playSound(int toneType) { int msecDelay = 1; // use the MediaPlayer to prompt the user if (mToneGenerator != null) { mToneGenerator.startTone(toneType); msecDelay = StrictMath.max(msecDelay, 300); } // use the Vibrator to prompt the user if (mAudioManager != null && mAudioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER)) { final int VIBRATOR_TIME = 150; final int VIBRATOR_GUARD_TIME = 150; Vibrator vibrator = new Vibrator(); vibrator.vibrate(VIBRATOR_TIME); msecDelay = StrictMath.max(msecDelay, VIBRATOR_TIME + VIBRATOR_GUARD_TIME); } return msecDelay; } protected void onDestroy() { synchronized(this) { mState = EXITING; } if (mAlertDialog != null) { mAlertDialog.dismiss(); } // set the volume back to the level it was before we started. mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mBluetoothVoiceVolume, 0); mAudioManager.abandonAudioFocus(null); // shut down bluetooth, if it exists if (mBluetoothHeadset != null) { mBluetoothHeadset.stopVoiceRecognition(mBluetoothDevice); mAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset); mBluetoothHeadset = null; } // shut down recognizer and wait for the thread to complete if (mRecognizerThread != null) { mRecognizerThread.interrupt(); try { mRecognizerThread.join(); } catch (InterruptedException e) { if (false) Log.d(TAG, "onStop mRecognizerThread.join exception " + e); } mRecognizerThread = null; } // clean up UI mHandler.removeCallbacks(mMicFlasher); mHandler.removeMessages(0); if (mTts != null) { mTts.stop(); mTts.shutdown(); mTts = null; } unregisterReceiver(mReceiver); super.onDestroy(); releaseWakeLock(); } private void acquireWakeLock(Context context) { if (mWakeLock == null) { PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VoiceDialer"); mWakeLock.acquire(); } } private void releaseWakeLock() { if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } private Runnable mMicFlasher = new Runnable() { int visible = View.VISIBLE; public void run() { findViewById(R.id.microphone_view).setVisibility(visible); findViewById(R.id.state).setVisibility(visible); visible = visible == View.VISIBLE ? View.INVISIBLE : View.VISIBLE; mHandler.postDelayed(this, 750); } }; }
true
true
public void onRecognitionSuccess(final Intent[] intents) { if (false) Log.d(TAG, "CommandRecognizerClient onRecognitionSuccess " + intents.length); if (mState != WAITING_FOR_COMMAND) { if (false) Log.d(TAG, "not waiting for command, ignoring"); return; } // store the intents in a member variable so that we can access it // later when the user chooses which action to perform. mAvailableChoices = intents; mHandler.post(new Runnable() { public void run() { if (!mUsingBluetooth) { playSound(ToneGenerator.TONE_PROP_ACK); } mHandler.removeCallbacks(mMicFlasher); String[] sentences = new String[intents.length]; for (int i = 0; i < intents.length; i++) { sentences[i] = intents[i].getStringExtra( RecognizerEngine.SENTENCE_EXTRA); } if (intents.length == 0) { onRecognitionFailure("zero intents"); return; } if (intents.length > 0) { // see if we the response was "exit" or "cancel". String value = intents[0].getStringExtra( RecognizerEngine.SEMANTIC_EXTRA); if (false) Log.d(TAG, "value " + value); if ("X".equals(value)) { exitActivity(); return; } } if (mUsingBluetooth && (intents.length == 1 || !Intent.ACTION_CALL_PRIVILEGED.equals( intents[0].getAction()))) { // When we're running in bluetooth mode, we expect // that the user is not looking at the screen and cannot // interact with the device in any way besides voice // commands. In this case we need to minimize how many // interactions the user has to perform in order to call // someone. // So if there is only one match, instead of making the // user confirm, we just assume it's correct, speak // the choice over TTS, and then dispatch it. // If there are multiple matches for some intent type // besides "call", it's too difficult for the user to // explain which one they meant, so we just take the highest // confidence match and dispatch that. // Speak the sentence for the action we are about // to dispatch so that the user knows what is happening. mChosenAction = intents[0]; performChoice(); return; } else { // Either we are not running in bluetooth mode, // or we had multiple matches. Either way, we need // the user to confirm the choice. // Put up a dialog from which the user can select // his/her choice. DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { if (false) { Log.d(TAG, "cancelListener.onCancel"); } dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "clickListener.onClick " + which); } startActivityHelp(intents[which]); dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener negativeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "negativeListener.onClick " + which); } dialog.dismiss(); finish(); } }; mAlertDialog = new AlertDialog.Builder(VoiceDialerActivity.this) .setTitle(R.string.title) .setItems(sentences, clickListener) .setOnCancelListener(cancelListener) .setNegativeButton(android.R.string.cancel, negativeListener) .show(); waitForChoice(); } } }); }
public void onRecognitionSuccess(final Intent[] intents) { if (false) Log.d(TAG, "CommandRecognizerClient onRecognitionSuccess " + intents.length); if (mState != WAITING_FOR_COMMAND) { if (false) Log.d(TAG, "not waiting for command, ignoring"); return; } // store the intents in a member variable so that we can access it // later when the user chooses which action to perform. mAvailableChoices = intents; mHandler.post(new Runnable() { public void run() { if (!mUsingBluetooth) { playSound(ToneGenerator.TONE_PROP_ACK); } mHandler.removeCallbacks(mMicFlasher); String[] sentences = new String[intents.length]; for (int i = 0; i < intents.length; i++) { sentences[i] = intents[i].getStringExtra( RecognizerEngine.SENTENCE_EXTRA); } if (intents.length == 0) { onRecognitionFailure("zero intents"); return; } if (intents.length > 0) { // see if we the response was "exit" or "cancel". String value = intents[0].getStringExtra( RecognizerEngine.SEMANTIC_EXTRA); if (false) Log.d(TAG, "value " + value); if ("X".equals(value)) { exitActivity(); return; } } if (mUsingBluetooth && (intents.length == 1 || !Intent.ACTION_CALL_PRIVILEGED.equals( intents[0].getAction()))) { // When we're running in bluetooth mode, we expect // that the user is not looking at the screen and cannot // interact with the device in any way besides voice // commands. In this case we need to minimize how many // interactions the user has to perform in order to call // someone. // So if there is only one match, instead of making the // user confirm, we just assume it's correct, speak // the choice over TTS, and then dispatch it. // If there are multiple matches for some intent type // besides "call", it's too difficult for the user to // explain which one they meant, so we just take the highest // confidence match and dispatch that. // Speak the sentence for the action we are about // to dispatch so that the user knows what is happening. mChosenAction = intents[0]; performChoice(); return; } else { // Either we are not running in bluetooth mode, // or we had multiple matches. Either way, we need // the user to confirm the choice. // Put up a dialog from which the user can select // his/her choice. DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { if (false) { Log.d(TAG, "cancelListener.onCancel"); } dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "clickListener.onClick " + which); } startActivityHelp(intents[which]); dialog.dismiss(); finish(); } }; DialogInterface.OnClickListener negativeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (false) { Log.d(TAG, "negativeListener.onClick " + which); } dialog.dismiss(); finish(); } }; mAlertDialog = new AlertDialog.Builder(VoiceDialerActivity.this, AlertDialog.THEME_HOLO_DARK) .setTitle(R.string.title) .setItems(sentences, clickListener) .setOnCancelListener(cancelListener) .setNegativeButton(android.R.string.cancel, negativeListener) .show(); waitForChoice(); } } }); }
diff --git a/src/com/android/contacts/model/EntityModifier.java b/src/com/android/contacts/model/EntityModifier.java index a0a54efaf..61c0c75aa 100644 --- a/src/com/android/contacts/model/EntityModifier.java +++ b/src/com/android/contacts/model/EntityModifier.java @@ -1,477 +1,477 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.model; import com.android.contacts.model.ContactsSource.DataKind; import com.android.contacts.model.ContactsSource.EditField; import com.android.contacts.model.ContactsSource.EditType; import com.android.contacts.model.EntityDelta.ValuesDelta; import com.google.android.collect.Lists; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.Intents.Insert; import android.text.TextUtils; import android.util.Log; import android.util.SparseIntArray; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Helper methods for modifying an {@link EntityDelta}, such as inserting * new rows, or enforcing {@link ContactsSource}. */ public class EntityModifier { private static final String TAG = "EntityModifier"; /** * For the given {@link EntityDelta}, determine if the given * {@link DataKind} could be inserted under specific * {@link ContactsSource}. */ public static boolean canInsert(EntityDelta state, DataKind kind) { // Insert possible when have valid types and under overall maximum final int visibleCount = state.getMimeEntriesCount(kind.mimeType, true); final boolean validTypes = hasValidTypes(state, kind); final boolean validOverall = (kind.typeOverallMax == -1) || (visibleCount < kind.typeOverallMax); return (validTypes && validOverall); } public static boolean hasValidTypes(EntityDelta state, DataKind kind) { if (EntityModifier.hasEditTypes(kind)) { return (getValidTypes(state, kind).size() > 0); } else { return true; } } /** * Ensure that at least one of the given {@link DataKind} exists in the * given {@link EntityDelta} state, and try creating one if none exist. */ public static void ensureKindExists(EntityDelta state, ContactsSource source, String mimeType) { final DataKind kind = source.getKindForMimetype(mimeType); final boolean hasChild = state.getMimeEntriesCount(mimeType, true) > 0; if (!hasChild && kind != null) { // Create child when none exists and valid kind insertChild(state, kind); } } /** * For the given {@link EntityDelta} and {@link DataKind}, return the * list possible {@link EditType} options available based on * {@link ContactsSource}. */ public static ArrayList<EditType> getValidTypes(EntityDelta state, DataKind kind) { return getValidTypes(state, kind, null, true, null); } /** * For the given {@link EntityDelta} and {@link DataKind}, return the * list possible {@link EditType} options available based on * {@link ContactsSource}. * * @param forceInclude Always include this {@link EditType} in the returned * list, even when an otherwise-invalid choice. This is useful * when showing a dialog that includes the current type. */ public static ArrayList<EditType> getValidTypes(EntityDelta state, DataKind kind, EditType forceInclude) { return getValidTypes(state, kind, forceInclude, true, null); } /** * For the given {@link EntityDelta} and {@link DataKind}, return the * list possible {@link EditType} options available based on * {@link ContactsSource}. * * @param forceInclude Always include this {@link EditType} in the returned * list, even when an otherwise-invalid choice. This is useful * when showing a dialog that includes the current type. * @param includeSecondary If true, include any valid types marked as * {@link EditType#secondary}. * @param typeCount When provided, will be used for the frequency count of * each {@link EditType}, otherwise built using * {@link #getTypeFrequencies(EntityDelta, DataKind)}. */ private static ArrayList<EditType> getValidTypes(EntityDelta state, DataKind kind, EditType forceInclude, boolean includeSecondary, SparseIntArray typeCount) { final ArrayList<EditType> validTypes = Lists.newArrayList(); // Bail early if no types provided if (!hasEditTypes(kind)) return validTypes; if (typeCount == null) { // Build frequency counts if not provided typeCount = getTypeFrequencies(state, kind); } // Build list of valid types final int overallCount = typeCount.get(FREQUENCY_TOTAL); for (EditType type : kind.typeList) { final boolean validOverall = (kind.typeOverallMax == -1 ? true : overallCount < kind.typeOverallMax); final boolean validSpecific = (type.specificMax == -1 ? true : typeCount .get(type.rawValue) < type.specificMax); final boolean validSecondary = (includeSecondary ? true : !type.secondary); final boolean forcedInclude = type.equals(forceInclude); if (forcedInclude || (validOverall && validSpecific && validSecondary)) { // Type is valid when no limit, under limit, or forced include validTypes.add(type); } } return validTypes; } private static final int FREQUENCY_TOTAL = Integer.MIN_VALUE; /** * Count up the frequency that each {@link EditType} appears in the given * {@link EntityDelta}. The returned {@link SparseIntArray} maps from * {@link EditType#rawValue} to counts, with the total overall count stored * as {@link #FREQUENCY_TOTAL}. */ private static SparseIntArray getTypeFrequencies(EntityDelta state, DataKind kind) { final SparseIntArray typeCount = new SparseIntArray(); // Find all entries for this kind, bailing early if none found final List<ValuesDelta> mimeEntries = state.getMimeEntries(kind.mimeType); if (mimeEntries == null) return typeCount; int totalCount = 0; for (ValuesDelta entry : mimeEntries) { // Only count visible entries if (!entry.isVisible()) continue; totalCount++; final EditType type = getCurrentType(entry, kind); if (type != null) { final int count = typeCount.get(type.rawValue); typeCount.put(type.rawValue, count + 1); } } typeCount.put(FREQUENCY_TOTAL, totalCount); return typeCount; } /** * Check if the given {@link DataKind} has multiple types that should be * displayed for users to pick. */ public static boolean hasEditTypes(DataKind kind) { return kind.typeList != null && kind.typeList.size() > 0; } /** * Find the {@link EditType} that describes the given * {@link ValuesDelta} row, assuming the given {@link DataKind} dictates * the possible types. */ public static EditType getCurrentType(ValuesDelta entry, DataKind kind) { final Long rawValue = entry.getAsLong(kind.typeColumn); if (rawValue == null) return null; return getType(kind, rawValue.intValue()); } /** * Find the {@link EditType} that describes the given {@link ContentValues} row, * assuming the given {@link DataKind} dictates the possible types. */ public static EditType getCurrentType(ContentValues entry, DataKind kind) { if (kind.typeColumn == null) return null; final Integer rawValue = entry.getAsInteger(kind.typeColumn); if (rawValue == null) return null; return getType(kind, rawValue); } /** * Find the {@link EditType} that describes the given {@link Cursor} row, * assuming the given {@link DataKind} dictates the possible types. */ public static EditType getCurrentType(Cursor cursor, DataKind kind) { if (kind.typeColumn == null) return null; final int index = cursor.getColumnIndex(kind.typeColumn); if (index == -1) return null; final int rawValue = cursor.getInt(index); return getType(kind, rawValue); } /** * Find the {@link EditType} with the given {@link EditType#rawValue}. */ public static EditType getType(DataKind kind, int rawValue) { for (EditType type : kind.typeList) { if (type.rawValue == rawValue) { return type; } } return null; } /** * Return the precedence for the the given {@link EditType#rawValue}, where * lower numbers are higher precedence. */ public static int getTypePrecedence(DataKind kind, int rawValue) { for (int i = 0; i < kind.typeList.size(); i++) { final EditType type = kind.typeList.get(i); if (type.rawValue == rawValue) { return i; } } return Integer.MAX_VALUE; } /** * Find the best {@link EditType} for a potential insert. The "best" is the * first primary type that doesn't already exist. When all valid types * exist, we pick the last valid option. */ public static EditType getBestValidType(EntityDelta state, DataKind kind, boolean includeSecondary, int exactValue) { // Shortcut when no types if (kind.typeColumn == null) return null; // Find type counts and valid primary types, bail if none final SparseIntArray typeCount = getTypeFrequencies(state, kind); final ArrayList<EditType> validTypes = getValidTypes(state, kind, null, includeSecondary, typeCount); if (validTypes.size() == 0) return null; // Keep track of the last valid type final EditType lastType = validTypes.get(validTypes.size() - 1); // Remove any types that already exist Iterator<EditType> iterator = validTypes.iterator(); while (iterator.hasNext()) { final EditType type = iterator.next(); final int count = typeCount.get(type.rawValue); if (count == exactValue) { // Found exact value match return type; } if (count > 0) { // Type already appears, so don't consider iterator.remove(); } } // Use the best remaining, otherwise the last valid if (validTypes.size() > 0) { return validTypes.get(0); } else { return lastType; } } /** * Insert a new child of kind {@link DataKind} into the given * {@link EntityDelta}. Tries using the best {@link EditType} found using * {@link #getBestValidType(EntityDelta, DataKind, boolean, int)}. */ public static ValuesDelta insertChild(EntityDelta state, DataKind kind) { // First try finding a valid primary EditType bestType = getBestValidType(state, kind, false, Integer.MIN_VALUE); if (bestType == null) { // No valid primary found, so expand search to secondary bestType = getBestValidType(state, kind, true, Integer.MIN_VALUE); } return insertChild(state, kind, bestType); } /** * Insert a new child of kind {@link DataKind} into the given * {@link EntityDelta}, marked with the given {@link EditType}. */ public static ValuesDelta insertChild(EntityDelta state, DataKind kind, EditType type) { // Bail early if invalid kind if (kind == null) return null; final ContentValues after = new ContentValues(); // Our parent CONTACT_ID is provided later after.put(Data.MIMETYPE, kind.mimeType); // Fill-in with any requested default values if (kind.defaultValues != null) { after.putAll(kind.defaultValues); } if (kind.typeColumn != null && type != null) { // Set type, if provided after.put(kind.typeColumn, type.rawValue); } final ValuesDelta child = ValuesDelta.fromAfter(after); state.addEntry(child); return child; } /** * Processing to trim any empty {@link ValuesDelta} rows from the given * {@link EntityDelta}, assuming the given {@link ContactsSource} dictates * the structure for various fields. This method ignores rows not described * by the {@link ContactsSource}. */ public static void trimEmpty(ContactsSource source, EntityDelta state) { // Walk through entries for each well-known kind for (DataKind kind : source.getSortedDataKinds()) { final String mimeType = kind.mimeType; final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType); if (entries == null) continue; for (ValuesDelta entry : entries) { // Test and remove this row if empty final boolean touched = entry.isInsert() || entry.isUpdate(); if (touched && EntityModifier.isEmpty(entry, kind)) { // TODO: remove this verbose logging Log.w(TAG, "Trimming: " + entry.toString()); entry.markDeleted(); } } } } /** * Test if the given {@link ValuesDelta} would be considered "empty" in * terms of {@link DataKind#fieldList}. */ public static boolean isEmpty(ValuesDelta values, DataKind kind) { boolean hasValues = false; for (EditField field : kind.fieldList) { // If any field has values, we're not empty final String value = values.getAsString(field.column); if (!TextUtils.isEmpty(value)) { hasValues = true; } } return !hasValues; } /** * Parse the given {@link Bundle} into the given {@link EntityDelta} state, * assuming the extras defined through {@link Intents}. */ public static void parseExtras(Context context, ContactsSource source, EntityDelta state, Bundle extras) { if (extras == null || extras.size() == 0) { // Bail early if no useful data return; } { // StructuredName EntityModifier.ensureKindExists(state, source, StructuredName.CONTENT_ITEM_TYPE); final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE); final String name = extras.getString(Insert.NAME); if (!TextUtils.isEmpty(name) && TextUtils.isGraphic(name)) { child.put(StructuredName.GIVEN_NAME, name); } final String phoneticName = extras.getString(Insert.PHONETIC_NAME); if (!TextUtils.isEmpty(phoneticName) && TextUtils.isGraphic(phoneticName)) { child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName); } } { // StructuredPostal final DataKind kind = source.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.POSTAL_TYPE, Insert.POSTAL, - StructuredPostal.FORMATTED_ADDRESS); + StructuredPostal.STREET); } { // Phone final DataKind kind = source.getKindForMimetype(Phone.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE, Phone.NUMBER); } { // Email final DataKind kind = source.getKindForMimetype(Email.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL, Email.DATA); } { // Im // TODO: handle decodeImProtocol for legacy reasons final DataKind kind = source.getKindForMimetype(Im.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA); } } /** * Parse a specific entry from the given {@link Bundle} and insert into the * given {@link EntityDelta}. Silently skips the insert when missing value * or no valid {@link EditType} found. * * @param typeExtra {@link Bundle} key that holds the incoming * {@link EditType#rawValue} value. * @param valueExtra {@link Bundle} key that holds the incoming value. * @param valueColumn Column to write value into {@link ValuesDelta}. */ public static void parseExtras(EntityDelta state, DataKind kind, Bundle extras, String typeExtra, String valueExtra, String valueColumn) { final String value = extras.getString(valueExtra); // Bail when can't insert type, or value missing final boolean canInsert = EntityModifier.canInsert(state, kind); final boolean validValue = (value != null && TextUtils.isGraphic(value)); if (!validValue || !canInsert) return; // Find exact type, or otherwise best type final int typeValue = extras.getInt(typeExtra, Integer.MIN_VALUE); final EditType editType = EntityModifier.getBestValidType(state, kind, true, typeValue); // Create data row and fill with value final ValuesDelta child = EntityModifier.insertChild(state, kind, editType); child.put(valueColumn, value); if (editType != null && editType.customColumn != null) { // Write down label when custom type picked child.put(editType.customColumn, extras.getString(typeExtra)); } } }
true
true
public static void parseExtras(Context context, ContactsSource source, EntityDelta state, Bundle extras) { if (extras == null || extras.size() == 0) { // Bail early if no useful data return; } { // StructuredName EntityModifier.ensureKindExists(state, source, StructuredName.CONTENT_ITEM_TYPE); final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE); final String name = extras.getString(Insert.NAME); if (!TextUtils.isEmpty(name) && TextUtils.isGraphic(name)) { child.put(StructuredName.GIVEN_NAME, name); } final String phoneticName = extras.getString(Insert.PHONETIC_NAME); if (!TextUtils.isEmpty(phoneticName) && TextUtils.isGraphic(phoneticName)) { child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName); } } { // StructuredPostal final DataKind kind = source.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.POSTAL_TYPE, Insert.POSTAL, StructuredPostal.FORMATTED_ADDRESS); } { // Phone final DataKind kind = source.getKindForMimetype(Phone.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE, Phone.NUMBER); } { // Email final DataKind kind = source.getKindForMimetype(Email.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL, Email.DATA); } { // Im // TODO: handle decodeImProtocol for legacy reasons final DataKind kind = source.getKindForMimetype(Im.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA); } }
public static void parseExtras(Context context, ContactsSource source, EntityDelta state, Bundle extras) { if (extras == null || extras.size() == 0) { // Bail early if no useful data return; } { // StructuredName EntityModifier.ensureKindExists(state, source, StructuredName.CONTENT_ITEM_TYPE); final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE); final String name = extras.getString(Insert.NAME); if (!TextUtils.isEmpty(name) && TextUtils.isGraphic(name)) { child.put(StructuredName.GIVEN_NAME, name); } final String phoneticName = extras.getString(Insert.PHONETIC_NAME); if (!TextUtils.isEmpty(phoneticName) && TextUtils.isGraphic(phoneticName)) { child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName); } } { // StructuredPostal final DataKind kind = source.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.POSTAL_TYPE, Insert.POSTAL, StructuredPostal.STREET); } { // Phone final DataKind kind = source.getKindForMimetype(Phone.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE, Phone.NUMBER); parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE, Phone.NUMBER); } { // Email final DataKind kind = source.getKindForMimetype(Email.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL, Email.DATA); parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL, Email.DATA); } { // Im // TODO: handle decodeImProtocol for legacy reasons final DataKind kind = source.getKindForMimetype(Im.CONTENT_ITEM_TYPE); parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA); } }
diff --git a/src/main/java/plugins/WebOfTrust/pages/IdenticonGenerator.java b/src/main/java/plugins/WebOfTrust/pages/IdenticonGenerator.java index bc4d357..0355320 100644 --- a/src/main/java/plugins/WebOfTrust/pages/IdenticonGenerator.java +++ b/src/main/java/plugins/WebOfTrust/pages/IdenticonGenerator.java @@ -1,79 +1,79 @@ package plugins.WebOfTrust.pages; import java.awt.image.RenderedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import javax.imageio.ImageIO; import plugins.WebOfTrust.identicon.Identicon; import freenet.client.HighLevelSimpleClient; import freenet.clients.http.LinkEnabledCallback; import freenet.clients.http.Toadlet; import freenet.clients.http.ToadletContext; import freenet.clients.http.ToadletContextClosedException; import freenet.support.Base64; import freenet.support.IllegalBase64Exception; import freenet.support.api.HTTPRequest; import freenet.support.io.Closer; public class IdenticonGenerator extends Toadlet implements LinkEnabledCallback { private final String path; public IdenticonGenerator(HighLevelSimpleClient client, String URLPath) { super(client); this.path = URLPath; } public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { - // FIXME: use failsafe get with max length of routig key + // FIXME: use failsafe get with max length of routing key String identityId = request.getParam("identity"); int width = 128; int height = 128; try { width = Integer.parseInt(request.getParam("width")); height = Integer.parseInt(request.getParam("height")); } catch (NumberFormatException nfe1) { /* could not parse, ignore. defaults are fine. */ } if (width < 1) { width = 128; } if (height < 1) { height = 128; } if (height > 800 || width > 800) { // don't let some bad guy eat up our RAM height = 800; width = 800; } ByteArrayOutputStream imageOutputStream = null; byte[] image; try { RenderedImage identiconImage = new Identicon(Base64.decode(identityId)).render(width, height); imageOutputStream = new ByteArrayOutputStream(); ImageIO.write(identiconImage, "png", imageOutputStream); image = imageOutputStream.toByteArray(); writeReply(ctx, 200, "image/png", "OK", image, 0, image.length); } catch (IllegalBase64Exception e) { writeReply(ctx, 403, "text/plain", "invalid routing key", "invalid routing key: " + e.getMessage()); } finally { Closer.close(imageOutputStream); image = null; } } @Override public boolean isEnabled(ToadletContext ctx) { return true; } @Override public String path() { return path; } }
true
true
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { // FIXME: use failsafe get with max length of routig key String identityId = request.getParam("identity"); int width = 128; int height = 128; try { width = Integer.parseInt(request.getParam("width")); height = Integer.parseInt(request.getParam("height")); } catch (NumberFormatException nfe1) { /* could not parse, ignore. defaults are fine. */ } if (width < 1) { width = 128; } if (height < 1) { height = 128; } if (height > 800 || width > 800) { // don't let some bad guy eat up our RAM height = 800; width = 800; } ByteArrayOutputStream imageOutputStream = null; byte[] image; try { RenderedImage identiconImage = new Identicon(Base64.decode(identityId)).render(width, height); imageOutputStream = new ByteArrayOutputStream(); ImageIO.write(identiconImage, "png", imageOutputStream); image = imageOutputStream.toByteArray(); writeReply(ctx, 200, "image/png", "OK", image, 0, image.length); } catch (IllegalBase64Exception e) { writeReply(ctx, 403, "text/plain", "invalid routing key", "invalid routing key: " + e.getMessage()); } finally { Closer.close(imageOutputStream); image = null; } }
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { // FIXME: use failsafe get with max length of routing key String identityId = request.getParam("identity"); int width = 128; int height = 128; try { width = Integer.parseInt(request.getParam("width")); height = Integer.parseInt(request.getParam("height")); } catch (NumberFormatException nfe1) { /* could not parse, ignore. defaults are fine. */ } if (width < 1) { width = 128; } if (height < 1) { height = 128; } if (height > 800 || width > 800) { // don't let some bad guy eat up our RAM height = 800; width = 800; } ByteArrayOutputStream imageOutputStream = null; byte[] image; try { RenderedImage identiconImage = new Identicon(Base64.decode(identityId)).render(width, height); imageOutputStream = new ByteArrayOutputStream(); ImageIO.write(identiconImage, "png", imageOutputStream); image = imageOutputStream.toByteArray(); writeReply(ctx, 200, "image/png", "OK", image, 0, image.length); } catch (IllegalBase64Exception e) { writeReply(ctx, 403, "text/plain", "invalid routing key", "invalid routing key: " + e.getMessage()); } finally { Closer.close(imageOutputStream); image = null; } }
diff --git a/loci/formats/BaseTiffReader.java b/loci/formats/BaseTiffReader.java index d2531f8e9..eb2450528 100644 --- a/loci/formats/BaseTiffReader.java +++ b/loci/formats/BaseTiffReader.java @@ -1,522 +1,521 @@ // // BaseTiffReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-2006 Melissa Linkert, Curtis Rueden and Eric Kjellman. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Hashtable; /** * BaseTiffReader is the superclass for file format readers compatible with * or derived from the TIFF 6.0 file format. * * @author Curtis Rueden ctrueden at wisc.edu * @author Melissa Linkert linkert at cs.wisc.edu */ public abstract class BaseTiffReader extends FormatReader { // -- Fields -- /** Random access file for the current TIFF. */ protected RandomAccessFile in; /** List of IFDs for the current TIFF. */ protected Hashtable[] ifds; /** Number of images in the current TIFF stack. */ protected int numImages; // -- Constructors -- /** Constructs a new BaseTiffReader. */ public BaseTiffReader(String name, String suffix) { super(name, suffix); } /** Constructs a new BaseTiffReader. */ public BaseTiffReader(String name, String[] suffixes) { super(name, suffixes); } // -- BaseTiffReader API methods -- /** Gets the dimensions of the given (possibly multi-page) TIFF file. */ public int[] getTiffDimensions(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (ifds == null || ifds.length == 0) return null; return new int[] { TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_WIDTH, false, -1), TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_LENGTH, false, -1), numImages }; } // -- Internal BaseTiffReader API methods -- /** Populates the metadata hashtable and OME root node. */ protected void initMetadata() { initStandardMetadata(); initOMEMetadata(); } /** Parses standard metadata. */ protected void initStandardMetadata() { Hashtable ifd = ifds[0]; put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH); put("ImageLength", ifd, TiffTools.IMAGE_LENGTH); put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE); int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION); String compression = null; switch (comp) { case TiffTools.UNCOMPRESSED: compression = "None"; break; case TiffTools.CCITT_1D: compression = "CCITT Group 3 1-Dimensional Modified Huffman"; break; case TiffTools.GROUP_3_FAX: compression = "CCITT T.4 bilevel encoding"; break; case TiffTools.GROUP_4_FAX: compression = "CCITT T.6 bilevel encoding"; break; case TiffTools.LZW: compression = "LZW"; break; case TiffTools.JPEG: compression = "JPEG"; break; case TiffTools.PACK_BITS: compression = "PackBits"; break; } put("Compression", compression); int photo = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION); String photoInterp = null; switch (photo) { case TiffTools.WHITE_IS_ZERO: photoInterp = "WhiteIsZero"; break; case TiffTools.BLACK_IS_ZERO: photoInterp = "BlackIsZero"; break; case TiffTools.RGB: photoInterp = "RGB"; break; case TiffTools.RGB_PALETTE: photoInterp = "Palette"; break; case TiffTools.TRANSPARENCY_MASK: photoInterp = "Transparency Mask"; break; case TiffTools.CMYK: photoInterp = "CMYK"; break; case TiffTools.Y_CB_CR: photoInterp = "YCbCr"; break; case TiffTools.CIE_LAB: photoInterp = "CIELAB"; break; } put("PhotometricInterpretation", photoInterp); putInt("CellWidth", ifd, TiffTools.CELL_WIDTH); putInt("CellLength", ifd, TiffTools.CELL_LENGTH); int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION); String orientation = null; // there is no case 0 switch (or) { case 1: orientation = "1st row -> top; 1st column -> left"; break; case 2: orientation = "1st row -> top; 1st column -> right"; break; case 3: orientation = "1st row -> bottom; 1st column -> right"; break; case 4: orientation = "1st row -> bottom; 1st column -> left"; break; case 5: orientation = "1st row -> left; 1st column -> top"; break; case 6: orientation = "1st row -> right; 1st column -> top"; break; case 7: orientation = "1st row -> right; 1st column -> bottom"; break; case 8: orientation = "1st row -> left; 1st column -> bottom"; break; } put("Orientation", orientation); putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL); put("Software", ifd, TiffTools.SOFTWARE); put("DateTime", ifd, TiffTools.DATE_TIME); put("Artist", ifd, TiffTools.ARTIST); put("HostComputer", ifd, TiffTools.HOST_COMPUTER); put("Copyright", ifd, TiffTools.COPYRIGHT); put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE); int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING); String threshholding = null; switch (thresh) { case 1: threshholding = "No dithering or halftoning"; break; case 2: threshholding = "Ordered dithering or halftoning"; break; case 3: threshholding = "Randomized error diffusion"; break; } put("Threshholding", threshholding); int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER); String fillOrder = null; switch (fill) { case 1: fillOrder = "Pixels with lower column values are stored " + "in the higher order bits of a byte"; break; case 2: fillOrder = "Pixels with lower column values are stored " + "in the lower order bits of a byte"; break; } put("FillOrder", fillOrder); putInt("Make", ifd, TiffTools.MAKE); putInt("Model", ifd, TiffTools.MODEL); putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE); putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE); putInt("XResolution", ifd, TiffTools.X_RESOLUTION); putInt("YResolution", ifd, TiffTools.Y_RESOLUTION); int planar = TiffTools.getIFDIntValue(ifd, TiffTools.PLANAR_CONFIGURATION); String planarConfig = null; switch (planar) { case 1: planarConfig = "Chunky"; break; case 2: planarConfig = "Planar"; break; } put("PlanarConfiguration", planarConfig); putInt("XPosition", ifd, TiffTools.X_POSITION); putInt("YPosition", ifd, TiffTools.Y_POSITION); putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS); putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS); putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT); putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE); putInt("T4Options", ifd, TiffTools.T4_OPTIONS); putInt("T6Options", ifd, TiffTools.T6_OPTIONS); int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT); String resUnit = null; switch (res) { case 1: resUnit = "None"; break; case 2: resUnit = "Inch"; break; case 3: resUnit = "Centimeter"; break; } put("ResolutionUnit", resUnit); putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER); putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION); int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR); String predictor = null; switch (predict) { case 1: predictor = "No prediction scheme"; break; case 2: predictor = "Horizontal differencing"; break; } put("Predictor", predictor); putInt("WhitePoint", ifd, TiffTools.WHITE_POINT); putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES); putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS); putInt("TileWidth", ifd, TiffTools.TILE_WIDTH); putInt("TileLength", ifd, TiffTools.TILE_LENGTH); putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS); putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS); int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET); String inkSet = null; switch (ink) { case 1: inkSet = "CMYK"; break; case 2: inkSet = "Other"; break; } put("InkSet", inkSet); putInt("InkNames", ifd, TiffTools.INK_NAMES); putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS); putInt("DotRange", ifd, TiffTools.DOT_RANGE); put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER); putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES); int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT); String sampleFormat = null; switch (fmt) { case 1: sampleFormat = "unsigned integer"; break; case 2: sampleFormat = "two's complement signed integer"; break; case 3: sampleFormat = "IEEE floating point"; break; case 4: sampleFormat = "undefined"; break; } put("SampleFormat", sampleFormat); putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE); putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE); putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE); int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC); String jpegProc = null; switch (jpeg) { case 1: jpegProc = "baseline sequential process"; break; case 14: jpegProc = "lossless process with Huffman coding"; break; } put("JPEGProc", jpegProc); putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT); putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL); putInt("JPEGLosslessPredictors", ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS); putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS); putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES); putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES); putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES); putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS); int ycbcr = TiffTools.getIFDIntValue(ifd, TiffTools.Y_CB_CR_SUB_SAMPLING); String subSampling = null; switch (ycbcr) { case 1: subSampling = "chroma image dimensions = luma image dimensions"; break; case 2: subSampling = "chroma image dimensions are " + "half the luma image dimensions"; break; case 4: subSampling = "chroma image dimensions are " + "1/4 the luma image dimensions"; break; } put("YCbCrSubSampling", subSampling); putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING); putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE); // bits per sample and number of channels Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE); int bps = -1, numC = 3; if (bpsObj instanceof int[]) { int[] q = (int[]) bpsObj; bps = q[0]; numC = q.length; } else if (bpsObj instanceof Number) { bps = ((Number) bpsObj).intValue(); numC = 1; } put("BitsPerSample", bps); put("NumberOfChannels", numC); // TIFF comment String comment = null; - Object commentObj = (String) - TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); - if (commentObj instanceof String) comment = (String) commentObj; - else if (commentObj instanceof String[]) { - String[] s = (String[]) commentObj; + Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); + if (o instanceof String) comment = (String) o; + else if (o instanceof String[]) { + String[] s = (String[]) o; if (s.length > 0) comment = s[0]; } - else if (commentObj != null) comment = commentObj.toString(); + else if (o != null) comment = o.toString(); if (comment != null) { // sanitize comment comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF comment = comment.replaceAll("\r", "\n"); // CR to LF put("Comment", comment); } } /** Parses OME-XML metadata. */ protected void initOMEMetadata() { final String unknown = "unknown"; Hashtable ifd = ifds[0]; try { if (ome == null) return; // OME-XML functionality is not available // populate Pixels element int sizeX = TiffTools.getIFDIntValue(ifd, TiffTools.IMAGE_WIDTH); int sizeY = TiffTools.getIFDIntValue(ifd, TiffTools.IMAGE_LENGTH); int sizeZ = 1; int sizeT = ifds.length; int sizeC = ((Integer) metadata.get("NumberOfChannels")).intValue(); boolean bigEndian = !TiffTools.isLittleEndian(ifd); int sample = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT); String pixelType; switch (sample) { case 1: pixelType = "int"; break; case 2: pixelType = "Uint"; break; case 3: pixelType = "float"; break; default: pixelType = unknown; } if (pixelType.indexOf("int") >= 0) { // int or Uint pixelType += TiffTools.getIFDIntValue(ifd, TiffTools.BITS_PER_SAMPLE); } OMETools.setPixels(ome, new Integer(sizeX), new Integer(sizeY), new Integer(sizeZ), new Integer(sizeC), new Integer(sizeT), pixelType, new Boolean(bigEndian), null); // populate Experimenter element String artist = (String) TiffTools.getIFDValue(ifd, TiffTools.ARTIST); if (artist != null) { String firstName = null, lastName = null; int ndx = artist.indexOf(" "); if (ndx < 0) lastName = artist; else { firstName = artist.substring(0, ndx); lastName = artist.substring(ndx + 1); } String email = (String) TiffTools.getIFDValue(ifd, TiffTools.HOST_COMPUTER); OMETools.setExperimenter(ome, firstName, lastName, email, null, null, null); } // populate Image element String creationDate = (String) TiffTools.getIFDValue(ifd, TiffTools.DATE_TIME); String description = (String) metadata.get("Comment"); OMETools.setImage(ome, null, creationDate, description); // populate Dimensions element int pixelSizeX = TiffTools.getIFDIntValue(ifd, TiffTools.CELL_WIDTH, false, 0); int pixelSizeY = TiffTools.getIFDIntValue(ifd, TiffTools.CELL_LENGTH, false, 0); int pixelSizeZ = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION, false, 0); OMETools.setDimensions(ome, new Float(pixelSizeX), new Float(pixelSizeY), new Float(pixelSizeZ), null, null); // OMETools.setAttribute(ome, "ChannelInfo", "SamplesPerPixel", "" + // TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLES_PER_PIXEL)); // int photoInterp2 = TiffTools.getIFDIntValue(ifd, // TiffTools.PHOTOMETRIC_INTERPRETATION, true, 0); // String photo2; // switch (photoInterp2) { // case 0: photo2 = "monochrome"; break; // case 1: photo2 = "monochrome"; break; // case 2: photo2 = "RGB"; break; // case 3: photo2 = "monochrome"; break; // case 4: photo2 = "RGB"; break; // default: photo2 = unknown; // } // OMETools.setAttribute(ome, "ChannelInfo", // "PhotometricInterpretation", photo2); // populate StageLabel element Object x = TiffTools.getIFDValue(ifd, TiffTools.X_POSITION); Object y = TiffTools.getIFDValue(ifd, TiffTools.Y_POSITION); Float stageX; Float stageY; if (x instanceof TiffRational) { stageX = x == null ? null : new Float(((TiffRational) x).floatValue()); stageY = y == null ? null : new Float(((TiffRational) y).floatValue()); } else { stageX = x == null ? null : new Float((String) x); stageY = y == null ? null : new Float((String) y); } OMETools.setStageLabel(ome, null, stageX, stageY, null); // populate Instrument element String model = (String) TiffTools.getIFDValue(ifd, TiffTools.MODEL); String serialNumber = (String) TiffTools.getIFDValue(ifd, TiffTools.MAKE); OMETools.setInstrument(ome, null, model, serialNumber, null); } catch (FormatException exc) { exc.printStackTrace(); } } // -- FormatReader API methods -- /** Checks if the given block is a valid header for a TIFF file. */ public boolean isThisType(byte[] block) { return TiffTools.isValidHeader(block); } /** Determines the number of images in the given TIFF file. */ public int getImageCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); return numImages; } /** Obtains the specified image from the given TIFF file. */ public BufferedImage open(String id, int no) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (no < 0 || no >= numImages) { throw new FormatException("Invalid image number: " + no); } return TiffTools.getImage(ifds[no], in); } /** Closes any open files. */ public void close() throws FormatException, IOException { if (in != null) in.close(); in = null; currentId = null; } /** Initializes the given TIFF file. */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessFile(id, "r"); ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); numImages = ifds.length; initMetadata(); } // -- Helper methods -- protected void put(String key, Object value) { if (value == null) return; metadata.put(key, value); } protected void put(String key, int value) { if (value == -1) return; // indicates missing value metadata.put(key, new Integer(value)); } protected void put(String key, boolean value) { put(key, new Boolean(value)); } protected void put(String key, byte value) { put(key, new Byte(value)); } protected void put(String key, char value) { put(key, new Character(value)); } protected void put(String key, double value) { put(key, new Double(value)); } protected void put(String key, float value) { put(key, new Float(value)); } protected void put(String key, long value) { put(key, new Long(value)); } protected void put(String key, short value) { put(key, new Short(value)); } protected void put(String key, Hashtable ifd, int tag) { put(key, TiffTools.getIFDValue(ifd, tag)); } protected void putInt(String key, Hashtable ifd, int tag) { put(key, TiffTools.getIFDIntValue(ifd, tag)); } }
false
true
protected void initStandardMetadata() { Hashtable ifd = ifds[0]; put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH); put("ImageLength", ifd, TiffTools.IMAGE_LENGTH); put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE); int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION); String compression = null; switch (comp) { case TiffTools.UNCOMPRESSED: compression = "None"; break; case TiffTools.CCITT_1D: compression = "CCITT Group 3 1-Dimensional Modified Huffman"; break; case TiffTools.GROUP_3_FAX: compression = "CCITT T.4 bilevel encoding"; break; case TiffTools.GROUP_4_FAX: compression = "CCITT T.6 bilevel encoding"; break; case TiffTools.LZW: compression = "LZW"; break; case TiffTools.JPEG: compression = "JPEG"; break; case TiffTools.PACK_BITS: compression = "PackBits"; break; } put("Compression", compression); int photo = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION); String photoInterp = null; switch (photo) { case TiffTools.WHITE_IS_ZERO: photoInterp = "WhiteIsZero"; break; case TiffTools.BLACK_IS_ZERO: photoInterp = "BlackIsZero"; break; case TiffTools.RGB: photoInterp = "RGB"; break; case TiffTools.RGB_PALETTE: photoInterp = "Palette"; break; case TiffTools.TRANSPARENCY_MASK: photoInterp = "Transparency Mask"; break; case TiffTools.CMYK: photoInterp = "CMYK"; break; case TiffTools.Y_CB_CR: photoInterp = "YCbCr"; break; case TiffTools.CIE_LAB: photoInterp = "CIELAB"; break; } put("PhotometricInterpretation", photoInterp); putInt("CellWidth", ifd, TiffTools.CELL_WIDTH); putInt("CellLength", ifd, TiffTools.CELL_LENGTH); int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION); String orientation = null; // there is no case 0 switch (or) { case 1: orientation = "1st row -> top; 1st column -> left"; break; case 2: orientation = "1st row -> top; 1st column -> right"; break; case 3: orientation = "1st row -> bottom; 1st column -> right"; break; case 4: orientation = "1st row -> bottom; 1st column -> left"; break; case 5: orientation = "1st row -> left; 1st column -> top"; break; case 6: orientation = "1st row -> right; 1st column -> top"; break; case 7: orientation = "1st row -> right; 1st column -> bottom"; break; case 8: orientation = "1st row -> left; 1st column -> bottom"; break; } put("Orientation", orientation); putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL); put("Software", ifd, TiffTools.SOFTWARE); put("DateTime", ifd, TiffTools.DATE_TIME); put("Artist", ifd, TiffTools.ARTIST); put("HostComputer", ifd, TiffTools.HOST_COMPUTER); put("Copyright", ifd, TiffTools.COPYRIGHT); put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE); int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING); String threshholding = null; switch (thresh) { case 1: threshholding = "No dithering or halftoning"; break; case 2: threshholding = "Ordered dithering or halftoning"; break; case 3: threshholding = "Randomized error diffusion"; break; } put("Threshholding", threshholding); int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER); String fillOrder = null; switch (fill) { case 1: fillOrder = "Pixels with lower column values are stored " + "in the higher order bits of a byte"; break; case 2: fillOrder = "Pixels with lower column values are stored " + "in the lower order bits of a byte"; break; } put("FillOrder", fillOrder); putInt("Make", ifd, TiffTools.MAKE); putInt("Model", ifd, TiffTools.MODEL); putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE); putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE); putInt("XResolution", ifd, TiffTools.X_RESOLUTION); putInt("YResolution", ifd, TiffTools.Y_RESOLUTION); int planar = TiffTools.getIFDIntValue(ifd, TiffTools.PLANAR_CONFIGURATION); String planarConfig = null; switch (planar) { case 1: planarConfig = "Chunky"; break; case 2: planarConfig = "Planar"; break; } put("PlanarConfiguration", planarConfig); putInt("XPosition", ifd, TiffTools.X_POSITION); putInt("YPosition", ifd, TiffTools.Y_POSITION); putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS); putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS); putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT); putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE); putInt("T4Options", ifd, TiffTools.T4_OPTIONS); putInt("T6Options", ifd, TiffTools.T6_OPTIONS); int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT); String resUnit = null; switch (res) { case 1: resUnit = "None"; break; case 2: resUnit = "Inch"; break; case 3: resUnit = "Centimeter"; break; } put("ResolutionUnit", resUnit); putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER); putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION); int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR); String predictor = null; switch (predict) { case 1: predictor = "No prediction scheme"; break; case 2: predictor = "Horizontal differencing"; break; } put("Predictor", predictor); putInt("WhitePoint", ifd, TiffTools.WHITE_POINT); putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES); putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS); putInt("TileWidth", ifd, TiffTools.TILE_WIDTH); putInt("TileLength", ifd, TiffTools.TILE_LENGTH); putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS); putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS); int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET); String inkSet = null; switch (ink) { case 1: inkSet = "CMYK"; break; case 2: inkSet = "Other"; break; } put("InkSet", inkSet); putInt("InkNames", ifd, TiffTools.INK_NAMES); putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS); putInt("DotRange", ifd, TiffTools.DOT_RANGE); put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER); putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES); int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT); String sampleFormat = null; switch (fmt) { case 1: sampleFormat = "unsigned integer"; break; case 2: sampleFormat = "two's complement signed integer"; break; case 3: sampleFormat = "IEEE floating point"; break; case 4: sampleFormat = "undefined"; break; } put("SampleFormat", sampleFormat); putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE); putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE); putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE); int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC); String jpegProc = null; switch (jpeg) { case 1: jpegProc = "baseline sequential process"; break; case 14: jpegProc = "lossless process with Huffman coding"; break; } put("JPEGProc", jpegProc); putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT); putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL); putInt("JPEGLosslessPredictors", ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS); putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS); putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES); putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES); putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES); putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS); int ycbcr = TiffTools.getIFDIntValue(ifd, TiffTools.Y_CB_CR_SUB_SAMPLING); String subSampling = null; switch (ycbcr) { case 1: subSampling = "chroma image dimensions = luma image dimensions"; break; case 2: subSampling = "chroma image dimensions are " + "half the luma image dimensions"; break; case 4: subSampling = "chroma image dimensions are " + "1/4 the luma image dimensions"; break; } put("YCbCrSubSampling", subSampling); putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING); putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE); // bits per sample and number of channels Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE); int bps = -1, numC = 3; if (bpsObj instanceof int[]) { int[] q = (int[]) bpsObj; bps = q[0]; numC = q.length; } else if (bpsObj instanceof Number) { bps = ((Number) bpsObj).intValue(); numC = 1; } put("BitsPerSample", bps); put("NumberOfChannels", numC); // TIFF comment String comment = null; Object commentObj = (String) TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); if (commentObj instanceof String) comment = (String) commentObj; else if (commentObj instanceof String[]) { String[] s = (String[]) commentObj; if (s.length > 0) comment = s[0]; } else if (commentObj != null) comment = commentObj.toString(); if (comment != null) { // sanitize comment comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF comment = comment.replaceAll("\r", "\n"); // CR to LF put("Comment", comment); } }
protected void initStandardMetadata() { Hashtable ifd = ifds[0]; put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH); put("ImageLength", ifd, TiffTools.IMAGE_LENGTH); put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE); int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION); String compression = null; switch (comp) { case TiffTools.UNCOMPRESSED: compression = "None"; break; case TiffTools.CCITT_1D: compression = "CCITT Group 3 1-Dimensional Modified Huffman"; break; case TiffTools.GROUP_3_FAX: compression = "CCITT T.4 bilevel encoding"; break; case TiffTools.GROUP_4_FAX: compression = "CCITT T.6 bilevel encoding"; break; case TiffTools.LZW: compression = "LZW"; break; case TiffTools.JPEG: compression = "JPEG"; break; case TiffTools.PACK_BITS: compression = "PackBits"; break; } put("Compression", compression); int photo = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION); String photoInterp = null; switch (photo) { case TiffTools.WHITE_IS_ZERO: photoInterp = "WhiteIsZero"; break; case TiffTools.BLACK_IS_ZERO: photoInterp = "BlackIsZero"; break; case TiffTools.RGB: photoInterp = "RGB"; break; case TiffTools.RGB_PALETTE: photoInterp = "Palette"; break; case TiffTools.TRANSPARENCY_MASK: photoInterp = "Transparency Mask"; break; case TiffTools.CMYK: photoInterp = "CMYK"; break; case TiffTools.Y_CB_CR: photoInterp = "YCbCr"; break; case TiffTools.CIE_LAB: photoInterp = "CIELAB"; break; } put("PhotometricInterpretation", photoInterp); putInt("CellWidth", ifd, TiffTools.CELL_WIDTH); putInt("CellLength", ifd, TiffTools.CELL_LENGTH); int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION); String orientation = null; // there is no case 0 switch (or) { case 1: orientation = "1st row -> top; 1st column -> left"; break; case 2: orientation = "1st row -> top; 1st column -> right"; break; case 3: orientation = "1st row -> bottom; 1st column -> right"; break; case 4: orientation = "1st row -> bottom; 1st column -> left"; break; case 5: orientation = "1st row -> left; 1st column -> top"; break; case 6: orientation = "1st row -> right; 1st column -> top"; break; case 7: orientation = "1st row -> right; 1st column -> bottom"; break; case 8: orientation = "1st row -> left; 1st column -> bottom"; break; } put("Orientation", orientation); putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL); put("Software", ifd, TiffTools.SOFTWARE); put("DateTime", ifd, TiffTools.DATE_TIME); put("Artist", ifd, TiffTools.ARTIST); put("HostComputer", ifd, TiffTools.HOST_COMPUTER); put("Copyright", ifd, TiffTools.COPYRIGHT); put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE); int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING); String threshholding = null; switch (thresh) { case 1: threshholding = "No dithering or halftoning"; break; case 2: threshholding = "Ordered dithering or halftoning"; break; case 3: threshholding = "Randomized error diffusion"; break; } put("Threshholding", threshholding); int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER); String fillOrder = null; switch (fill) { case 1: fillOrder = "Pixels with lower column values are stored " + "in the higher order bits of a byte"; break; case 2: fillOrder = "Pixels with lower column values are stored " + "in the lower order bits of a byte"; break; } put("FillOrder", fillOrder); putInt("Make", ifd, TiffTools.MAKE); putInt("Model", ifd, TiffTools.MODEL); putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE); putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE); putInt("XResolution", ifd, TiffTools.X_RESOLUTION); putInt("YResolution", ifd, TiffTools.Y_RESOLUTION); int planar = TiffTools.getIFDIntValue(ifd, TiffTools.PLANAR_CONFIGURATION); String planarConfig = null; switch (planar) { case 1: planarConfig = "Chunky"; break; case 2: planarConfig = "Planar"; break; } put("PlanarConfiguration", planarConfig); putInt("XPosition", ifd, TiffTools.X_POSITION); putInt("YPosition", ifd, TiffTools.Y_POSITION); putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS); putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS); putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT); putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE); putInt("T4Options", ifd, TiffTools.T4_OPTIONS); putInt("T6Options", ifd, TiffTools.T6_OPTIONS); int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT); String resUnit = null; switch (res) { case 1: resUnit = "None"; break; case 2: resUnit = "Inch"; break; case 3: resUnit = "Centimeter"; break; } put("ResolutionUnit", resUnit); putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER); putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION); int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR); String predictor = null; switch (predict) { case 1: predictor = "No prediction scheme"; break; case 2: predictor = "Horizontal differencing"; break; } put("Predictor", predictor); putInt("WhitePoint", ifd, TiffTools.WHITE_POINT); putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES); putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS); putInt("TileWidth", ifd, TiffTools.TILE_WIDTH); putInt("TileLength", ifd, TiffTools.TILE_LENGTH); putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS); putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS); int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET); String inkSet = null; switch (ink) { case 1: inkSet = "CMYK"; break; case 2: inkSet = "Other"; break; } put("InkSet", inkSet); putInt("InkNames", ifd, TiffTools.INK_NAMES); putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS); putInt("DotRange", ifd, TiffTools.DOT_RANGE); put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER); putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES); int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT); String sampleFormat = null; switch (fmt) { case 1: sampleFormat = "unsigned integer"; break; case 2: sampleFormat = "two's complement signed integer"; break; case 3: sampleFormat = "IEEE floating point"; break; case 4: sampleFormat = "undefined"; break; } put("SampleFormat", sampleFormat); putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE); putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE); putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE); int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC); String jpegProc = null; switch (jpeg) { case 1: jpegProc = "baseline sequential process"; break; case 14: jpegProc = "lossless process with Huffman coding"; break; } put("JPEGProc", jpegProc); putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT); putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL); putInt("JPEGLosslessPredictors", ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS); putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS); putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES); putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES); putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES); putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS); int ycbcr = TiffTools.getIFDIntValue(ifd, TiffTools.Y_CB_CR_SUB_SAMPLING); String subSampling = null; switch (ycbcr) { case 1: subSampling = "chroma image dimensions = luma image dimensions"; break; case 2: subSampling = "chroma image dimensions are " + "half the luma image dimensions"; break; case 4: subSampling = "chroma image dimensions are " + "1/4 the luma image dimensions"; break; } put("YCbCrSubSampling", subSampling); putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING); putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE); // bits per sample and number of channels Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE); int bps = -1, numC = 3; if (bpsObj instanceof int[]) { int[] q = (int[]) bpsObj; bps = q[0]; numC = q.length; } else if (bpsObj instanceof Number) { bps = ((Number) bpsObj).intValue(); numC = 1; } put("BitsPerSample", bps); put("NumberOfChannels", numC); // TIFF comment String comment = null; Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION); if (o instanceof String) comment = (String) o; else if (o instanceof String[]) { String[] s = (String[]) o; if (s.length > 0) comment = s[0]; } else if (o != null) comment = o.toString(); if (comment != null) { // sanitize comment comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF comment = comment.replaceAll("\r", "\n"); // CR to LF put("Comment", comment); } }
diff --git a/src/indaprojekt/PauseState.java b/src/indaprojekt/PauseState.java index f3155dc..210a0a6 100644 --- a/src/indaprojekt/PauseState.java +++ b/src/indaprojekt/PauseState.java @@ -1,67 +1,67 @@ package indaprojekt; import indaprojekt.Button.ActionPerformer; import java.awt.geom.Rectangle2D; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.StateBasedGame; public class PauseState extends ButtonMenuState { private final int MIDDLE_X = Game.WINDOW_WIDTH/2; private int pauseTextY = 50; private int resumeGameY = 250; private int mainMenuY = 400; public PauseState(int stateID) { super(stateID); } @Override public void init(final GameContainer gc, final StateBasedGame game) throws SlickException { //background is in ButtonMenuState background = new Image("res//images//bakgrund.png"); // Resume button: Image resumeOption = new Image("res//images//resumeGame.png"); int resumeGameX = MIDDLE_X - (resumeOption.getWidth()/2); int resumeW = resumeOption.getWidth(); int resumeH = resumeOption.getHeight(); Button resumeButton = new Button(resumeOption, resumeOption, new Rectangle2D.Float(resumeGameX, resumeGameY, resumeW, resumeH)); resumeButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.GAME_PLAY_STATE); } }); addButton(resumeButton); Image pauseImage = new Image("res//images//pause.png"); int pauseTextX = MIDDLE_X - (pauseImage.getWidth()/2); Button pauseText = new Button(pauseImage, pauseImage, new Rectangle2D.Float(pauseTextX, pauseTextY, pauseImage.getWidth(), pauseImage.getHeight())); addButton(pauseText); // Main menu button. Image mainMenuImage = new Image("res//images//mainMenu.png"); Image mainMenuImageH = new Image("res//images//mainMenu.png"); int mainMenuX = MIDDLE_X - (mainMenuImage.getWidth()/2); Button mainMenuButton = new Button(mainMenuImage, mainMenuImageH, new Rectangle2D.Float(mainMenuX, mainMenuY, mainMenuImage.getWidth(), mainMenuImage.getHeight())); - resumeButton.setAction(new ActionPerformer() { + mainMenuButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.MAIN_MENU_STATE); } }); addButton(mainMenuButton); } }
true
true
public void init(final GameContainer gc, final StateBasedGame game) throws SlickException { //background is in ButtonMenuState background = new Image("res//images//bakgrund.png"); // Resume button: Image resumeOption = new Image("res//images//resumeGame.png"); int resumeGameX = MIDDLE_X - (resumeOption.getWidth()/2); int resumeW = resumeOption.getWidth(); int resumeH = resumeOption.getHeight(); Button resumeButton = new Button(resumeOption, resumeOption, new Rectangle2D.Float(resumeGameX, resumeGameY, resumeW, resumeH)); resumeButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.GAME_PLAY_STATE); } }); addButton(resumeButton); Image pauseImage = new Image("res//images//pause.png"); int pauseTextX = MIDDLE_X - (pauseImage.getWidth()/2); Button pauseText = new Button(pauseImage, pauseImage, new Rectangle2D.Float(pauseTextX, pauseTextY, pauseImage.getWidth(), pauseImage.getHeight())); addButton(pauseText); // Main menu button. Image mainMenuImage = new Image("res//images//mainMenu.png"); Image mainMenuImageH = new Image("res//images//mainMenu.png"); int mainMenuX = MIDDLE_X - (mainMenuImage.getWidth()/2); Button mainMenuButton = new Button(mainMenuImage, mainMenuImageH, new Rectangle2D.Float(mainMenuX, mainMenuY, mainMenuImage.getWidth(), mainMenuImage.getHeight())); resumeButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.MAIN_MENU_STATE); } }); addButton(mainMenuButton); }
public void init(final GameContainer gc, final StateBasedGame game) throws SlickException { //background is in ButtonMenuState background = new Image("res//images//bakgrund.png"); // Resume button: Image resumeOption = new Image("res//images//resumeGame.png"); int resumeGameX = MIDDLE_X - (resumeOption.getWidth()/2); int resumeW = resumeOption.getWidth(); int resumeH = resumeOption.getHeight(); Button resumeButton = new Button(resumeOption, resumeOption, new Rectangle2D.Float(resumeGameX, resumeGameY, resumeW, resumeH)); resumeButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.GAME_PLAY_STATE); } }); addButton(resumeButton); Image pauseImage = new Image("res//images//pause.png"); int pauseTextX = MIDDLE_X - (pauseImage.getWidth()/2); Button pauseText = new Button(pauseImage, pauseImage, new Rectangle2D.Float(pauseTextX, pauseTextY, pauseImage.getWidth(), pauseImage.getHeight())); addButton(pauseText); // Main menu button. Image mainMenuImage = new Image("res//images//mainMenu.png"); Image mainMenuImageH = new Image("res//images//mainMenu.png"); int mainMenuX = MIDDLE_X - (mainMenuImage.getWidth()/2); Button mainMenuButton = new Button(mainMenuImage, mainMenuImageH, new Rectangle2D.Float(mainMenuX, mainMenuY, mainMenuImage.getWidth(), mainMenuImage.getHeight())); mainMenuButton.setAction(new ActionPerformer() { @Override public void doAction() { game.enterState(IceIceBabyGame.MAIN_MENU_STATE); } }); addButton(mainMenuButton); }
diff --git a/op-gae/test/com/oddprints/checkout/GoogleCheckoutNotificationHandlerTest.java b/op-gae/test/com/oddprints/checkout/GoogleCheckoutNotificationHandlerTest.java index 604e83e..406ed84 100644 --- a/op-gae/test/com/oddprints/checkout/GoogleCheckoutNotificationHandlerTest.java +++ b/op-gae/test/com/oddprints/checkout/GoogleCheckoutNotificationHandlerTest.java @@ -1,88 +1,89 @@ package com.oddprints.checkout; import static org.junit.Assert.assertEquals; import javax.jdo.PersistenceManager; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.checkout.sdk.domain.Address; import com.google.checkout.sdk.domain.AnyMultiple; import com.google.checkout.sdk.domain.AuthorizationAmountNotification; import com.google.checkout.sdk.domain.OrderSummary; import com.google.checkout.sdk.domain.ShoppingCart; import com.google.common.collect.Lists; import com.oddprints.Environment; import com.oddprints.PMF; import com.oddprints.PrintSize; import com.oddprints.TestUtils; import com.oddprints.dao.Basket; import com.oddprints.dao.Basket.State; public class GoogleCheckoutNotificationHandlerTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( new LocalDatastoreServiceTestConfig()); @Before public void setUp() { helper.setUp(); TestUtils.INSTANCE.addSettingsFromTestFile(); } @After public void tearDown() { helper.tearDown(); } @Test public void on_authorize_submits_to_pwinty() { PersistenceManager pm = PMF.get().getPersistenceManager(); // create basket Basket basket = new Basket(Environment.SANDBOX); basket.addItem(null, 0, "2x2", PrintSize._4x6); basket.setState(State.awaiting_payment); pm.makePersistent(basket); String idString = basket.getIdString(); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); OrderSummary orderSummary = Mockito.mock(OrderSummary.class); ShoppingCart cart = Mockito.mock(ShoppingCart.class); Mockito.when(orderSummary.getShoppingCart()).thenReturn(cart); AnyMultiple am = Mockito.mock(AnyMultiple.class); Mockito.when(am.getContent()).thenReturn( Lists.newArrayList((Object) idString)); Mockito.when(cart.getMerchantPrivateData()).thenReturn(am); Address address = Mockito.mock(Address.class); - address.setEmail("[email protected]"); + Mockito.when(address.getEmail()).thenReturn("[email protected]"); + Mockito.when(address.getContactName()).thenReturn("junit google"); Mockito.when(orderSummary.getBuyerShippingAddress()) .thenReturn(address); AuthorizationAmountNotification notification = Mockito .mock(AuthorizationAmountNotification.class); CheckoutNotificationHandler checkoutNotificationHandler = new CheckoutNotificationHandler(); GoogleCheckoutNotificationHandler g = new GoogleCheckoutNotificationHandler( request, response, checkoutNotificationHandler); g.onAuthorizationAmountNotification(orderSummary, notification); pm = PMF.get().getPersistenceManager(); basket = Basket.getBasketByKeyString(idString, pm); assertEquals(State.payment_received, basket.getState()); } }
true
true
public void on_authorize_submits_to_pwinty() { PersistenceManager pm = PMF.get().getPersistenceManager(); // create basket Basket basket = new Basket(Environment.SANDBOX); basket.addItem(null, 0, "2x2", PrintSize._4x6); basket.setState(State.awaiting_payment); pm.makePersistent(basket); String idString = basket.getIdString(); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); OrderSummary orderSummary = Mockito.mock(OrderSummary.class); ShoppingCart cart = Mockito.mock(ShoppingCart.class); Mockito.when(orderSummary.getShoppingCart()).thenReturn(cart); AnyMultiple am = Mockito.mock(AnyMultiple.class); Mockito.when(am.getContent()).thenReturn( Lists.newArrayList((Object) idString)); Mockito.when(cart.getMerchantPrivateData()).thenReturn(am); Address address = Mockito.mock(Address.class); address.setEmail("[email protected]"); Mockito.when(orderSummary.getBuyerShippingAddress()) .thenReturn(address); AuthorizationAmountNotification notification = Mockito .mock(AuthorizationAmountNotification.class); CheckoutNotificationHandler checkoutNotificationHandler = new CheckoutNotificationHandler(); GoogleCheckoutNotificationHandler g = new GoogleCheckoutNotificationHandler( request, response, checkoutNotificationHandler); g.onAuthorizationAmountNotification(orderSummary, notification); pm = PMF.get().getPersistenceManager(); basket = Basket.getBasketByKeyString(idString, pm); assertEquals(State.payment_received, basket.getState()); }
public void on_authorize_submits_to_pwinty() { PersistenceManager pm = PMF.get().getPersistenceManager(); // create basket Basket basket = new Basket(Environment.SANDBOX); basket.addItem(null, 0, "2x2", PrintSize._4x6); basket.setState(State.awaiting_payment); pm.makePersistent(basket); String idString = basket.getIdString(); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); OrderSummary orderSummary = Mockito.mock(OrderSummary.class); ShoppingCart cart = Mockito.mock(ShoppingCart.class); Mockito.when(orderSummary.getShoppingCart()).thenReturn(cart); AnyMultiple am = Mockito.mock(AnyMultiple.class); Mockito.when(am.getContent()).thenReturn( Lists.newArrayList((Object) idString)); Mockito.when(cart.getMerchantPrivateData()).thenReturn(am); Address address = Mockito.mock(Address.class); Mockito.when(address.getEmail()).thenReturn("[email protected]"); Mockito.when(address.getContactName()).thenReturn("junit google"); Mockito.when(orderSummary.getBuyerShippingAddress()) .thenReturn(address); AuthorizationAmountNotification notification = Mockito .mock(AuthorizationAmountNotification.class); CheckoutNotificationHandler checkoutNotificationHandler = new CheckoutNotificationHandler(); GoogleCheckoutNotificationHandler g = new GoogleCheckoutNotificationHandler( request, response, checkoutNotificationHandler); g.onAuthorizationAmountNotification(orderSummary, notification); pm = PMF.get().getPersistenceManager(); basket = Basket.getBasketByKeyString(idString, pm); assertEquals(State.payment_received, basket.getState()); }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java index 3982de7c5..cb9144279 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java @@ -1,231 +1,231 @@ package net.aufdemrand.denizen.scripts.commands; import java.util.HashMap; import java.util.Map; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.interfaces.DenizenRegistry; import net.aufdemrand.denizen.interfaces.RegistrationableInstance; import net.aufdemrand.denizen.scripts.commands.core.*; import net.aufdemrand.denizen.utilities.debugging.dB; public class CommandRegistry implements DenizenRegistry { public Denizen denizen; public CommandRegistry(Denizen denizen) { this.denizen = denizen; } private Map<String, AbstractCommand> instances = new HashMap<String, AbstractCommand>(); private Map<Class<? extends AbstractCommand>, String> classes = new HashMap<Class<? extends AbstractCommand>, String>(); @Override public boolean register(String commandName, RegistrationableInstance commandInstance) { this.instances.put(commandName.toUpperCase(), (AbstractCommand) commandInstance); this.classes.put(((AbstractCommand) commandInstance).getClass(), commandName.toUpperCase()); return true; } @Override public Map<String, AbstractCommand> list() { return instances; } @Override public AbstractCommand get(String commandName) { if (instances.containsKey(commandName.toUpperCase())) return instances.get(commandName.toUpperCase()); else return null; } @Override public <T extends RegistrationableInstance> T get(Class<T> clazz) { if (classes.containsKey(clazz)) return (T) clazz.cast(instances.get(classes.get(clazz))); else return null; } @Override public void registerCoreMembers() { registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"announcement text\"] (to_ops)", 1); registerCoreMember(AttackCommand.class, "ATTACK", "attack (stop)", 0); registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:name] [assume|add|remove|walkto|walknear] (range:#)", 2); registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}|remove] (script:assignment_script)", 1); registerCoreMember(CastCommand.class, "CAST", "cast [effect] (duration:#{60s}) (power:#{1}) (target(s):npc|player|npc.#|player.player_name|entity_name)", 1); registerCoreMember(ChatCommand.class, "CHAT", "chat [\"chat text\"] (npcid:#) (target(s):npc.#|player.name{attached player})", 1); registerCoreMember(ClearCommand.class, "CLEAR", "clear (queue:name) (...)", 1); registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown (duration:#{60s}) (global|player:name{attached player}) (script:name)", 1); registerCoreMember(CooldownCommand.class, "COPYBLOCK", "copyblock [location:x,y,z,world] [to:x,y,z,world]", 1); registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [\"value\"]", 1); registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npcid:#)", 0); registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem [item_name|remove] [location:x,y,z,world] (duration:#)", 2); registerCoreMember(DropCommand.class, "DROP", "drop [item:#(:#)|item:material(:#)|xp] (qty:#{1}) (location:x,y,z,world)", 1); registerCoreMember(EngageCommand.class, "ENGAGE", "engage (duration:#) (npcid:#)", 0); registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player|as_op|as_npc|as_server] [\"Bukkit command\"]", 2); registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}|give|take] (level) [#] (player:player_name)", 2); registerCoreMember(FailCommand.class, "FAIL", "fail (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FeedCommand.class, "FEED", "feed (amt:#) (target:npc|{player})", 0); registerCoreMember(FinishCommand.class, "FINISH", "finish (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FinishCommand.class, "FISH", "fish (stop) (location:x,y,z,world)", 1); registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}|npc|global) [name([#])](:action)[:value] (duration:#)", 1); registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop)", 0); registerCoreMember(GiveCommand.class, "GIVE", "give [money|item:#(:#)|item:material(:#)] (qty:#)", 1); - registerCoreMember(GiveCommand.class, + registerCoreMember(GroupCommand.class, "GROUP", "group [add|remove] [group] (player:player_name) (world:world_name)", 2); registerCoreMember(HealCommand.class, "HEAL", "heal (amt:#) (target:npc|{player})", 0); registerCoreMember(IfCommand.class, "IF", "if [comparable] (!)(operator) (compared_to) (bridge) (...) [command] (else) (command) +--> see documentation.", 2); registerCoreMember(ListenCommand.class, "LISTEN", "listen [listener_type] [id:listener_id] (...) +--> see documentation - http://bit.ly/XJlKwm", 2); registerCoreMember(LookCommand.class, "LOOK", "look (player) [location:x,y,z,world]", 1); registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [toggle:true|false]", 1); registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [location:x,y,z,world] [material:data] (radius:#) (height:#) (depth:#)", 2); registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [chat_color] (target:player_name)", 1); registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"narration text\"] (player:name) (format:format)", 1); registerCoreMember(NewCommand.class, "NEW", "new itemstack [item:material] (qty:#)", 2); registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [location:x,y,z,world] [sound:name] (volume:#) (pitch:#)", 2); - registerCoreMember(GiveCommand.class, + registerCoreMember(PermissionCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:player_name) (group:group_name) (world:world_name)", 2); registerCoreMember(PoseCommand.class, "POSE", "pose (player) [id:name]", 1); registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:id{residing_queue}) [clear|pause|resume|delay:#]", 1); registerCoreMember(RandomCommand.class, "RANDOM", "random [#]", 1); registerCoreMember(RemoveCommand.class, "REMOVE", "remove (npcid:#)", 0); registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [script_name] (instantly) (queue|queue:queue_name) (delay:#)", 1); registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:book_script] (give|{drop}|equip) (location:x,y,z,world) OR scribe [item:id.name] [script:book_script]", 1); registerCoreMember(ShootCommand.class, "SHOOT", "shoot [entity:name] (ride) (burn) (explosion:#) (location:x,y,z,world) (script:name)", 1); registerCoreMember(SitCommand.class, "SIT", "sit (location:x,y,z,world)", 0); registerCoreMember(StandCommand.class, "STAND", "stand", 0); registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [location:x,y,z,world]", 1); registerCoreMember(SwitchCommand.class, "SWITCH", "switch [location:x,y,z,world] (state:[{toggle}|on|off]) (duration:#)", 1); registerCoreMember(TakeCommand.class, "TAKE", "take [money|iteminhand|item:#(:#)|item:material(:#)] (qty:#)", 1); registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (npc) [location:x,y,z,world] (target(s):[npc.#]|[player.name])", 1); registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:trigger_name] [(toggle:true|false)|(cooldown:#.#)|(radius:#)]", 2); registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (toggle:{true}|false|toggle)", 0); registerCoreMember(WaitCommand.class, "WAIT", "wait (duration:#{5s}) (queue:queue_type) (player:player_name{attached}) (npcid:#{attached})", 0); registerCoreMember(WalkToCommand.class, "WALKTO", "walkto [location:x,y,z,world] (speed:#)", 1); registerCoreMember(ZapCommand.class, "ZAP", "zap [#|step:step_name] (script:script_name{current_script}) (duration:#)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); } private <T extends AbstractCommand> void registerCoreMember(Class<T> cmd, String name, String hint, int args) { try { cmd.newInstance().activate().as(name).withOptions(hint, args); } catch(Exception e) { dB.echoError("Could not register command " + name + ": " + e.getMessage()); if (dB.showStackTraces) e.printStackTrace(); } } @Override public void disableCoreMembers() { for (RegistrationableInstance member : instances.values()) try { member.onDisable(); } catch (Exception e) { dB.echoError("Unable to disable '" + member.getClass().getName() + "'!"); if (dB.showStackTraces) e.printStackTrace(); } } }
false
true
public void registerCoreMembers() { registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"announcement text\"] (to_ops)", 1); registerCoreMember(AttackCommand.class, "ATTACK", "attack (stop)", 0); registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:name] [assume|add|remove|walkto|walknear] (range:#)", 2); registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}|remove] (script:assignment_script)", 1); registerCoreMember(CastCommand.class, "CAST", "cast [effect] (duration:#{60s}) (power:#{1}) (target(s):npc|player|npc.#|player.player_name|entity_name)", 1); registerCoreMember(ChatCommand.class, "CHAT", "chat [\"chat text\"] (npcid:#) (target(s):npc.#|player.name{attached player})", 1); registerCoreMember(ClearCommand.class, "CLEAR", "clear (queue:name) (...)", 1); registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown (duration:#{60s}) (global|player:name{attached player}) (script:name)", 1); registerCoreMember(CooldownCommand.class, "COPYBLOCK", "copyblock [location:x,y,z,world] [to:x,y,z,world]", 1); registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [\"value\"]", 1); registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npcid:#)", 0); registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem [item_name|remove] [location:x,y,z,world] (duration:#)", 2); registerCoreMember(DropCommand.class, "DROP", "drop [item:#(:#)|item:material(:#)|xp] (qty:#{1}) (location:x,y,z,world)", 1); registerCoreMember(EngageCommand.class, "ENGAGE", "engage (duration:#) (npcid:#)", 0); registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player|as_op|as_npc|as_server] [\"Bukkit command\"]", 2); registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}|give|take] (level) [#] (player:player_name)", 2); registerCoreMember(FailCommand.class, "FAIL", "fail (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FeedCommand.class, "FEED", "feed (amt:#) (target:npc|{player})", 0); registerCoreMember(FinishCommand.class, "FINISH", "finish (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FinishCommand.class, "FISH", "fish (stop) (location:x,y,z,world)", 1); registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}|npc|global) [name([#])](:action)[:value] (duration:#)", 1); registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop)", 0); registerCoreMember(GiveCommand.class, "GIVE", "give [money|item:#(:#)|item:material(:#)] (qty:#)", 1); registerCoreMember(GiveCommand.class, "GROUP", "group [add|remove] [group] (player:player_name) (world:world_name)", 2); registerCoreMember(HealCommand.class, "HEAL", "heal (amt:#) (target:npc|{player})", 0); registerCoreMember(IfCommand.class, "IF", "if [comparable] (!)(operator) (compared_to) (bridge) (...) [command] (else) (command) +--> see documentation.", 2); registerCoreMember(ListenCommand.class, "LISTEN", "listen [listener_type] [id:listener_id] (...) +--> see documentation - http://bit.ly/XJlKwm", 2); registerCoreMember(LookCommand.class, "LOOK", "look (player) [location:x,y,z,world]", 1); registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [toggle:true|false]", 1); registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [location:x,y,z,world] [material:data] (radius:#) (height:#) (depth:#)", 2); registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [chat_color] (target:player_name)", 1); registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"narration text\"] (player:name) (format:format)", 1); registerCoreMember(NewCommand.class, "NEW", "new itemstack [item:material] (qty:#)", 2); registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [location:x,y,z,world] [sound:name] (volume:#) (pitch:#)", 2); registerCoreMember(GiveCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:player_name) (group:group_name) (world:world_name)", 2); registerCoreMember(PoseCommand.class, "POSE", "pose (player) [id:name]", 1); registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:id{residing_queue}) [clear|pause|resume|delay:#]", 1); registerCoreMember(RandomCommand.class, "RANDOM", "random [#]", 1); registerCoreMember(RemoveCommand.class, "REMOVE", "remove (npcid:#)", 0); registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [script_name] (instantly) (queue|queue:queue_name) (delay:#)", 1); registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:book_script] (give|{drop}|equip) (location:x,y,z,world) OR scribe [item:id.name] [script:book_script]", 1); registerCoreMember(ShootCommand.class, "SHOOT", "shoot [entity:name] (ride) (burn) (explosion:#) (location:x,y,z,world) (script:name)", 1); registerCoreMember(SitCommand.class, "SIT", "sit (location:x,y,z,world)", 0); registerCoreMember(StandCommand.class, "STAND", "stand", 0); registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [location:x,y,z,world]", 1); registerCoreMember(SwitchCommand.class, "SWITCH", "switch [location:x,y,z,world] (state:[{toggle}|on|off]) (duration:#)", 1); registerCoreMember(TakeCommand.class, "TAKE", "take [money|iteminhand|item:#(:#)|item:material(:#)] (qty:#)", 1); registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (npc) [location:x,y,z,world] (target(s):[npc.#]|[player.name])", 1); registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:trigger_name] [(toggle:true|false)|(cooldown:#.#)|(radius:#)]", 2); registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (toggle:{true}|false|toggle)", 0); registerCoreMember(WaitCommand.class, "WAIT", "wait (duration:#{5s}) (queue:queue_type) (player:player_name{attached}) (npcid:#{attached})", 0); registerCoreMember(WalkToCommand.class, "WALKTO", "walkto [location:x,y,z,world] (speed:#)", 1); registerCoreMember(ZapCommand.class, "ZAP", "zap [#|step:step_name] (script:script_name{current_script}) (duration:#)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); }
public void registerCoreMembers() { registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"announcement text\"] (to_ops)", 1); registerCoreMember(AttackCommand.class, "ATTACK", "attack (stop)", 0); registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:name] [assume|add|remove|walkto|walknear] (range:#)", 2); registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}|remove] (script:assignment_script)", 1); registerCoreMember(CastCommand.class, "CAST", "cast [effect] (duration:#{60s}) (power:#{1}) (target(s):npc|player|npc.#|player.player_name|entity_name)", 1); registerCoreMember(ChatCommand.class, "CHAT", "chat [\"chat text\"] (npcid:#) (target(s):npc.#|player.name{attached player})", 1); registerCoreMember(ClearCommand.class, "CLEAR", "clear (queue:name) (...)", 1); registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown (duration:#{60s}) (global|player:name{attached player}) (script:name)", 1); registerCoreMember(CooldownCommand.class, "COPYBLOCK", "copyblock [location:x,y,z,world] [to:x,y,z,world]", 1); registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [\"value\"]", 1); registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npcid:#)", 0); registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem [item_name|remove] [location:x,y,z,world] (duration:#)", 2); registerCoreMember(DropCommand.class, "DROP", "drop [item:#(:#)|item:material(:#)|xp] (qty:#{1}) (location:x,y,z,world)", 1); registerCoreMember(EngageCommand.class, "ENGAGE", "engage (duration:#) (npcid:#)", 0); registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player|as_op|as_npc|as_server] [\"Bukkit command\"]", 2); registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}|give|take] (level) [#] (player:player_name)", 2); registerCoreMember(FailCommand.class, "FAIL", "fail (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FeedCommand.class, "FEED", "feed (amt:#) (target:npc|{player})", 0); registerCoreMember(FinishCommand.class, "FINISH", "finish (script:name{attached script}) (player:player_name)", 0); registerCoreMember(FinishCommand.class, "FISH", "fish (stop) (location:x,y,z,world)", 1); registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}|npc|global) [name([#])](:action)[:value] (duration:#)", 1); registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop)", 0); registerCoreMember(GiveCommand.class, "GIVE", "give [money|item:#(:#)|item:material(:#)] (qty:#)", 1); registerCoreMember(GroupCommand.class, "GROUP", "group [add|remove] [group] (player:player_name) (world:world_name)", 2); registerCoreMember(HealCommand.class, "HEAL", "heal (amt:#) (target:npc|{player})", 0); registerCoreMember(IfCommand.class, "IF", "if [comparable] (!)(operator) (compared_to) (bridge) (...) [command] (else) (command) +--> see documentation.", 2); registerCoreMember(ListenCommand.class, "LISTEN", "listen [listener_type] [id:listener_id] (...) +--> see documentation - http://bit.ly/XJlKwm", 2); registerCoreMember(LookCommand.class, "LOOK", "look (player) [location:x,y,z,world]", 1); registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [toggle:true|false]", 1); registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [location:x,y,z,world] [material:data] (radius:#) (height:#) (depth:#)", 2); registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [chat_color] (target:player_name)", 1); registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"narration text\"] (player:name) (format:format)", 1); registerCoreMember(NewCommand.class, "NEW", "new itemstack [item:material] (qty:#)", 2); registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [location:x,y,z,world] [sound:name] (volume:#) (pitch:#)", 2); registerCoreMember(PermissionCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:player_name) (group:group_name) (world:world_name)", 2); registerCoreMember(PoseCommand.class, "POSE", "pose (player) [id:name]", 1); registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:id{residing_queue}) [clear|pause|resume|delay:#]", 1); registerCoreMember(RandomCommand.class, "RANDOM", "random [#]", 1); registerCoreMember(RemoveCommand.class, "REMOVE", "remove (npcid:#)", 0); registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [script_name] (instantly) (queue|queue:queue_name) (delay:#)", 1); registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:book_script] (give|{drop}|equip) (location:x,y,z,world) OR scribe [item:id.name] [script:book_script]", 1); registerCoreMember(ShootCommand.class, "SHOOT", "shoot [entity:name] (ride) (burn) (explosion:#) (location:x,y,z,world) (script:name)", 1); registerCoreMember(SitCommand.class, "SIT", "sit (location:x,y,z,world)", 0); registerCoreMember(StandCommand.class, "STAND", "stand", 0); registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [location:x,y,z,world]", 1); registerCoreMember(SwitchCommand.class, "SWITCH", "switch [location:x,y,z,world] (state:[{toggle}|on|off]) (duration:#)", 1); registerCoreMember(TakeCommand.class, "TAKE", "take [money|iteminhand|item:#(:#)|item:material(:#)] (qty:#)", 1); registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (npc) [location:x,y,z,world] (target(s):[npc.#]|[player.name])", 1); registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:trigger_name] [(toggle:true|false)|(cooldown:#.#)|(radius:#)]", 2); registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (toggle:{true}|false|toggle)", 0); registerCoreMember(WaitCommand.class, "WAIT", "wait (duration:#{5s}) (queue:queue_type) (player:player_name{attached}) (npcid:#{attached})", 0); registerCoreMember(WalkToCommand.class, "WALKTO", "walkto [location:x,y,z,world] (speed:#)", 1); registerCoreMember(ZapCommand.class, "ZAP", "zap [#|step:step_name] (script:script_name{current_script}) (duration:#)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); }
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/script/DataAdapterTopLevelScope.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/script/DataAdapterTopLevelScope.java index 5069a7936..9d3b0374b 100644 --- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/script/DataAdapterTopLevelScope.java +++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/api/script/DataAdapterTopLevelScope.java @@ -1,209 +1,206 @@ /* ************************************************************************* * Copyright (c) 2006 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation * ************************************************************************* */ package org.eclipse.birt.report.data.adapter.api.script; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.CoreJavaScriptInitializer; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.mozilla.javascript.Context; import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.Scriptable; /** * Top-level scope created by Data Adaptor. This scope provides implementation of some * report level script object (e.g., "params") */ public class DataAdapterTopLevelScope extends ImporterTopLevel { private static final long serialVersionUID = 4230948829384l; private static final String PROP_PARAMS = "params"; private static final String PROP_REPORTCONTEXT = "reportContext"; private ModuleHandle designModule; private Scriptable paramsProp; private Object reportContextProp; /** * Constructor; initializes standard objects in scope * @param cx Context used to initialze scope * @param module Module associated with this scope; can be null */ public DataAdapterTopLevelScope( Context cx, ModuleHandle module ) { super(cx); // init BIRT native objects new CoreJavaScriptInitializer( ).initialize( cx, this ); designModule = module; } public boolean has(String name, Scriptable start) { if ( super.has(name, start) ) return true; // "params" is available only if we have a module if ( designModule != null && PROP_PARAMS.equals(name) ) return true; if ( PROP_REPORTCONTEXT.equals( name ) ) return true; return false; } public Object get(String name, Scriptable start) { Object result = super.get(name, start); if (result != NOT_FOUND) return result; if ( designModule != null && PROP_PARAMS.equals(name) ) { return getParamsScriptable(); } if ( PROP_REPORTCONTEXT.equals( name ) ) return getReportContext( ); return NOT_FOUND; } /** * Gets a object which implements the "reportContext" property * @throws InvocationTargetException * @throws InstantiationException * @throws IllegalAccessException */ private Object getReportContext() { if ( reportContextProp != null ) return reportContextProp; assert designModule != null; reportContextProp = new ReportContextObject( designModule ); return reportContextProp; } /** * Gets a scriptable object which implements the "params" property */ private Scriptable getParamsScriptable( ) { if ( paramsProp != null ) return paramsProp; assert designModule != null; Map parameters = new HashMap( ); List paramsList = designModule.getAllParameters( ); for ( int i = 0; i < paramsList.size( ); i++ ) { Object parameterObject = paramsList.get( i ); if ( parameterObject instanceof ScalarParameterHandle ) { Object value = getParamDefaultValue( parameterObject ); parameters.put( ( (ScalarParameterHandle) parameterObject ).getQualifiedName( ), new DummyParameterAttribute( value, "" ) ); } } paramsProp = new ReportParameters( parameters, this ); return paramsProp; } /** * Gets the default value of a parameter. If a usable default value is * defined, use it; otherwise use a default value appropriate for the data * type */ private Object getParamDefaultValue( Object params ) { if ( !( params instanceof ScalarParameterHandle ) ) return null; ScalarParameterHandle sp = (ScalarParameterHandle) params; String defaultValue = sp.getDefaultValue( ); String type = sp.getDataType( ); if ( defaultValue == null ) { // No default value; if param allows null value, null is used if ( sp.allowNull( ) ) return null; // Return a fixed default value appropriate for the data type if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { - if ( sp.allowBlank( ) ) - return ""; - else - return "null"; + return ""; } if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) return new Double( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) return new BigDecimal( (double) 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) return new Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) return new java.sql.Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) return new java.sql.Time( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) return Boolean.FALSE; if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) return new Integer( 0 ); // unknown parameter type; unexpected assert false; return null; } // Convert default value to the correct data type int typeNum = DataType.ANY_TYPE; if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) typeNum = DataType.STRING_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) typeNum = DataType.DOUBLE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) typeNum = DataType.DECIMAL_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) typeNum = DataType.DATE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) typeNum = DataType.BOOLEAN_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) typeNum = DataType.INTEGER_TYPE; try { return DataTypeUtil.convert( defaultValue, typeNum ); } catch ( BirtException e ) { return null; } } }
true
true
private Object getParamDefaultValue( Object params ) { if ( !( params instanceof ScalarParameterHandle ) ) return null; ScalarParameterHandle sp = (ScalarParameterHandle) params; String defaultValue = sp.getDefaultValue( ); String type = sp.getDataType( ); if ( defaultValue == null ) { // No default value; if param allows null value, null is used if ( sp.allowNull( ) ) return null; // Return a fixed default value appropriate for the data type if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { if ( sp.allowBlank( ) ) return ""; else return "null"; } if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) return new Double( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) return new BigDecimal( (double) 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) return new Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) return new java.sql.Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) return new java.sql.Time( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) return Boolean.FALSE; if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) return new Integer( 0 ); // unknown parameter type; unexpected assert false; return null; } // Convert default value to the correct data type int typeNum = DataType.ANY_TYPE; if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) typeNum = DataType.STRING_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) typeNum = DataType.DOUBLE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) typeNum = DataType.DECIMAL_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) typeNum = DataType.DATE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) typeNum = DataType.BOOLEAN_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) typeNum = DataType.INTEGER_TYPE; try { return DataTypeUtil.convert( defaultValue, typeNum ); } catch ( BirtException e ) { return null; } }
private Object getParamDefaultValue( Object params ) { if ( !( params instanceof ScalarParameterHandle ) ) return null; ScalarParameterHandle sp = (ScalarParameterHandle) params; String defaultValue = sp.getDefaultValue( ); String type = sp.getDataType( ); if ( defaultValue == null ) { // No default value; if param allows null value, null is used if ( sp.allowNull( ) ) return null; // Return a fixed default value appropriate for the data type if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) { return ""; } if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) return new Double( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) return new BigDecimal( (double) 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) return new Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) return new java.sql.Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) return new java.sql.Time( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) return Boolean.FALSE; if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) return new Integer( 0 ); // unknown parameter type; unexpected assert false; return null; } // Convert default value to the correct data type int typeNum = DataType.ANY_TYPE; if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) typeNum = DataType.STRING_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) typeNum = DataType.DOUBLE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) typeNum = DataType.DECIMAL_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) typeNum = DataType.DATE_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) typeNum = DataType.BOOLEAN_TYPE; else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) typeNum = DataType.INTEGER_TYPE; try { return DataTypeUtil.convert( defaultValue, typeNum ); } catch ( BirtException e ) { return null; } }
diff --git a/src/main/java/tk/nekotech/cah/listeners/PlayerListener.java b/src/main/java/tk/nekotech/cah/listeners/PlayerListener.java index dc9c4f2..a1c8c42 100644 --- a/src/main/java/tk/nekotech/cah/listeners/PlayerListener.java +++ b/src/main/java/tk/nekotech/cah/listeners/PlayerListener.java @@ -1,160 +1,160 @@ package tk.nekotech.cah.listeners; import java.util.Collections; import org.pircbotx.PircBotX; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.NickChangeEvent; import tk.nekotech.cah.CardsAgainstHumanity; import tk.nekotech.cah.GameStatus; import tk.nekotech.cah.Player; import tk.nekotech.cah.card.WhiteCard; public class PlayerListener extends MasterListener { private final CardsAgainstHumanity cah; public PlayerListener(final PircBotX bot, final CardsAgainstHumanity cah) { super(bot); this.cah = cah; } @Override @SuppressWarnings("rawtypes") public void onMessage(final MessageEvent event) { if (event.getUser().getNick().contains("CAH-Master") || !this.cah.inSession() || event.getMessage().equalsIgnoreCase("join") || event.getMessage().equalsIgnoreCase("quit")) { return; } final Player player = this.cah.getPlayer(event.getUser().getNick()); if (player == null) { return; } final String[] message = event.getMessage().toLowerCase().split(" "); if (message.length == 1 && message[0].equalsIgnoreCase("info")) { this.bot.sendNotice(event.getUser(), "You currently have " + player.getScore() + " awesome points. The black card is: " + this.cah.blackCard.getColored()); this.bot.sendNotice(event.getUser(), "Your cards are: " + this.cah.getCards(player)); return; } if (player.isCzar()) { if (this.cah.gameStatus == GameStatus.IN_SESSION && message.length == 1) { this.bot.sendNotice(event.getUser(), "You're the czar; please wait until it's time for voting."); } else { if (message.length == 1) { int chosen = 0; try { chosen = Integer.parseInt(message[0]); } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "Uh-oh! I couldn't find that answer. Try a number instead."); } if (chosen > this.cah.playerIter.size()) { this.bot.sendNotice(event.getUser(), "I couldn't find that answer."); } else { chosen = chosen - 1; final Player win = this.cah.playerIter.get(chosen); final StringBuilder send = new StringBuilder(); send.append(win.getName() + " wins this round; card was "); if (this.cah.blackCard.getAnswers() == 1) { send.append(this.cah.blackCard.getColored().replace("_", win.getPlayedCards()[0].getColored())); } else { send.append(this.cah.blackCard.getColored().replaceFirst("_", win.getPlayedCards()[0].getColored()).replaceFirst("_", win.getPlayedCards()[1].getColored())); } win.addPoint(); - send.append(win.getName() + " now has " + win.getScore()); + send.append(" " + win.getName() + " now has " + win.getScore()); this.cah.spamBot.sendMessage("##cah", send.toString()); this.cah.nextRound(); } } } return; } if (this.cah.gameStatus == GameStatus.CZAR_TURN) { return; } if (message.length == 1 && this.cah.blackCard.getAnswers() == 1) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } int answer = 0; try { answer = Integer.parseInt(message[0]); if (answer < 1 || answer > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played a card this round!"); } else { answer = answer - 1; final WhiteCard card = player.getCards().get(answer); this.bot.sendNotice(event.getUser(), "Saved answer " + card.getFull() + "!"); player.playCard(card); this.cah.checkNext(); } } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Try use a number instead."); } } else if (message.length == 2 && this.cah.blackCard.getAnswers() == 2) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } final int[] answers = new int[2]; for (int i = 0; i < 2; i++) { try { answers[i] = Integer.parseInt(message[i]); } catch (final NumberFormatException e) { answers[i] = -55; } } if (answers[0] == -55 || answers[1] == -55) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Ensure you entered two numbers."); } else if (answers[0] < 1 || answers[0] > 10 || answers[1] < 1 || answers[1] > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played your cards this round!"); } else { final WhiteCard[] cards = new WhiteCard[2]; for (int i = 0; i < 2; i++) { answers[i] = answers[i] - 1; cards[i] = player.getCards().get(answers[i]); } this.bot.sendNotice(event.getUser(), "Saved answers " + cards[0].getFull() + ", " + cards[1].getFull() + "!"); player.playCards(cards); this.cah.checkNext(); } } } else if (message.length == 2 && message[0].equals("drop")) { int card = 0; try { card = Integer.parseInt(message[1]); if (player.getScore() < 1) { this.bot.sendNotice(event.getUser(), "You don't have enough awesome points to do that."); } else if (card > 10 || card < 1) { this.bot.sendNotice(event.getUser(), "You don't have that card! Pick a card between 1-10."); } else if (player.getChanged() == 10) { this.bot.sendNotice(event.getUser(), "You've already changed your full deck this round. Wait until next round before changing again."); } else { card = card - 1; final WhiteCard old = player.getCards().get(card); player.getCards().remove(old); Collections.shuffle(this.cah.whiteCards); final WhiteCard newc = this.cah.whiteCards.get(0); player.getCards().add(newc); this.cah.whiteCards.remove(newc); this.cah.whiteCards.add(old); player.subtractPoint(); this.bot.sendNotice(event.getUser(), "You dropped card [" + old.getColored() + "] and picked up [" + newc.getColored() + "]; you now have " + player.getScore() + " awesome points."); } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You need to specify an amount of cards to drop."); } } } @Override @SuppressWarnings("rawtypes") public void onNickChange(final NickChangeEvent event) { final Player player = this.cah.getPlayer(event.getOldNick()); if (player != null) { player.setName(event.getNewNick()); } } }
true
true
public void onMessage(final MessageEvent event) { if (event.getUser().getNick().contains("CAH-Master") || !this.cah.inSession() || event.getMessage().equalsIgnoreCase("join") || event.getMessage().equalsIgnoreCase("quit")) { return; } final Player player = this.cah.getPlayer(event.getUser().getNick()); if (player == null) { return; } final String[] message = event.getMessage().toLowerCase().split(" "); if (message.length == 1 && message[0].equalsIgnoreCase("info")) { this.bot.sendNotice(event.getUser(), "You currently have " + player.getScore() + " awesome points. The black card is: " + this.cah.blackCard.getColored()); this.bot.sendNotice(event.getUser(), "Your cards are: " + this.cah.getCards(player)); return; } if (player.isCzar()) { if (this.cah.gameStatus == GameStatus.IN_SESSION && message.length == 1) { this.bot.sendNotice(event.getUser(), "You're the czar; please wait until it's time for voting."); } else { if (message.length == 1) { int chosen = 0; try { chosen = Integer.parseInt(message[0]); } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "Uh-oh! I couldn't find that answer. Try a number instead."); } if (chosen > this.cah.playerIter.size()) { this.bot.sendNotice(event.getUser(), "I couldn't find that answer."); } else { chosen = chosen - 1; final Player win = this.cah.playerIter.get(chosen); final StringBuilder send = new StringBuilder(); send.append(win.getName() + " wins this round; card was "); if (this.cah.blackCard.getAnswers() == 1) { send.append(this.cah.blackCard.getColored().replace("_", win.getPlayedCards()[0].getColored())); } else { send.append(this.cah.blackCard.getColored().replaceFirst("_", win.getPlayedCards()[0].getColored()).replaceFirst("_", win.getPlayedCards()[1].getColored())); } win.addPoint(); send.append(win.getName() + " now has " + win.getScore()); this.cah.spamBot.sendMessage("##cah", send.toString()); this.cah.nextRound(); } } } return; } if (this.cah.gameStatus == GameStatus.CZAR_TURN) { return; } if (message.length == 1 && this.cah.blackCard.getAnswers() == 1) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } int answer = 0; try { answer = Integer.parseInt(message[0]); if (answer < 1 || answer > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played a card this round!"); } else { answer = answer - 1; final WhiteCard card = player.getCards().get(answer); this.bot.sendNotice(event.getUser(), "Saved answer " + card.getFull() + "!"); player.playCard(card); this.cah.checkNext(); } } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Try use a number instead."); } } else if (message.length == 2 && this.cah.blackCard.getAnswers() == 2) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } final int[] answers = new int[2]; for (int i = 0; i < 2; i++) { try { answers[i] = Integer.parseInt(message[i]); } catch (final NumberFormatException e) { answers[i] = -55; } } if (answers[0] == -55 || answers[1] == -55) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Ensure you entered two numbers."); } else if (answers[0] < 1 || answers[0] > 10 || answers[1] < 1 || answers[1] > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played your cards this round!"); } else { final WhiteCard[] cards = new WhiteCard[2]; for (int i = 0; i < 2; i++) { answers[i] = answers[i] - 1; cards[i] = player.getCards().get(answers[i]); } this.bot.sendNotice(event.getUser(), "Saved answers " + cards[0].getFull() + ", " + cards[1].getFull() + "!"); player.playCards(cards); this.cah.checkNext(); } } } else if (message.length == 2 && message[0].equals("drop")) { int card = 0; try { card = Integer.parseInt(message[1]); if (player.getScore() < 1) { this.bot.sendNotice(event.getUser(), "You don't have enough awesome points to do that."); } else if (card > 10 || card < 1) { this.bot.sendNotice(event.getUser(), "You don't have that card! Pick a card between 1-10."); } else if (player.getChanged() == 10) { this.bot.sendNotice(event.getUser(), "You've already changed your full deck this round. Wait until next round before changing again."); } else { card = card - 1; final WhiteCard old = player.getCards().get(card); player.getCards().remove(old); Collections.shuffle(this.cah.whiteCards); final WhiteCard newc = this.cah.whiteCards.get(0); player.getCards().add(newc); this.cah.whiteCards.remove(newc); this.cah.whiteCards.add(old); player.subtractPoint(); this.bot.sendNotice(event.getUser(), "You dropped card [" + old.getColored() + "] and picked up [" + newc.getColored() + "]; you now have " + player.getScore() + " awesome points."); } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You need to specify an amount of cards to drop."); } } }
public void onMessage(final MessageEvent event) { if (event.getUser().getNick().contains("CAH-Master") || !this.cah.inSession() || event.getMessage().equalsIgnoreCase("join") || event.getMessage().equalsIgnoreCase("quit")) { return; } final Player player = this.cah.getPlayer(event.getUser().getNick()); if (player == null) { return; } final String[] message = event.getMessage().toLowerCase().split(" "); if (message.length == 1 && message[0].equalsIgnoreCase("info")) { this.bot.sendNotice(event.getUser(), "You currently have " + player.getScore() + " awesome points. The black card is: " + this.cah.blackCard.getColored()); this.bot.sendNotice(event.getUser(), "Your cards are: " + this.cah.getCards(player)); return; } if (player.isCzar()) { if (this.cah.gameStatus == GameStatus.IN_SESSION && message.length == 1) { this.bot.sendNotice(event.getUser(), "You're the czar; please wait until it's time for voting."); } else { if (message.length == 1) { int chosen = 0; try { chosen = Integer.parseInt(message[0]); } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "Uh-oh! I couldn't find that answer. Try a number instead."); } if (chosen > this.cah.playerIter.size()) { this.bot.sendNotice(event.getUser(), "I couldn't find that answer."); } else { chosen = chosen - 1; final Player win = this.cah.playerIter.get(chosen); final StringBuilder send = new StringBuilder(); send.append(win.getName() + " wins this round; card was "); if (this.cah.blackCard.getAnswers() == 1) { send.append(this.cah.blackCard.getColored().replace("_", win.getPlayedCards()[0].getColored())); } else { send.append(this.cah.blackCard.getColored().replaceFirst("_", win.getPlayedCards()[0].getColored()).replaceFirst("_", win.getPlayedCards()[1].getColored())); } win.addPoint(); send.append(" " + win.getName() + " now has " + win.getScore()); this.cah.spamBot.sendMessage("##cah", send.toString()); this.cah.nextRound(); } } } return; } if (this.cah.gameStatus == GameStatus.CZAR_TURN) { return; } if (message.length == 1 && this.cah.blackCard.getAnswers() == 1) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } int answer = 0; try { answer = Integer.parseInt(message[0]); if (answer < 1 || answer > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played a card this round!"); } else { answer = answer - 1; final WhiteCard card = player.getCards().get(answer); this.bot.sendNotice(event.getUser(), "Saved answer " + card.getFull() + "!"); player.playCard(card); this.cah.checkNext(); } } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Try use a number instead."); } } else if (message.length == 2 && this.cah.blackCard.getAnswers() == 2) { if (player.isWaiting()) { this.bot.sendNotice(event.getUser(), "You're currently waiting for the next round. Hold tight!"); } final int[] answers = new int[2]; for (int i = 0; i < 2; i++) { try { answers[i] = Integer.parseInt(message[i]); } catch (final NumberFormatException e) { answers[i] = -55; } } if (answers[0] == -55 || answers[1] == -55) { this.bot.sendNotice(event.getUser(), "You can't answer with that! Ensure you entered two numbers."); } else if (answers[0] < 1 || answers[0] > 10 || answers[1] < 1 || answers[1] > 10) { this.bot.sendNotice(event.getUser(), "Use a number that you actually have!"); } else { if (player.hasPlayedCards()) { this.bot.sendNotice(event.getUser(), "You've already played your cards this round!"); } else { final WhiteCard[] cards = new WhiteCard[2]; for (int i = 0; i < 2; i++) { answers[i] = answers[i] - 1; cards[i] = player.getCards().get(answers[i]); } this.bot.sendNotice(event.getUser(), "Saved answers " + cards[0].getFull() + ", " + cards[1].getFull() + "!"); player.playCards(cards); this.cah.checkNext(); } } } else if (message.length == 2 && message[0].equals("drop")) { int card = 0; try { card = Integer.parseInt(message[1]); if (player.getScore() < 1) { this.bot.sendNotice(event.getUser(), "You don't have enough awesome points to do that."); } else if (card > 10 || card < 1) { this.bot.sendNotice(event.getUser(), "You don't have that card! Pick a card between 1-10."); } else if (player.getChanged() == 10) { this.bot.sendNotice(event.getUser(), "You've already changed your full deck this round. Wait until next round before changing again."); } else { card = card - 1; final WhiteCard old = player.getCards().get(card); player.getCards().remove(old); Collections.shuffle(this.cah.whiteCards); final WhiteCard newc = this.cah.whiteCards.get(0); player.getCards().add(newc); this.cah.whiteCards.remove(newc); this.cah.whiteCards.add(old); player.subtractPoint(); this.bot.sendNotice(event.getUser(), "You dropped card [" + old.getColored() + "] and picked up [" + newc.getColored() + "]; you now have " + player.getScore() + " awesome points."); } } catch (final NumberFormatException e) { this.bot.sendNotice(event.getUser(), "You need to specify an amount of cards to drop."); } } }
diff --git a/JavaSource/org/unitime/timetable/solver/SolverPassivationThread.java b/JavaSource/org/unitime/timetable/solver/SolverPassivationThread.java index e70dd97a..24a7a221 100644 --- a/JavaSource/org/unitime/timetable/solver/SolverPassivationThread.java +++ b/JavaSource/org/unitime/timetable/solver/SolverPassivationThread.java @@ -1,69 +1,70 @@ /* * UniTime 3.0 (University Course Timetabling & Student Sectioning Application) * Copyright (C) 2007, UniTime.org, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.unitime.timetable.solver; import java.io.File; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Tomas Muller */ public class SolverPassivationThread extends Thread { private static Log sLog = LogFactory.getLog(SolverPassivationThread.class); private File iFolder = null; private Hashtable iSolvers = null; public static long sDelay = 30000; public SolverPassivationThread(File folder, Hashtable solvers) { iFolder = folder; iSolvers = solvers; setName("SolverPasivationThread"); setDaemon(true); setPriority(Thread.MIN_PRIORITY); } public void run() { try { sLog.info("Solver passivation thread started."); while (true) { for (Iterator i=iSolvers.entrySet().iterator();i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); String puid = (String)entry.getKey(); SolverProxy solver = (SolverProxy)entry.getValue(); solver.passivateIfNeeded(iFolder, puid); } try { sleep(sDelay); } catch (InterruptedException e) { break; } } - sLog.info("Solver passivation thread finished."); + System.out.println("Solver passivation thread finished."); } catch (Exception e) { - sLog.error("Solver passivation thread failed, reason: "+e.getMessage(),e); + System.err.print("Solver passivation thread failed, reason: "+e.getMessage()); + e.printStackTrace(); } } }
false
true
public void run() { try { sLog.info("Solver passivation thread started."); while (true) { for (Iterator i=iSolvers.entrySet().iterator();i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); String puid = (String)entry.getKey(); SolverProxy solver = (SolverProxy)entry.getValue(); solver.passivateIfNeeded(iFolder, puid); } try { sleep(sDelay); } catch (InterruptedException e) { break; } } sLog.info("Solver passivation thread finished."); } catch (Exception e) { sLog.error("Solver passivation thread failed, reason: "+e.getMessage(),e); } }
public void run() { try { sLog.info("Solver passivation thread started."); while (true) { for (Iterator i=iSolvers.entrySet().iterator();i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); String puid = (String)entry.getKey(); SolverProxy solver = (SolverProxy)entry.getValue(); solver.passivateIfNeeded(iFolder, puid); } try { sleep(sDelay); } catch (InterruptedException e) { break; } } System.out.println("Solver passivation thread finished."); } catch (Exception e) { System.err.print("Solver passivation thread failed, reason: "+e.getMessage()); e.printStackTrace(); } }
diff --git a/src/main/java/emcshop/gui/ErrorDialog.java b/src/main/java/emcshop/gui/ErrorDialog.java index 5e2291f..4cadf49 100644 --- a/src/main/java/emcshop/gui/ErrorDialog.java +++ b/src/main/java/emcshop/gui/ErrorDialog.java @@ -1,88 +1,88 @@ package emcshop.gui; import java.awt.Font; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang3.exception.ExceptionUtils; import emcshop.gui.images.ImageManager; /** * Generic dialog for displaying uncaught exceptions. * @author Michael Angstadt */ @SuppressWarnings("serial") public class ErrorDialog extends JDialog { private static final Logger logger = Logger.getLogger(ErrorDialog.class.getName()); private ErrorDialog(Window owner, String displayMessage, Throwable thrown, String buttonText) { super(owner, "Error"); setModalityType(ModalityType.DOCUMENT_MODAL); //go on top of all windows setDefaultCloseOperation(DISPOSE_ON_CLOSE); //close when escape is pressed getRootPane().registerKeyboardAction(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); JTextArea displayText = new JTextArea(displayMessage); displayText.setEditable(false); displayText.setBackground(getBackground()); displayText.setLineWrap(true); displayText.setWrapStyleWord(true); //http://stackoverflow.com/questions/1196797/where-are-these-error-and-warning-icons-as-a-java-resource JLabel errorIcon = new JLabel(ImageManager.getErrorIcon()); JTextArea stackTrace = new JTextArea(ExceptionUtils.getStackTrace(thrown)); stackTrace.setEditable(false); stackTrace.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); JButton close = new JButton(buttonText); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); setLayout(new MigLayout()); add(errorIcon, "span 1 3"); - add(displayText, "w 200, align left, wrap"); //TODO when this uses "growx", it won't shrink when the window width decreases + add(displayText, "w 100:100%:100%, align left, wrap"); JScrollPane scroll = new JScrollPane(stackTrace); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - add(scroll, "grow, align center, wrap"); + add(scroll, "grow, w 100%, h 100%, align center, wrap"); add(close, "align center"); setSize(500, 300); } public static void show(Window owner, String displayMessage, Throwable thrown) { show(owner, displayMessage, thrown, "Close"); } public static void show(Window owner, String displayMessage, Throwable thrown, String buttonText) { logger.log(Level.SEVERE, displayMessage, thrown); new ErrorDialog(owner, displayMessage, thrown, buttonText).setVisible(true); } }
false
true
private ErrorDialog(Window owner, String displayMessage, Throwable thrown, String buttonText) { super(owner, "Error"); setModalityType(ModalityType.DOCUMENT_MODAL); //go on top of all windows setDefaultCloseOperation(DISPOSE_ON_CLOSE); //close when escape is pressed getRootPane().registerKeyboardAction(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); JTextArea displayText = new JTextArea(displayMessage); displayText.setEditable(false); displayText.setBackground(getBackground()); displayText.setLineWrap(true); displayText.setWrapStyleWord(true); //http://stackoverflow.com/questions/1196797/where-are-these-error-and-warning-icons-as-a-java-resource JLabel errorIcon = new JLabel(ImageManager.getErrorIcon()); JTextArea stackTrace = new JTextArea(ExceptionUtils.getStackTrace(thrown)); stackTrace.setEditable(false); stackTrace.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); JButton close = new JButton(buttonText); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); setLayout(new MigLayout()); add(errorIcon, "span 1 3"); add(displayText, "w 200, align left, wrap"); //TODO when this uses "growx", it won't shrink when the window width decreases JScrollPane scroll = new JScrollPane(stackTrace); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); add(scroll, "grow, align center, wrap"); add(close, "align center"); setSize(500, 300); }
private ErrorDialog(Window owner, String displayMessage, Throwable thrown, String buttonText) { super(owner, "Error"); setModalityType(ModalityType.DOCUMENT_MODAL); //go on top of all windows setDefaultCloseOperation(DISPOSE_ON_CLOSE); //close when escape is pressed getRootPane().registerKeyboardAction(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); JTextArea displayText = new JTextArea(displayMessage); displayText.setEditable(false); displayText.setBackground(getBackground()); displayText.setLineWrap(true); displayText.setWrapStyleWord(true); //http://stackoverflow.com/questions/1196797/where-are-these-error-and-warning-icons-as-a-java-resource JLabel errorIcon = new JLabel(ImageManager.getErrorIcon()); JTextArea stackTrace = new JTextArea(ExceptionUtils.getStackTrace(thrown)); stackTrace.setEditable(false); stackTrace.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); JButton close = new JButton(buttonText); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); setLayout(new MigLayout()); add(errorIcon, "span 1 3"); add(displayText, "w 100:100%:100%, align left, wrap"); JScrollPane scroll = new JScrollPane(stackTrace); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); add(scroll, "grow, w 100%, h 100%, align center, wrap"); add(close, "align center"); setSize(500, 300); }
diff --git a/plugins/org.jboss.tools.esb.project.core/src/org/jboss/tools/esb/core/module/JBossESBModuleFactory.java b/plugins/org.jboss.tools.esb.project.core/src/org/jboss/tools/esb/core/module/JBossESBModuleFactory.java index 49665f9..f100bd7 100644 --- a/plugins/org.jboss.tools.esb.project.core/src/org/jboss/tools/esb/core/module/JBossESBModuleFactory.java +++ b/plugins/org.jboss.tools.esb.project.core/src/org/jboss/tools/esb/core/module/JBossESBModuleFactory.java @@ -1,44 +1,47 @@ package org.jboss.tools.esb.core.module; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.wst.common.project.facet.core.IFacetedProject; import org.eclipse.wst.common.project.facet.core.IProjectFacet; import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.model.ModuleDelegate; import org.eclipse.wst.server.core.util.ProjectModule; import org.eclipse.wst.server.core.util.ProjectModuleFactoryDelegate; import org.jboss.tools.esb.core.ESBProjectUtilities; public class JBossESBModuleFactory extends ProjectModuleFactoryDelegate { public JBossESBModuleFactory() { } @Override public ModuleDelegate getModuleDelegate(IModule module) { if(module instanceof JBossESBModule){ IProject project = module.getProject(); return new JBossESBModuleDelegate(project); } return null; } protected IModule[] createModules(IProject project) { IFacetedProject facetProject; try { facetProject = ProjectFacetsManager.create(project); + if (facetProject == null) { + return null; + } IProjectFacet esbFacet = ProjectFacetsManager.getProjectFacet(ESBProjectUtilities.ESB_PROJECT_FACET); if(facetProject.hasProjectFacet(esbFacet)){ JBossESBModule module = new JBossESBModule(project, this, this.getId()); return new IModule[]{ module }; } } catch (CoreException e) { e.printStackTrace(); } return null; } }
true
true
protected IModule[] createModules(IProject project) { IFacetedProject facetProject; try { facetProject = ProjectFacetsManager.create(project); IProjectFacet esbFacet = ProjectFacetsManager.getProjectFacet(ESBProjectUtilities.ESB_PROJECT_FACET); if(facetProject.hasProjectFacet(esbFacet)){ JBossESBModule module = new JBossESBModule(project, this, this.getId()); return new IModule[]{ module }; } } catch (CoreException e) { e.printStackTrace(); } return null; }
protected IModule[] createModules(IProject project) { IFacetedProject facetProject; try { facetProject = ProjectFacetsManager.create(project); if (facetProject == null) { return null; } IProjectFacet esbFacet = ProjectFacetsManager.getProjectFacet(ESBProjectUtilities.ESB_PROJECT_FACET); if(facetProject.hasProjectFacet(esbFacet)){ JBossESBModule module = new JBossESBModule(project, this, this.getId()); return new IModule[]{ module }; } } catch (CoreException e) { e.printStackTrace(); } return null; }
diff --git a/src/com/feeba/editor/EditorGUI.java b/src/com/feeba/editor/EditorGUI.java index 5fac066..e531c60 100644 --- a/src/com/feeba/editor/EditorGUI.java +++ b/src/com/feeba/editor/EditorGUI.java @@ -1,911 +1,912 @@ package com.feeba.editor; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Toolkit; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JButton; import javax.swing.JTabbedPane; import com.feeba.core.FeebaCore; import com.feeba.data.Question; import com.feeba.data.ReturnDataController; import com.feeba.data.Survey; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.awt.Component; import javax.swing.Box; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Color; import javax.swing.ImageIcon; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Insets; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import javax.swing.JLayeredPane; import java.awt.FlowLayout; import javax.swing.SpringLayout; import java.awt.Font; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import com.feeba.data.QuestionType; import javax.swing.JTextField; import javax.swing.JTextArea; import javax.swing.border.LineBorder; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.ComponentOrientation; import java.awt.SystemColor; public class EditorGUI extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; public static JList questions; public static JLabel backgroundPreview; public static JTabbedPane tabbedPane; private JTextField questionNameEdit; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; private JTextField textField_5; private JTextField textField_6; private JTextField textField_7; private JTextField textField_8; private JTextField textField_9; public static JPanel editPanel; boolean mouseDragging = false; private JComboBox questionTypeEdit; private JTextArea questionTextEdit; public static JPanel results; public static Box questionWrapper; private JLabel lblAntwortmglichkeit; private JPanel choicesEdit; public final Color UICOLOR = FeebaCore.FEEBA_BLUE; public static JComboBox comboBox; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { EditorGUI frame = new EditorGUI(); frame.setState(Frame.NORMAL); //start editor maximized Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension dimension = toolkit.getScreenSize(); frame.setSize(dimension); frame.setVisible(true); updateBackgroundLabel(backgroundPreview,tabbedPane); } catch (Exception e) { e.printStackTrace(); } } private void updateBackgroundLabel(JLabel label, JTabbedPane pane) { label.setSize(new Dimension(pane.getWidth(),pane.getHeight())); } }); } /** * Create the frame. */ public EditorGUI() { setTitle("Feeba"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 821, 544); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(null); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel toolBar = new JPanel(); toolBar.setBackground(new Color(0x222325)); toolBar.setAlignmentY(Component.CENTER_ALIGNMENT); toolBar.setPreferredSize(new Dimension(16, 50)); contentPane.add(toolBar, BorderLayout.NORTH); SpringLayout sl_toolBar = new SpringLayout(); toolBar.setLayout(sl_toolBar); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(EditorGUI.class.getResource("/images/logo_toolbar.png"))); toolBar.add(lblNewLabel); JPanel panel_1 = new JPanel(); sl_toolBar.putConstraint(SpringLayout.WEST, panel_1, 50, SpringLayout.EAST, lblNewLabel); sl_toolBar.putConstraint(SpringLayout.NORTH, panel_1, 0, SpringLayout.NORTH, toolBar); panel_1.setOpaque(false); toolBar.add(panel_1); JButton btnNewButton = new JButton("Fragebogen Laden"); panel_1.add(btnNewButton); btnNewButton.setAlignmentX(Component.CENTER_ALIGNMENT); btnNewButton.setHorizontalTextPosition(SwingConstants.LEADING); btnNewButton.setAlignmentY(Component.TOP_ALIGNMENT); btnNewButton.setMargin(new Insets(0, 0, 0, 0)); btnNewButton.setPreferredSize(new Dimension(200, 50)); btnNewButton.setForeground(Color.WHITE); btnNewButton.setFont(new Font("Helvetica", Font.BOLD, 10)); btnNewButton.setOpaque(true); btnNewButton.setBackground(new Color(0x17748F)); btnNewButton.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut); JButton btnFragebogenSpeichern = new JButton("Fragebogen Speichern"); panel_1.add(btnFragebogenSpeichern); btnFragebogenSpeichern.setMargin(new Insets(0, 0, 0, 0)); btnFragebogenSpeichern.setPreferredSize(new Dimension(200, 50)); btnFragebogenSpeichern.setForeground(Color.WHITE); btnFragebogenSpeichern.setFont(new Font("Helvetica", Font.BOLD, 10)); btnFragebogenSpeichern.setBackground(new Color(0x17748F)); btnFragebogenSpeichern.setOpaque(true); btnFragebogenSpeichern.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut_1 = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut_1); JButton btnUmfrageStarten = new JButton("Umfrage Starten"); panel_1.add(btnUmfrageStarten); btnUmfrageStarten.setMargin(new Insets(0, 0, 0, 0)); btnUmfrageStarten.setPreferredSize(new Dimension(200, 50)); btnUmfrageStarten.setForeground(Color.WHITE); btnUmfrageStarten.setBackground(new Color(0x17748F)); btnUmfrageStarten.setOpaque(true); btnUmfrageStarten.setBorder(new LineBorder(new Color(0x17748F), 7)); btnUmfrageStarten.setFont(new Font("Helvetica", Font.BOLD, 10)); btnUmfrageStarten.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(FeebaCore.currentSurvey!=null){ EditorController.startSurvey();} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } }); btnFragebogenSpeichern.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { saveFileChoser(); } }); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { openFileChooser(); } }); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBorder(new LineBorder(Color.WHITE, 12)); tabbedPane.setBackground(null); ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource(); int index = sourceTabbedPane.getSelectedIndex(); if(index ==1) { if(FeebaCore.currentSurvey!=null){ EditorController.generateChart(results,questions.getSelectedIndex());} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } } }; tabbedPane.addChangeListener(changeListener); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel preview = new JPanel(); preview.setBorder(null); preview.setBackground(null); tabbedPane.addTab("Vorschau", null, preview, null); SpringLayout sl_preview = new SpringLayout(); preview.setLayout(sl_preview); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, layeredPane, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, layeredPane, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, layeredPane, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, layeredPane, 0, SpringLayout.EAST, preview); preview.add(layeredPane); SpringLayout sl_layeredPane = new SpringLayout(); layeredPane.setLayout(sl_layeredPane); JPanel panel_3 = new JPanel(); panel_3.setOpaque(false); sl_layeredPane.putConstraint(SpringLayout.NORTH, panel_3, 0, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.WEST, panel_3, 0, SpringLayout.WEST, layeredPane); sl_layeredPane.putConstraint(SpringLayout.SOUTH, panel_3, 444, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.EAST, panel_3, 0, SpringLayout.EAST, layeredPane); panel_3.setBackground(null); layeredPane.add(panel_3); SpringLayout sl_panel_3 = new SpringLayout(); panel_3.setLayout(sl_panel_3); final JLabel questionName = new JLabel(""); questionName.setFont(new Font("Helvetica", Font.PLAIN, 30)); questionName.setForeground(Color.WHITE); sl_panel_3.putConstraint(SpringLayout.NORTH, questionName, 103, SpringLayout.NORTH, panel_3); sl_panel_3.putConstraint(SpringLayout.WEST, questionName, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionName, 0, SpringLayout.EAST, panel_3); questionName.setHorizontalAlignment(SwingConstants.CENTER); questionName.setBackground(null); panel_3.add(questionName); final JLabel questionText = new JLabel(""); questionText.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionText, 100, SpringLayout.SOUTH, questionName); questionText.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionText.setForeground(Color.WHITE); questionText.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionText, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionText, 0, SpringLayout.EAST, panel_3); panel_3.add(questionText); final JLabel questionChoices = new JLabel(""); questionChoices.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionChoices, 80, SpringLayout.SOUTH, questionText); questionChoices.setFont(new Font("Lucida Grande", Font.PLAIN, 23)); questionChoices.setForeground(Color.WHITE); questionChoices.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionChoices, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionChoices, 0, SpringLayout.EAST, panel_3); panel_3.add(questionChoices); backgroundPreview = new JLabel(""); backgroundPreview.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, backgroundPreview, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, backgroundPreview, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, backgroundPreview, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, backgroundPreview, 0, SpringLayout.EAST, preview); preview.add(backgroundPreview); backgroundPreview.setAlignmentY(Component.TOP_ALIGNMENT); backgroundPreview.setIconTextGap(0); results = new JPanel(); results.setEnabled(false); results.setBackground(Color.WHITE); tabbedPane.addTab("Auswertung", null, results, null); GridBagLayout gbl_results = new GridBagLayout(); gbl_results.columnWidths = new int[]{0}; gbl_results.rowHeights = new int[]{0}; gbl_results.columnWeights = new double[]{Double.MIN_VALUE}; gbl_results.rowWeights = new double[]{Double.MIN_VALUE}; results.setLayout(gbl_results); questionWrapper = Box.createVerticalBox(); + questionWrapper.setPreferredSize(new Dimension(200, 200)); questionWrapper.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); questionWrapper.setAlignmentY(Component.TOP_ALIGNMENT); questionWrapper.setBorder(null); contentPane.add(questionWrapper, BorderLayout.WEST); questions = new JList(); - questions.setMinimumSize(new Dimension(200, 2000)); + questions.setMinimumSize(new Dimension(200, 200)); questions.setMaximumSize(new Dimension(200, 200)); questions.setFont(new Font("Helvetica", Font.PLAIN, 15)); questions.setSelectionBackground(new Color(0x17748F)); questions.setBorder(null); questions.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int selectedIndex = questions.getSelectedIndex(); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); fillEditFields(selectedIndex,questionNameEdit,questionTextEdit,questionTypeEdit); EditorController.generateChart(results,selectedIndex); } }); Component verticalStrut = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut); questions.setPreferredSize(new Dimension(200, 10)); JScrollPane questionScroller = new JScrollPane(questions); questionScroller.setBorder(null); questionWrapper.add(questionScroller); JPanel panel = new JPanel(); panel.setOpaque(false); panel.setBorder(null); panel.setBackground(new Color(0x2D2F31)); panel.setMaximumSize(new Dimension(32767, 30)); panel.setPreferredSize(new Dimension(200, 30)); panel.setSize(new Dimension(200, 40)); questionWrapper.add(panel); JButton button = new JButton("+"); button.setForeground(Color.DARK_GRAY); button.setBackground(SystemColor.inactiveCaption); button.setFont(new Font("Helvetica", Font.PLAIN, 22)); button.setOpaque(true); button.setAlignmentY(Component.BOTTOM_ALIGNMENT); button.setMargin(new Insets(0, 0, 0, 0)); button.setPreferredSize(new Dimension(24, 24)); button.setBorder(null); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); SpringLayout sl_panel = new SpringLayout(); sl_panel.putConstraint(SpringLayout.NORTH, button, 3, SpringLayout.NORTH, panel); sl_panel.putConstraint(SpringLayout.EAST, button, -3, SpringLayout.EAST, panel); panel.setLayout(sl_panel); panel.add(button); JButton button_1 = new JButton("-"); button_1.setForeground(Color.DARK_GRAY); sl_panel.putConstraint(SpringLayout.EAST, button_1, -3, SpringLayout.WEST, button); button_1.setFont(new Font("Helvetica", Font.PLAIN, 25)); button_1.setOpaque(true); button_1.setBackground(SystemColor.inactiveCaptionBorder); sl_panel.putConstraint(SpringLayout.SOUTH, button_1, 0, SpringLayout.SOUTH, button); button_1.setPreferredSize(new Dimension(24, 24)); button_1.setMargin(new Insets(0, 0, 0, 0)); button_1.setBorder(null); button_1.setAlignmentY(1.0f); panel.add(button_1); Component verticalStrut_1 = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut_1); editPanel = new JPanel(); editPanel.setBorder(new LineBorder(Color.WHITE, 10)); editPanel.setBackground(Color.WHITE); editPanel.setPreferredSize(new Dimension(250, 10)); contentPane.add(editPanel, BorderLayout.EAST); SpringLayout sl_editPanel = new SpringLayout(); editPanel.setLayout(sl_editPanel); editPanel.setVisible(false); questionTypeEdit = new JComboBox(); sl_editPanel.putConstraint(SpringLayout.EAST, questionTypeEdit, -14, SpringLayout.EAST, editPanel); questionTypeEdit.setModel(new DefaultComboBoxModel(QuestionType.values())); questionTypeEdit.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { System.out.println("Change:" + e.paramString()); //EditorController.loadedSurvey.getQuestions().get(questions.getSelectedIndex()).changeQuestionType((QuestionType)questionTypeEdit.getSelectedItem()); toggleChoices(); } }); editPanel.add(questionTypeEdit); JLabel questionType = new JLabel("Fragetyp: "); questionType.setBorder(new LineBorder(UICOLOR, 7)); questionType.setForeground(Color.WHITE); questionType.setOpaque(true); questionType.setBackground(UICOLOR); questionType.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, questionType, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTypeEdit, 6, SpringLayout.SOUTH, questionType); sl_editPanel.putConstraint(SpringLayout.WEST, questionTypeEdit, 10, SpringLayout.WEST, questionType); sl_editPanel.putConstraint(SpringLayout.NORTH, questionType, 10, SpringLayout.NORTH, editPanel); editPanel.add(questionType); JLabel lblFrage = new JLabel("Name: "); sl_editPanel.putConstraint(SpringLayout.WEST, lblFrage, 0, SpringLayout.WEST, questionType); lblFrage.setOpaque(true); lblFrage.setBackground(UICOLOR); lblFrage.setBorder(new LineBorder(UICOLOR, 7)); lblFrage.setForeground(Color.WHITE); lblFrage.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.NORTH, lblFrage, 10, SpringLayout.SOUTH, questionTypeEdit); editPanel.add(lblFrage); questionNameEdit = new JTextField(); sl_editPanel.putConstraint(SpringLayout.NORTH, questionNameEdit, 10, SpringLayout.SOUTH, lblFrage); sl_editPanel.putConstraint(SpringLayout.WEST, questionNameEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionNameEdit, 0, SpringLayout.EAST, questionTypeEdit); questionNameEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setName(questionNameEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionNameEdit.setForeground(Color.WHITE); questionNameEdit.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionNameEdit.setBackground(Color.LIGHT_GRAY); questionNameEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 7)); editPanel.add(questionNameEdit); questionNameEdit.setColumns(10); JLabel choicesLbl = new JLabel("Frage: "); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesLbl, 10, SpringLayout.SOUTH, questionNameEdit); choicesLbl.setOpaque(true); choicesLbl.setBackground(UICOLOR); choicesLbl.setBorder(new LineBorder(UICOLOR, 7)); choicesLbl.setForeground(Color.WHITE); choicesLbl.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, choicesLbl, 10, SpringLayout.WEST, editPanel); editPanel.add(choicesLbl); choicesEdit = new JPanel(); sl_editPanel.putConstraint(SpringLayout.WEST, choicesEdit, 0, SpringLayout.WEST, questionNameEdit); choicesEdit.setBackground(Color.WHITE); editPanel.add(choicesEdit); GridBagLayout gbl_choicesEdit = new GridBagLayout(); gbl_choicesEdit.columnWidths = new int[] {40, 150, 0}; gbl_choicesEdit.rowHeights = new int[] {20, 20, 20, 20, 20, 20, 20, 20, 20}; gbl_choicesEdit.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_choicesEdit.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; choicesEdit.setLayout(gbl_choicesEdit); JLabel lblA = new JLabel("A : "); lblA.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblA = new GridBagConstraints(); gbc_lblA.insets = new Insets(0, 0, 5, 5); gbc_lblA.anchor = GridBagConstraints.WEST; gbc_lblA.gridx = 0; gbc_lblA.gridy = 0; choicesEdit.add(lblA, gbc_lblA); textField_5 = new JTextField(); textField_5.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_5.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_5.setBackground(Color.LIGHT_GRAY); textField_5.setForeground(Color.WHITE); textField_5.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_5 = new GridBagConstraints(); gbc_textField_5.fill = GridBagConstraints.BOTH; gbc_textField_5.insets = new Insets(0, 0, 5, 0); gbc_textField_5.gridx = 1; gbc_textField_5.gridy = 0; choicesEdit.add(textField_5, gbc_textField_5); textField_5.setColumns(8); JLabel lblB = new JLabel("B : "); lblB.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblB = new GridBagConstraints(); gbc_lblB.fill = GridBagConstraints.BOTH; gbc_lblB.insets = new Insets(0, 0, 5, 5); gbc_lblB.gridx = 0; gbc_lblB.gridy = 1; choicesEdit.add(lblB, gbc_lblB); textField_8 = new JTextField(); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setForeground(Color.WHITE); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_8.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_8 = new GridBagConstraints(); gbc_textField_8.fill = GridBagConstraints.BOTH; gbc_textField_8.insets = new Insets(0, 0, 5, 0); gbc_textField_8.gridx = 1; gbc_textField_8.gridy = 1; choicesEdit.add(textField_8, gbc_textField_8); textField_8.setColumns(8); JLabel lblC = new JLabel("C : "); lblC.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblC = new GridBagConstraints(); gbc_lblC.fill = GridBagConstraints.BOTH; gbc_lblC.insets = new Insets(0, 0, 5, 5); gbc_lblC.gridx = 0; gbc_lblC.gridy = 2; choicesEdit.add(lblC, gbc_lblC); textField_7 = new JTextField(); GridBagConstraints gbc_textField_7 = new GridBagConstraints(); textField_7.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_7.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_7.setBackground(Color.LIGHT_GRAY); textField_7.setForeground(Color.WHITE); gbc_textField_7.fill = GridBagConstraints.BOTH; gbc_textField_7.insets = new Insets(0, 0, 5, 0); gbc_textField_7.gridx = 1; gbc_textField_7.gridy = 2; choicesEdit.add(textField_7, gbc_textField_7); textField_7.setColumns(8); JLabel lblD = new JLabel("D : "); lblD.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblD = new GridBagConstraints(); gbc_lblD.fill = GridBagConstraints.BOTH; gbc_lblD.insets = new Insets(0, 0, 5, 5); gbc_lblD.gridx = 0; gbc_lblD.gridy = 3; choicesEdit.add(lblD, gbc_lblD); textField_6 = new JTextField(); GridBagConstraints gbc_textField_6 = new GridBagConstraints(); textField_6.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_6.setForeground(Color.WHITE); textField_6.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_6.setBackground(Color.LIGHT_GRAY); gbc_textField_6.fill = GridBagConstraints.BOTH; gbc_textField_6.insets = new Insets(0, 0, 5, 0); gbc_textField_6.gridx = 1; gbc_textField_6.gridy = 3; choicesEdit.add(textField_6, gbc_textField_6); textField_6.setColumns(10); JLabel lblE = new JLabel("E : "); lblE.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblE = new GridBagConstraints(); gbc_lblE.fill = GridBagConstraints.BOTH; gbc_lblE.insets = new Insets(0, 0, 5, 5); gbc_lblE.gridx = 0; gbc_lblE.gridy = 4; choicesEdit.add(lblE, gbc_lblE); textField_4 = new JTextField(); GridBagConstraints gbc_textField_4 = new GridBagConstraints(); textField_4.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_4.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_4.setBackground(Color.LIGHT_GRAY); textField_4.setForeground(Color.WHITE); gbc_textField_4.fill = GridBagConstraints.BOTH; gbc_textField_4.insets = new Insets(0, 0, 5, 0); gbc_textField_4.gridx = 1; gbc_textField_4.gridy = 4; choicesEdit.add(textField_4, gbc_textField_4); textField_4.setColumns(10); JLabel lblF = new JLabel("F : "); lblF.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblF = new GridBagConstraints(); gbc_lblF.anchor = GridBagConstraints.WEST; gbc_lblF.fill = GridBagConstraints.BOTH; gbc_lblF.insets = new Insets(0, 0, 5, 5); gbc_lblF.gridx = 0; gbc_lblF.gridy = 5; choicesEdit.add(lblF, gbc_lblF); textField_3 = new JTextField(); GridBagConstraints gbc_textField_3 = new GridBagConstraints(); textField_3.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_3.setForeground(Color.WHITE); textField_3.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_3.setBackground(Color.LIGHT_GRAY); gbc_textField_3.fill = GridBagConstraints.BOTH; gbc_textField_3.insets = new Insets(0, 0, 5, 0); gbc_textField_3.gridx = 1; gbc_textField_3.gridy = 5; choicesEdit.add(textField_3, gbc_textField_3); textField_3.setColumns(10); JLabel lblG = new JLabel("G : "); lblG.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblG = new GridBagConstraints(); gbc_lblG.fill = GridBagConstraints.BOTH; gbc_lblG.insets = new Insets(0, 0, 5, 5); gbc_lblG.gridx = 0; gbc_lblG.gridy = 6; choicesEdit.add(lblG, gbc_lblG); textField_1 = new JTextField(); GridBagConstraints gbc_textField_1 = new GridBagConstraints(); textField_1.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_1.setForeground(Color.WHITE); textField_1.setBackground(Color.LIGHT_GRAY); textField_1.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_1.fill = GridBagConstraints.BOTH; gbc_textField_1.insets = new Insets(0, 0, 5, 0); gbc_textField_1.gridx = 1; gbc_textField_1.gridy = 6; choicesEdit.add(textField_1, gbc_textField_1); textField_1.setColumns(10); JLabel lblH = new JLabel("H : "); lblH.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblH = new GridBagConstraints(); gbc_lblH.fill = GridBagConstraints.BOTH; gbc_lblH.insets = new Insets(0, 0, 5, 5); gbc_lblH.gridx = 0; gbc_lblH.gridy = 7; choicesEdit.add(lblH, gbc_lblH); textField_2 = new JTextField(); GridBagConstraints gbc_textField_2 = new GridBagConstraints(); textField_2.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_2.setBackground(Color.LIGHT_GRAY); textField_2.setForeground(Color.WHITE); textField_2.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_2.fill = GridBagConstraints.BOTH; gbc_textField_2.insets = new Insets(0, 0, 5, 0); gbc_textField_2.gridx = 1; gbc_textField_2.gridy = 7; choicesEdit.add(textField_2, gbc_textField_2); textField_2.setColumns(10); JLabel lblI = new JLabel("I : "); lblI.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblI = new GridBagConstraints(); gbc_lblI.anchor = GridBagConstraints.WEST; gbc_lblI.fill = GridBagConstraints.VERTICAL; gbc_lblI.insets = new Insets(0, 0, 0, 5); gbc_lblI.gridx = 0; gbc_lblI.gridy = 8; choicesEdit.add(lblI, gbc_lblI); lblAntwortmglichkeit = new JLabel("Antwortm\u00F6glichkeiten: "); lblAntwortmglichkeit.setOpaque(true); lblAntwortmglichkeit.setBackground(UICOLOR); lblAntwortmglichkeit.setBorder(new LineBorder(UICOLOR, 7)); lblAntwortmglichkeit.setForeground(Color.WHITE); lblAntwortmglichkeit.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, lblAntwortmglichkeit, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesEdit, 14, SpringLayout.SOUTH, lblAntwortmglichkeit); textField_9 = new JTextField(); GridBagConstraints gbc_textField_9 = new GridBagConstraints(); gbc_textField_9.fill = GridBagConstraints.BOTH; textField_9.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_9.setBackground(Color.LIGHT_GRAY); textField_9.setForeground(Color.WHITE); textField_9.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_9.insets = new Insets(0, 0, 5, 0); gbc_textField_9.gridx = 1; gbc_textField_9.gridy = 8; choicesEdit.add(textField_9, gbc_textField_9); textField_9.setColumns(10); editPanel.add(lblAntwortmglichkeit); questionTextEdit = new JTextArea(); sl_editPanel.putConstraint(SpringLayout.NORTH, lblAntwortmglichkeit, 10, SpringLayout.SOUTH, questionTextEdit); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTextEdit, 10, SpringLayout.SOUTH, choicesLbl); sl_editPanel.putConstraint(SpringLayout.WEST, questionTextEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionTextEdit, 0, SpringLayout.EAST, questionTypeEdit); questionTextEdit.setLineWrap(true); questionTextEdit.setWrapStyleWord(true); sl_editPanel.putConstraint(SpringLayout.EAST, choicesEdit, 0, SpringLayout.EAST, questionTextEdit); questionTextEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setQuestionText(questionTextEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionTextEdit.setForeground(Color.WHITE); questionTextEdit.setFont(new Font("Helvetica", Font.PLAIN, 16)); questionTextEdit.setBackground(Color.LIGHT_GRAY); questionTextEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 6)); questionTextEdit.setRows(3); editPanel.add(questionTextEdit); JPanel panel_2 = new JPanel(); panel_2.setOpaque(false); panel_2.setPreferredSize(new Dimension(250, 10)); contentPane.add(panel_2, BorderLayout.EAST); SpringLayout sl_panel_2 = new SpringLayout(); panel_2.setLayout(sl_panel_2); comboBox = new JComboBox(); sl_panel_2.putConstraint(SpringLayout.WEST, comboBox, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, comboBox, -52, SpringLayout.EAST, panel_2); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Kuchendiagramm", "Balkendiagramm", "Radardiagramm"})); comboBox.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { EditorController.generateChart(results, questions.getSelectedIndex());} }); panel_2.add(comboBox); JLabel lblDiagrammtyp = new JLabel("Diagrammtyp: "); sl_panel_2.putConstraint(SpringLayout.NORTH, comboBox, 50, SpringLayout.NORTH, lblDiagrammtyp); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammtyp, 50, SpringLayout.NORTH, panel_2); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammtyp, 0, SpringLayout.WEST, comboBox); lblDiagrammtyp.setOpaque(true); lblDiagrammtyp.setForeground(Color.WHITE); lblDiagrammtyp.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammtyp.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammtyp.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammtyp); JButton btnNewButton_1 = new JButton("Daten zur\u00FCcksetzen"); btnNewButton_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.resetResults(questions.getSelectedIndex()); EditorController.generateChart(results, questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnNewButton_1, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, btnNewButton_1, 240, SpringLayout.WEST, panel_2); panel_2.add(btnNewButton_1); JLabel lblDiagrammaktionen = new JLabel("Diagrammaktionen: "); sl_panel_2.putConstraint(SpringLayout.NORTH, btnNewButton_1, 50, SpringLayout.NORTH, lblDiagrammaktionen); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammaktionen, 50, SpringLayout.NORTH, comboBox); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammaktionen, 0, SpringLayout.WEST, comboBox); lblDiagrammaktionen.setOpaque(true); lblDiagrammaktionen.setForeground(Color.WHITE); lblDiagrammaktionen.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammaktionen.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammaktionen.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammaktionen); JButton btnDiagrammAlsBild = new JButton("Diagramm als Bild speichern..."); sl_panel_2.putConstraint(SpringLayout.NORTH, btnDiagrammAlsBild, 40, SpringLayout.NORTH, btnNewButton_1); btnDiagrammAlsBild.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.saveChartImage((JLabel) results.getComponents()[0], questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnDiagrammAlsBild, 0, SpringLayout.WEST, comboBox); panel_2.add(btnDiagrammAlsBild); } public static void openFileChooser() { final JFileChooser chooser = new JFileChooser("Fragebogen laden"); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.addChoosableFileFilter(new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().toLowerCase().endsWith(".feeba"); } public String getDescription () { return "Feeba Frageb�gen (*.feeba)"; } }); chooser.setMultiSelectionEnabled(false); chooser.setVisible(true); final int result = chooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { tabbedPane.setVisible(true); questionWrapper.setVisible(true); File inputFile = chooser.getSelectedFile(); String inputDir = inputFile.getPath(); EditorController.loadSurvey(inputDir,questions,backgroundPreview); editPanel.setVisible(true); } } private void saveFileChoser() { JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File(FeebaCore.currentSurvey.getName()+".feeba")); chooser.setDialogTitle("Speichern unter..."); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.addChoosableFileFilter(new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().toLowerCase().endsWith(".feeba"); } public String getDescription() { return "Feeba Fragebogen (*.feeba)"; } }); chooser.setVisible(true); final int result = chooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File saveFile = chooser.getSelectedFile(); String saveDir = saveFile.getPath(); EditorController.saveSurvey(saveDir); } } private void fillPreviewFields(int selectedIndex, JLabel name, JLabel text, JLabel answers) { Question ques = FeebaCore.currentSurvey.getQuestions().get(selectedIndex); name.setText("Frage " + (questions.getSelectedIndex()+1) + " - " + ques.getName()); text.setText(ques.getQuestionText()); answers.setText(ques.getChoicesText()); } private void fillEditFields(int selectedIndex, JTextField questionNameEdit, JTextArea questionTextEdit, JComboBox questionTypeEdit) { Question ques = FeebaCore.currentSurvey.getQuestions().get(selectedIndex); questionNameEdit.setText(ques.getName()); questionTextEdit.setText(ques.getQuestionText()); questionTypeEdit.setSelectedItem(ques.getType()); toggleChoices(); } public void toggleChoices() { JComboBox jcb = getQuestionTypeEdit(); if(jcb.getSelectedItem().equals(QuestionType.FREETEXT)) { lblAntwortmglichkeit.setVisible(false); choicesEdit.setVisible(false); } else { lblAntwortmglichkeit.setVisible(true); choicesEdit.setVisible(true); } } protected JComboBox getQuestionTypeEdit() { return questionTypeEdit; } public JLabel getLblAntwortmglichkeit() { return lblAntwortmglichkeit; } public JPanel getChoicesEdit() { return choicesEdit; } }
false
true
public EditorGUI() { setTitle("Feeba"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 821, 544); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(null); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel toolBar = new JPanel(); toolBar.setBackground(new Color(0x222325)); toolBar.setAlignmentY(Component.CENTER_ALIGNMENT); toolBar.setPreferredSize(new Dimension(16, 50)); contentPane.add(toolBar, BorderLayout.NORTH); SpringLayout sl_toolBar = new SpringLayout(); toolBar.setLayout(sl_toolBar); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(EditorGUI.class.getResource("/images/logo_toolbar.png"))); toolBar.add(lblNewLabel); JPanel panel_1 = new JPanel(); sl_toolBar.putConstraint(SpringLayout.WEST, panel_1, 50, SpringLayout.EAST, lblNewLabel); sl_toolBar.putConstraint(SpringLayout.NORTH, panel_1, 0, SpringLayout.NORTH, toolBar); panel_1.setOpaque(false); toolBar.add(panel_1); JButton btnNewButton = new JButton("Fragebogen Laden"); panel_1.add(btnNewButton); btnNewButton.setAlignmentX(Component.CENTER_ALIGNMENT); btnNewButton.setHorizontalTextPosition(SwingConstants.LEADING); btnNewButton.setAlignmentY(Component.TOP_ALIGNMENT); btnNewButton.setMargin(new Insets(0, 0, 0, 0)); btnNewButton.setPreferredSize(new Dimension(200, 50)); btnNewButton.setForeground(Color.WHITE); btnNewButton.setFont(new Font("Helvetica", Font.BOLD, 10)); btnNewButton.setOpaque(true); btnNewButton.setBackground(new Color(0x17748F)); btnNewButton.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut); JButton btnFragebogenSpeichern = new JButton("Fragebogen Speichern"); panel_1.add(btnFragebogenSpeichern); btnFragebogenSpeichern.setMargin(new Insets(0, 0, 0, 0)); btnFragebogenSpeichern.setPreferredSize(new Dimension(200, 50)); btnFragebogenSpeichern.setForeground(Color.WHITE); btnFragebogenSpeichern.setFont(new Font("Helvetica", Font.BOLD, 10)); btnFragebogenSpeichern.setBackground(new Color(0x17748F)); btnFragebogenSpeichern.setOpaque(true); btnFragebogenSpeichern.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut_1 = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut_1); JButton btnUmfrageStarten = new JButton("Umfrage Starten"); panel_1.add(btnUmfrageStarten); btnUmfrageStarten.setMargin(new Insets(0, 0, 0, 0)); btnUmfrageStarten.setPreferredSize(new Dimension(200, 50)); btnUmfrageStarten.setForeground(Color.WHITE); btnUmfrageStarten.setBackground(new Color(0x17748F)); btnUmfrageStarten.setOpaque(true); btnUmfrageStarten.setBorder(new LineBorder(new Color(0x17748F), 7)); btnUmfrageStarten.setFont(new Font("Helvetica", Font.BOLD, 10)); btnUmfrageStarten.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(FeebaCore.currentSurvey!=null){ EditorController.startSurvey();} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } }); btnFragebogenSpeichern.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { saveFileChoser(); } }); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { openFileChooser(); } }); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBorder(new LineBorder(Color.WHITE, 12)); tabbedPane.setBackground(null); ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource(); int index = sourceTabbedPane.getSelectedIndex(); if(index ==1) { if(FeebaCore.currentSurvey!=null){ EditorController.generateChart(results,questions.getSelectedIndex());} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } } }; tabbedPane.addChangeListener(changeListener); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel preview = new JPanel(); preview.setBorder(null); preview.setBackground(null); tabbedPane.addTab("Vorschau", null, preview, null); SpringLayout sl_preview = new SpringLayout(); preview.setLayout(sl_preview); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, layeredPane, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, layeredPane, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, layeredPane, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, layeredPane, 0, SpringLayout.EAST, preview); preview.add(layeredPane); SpringLayout sl_layeredPane = new SpringLayout(); layeredPane.setLayout(sl_layeredPane); JPanel panel_3 = new JPanel(); panel_3.setOpaque(false); sl_layeredPane.putConstraint(SpringLayout.NORTH, panel_3, 0, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.WEST, panel_3, 0, SpringLayout.WEST, layeredPane); sl_layeredPane.putConstraint(SpringLayout.SOUTH, panel_3, 444, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.EAST, panel_3, 0, SpringLayout.EAST, layeredPane); panel_3.setBackground(null); layeredPane.add(panel_3); SpringLayout sl_panel_3 = new SpringLayout(); panel_3.setLayout(sl_panel_3); final JLabel questionName = new JLabel(""); questionName.setFont(new Font("Helvetica", Font.PLAIN, 30)); questionName.setForeground(Color.WHITE); sl_panel_3.putConstraint(SpringLayout.NORTH, questionName, 103, SpringLayout.NORTH, panel_3); sl_panel_3.putConstraint(SpringLayout.WEST, questionName, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionName, 0, SpringLayout.EAST, panel_3); questionName.setHorizontalAlignment(SwingConstants.CENTER); questionName.setBackground(null); panel_3.add(questionName); final JLabel questionText = new JLabel(""); questionText.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionText, 100, SpringLayout.SOUTH, questionName); questionText.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionText.setForeground(Color.WHITE); questionText.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionText, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionText, 0, SpringLayout.EAST, panel_3); panel_3.add(questionText); final JLabel questionChoices = new JLabel(""); questionChoices.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionChoices, 80, SpringLayout.SOUTH, questionText); questionChoices.setFont(new Font("Lucida Grande", Font.PLAIN, 23)); questionChoices.setForeground(Color.WHITE); questionChoices.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionChoices, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionChoices, 0, SpringLayout.EAST, panel_3); panel_3.add(questionChoices); backgroundPreview = new JLabel(""); backgroundPreview.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, backgroundPreview, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, backgroundPreview, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, backgroundPreview, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, backgroundPreview, 0, SpringLayout.EAST, preview); preview.add(backgroundPreview); backgroundPreview.setAlignmentY(Component.TOP_ALIGNMENT); backgroundPreview.setIconTextGap(0); results = new JPanel(); results.setEnabled(false); results.setBackground(Color.WHITE); tabbedPane.addTab("Auswertung", null, results, null); GridBagLayout gbl_results = new GridBagLayout(); gbl_results.columnWidths = new int[]{0}; gbl_results.rowHeights = new int[]{0}; gbl_results.columnWeights = new double[]{Double.MIN_VALUE}; gbl_results.rowWeights = new double[]{Double.MIN_VALUE}; results.setLayout(gbl_results); questionWrapper = Box.createVerticalBox(); questionWrapper.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); questionWrapper.setAlignmentY(Component.TOP_ALIGNMENT); questionWrapper.setBorder(null); contentPane.add(questionWrapper, BorderLayout.WEST); questions = new JList(); questions.setMinimumSize(new Dimension(200, 2000)); questions.setMaximumSize(new Dimension(200, 200)); questions.setFont(new Font("Helvetica", Font.PLAIN, 15)); questions.setSelectionBackground(new Color(0x17748F)); questions.setBorder(null); questions.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int selectedIndex = questions.getSelectedIndex(); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); fillEditFields(selectedIndex,questionNameEdit,questionTextEdit,questionTypeEdit); EditorController.generateChart(results,selectedIndex); } }); Component verticalStrut = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut); questions.setPreferredSize(new Dimension(200, 10)); JScrollPane questionScroller = new JScrollPane(questions); questionScroller.setBorder(null); questionWrapper.add(questionScroller); JPanel panel = new JPanel(); panel.setOpaque(false); panel.setBorder(null); panel.setBackground(new Color(0x2D2F31)); panel.setMaximumSize(new Dimension(32767, 30)); panel.setPreferredSize(new Dimension(200, 30)); panel.setSize(new Dimension(200, 40)); questionWrapper.add(panel); JButton button = new JButton("+"); button.setForeground(Color.DARK_GRAY); button.setBackground(SystemColor.inactiveCaption); button.setFont(new Font("Helvetica", Font.PLAIN, 22)); button.setOpaque(true); button.setAlignmentY(Component.BOTTOM_ALIGNMENT); button.setMargin(new Insets(0, 0, 0, 0)); button.setPreferredSize(new Dimension(24, 24)); button.setBorder(null); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); SpringLayout sl_panel = new SpringLayout(); sl_panel.putConstraint(SpringLayout.NORTH, button, 3, SpringLayout.NORTH, panel); sl_panel.putConstraint(SpringLayout.EAST, button, -3, SpringLayout.EAST, panel); panel.setLayout(sl_panel); panel.add(button); JButton button_1 = new JButton("-"); button_1.setForeground(Color.DARK_GRAY); sl_panel.putConstraint(SpringLayout.EAST, button_1, -3, SpringLayout.WEST, button); button_1.setFont(new Font("Helvetica", Font.PLAIN, 25)); button_1.setOpaque(true); button_1.setBackground(SystemColor.inactiveCaptionBorder); sl_panel.putConstraint(SpringLayout.SOUTH, button_1, 0, SpringLayout.SOUTH, button); button_1.setPreferredSize(new Dimension(24, 24)); button_1.setMargin(new Insets(0, 0, 0, 0)); button_1.setBorder(null); button_1.setAlignmentY(1.0f); panel.add(button_1); Component verticalStrut_1 = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut_1); editPanel = new JPanel(); editPanel.setBorder(new LineBorder(Color.WHITE, 10)); editPanel.setBackground(Color.WHITE); editPanel.setPreferredSize(new Dimension(250, 10)); contentPane.add(editPanel, BorderLayout.EAST); SpringLayout sl_editPanel = new SpringLayout(); editPanel.setLayout(sl_editPanel); editPanel.setVisible(false); questionTypeEdit = new JComboBox(); sl_editPanel.putConstraint(SpringLayout.EAST, questionTypeEdit, -14, SpringLayout.EAST, editPanel); questionTypeEdit.setModel(new DefaultComboBoxModel(QuestionType.values())); questionTypeEdit.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { System.out.println("Change:" + e.paramString()); //EditorController.loadedSurvey.getQuestions().get(questions.getSelectedIndex()).changeQuestionType((QuestionType)questionTypeEdit.getSelectedItem()); toggleChoices(); } }); editPanel.add(questionTypeEdit); JLabel questionType = new JLabel("Fragetyp: "); questionType.setBorder(new LineBorder(UICOLOR, 7)); questionType.setForeground(Color.WHITE); questionType.setOpaque(true); questionType.setBackground(UICOLOR); questionType.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, questionType, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTypeEdit, 6, SpringLayout.SOUTH, questionType); sl_editPanel.putConstraint(SpringLayout.WEST, questionTypeEdit, 10, SpringLayout.WEST, questionType); sl_editPanel.putConstraint(SpringLayout.NORTH, questionType, 10, SpringLayout.NORTH, editPanel); editPanel.add(questionType); JLabel lblFrage = new JLabel("Name: "); sl_editPanel.putConstraint(SpringLayout.WEST, lblFrage, 0, SpringLayout.WEST, questionType); lblFrage.setOpaque(true); lblFrage.setBackground(UICOLOR); lblFrage.setBorder(new LineBorder(UICOLOR, 7)); lblFrage.setForeground(Color.WHITE); lblFrage.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.NORTH, lblFrage, 10, SpringLayout.SOUTH, questionTypeEdit); editPanel.add(lblFrage); questionNameEdit = new JTextField(); sl_editPanel.putConstraint(SpringLayout.NORTH, questionNameEdit, 10, SpringLayout.SOUTH, lblFrage); sl_editPanel.putConstraint(SpringLayout.WEST, questionNameEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionNameEdit, 0, SpringLayout.EAST, questionTypeEdit); questionNameEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setName(questionNameEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionNameEdit.setForeground(Color.WHITE); questionNameEdit.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionNameEdit.setBackground(Color.LIGHT_GRAY); questionNameEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 7)); editPanel.add(questionNameEdit); questionNameEdit.setColumns(10); JLabel choicesLbl = new JLabel("Frage: "); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesLbl, 10, SpringLayout.SOUTH, questionNameEdit); choicesLbl.setOpaque(true); choicesLbl.setBackground(UICOLOR); choicesLbl.setBorder(new LineBorder(UICOLOR, 7)); choicesLbl.setForeground(Color.WHITE); choicesLbl.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, choicesLbl, 10, SpringLayout.WEST, editPanel); editPanel.add(choicesLbl); choicesEdit = new JPanel(); sl_editPanel.putConstraint(SpringLayout.WEST, choicesEdit, 0, SpringLayout.WEST, questionNameEdit); choicesEdit.setBackground(Color.WHITE); editPanel.add(choicesEdit); GridBagLayout gbl_choicesEdit = new GridBagLayout(); gbl_choicesEdit.columnWidths = new int[] {40, 150, 0}; gbl_choicesEdit.rowHeights = new int[] {20, 20, 20, 20, 20, 20, 20, 20, 20}; gbl_choicesEdit.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_choicesEdit.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; choicesEdit.setLayout(gbl_choicesEdit); JLabel lblA = new JLabel("A : "); lblA.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblA = new GridBagConstraints(); gbc_lblA.insets = new Insets(0, 0, 5, 5); gbc_lblA.anchor = GridBagConstraints.WEST; gbc_lblA.gridx = 0; gbc_lblA.gridy = 0; choicesEdit.add(lblA, gbc_lblA); textField_5 = new JTextField(); textField_5.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_5.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_5.setBackground(Color.LIGHT_GRAY); textField_5.setForeground(Color.WHITE); textField_5.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_5 = new GridBagConstraints(); gbc_textField_5.fill = GridBagConstraints.BOTH; gbc_textField_5.insets = new Insets(0, 0, 5, 0); gbc_textField_5.gridx = 1; gbc_textField_5.gridy = 0; choicesEdit.add(textField_5, gbc_textField_5); textField_5.setColumns(8); JLabel lblB = new JLabel("B : "); lblB.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblB = new GridBagConstraints(); gbc_lblB.fill = GridBagConstraints.BOTH; gbc_lblB.insets = new Insets(0, 0, 5, 5); gbc_lblB.gridx = 0; gbc_lblB.gridy = 1; choicesEdit.add(lblB, gbc_lblB); textField_8 = new JTextField(); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setForeground(Color.WHITE); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_8.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_8 = new GridBagConstraints(); gbc_textField_8.fill = GridBagConstraints.BOTH; gbc_textField_8.insets = new Insets(0, 0, 5, 0); gbc_textField_8.gridx = 1; gbc_textField_8.gridy = 1; choicesEdit.add(textField_8, gbc_textField_8); textField_8.setColumns(8); JLabel lblC = new JLabel("C : "); lblC.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblC = new GridBagConstraints(); gbc_lblC.fill = GridBagConstraints.BOTH; gbc_lblC.insets = new Insets(0, 0, 5, 5); gbc_lblC.gridx = 0; gbc_lblC.gridy = 2; choicesEdit.add(lblC, gbc_lblC); textField_7 = new JTextField(); GridBagConstraints gbc_textField_7 = new GridBagConstraints(); textField_7.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_7.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_7.setBackground(Color.LIGHT_GRAY); textField_7.setForeground(Color.WHITE); gbc_textField_7.fill = GridBagConstraints.BOTH; gbc_textField_7.insets = new Insets(0, 0, 5, 0); gbc_textField_7.gridx = 1; gbc_textField_7.gridy = 2; choicesEdit.add(textField_7, gbc_textField_7); textField_7.setColumns(8); JLabel lblD = new JLabel("D : "); lblD.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblD = new GridBagConstraints(); gbc_lblD.fill = GridBagConstraints.BOTH; gbc_lblD.insets = new Insets(0, 0, 5, 5); gbc_lblD.gridx = 0; gbc_lblD.gridy = 3; choicesEdit.add(lblD, gbc_lblD); textField_6 = new JTextField(); GridBagConstraints gbc_textField_6 = new GridBagConstraints(); textField_6.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_6.setForeground(Color.WHITE); textField_6.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_6.setBackground(Color.LIGHT_GRAY); gbc_textField_6.fill = GridBagConstraints.BOTH; gbc_textField_6.insets = new Insets(0, 0, 5, 0); gbc_textField_6.gridx = 1; gbc_textField_6.gridy = 3; choicesEdit.add(textField_6, gbc_textField_6); textField_6.setColumns(10); JLabel lblE = new JLabel("E : "); lblE.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblE = new GridBagConstraints(); gbc_lblE.fill = GridBagConstraints.BOTH; gbc_lblE.insets = new Insets(0, 0, 5, 5); gbc_lblE.gridx = 0; gbc_lblE.gridy = 4; choicesEdit.add(lblE, gbc_lblE); textField_4 = new JTextField(); GridBagConstraints gbc_textField_4 = new GridBagConstraints(); textField_4.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_4.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_4.setBackground(Color.LIGHT_GRAY); textField_4.setForeground(Color.WHITE); gbc_textField_4.fill = GridBagConstraints.BOTH; gbc_textField_4.insets = new Insets(0, 0, 5, 0); gbc_textField_4.gridx = 1; gbc_textField_4.gridy = 4; choicesEdit.add(textField_4, gbc_textField_4); textField_4.setColumns(10); JLabel lblF = new JLabel("F : "); lblF.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblF = new GridBagConstraints(); gbc_lblF.anchor = GridBagConstraints.WEST; gbc_lblF.fill = GridBagConstraints.BOTH; gbc_lblF.insets = new Insets(0, 0, 5, 5); gbc_lblF.gridx = 0; gbc_lblF.gridy = 5; choicesEdit.add(lblF, gbc_lblF); textField_3 = new JTextField(); GridBagConstraints gbc_textField_3 = new GridBagConstraints(); textField_3.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_3.setForeground(Color.WHITE); textField_3.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_3.setBackground(Color.LIGHT_GRAY); gbc_textField_3.fill = GridBagConstraints.BOTH; gbc_textField_3.insets = new Insets(0, 0, 5, 0); gbc_textField_3.gridx = 1; gbc_textField_3.gridy = 5; choicesEdit.add(textField_3, gbc_textField_3); textField_3.setColumns(10); JLabel lblG = new JLabel("G : "); lblG.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblG = new GridBagConstraints(); gbc_lblG.fill = GridBagConstraints.BOTH; gbc_lblG.insets = new Insets(0, 0, 5, 5); gbc_lblG.gridx = 0; gbc_lblG.gridy = 6; choicesEdit.add(lblG, gbc_lblG); textField_1 = new JTextField(); GridBagConstraints gbc_textField_1 = new GridBagConstraints(); textField_1.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_1.setForeground(Color.WHITE); textField_1.setBackground(Color.LIGHT_GRAY); textField_1.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_1.fill = GridBagConstraints.BOTH; gbc_textField_1.insets = new Insets(0, 0, 5, 0); gbc_textField_1.gridx = 1; gbc_textField_1.gridy = 6; choicesEdit.add(textField_1, gbc_textField_1); textField_1.setColumns(10); JLabel lblH = new JLabel("H : "); lblH.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblH = new GridBagConstraints(); gbc_lblH.fill = GridBagConstraints.BOTH; gbc_lblH.insets = new Insets(0, 0, 5, 5); gbc_lblH.gridx = 0; gbc_lblH.gridy = 7; choicesEdit.add(lblH, gbc_lblH); textField_2 = new JTextField(); GridBagConstraints gbc_textField_2 = new GridBagConstraints(); textField_2.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_2.setBackground(Color.LIGHT_GRAY); textField_2.setForeground(Color.WHITE); textField_2.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_2.fill = GridBagConstraints.BOTH; gbc_textField_2.insets = new Insets(0, 0, 5, 0); gbc_textField_2.gridx = 1; gbc_textField_2.gridy = 7; choicesEdit.add(textField_2, gbc_textField_2); textField_2.setColumns(10); JLabel lblI = new JLabel("I : "); lblI.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblI = new GridBagConstraints(); gbc_lblI.anchor = GridBagConstraints.WEST; gbc_lblI.fill = GridBagConstraints.VERTICAL; gbc_lblI.insets = new Insets(0, 0, 0, 5); gbc_lblI.gridx = 0; gbc_lblI.gridy = 8; choicesEdit.add(lblI, gbc_lblI); lblAntwortmglichkeit = new JLabel("Antwortm\u00F6glichkeiten: "); lblAntwortmglichkeit.setOpaque(true); lblAntwortmglichkeit.setBackground(UICOLOR); lblAntwortmglichkeit.setBorder(new LineBorder(UICOLOR, 7)); lblAntwortmglichkeit.setForeground(Color.WHITE); lblAntwortmglichkeit.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, lblAntwortmglichkeit, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesEdit, 14, SpringLayout.SOUTH, lblAntwortmglichkeit); textField_9 = new JTextField(); GridBagConstraints gbc_textField_9 = new GridBagConstraints(); gbc_textField_9.fill = GridBagConstraints.BOTH; textField_9.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_9.setBackground(Color.LIGHT_GRAY); textField_9.setForeground(Color.WHITE); textField_9.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_9.insets = new Insets(0, 0, 5, 0); gbc_textField_9.gridx = 1; gbc_textField_9.gridy = 8; choicesEdit.add(textField_9, gbc_textField_9); textField_9.setColumns(10); editPanel.add(lblAntwortmglichkeit); questionTextEdit = new JTextArea(); sl_editPanel.putConstraint(SpringLayout.NORTH, lblAntwortmglichkeit, 10, SpringLayout.SOUTH, questionTextEdit); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTextEdit, 10, SpringLayout.SOUTH, choicesLbl); sl_editPanel.putConstraint(SpringLayout.WEST, questionTextEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionTextEdit, 0, SpringLayout.EAST, questionTypeEdit); questionTextEdit.setLineWrap(true); questionTextEdit.setWrapStyleWord(true); sl_editPanel.putConstraint(SpringLayout.EAST, choicesEdit, 0, SpringLayout.EAST, questionTextEdit); questionTextEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setQuestionText(questionTextEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionTextEdit.setForeground(Color.WHITE); questionTextEdit.setFont(new Font("Helvetica", Font.PLAIN, 16)); questionTextEdit.setBackground(Color.LIGHT_GRAY); questionTextEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 6)); questionTextEdit.setRows(3); editPanel.add(questionTextEdit); JPanel panel_2 = new JPanel(); panel_2.setOpaque(false); panel_2.setPreferredSize(new Dimension(250, 10)); contentPane.add(panel_2, BorderLayout.EAST); SpringLayout sl_panel_2 = new SpringLayout(); panel_2.setLayout(sl_panel_2); comboBox = new JComboBox(); sl_panel_2.putConstraint(SpringLayout.WEST, comboBox, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, comboBox, -52, SpringLayout.EAST, panel_2); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Kuchendiagramm", "Balkendiagramm", "Radardiagramm"})); comboBox.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { EditorController.generateChart(results, questions.getSelectedIndex());} }); panel_2.add(comboBox); JLabel lblDiagrammtyp = new JLabel("Diagrammtyp: "); sl_panel_2.putConstraint(SpringLayout.NORTH, comboBox, 50, SpringLayout.NORTH, lblDiagrammtyp); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammtyp, 50, SpringLayout.NORTH, panel_2); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammtyp, 0, SpringLayout.WEST, comboBox); lblDiagrammtyp.setOpaque(true); lblDiagrammtyp.setForeground(Color.WHITE); lblDiagrammtyp.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammtyp.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammtyp.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammtyp); JButton btnNewButton_1 = new JButton("Daten zur\u00FCcksetzen"); btnNewButton_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.resetResults(questions.getSelectedIndex()); EditorController.generateChart(results, questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnNewButton_1, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, btnNewButton_1, 240, SpringLayout.WEST, panel_2); panel_2.add(btnNewButton_1); JLabel lblDiagrammaktionen = new JLabel("Diagrammaktionen: "); sl_panel_2.putConstraint(SpringLayout.NORTH, btnNewButton_1, 50, SpringLayout.NORTH, lblDiagrammaktionen); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammaktionen, 50, SpringLayout.NORTH, comboBox); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammaktionen, 0, SpringLayout.WEST, comboBox); lblDiagrammaktionen.setOpaque(true); lblDiagrammaktionen.setForeground(Color.WHITE); lblDiagrammaktionen.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammaktionen.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammaktionen.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammaktionen); JButton btnDiagrammAlsBild = new JButton("Diagramm als Bild speichern..."); sl_panel_2.putConstraint(SpringLayout.NORTH, btnDiagrammAlsBild, 40, SpringLayout.NORTH, btnNewButton_1); btnDiagrammAlsBild.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.saveChartImage((JLabel) results.getComponents()[0], questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnDiagrammAlsBild, 0, SpringLayout.WEST, comboBox); panel_2.add(btnDiagrammAlsBild); }
public EditorGUI() { setTitle("Feeba"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 821, 544); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(null); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel toolBar = new JPanel(); toolBar.setBackground(new Color(0x222325)); toolBar.setAlignmentY(Component.CENTER_ALIGNMENT); toolBar.setPreferredSize(new Dimension(16, 50)); contentPane.add(toolBar, BorderLayout.NORTH); SpringLayout sl_toolBar = new SpringLayout(); toolBar.setLayout(sl_toolBar); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(EditorGUI.class.getResource("/images/logo_toolbar.png"))); toolBar.add(lblNewLabel); JPanel panel_1 = new JPanel(); sl_toolBar.putConstraint(SpringLayout.WEST, panel_1, 50, SpringLayout.EAST, lblNewLabel); sl_toolBar.putConstraint(SpringLayout.NORTH, panel_1, 0, SpringLayout.NORTH, toolBar); panel_1.setOpaque(false); toolBar.add(panel_1); JButton btnNewButton = new JButton("Fragebogen Laden"); panel_1.add(btnNewButton); btnNewButton.setAlignmentX(Component.CENTER_ALIGNMENT); btnNewButton.setHorizontalTextPosition(SwingConstants.LEADING); btnNewButton.setAlignmentY(Component.TOP_ALIGNMENT); btnNewButton.setMargin(new Insets(0, 0, 0, 0)); btnNewButton.setPreferredSize(new Dimension(200, 50)); btnNewButton.setForeground(Color.WHITE); btnNewButton.setFont(new Font("Helvetica", Font.BOLD, 10)); btnNewButton.setOpaque(true); btnNewButton.setBackground(new Color(0x17748F)); btnNewButton.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut); JButton btnFragebogenSpeichern = new JButton("Fragebogen Speichern"); panel_1.add(btnFragebogenSpeichern); btnFragebogenSpeichern.setMargin(new Insets(0, 0, 0, 0)); btnFragebogenSpeichern.setPreferredSize(new Dimension(200, 50)); btnFragebogenSpeichern.setForeground(Color.WHITE); btnFragebogenSpeichern.setFont(new Font("Helvetica", Font.BOLD, 10)); btnFragebogenSpeichern.setBackground(new Color(0x17748F)); btnFragebogenSpeichern.setOpaque(true); btnFragebogenSpeichern.setBorder(new LineBorder(new Color(0x17748F), 7)); Component horizontalStrut_1 = Box.createHorizontalStrut(1); panel_1.add(horizontalStrut_1); JButton btnUmfrageStarten = new JButton("Umfrage Starten"); panel_1.add(btnUmfrageStarten); btnUmfrageStarten.setMargin(new Insets(0, 0, 0, 0)); btnUmfrageStarten.setPreferredSize(new Dimension(200, 50)); btnUmfrageStarten.setForeground(Color.WHITE); btnUmfrageStarten.setBackground(new Color(0x17748F)); btnUmfrageStarten.setOpaque(true); btnUmfrageStarten.setBorder(new LineBorder(new Color(0x17748F), 7)); btnUmfrageStarten.setFont(new Font("Helvetica", Font.BOLD, 10)); btnUmfrageStarten.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(FeebaCore.currentSurvey!=null){ EditorController.startSurvey();} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } }); btnFragebogenSpeichern.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { saveFileChoser(); } }); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { openFileChooser(); } }); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBorder(new LineBorder(Color.WHITE, 12)); tabbedPane.setBackground(null); ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource(); int index = sourceTabbedPane.getSelectedIndex(); if(index ==1) { if(FeebaCore.currentSurvey!=null){ EditorController.generateChart(results,questions.getSelectedIndex());} else {JOptionPane.showMessageDialog(null, "Noch kein Fragebogen geladen!");} } } }; tabbedPane.addChangeListener(changeListener); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel preview = new JPanel(); preview.setBorder(null); preview.setBackground(null); tabbedPane.addTab("Vorschau", null, preview, null); SpringLayout sl_preview = new SpringLayout(); preview.setLayout(sl_preview); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, layeredPane, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, layeredPane, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, layeredPane, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, layeredPane, 0, SpringLayout.EAST, preview); preview.add(layeredPane); SpringLayout sl_layeredPane = new SpringLayout(); layeredPane.setLayout(sl_layeredPane); JPanel panel_3 = new JPanel(); panel_3.setOpaque(false); sl_layeredPane.putConstraint(SpringLayout.NORTH, panel_3, 0, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.WEST, panel_3, 0, SpringLayout.WEST, layeredPane); sl_layeredPane.putConstraint(SpringLayout.SOUTH, panel_3, 444, SpringLayout.NORTH, layeredPane); sl_layeredPane.putConstraint(SpringLayout.EAST, panel_3, 0, SpringLayout.EAST, layeredPane); panel_3.setBackground(null); layeredPane.add(panel_3); SpringLayout sl_panel_3 = new SpringLayout(); panel_3.setLayout(sl_panel_3); final JLabel questionName = new JLabel(""); questionName.setFont(new Font("Helvetica", Font.PLAIN, 30)); questionName.setForeground(Color.WHITE); sl_panel_3.putConstraint(SpringLayout.NORTH, questionName, 103, SpringLayout.NORTH, panel_3); sl_panel_3.putConstraint(SpringLayout.WEST, questionName, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionName, 0, SpringLayout.EAST, panel_3); questionName.setHorizontalAlignment(SwingConstants.CENTER); questionName.setBackground(null); panel_3.add(questionName); final JLabel questionText = new JLabel(""); questionText.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionText, 100, SpringLayout.SOUTH, questionName); questionText.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionText.setForeground(Color.WHITE); questionText.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionText, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionText, 0, SpringLayout.EAST, panel_3); panel_3.add(questionText); final JLabel questionChoices = new JLabel(""); questionChoices.setBackground(null); sl_panel_3.putConstraint(SpringLayout.SOUTH, questionChoices, 80, SpringLayout.SOUTH, questionText); questionChoices.setFont(new Font("Lucida Grande", Font.PLAIN, 23)); questionChoices.setForeground(Color.WHITE); questionChoices.setHorizontalAlignment(SwingConstants.CENTER); sl_panel_3.putConstraint(SpringLayout.WEST, questionChoices, 0, SpringLayout.WEST, panel_3); sl_panel_3.putConstraint(SpringLayout.EAST, questionChoices, 0, SpringLayout.EAST, panel_3); panel_3.add(questionChoices); backgroundPreview = new JLabel(""); backgroundPreview.setBackground(null); sl_preview.putConstraint(SpringLayout.NORTH, backgroundPreview, 0, SpringLayout.NORTH, preview); sl_preview.putConstraint(SpringLayout.WEST, backgroundPreview, 0, SpringLayout.WEST, preview); sl_preview.putConstraint(SpringLayout.SOUTH, backgroundPreview, 0, SpringLayout.SOUTH, preview); sl_preview.putConstraint(SpringLayout.EAST, backgroundPreview, 0, SpringLayout.EAST, preview); preview.add(backgroundPreview); backgroundPreview.setAlignmentY(Component.TOP_ALIGNMENT); backgroundPreview.setIconTextGap(0); results = new JPanel(); results.setEnabled(false); results.setBackground(Color.WHITE); tabbedPane.addTab("Auswertung", null, results, null); GridBagLayout gbl_results = new GridBagLayout(); gbl_results.columnWidths = new int[]{0}; gbl_results.rowHeights = new int[]{0}; gbl_results.columnWeights = new double[]{Double.MIN_VALUE}; gbl_results.rowWeights = new double[]{Double.MIN_VALUE}; results.setLayout(gbl_results); questionWrapper = Box.createVerticalBox(); questionWrapper.setPreferredSize(new Dimension(200, 200)); questionWrapper.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); questionWrapper.setAlignmentY(Component.TOP_ALIGNMENT); questionWrapper.setBorder(null); contentPane.add(questionWrapper, BorderLayout.WEST); questions = new JList(); questions.setMinimumSize(new Dimension(200, 200)); questions.setMaximumSize(new Dimension(200, 200)); questions.setFont(new Font("Helvetica", Font.PLAIN, 15)); questions.setSelectionBackground(new Color(0x17748F)); questions.setBorder(null); questions.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int selectedIndex = questions.getSelectedIndex(); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); fillEditFields(selectedIndex,questionNameEdit,questionTextEdit,questionTypeEdit); EditorController.generateChart(results,selectedIndex); } }); Component verticalStrut = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut); questions.setPreferredSize(new Dimension(200, 10)); JScrollPane questionScroller = new JScrollPane(questions); questionScroller.setBorder(null); questionWrapper.add(questionScroller); JPanel panel = new JPanel(); panel.setOpaque(false); panel.setBorder(null); panel.setBackground(new Color(0x2D2F31)); panel.setMaximumSize(new Dimension(32767, 30)); panel.setPreferredSize(new Dimension(200, 30)); panel.setSize(new Dimension(200, 40)); questionWrapper.add(panel); JButton button = new JButton("+"); button.setForeground(Color.DARK_GRAY); button.setBackground(SystemColor.inactiveCaption); button.setFont(new Font("Helvetica", Font.PLAIN, 22)); button.setOpaque(true); button.setAlignmentY(Component.BOTTOM_ALIGNMENT); button.setMargin(new Insets(0, 0, 0, 0)); button.setPreferredSize(new Dimension(24, 24)); button.setBorder(null); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); SpringLayout sl_panel = new SpringLayout(); sl_panel.putConstraint(SpringLayout.NORTH, button, 3, SpringLayout.NORTH, panel); sl_panel.putConstraint(SpringLayout.EAST, button, -3, SpringLayout.EAST, panel); panel.setLayout(sl_panel); panel.add(button); JButton button_1 = new JButton("-"); button_1.setForeground(Color.DARK_GRAY); sl_panel.putConstraint(SpringLayout.EAST, button_1, -3, SpringLayout.WEST, button); button_1.setFont(new Font("Helvetica", Font.PLAIN, 25)); button_1.setOpaque(true); button_1.setBackground(SystemColor.inactiveCaptionBorder); sl_panel.putConstraint(SpringLayout.SOUTH, button_1, 0, SpringLayout.SOUTH, button); button_1.setPreferredSize(new Dimension(24, 24)); button_1.setMargin(new Insets(0, 0, 0, 0)); button_1.setBorder(null); button_1.setAlignmentY(1.0f); panel.add(button_1); Component verticalStrut_1 = Box.createVerticalStrut(20); questionWrapper.add(verticalStrut_1); editPanel = new JPanel(); editPanel.setBorder(new LineBorder(Color.WHITE, 10)); editPanel.setBackground(Color.WHITE); editPanel.setPreferredSize(new Dimension(250, 10)); contentPane.add(editPanel, BorderLayout.EAST); SpringLayout sl_editPanel = new SpringLayout(); editPanel.setLayout(sl_editPanel); editPanel.setVisible(false); questionTypeEdit = new JComboBox(); sl_editPanel.putConstraint(SpringLayout.EAST, questionTypeEdit, -14, SpringLayout.EAST, editPanel); questionTypeEdit.setModel(new DefaultComboBoxModel(QuestionType.values())); questionTypeEdit.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { System.out.println("Change:" + e.paramString()); //EditorController.loadedSurvey.getQuestions().get(questions.getSelectedIndex()).changeQuestionType((QuestionType)questionTypeEdit.getSelectedItem()); toggleChoices(); } }); editPanel.add(questionTypeEdit); JLabel questionType = new JLabel("Fragetyp: "); questionType.setBorder(new LineBorder(UICOLOR, 7)); questionType.setForeground(Color.WHITE); questionType.setOpaque(true); questionType.setBackground(UICOLOR); questionType.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, questionType, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTypeEdit, 6, SpringLayout.SOUTH, questionType); sl_editPanel.putConstraint(SpringLayout.WEST, questionTypeEdit, 10, SpringLayout.WEST, questionType); sl_editPanel.putConstraint(SpringLayout.NORTH, questionType, 10, SpringLayout.NORTH, editPanel); editPanel.add(questionType); JLabel lblFrage = new JLabel("Name: "); sl_editPanel.putConstraint(SpringLayout.WEST, lblFrage, 0, SpringLayout.WEST, questionType); lblFrage.setOpaque(true); lblFrage.setBackground(UICOLOR); lblFrage.setBorder(new LineBorder(UICOLOR, 7)); lblFrage.setForeground(Color.WHITE); lblFrage.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.NORTH, lblFrage, 10, SpringLayout.SOUTH, questionTypeEdit); editPanel.add(lblFrage); questionNameEdit = new JTextField(); sl_editPanel.putConstraint(SpringLayout.NORTH, questionNameEdit, 10, SpringLayout.SOUTH, lblFrage); sl_editPanel.putConstraint(SpringLayout.WEST, questionNameEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionNameEdit, 0, SpringLayout.EAST, questionTypeEdit); questionNameEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setName(questionNameEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionNameEdit.setForeground(Color.WHITE); questionNameEdit.setFont(new Font("Helvetica", Font.PLAIN, 20)); questionNameEdit.setBackground(Color.LIGHT_GRAY); questionNameEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 7)); editPanel.add(questionNameEdit); questionNameEdit.setColumns(10); JLabel choicesLbl = new JLabel("Frage: "); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesLbl, 10, SpringLayout.SOUTH, questionNameEdit); choicesLbl.setOpaque(true); choicesLbl.setBackground(UICOLOR); choicesLbl.setBorder(new LineBorder(UICOLOR, 7)); choicesLbl.setForeground(Color.WHITE); choicesLbl.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, choicesLbl, 10, SpringLayout.WEST, editPanel); editPanel.add(choicesLbl); choicesEdit = new JPanel(); sl_editPanel.putConstraint(SpringLayout.WEST, choicesEdit, 0, SpringLayout.WEST, questionNameEdit); choicesEdit.setBackground(Color.WHITE); editPanel.add(choicesEdit); GridBagLayout gbl_choicesEdit = new GridBagLayout(); gbl_choicesEdit.columnWidths = new int[] {40, 150, 0}; gbl_choicesEdit.rowHeights = new int[] {20, 20, 20, 20, 20, 20, 20, 20, 20}; gbl_choicesEdit.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_choicesEdit.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; choicesEdit.setLayout(gbl_choicesEdit); JLabel lblA = new JLabel("A : "); lblA.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblA = new GridBagConstraints(); gbc_lblA.insets = new Insets(0, 0, 5, 5); gbc_lblA.anchor = GridBagConstraints.WEST; gbc_lblA.gridx = 0; gbc_lblA.gridy = 0; choicesEdit.add(lblA, gbc_lblA); textField_5 = new JTextField(); textField_5.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_5.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_5.setBackground(Color.LIGHT_GRAY); textField_5.setForeground(Color.WHITE); textField_5.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_5 = new GridBagConstraints(); gbc_textField_5.fill = GridBagConstraints.BOTH; gbc_textField_5.insets = new Insets(0, 0, 5, 0); gbc_textField_5.gridx = 1; gbc_textField_5.gridy = 0; choicesEdit.add(textField_5, gbc_textField_5); textField_5.setColumns(8); JLabel lblB = new JLabel("B : "); lblB.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblB = new GridBagConstraints(); gbc_lblB.fill = GridBagConstraints.BOTH; gbc_lblB.insets = new Insets(0, 0, 5, 5); gbc_lblB.gridx = 0; gbc_lblB.gridy = 1; choicesEdit.add(lblB, gbc_lblB); textField_8 = new JTextField(); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setForeground(Color.WHITE); textField_8.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_8.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_8.setBackground(Color.LIGHT_GRAY); GridBagConstraints gbc_textField_8 = new GridBagConstraints(); gbc_textField_8.fill = GridBagConstraints.BOTH; gbc_textField_8.insets = new Insets(0, 0, 5, 0); gbc_textField_8.gridx = 1; gbc_textField_8.gridy = 1; choicesEdit.add(textField_8, gbc_textField_8); textField_8.setColumns(8); JLabel lblC = new JLabel("C : "); lblC.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblC = new GridBagConstraints(); gbc_lblC.fill = GridBagConstraints.BOTH; gbc_lblC.insets = new Insets(0, 0, 5, 5); gbc_lblC.gridx = 0; gbc_lblC.gridy = 2; choicesEdit.add(lblC, gbc_lblC); textField_7 = new JTextField(); GridBagConstraints gbc_textField_7 = new GridBagConstraints(); textField_7.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_7.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_7.setBackground(Color.LIGHT_GRAY); textField_7.setForeground(Color.WHITE); gbc_textField_7.fill = GridBagConstraints.BOTH; gbc_textField_7.insets = new Insets(0, 0, 5, 0); gbc_textField_7.gridx = 1; gbc_textField_7.gridy = 2; choicesEdit.add(textField_7, gbc_textField_7); textField_7.setColumns(8); JLabel lblD = new JLabel("D : "); lblD.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblD = new GridBagConstraints(); gbc_lblD.fill = GridBagConstraints.BOTH; gbc_lblD.insets = new Insets(0, 0, 5, 5); gbc_lblD.gridx = 0; gbc_lblD.gridy = 3; choicesEdit.add(lblD, gbc_lblD); textField_6 = new JTextField(); GridBagConstraints gbc_textField_6 = new GridBagConstraints(); textField_6.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_6.setForeground(Color.WHITE); textField_6.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_6.setBackground(Color.LIGHT_GRAY); gbc_textField_6.fill = GridBagConstraints.BOTH; gbc_textField_6.insets = new Insets(0, 0, 5, 0); gbc_textField_6.gridx = 1; gbc_textField_6.gridy = 3; choicesEdit.add(textField_6, gbc_textField_6); textField_6.setColumns(10); JLabel lblE = new JLabel("E : "); lblE.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblE = new GridBagConstraints(); gbc_lblE.fill = GridBagConstraints.BOTH; gbc_lblE.insets = new Insets(0, 0, 5, 5); gbc_lblE.gridx = 0; gbc_lblE.gridy = 4; choicesEdit.add(lblE, gbc_lblE); textField_4 = new JTextField(); GridBagConstraints gbc_textField_4 = new GridBagConstraints(); textField_4.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_4.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_4.setBackground(Color.LIGHT_GRAY); textField_4.setForeground(Color.WHITE); gbc_textField_4.fill = GridBagConstraints.BOTH; gbc_textField_4.insets = new Insets(0, 0, 5, 0); gbc_textField_4.gridx = 1; gbc_textField_4.gridy = 4; choicesEdit.add(textField_4, gbc_textField_4); textField_4.setColumns(10); JLabel lblF = new JLabel("F : "); lblF.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblF = new GridBagConstraints(); gbc_lblF.anchor = GridBagConstraints.WEST; gbc_lblF.fill = GridBagConstraints.BOTH; gbc_lblF.insets = new Insets(0, 0, 5, 5); gbc_lblF.gridx = 0; gbc_lblF.gridy = 5; choicesEdit.add(lblF, gbc_lblF); textField_3 = new JTextField(); GridBagConstraints gbc_textField_3 = new GridBagConstraints(); textField_3.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_3.setForeground(Color.WHITE); textField_3.setBorder(new LineBorder(new Color(192, 192, 192), 4)); textField_3.setBackground(Color.LIGHT_GRAY); gbc_textField_3.fill = GridBagConstraints.BOTH; gbc_textField_3.insets = new Insets(0, 0, 5, 0); gbc_textField_3.gridx = 1; gbc_textField_3.gridy = 5; choicesEdit.add(textField_3, gbc_textField_3); textField_3.setColumns(10); JLabel lblG = new JLabel("G : "); lblG.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblG = new GridBagConstraints(); gbc_lblG.fill = GridBagConstraints.BOTH; gbc_lblG.insets = new Insets(0, 0, 5, 5); gbc_lblG.gridx = 0; gbc_lblG.gridy = 6; choicesEdit.add(lblG, gbc_lblG); textField_1 = new JTextField(); GridBagConstraints gbc_textField_1 = new GridBagConstraints(); textField_1.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_1.setForeground(Color.WHITE); textField_1.setBackground(Color.LIGHT_GRAY); textField_1.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_1.fill = GridBagConstraints.BOTH; gbc_textField_1.insets = new Insets(0, 0, 5, 0); gbc_textField_1.gridx = 1; gbc_textField_1.gridy = 6; choicesEdit.add(textField_1, gbc_textField_1); textField_1.setColumns(10); JLabel lblH = new JLabel("H : "); lblH.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblH = new GridBagConstraints(); gbc_lblH.fill = GridBagConstraints.BOTH; gbc_lblH.insets = new Insets(0, 0, 5, 5); gbc_lblH.gridx = 0; gbc_lblH.gridy = 7; choicesEdit.add(lblH, gbc_lblH); textField_2 = new JTextField(); GridBagConstraints gbc_textField_2 = new GridBagConstraints(); textField_2.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_2.setBackground(Color.LIGHT_GRAY); textField_2.setForeground(Color.WHITE); textField_2.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_2.fill = GridBagConstraints.BOTH; gbc_textField_2.insets = new Insets(0, 0, 5, 0); gbc_textField_2.gridx = 1; gbc_textField_2.gridy = 7; choicesEdit.add(textField_2, gbc_textField_2); textField_2.setColumns(10); JLabel lblI = new JLabel("I : "); lblI.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_lblI = new GridBagConstraints(); gbc_lblI.anchor = GridBagConstraints.WEST; gbc_lblI.fill = GridBagConstraints.VERTICAL; gbc_lblI.insets = new Insets(0, 0, 0, 5); gbc_lblI.gridx = 0; gbc_lblI.gridy = 8; choicesEdit.add(lblI, gbc_lblI); lblAntwortmglichkeit = new JLabel("Antwortm\u00F6glichkeiten: "); lblAntwortmglichkeit.setOpaque(true); lblAntwortmglichkeit.setBackground(UICOLOR); lblAntwortmglichkeit.setBorder(new LineBorder(UICOLOR, 7)); lblAntwortmglichkeit.setForeground(Color.WHITE); lblAntwortmglichkeit.setFont(new Font("Helvetica", Font.PLAIN, 15)); sl_editPanel.putConstraint(SpringLayout.WEST, lblAntwortmglichkeit, 10, SpringLayout.WEST, editPanel); sl_editPanel.putConstraint(SpringLayout.NORTH, choicesEdit, 14, SpringLayout.SOUTH, lblAntwortmglichkeit); textField_9 = new JTextField(); GridBagConstraints gbc_textField_9 = new GridBagConstraints(); gbc_textField_9.fill = GridBagConstraints.BOTH; textField_9.setFont(new Font("Helvetica", Font.PLAIN, 20)); textField_9.setBackground(Color.LIGHT_GRAY); textField_9.setForeground(Color.WHITE); textField_9.setBorder(new LineBorder(new Color(192, 192, 192), 4)); gbc_textField_9.insets = new Insets(0, 0, 5, 0); gbc_textField_9.gridx = 1; gbc_textField_9.gridy = 8; choicesEdit.add(textField_9, gbc_textField_9); textField_9.setColumns(10); editPanel.add(lblAntwortmglichkeit); questionTextEdit = new JTextArea(); sl_editPanel.putConstraint(SpringLayout.NORTH, lblAntwortmglichkeit, 10, SpringLayout.SOUTH, questionTextEdit); sl_editPanel.putConstraint(SpringLayout.NORTH, questionTextEdit, 10, SpringLayout.SOUTH, choicesLbl); sl_editPanel.putConstraint(SpringLayout.WEST, questionTextEdit, 0, SpringLayout.WEST, questionTypeEdit); sl_editPanel.putConstraint(SpringLayout.EAST, questionTextEdit, 0, SpringLayout.EAST, questionTypeEdit); questionTextEdit.setLineWrap(true); questionTextEdit.setWrapStyleWord(true); sl_editPanel.putConstraint(SpringLayout.EAST, choicesEdit, 0, SpringLayout.EAST, questionTextEdit); questionTextEdit.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent arg0) { int selectedIndex = questions.getSelectedIndex(); FeebaCore.currentSurvey.getQuestions().get(selectedIndex).setQuestionText(questionTextEdit.getText().toString()); fillPreviewFields(selectedIndex,questionName,questionText,questionChoices); } }); questionTextEdit.setForeground(Color.WHITE); questionTextEdit.setFont(new Font("Helvetica", Font.PLAIN, 16)); questionTextEdit.setBackground(Color.LIGHT_GRAY); questionTextEdit.setBorder(new LineBorder(Color.LIGHT_GRAY, 6)); questionTextEdit.setRows(3); editPanel.add(questionTextEdit); JPanel panel_2 = new JPanel(); panel_2.setOpaque(false); panel_2.setPreferredSize(new Dimension(250, 10)); contentPane.add(panel_2, BorderLayout.EAST); SpringLayout sl_panel_2 = new SpringLayout(); panel_2.setLayout(sl_panel_2); comboBox = new JComboBox(); sl_panel_2.putConstraint(SpringLayout.WEST, comboBox, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, comboBox, -52, SpringLayout.EAST, panel_2); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Kuchendiagramm", "Balkendiagramm", "Radardiagramm"})); comboBox.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { EditorController.generateChart(results, questions.getSelectedIndex());} }); panel_2.add(comboBox); JLabel lblDiagrammtyp = new JLabel("Diagrammtyp: "); sl_panel_2.putConstraint(SpringLayout.NORTH, comboBox, 50, SpringLayout.NORTH, lblDiagrammtyp); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammtyp, 50, SpringLayout.NORTH, panel_2); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammtyp, 0, SpringLayout.WEST, comboBox); lblDiagrammtyp.setOpaque(true); lblDiagrammtyp.setForeground(Color.WHITE); lblDiagrammtyp.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammtyp.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammtyp.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammtyp); JButton btnNewButton_1 = new JButton("Daten zur\u00FCcksetzen"); btnNewButton_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.resetResults(questions.getSelectedIndex()); EditorController.generateChart(results, questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnNewButton_1, 10, SpringLayout.WEST, panel_2); sl_panel_2.putConstraint(SpringLayout.EAST, btnNewButton_1, 240, SpringLayout.WEST, panel_2); panel_2.add(btnNewButton_1); JLabel lblDiagrammaktionen = new JLabel("Diagrammaktionen: "); sl_panel_2.putConstraint(SpringLayout.NORTH, btnNewButton_1, 50, SpringLayout.NORTH, lblDiagrammaktionen); sl_panel_2.putConstraint(SpringLayout.NORTH, lblDiagrammaktionen, 50, SpringLayout.NORTH, comboBox); sl_panel_2.putConstraint(SpringLayout.WEST, lblDiagrammaktionen, 0, SpringLayout.WEST, comboBox); lblDiagrammaktionen.setOpaque(true); lblDiagrammaktionen.setForeground(Color.WHITE); lblDiagrammaktionen.setFont(new Font("Helvetica", Font.PLAIN, 15)); lblDiagrammaktionen.setBorder(new LineBorder(UICOLOR, 7)); lblDiagrammaktionen.setBackground(new Color(23, 116, 143)); panel_2.add(lblDiagrammaktionen); JButton btnDiagrammAlsBild = new JButton("Diagramm als Bild speichern..."); sl_panel_2.putConstraint(SpringLayout.NORTH, btnDiagrammAlsBild, 40, SpringLayout.NORTH, btnNewButton_1); btnDiagrammAlsBild.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { EditorController.saveChartImage((JLabel) results.getComponents()[0], questions.getSelectedIndex()); } }); sl_panel_2.putConstraint(SpringLayout.WEST, btnDiagrammAlsBild, 0, SpringLayout.WEST, comboBox); panel_2.add(btnDiagrammAlsBild); }
diff --git a/loginshard/src/main/java/gwlpr/loginshard/LoginShardChannelInitializer.java b/loginshard/src/main/java/gwlpr/loginshard/LoginShardChannelInitializer.java index afa0199..a764425 100644 --- a/loginshard/src/main/java/gwlpr/loginshard/LoginShardChannelInitializer.java +++ b/loginshard/src/main/java/gwlpr/loginshard/LoginShardChannelInitializer.java @@ -1,39 +1,39 @@ /** * For copyright information see the LICENSE document. */ package gwlpr.loginshard; import gwlpr.protocol.NettyGWLoggingHandler; import gwlpr.protocol.NettyGWLoggingHandler.*; import gwlpr.protocol.handshake.HandshakeHandler; import gwlpr.protocol.loginserver.LoginServerCodec; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.logging.LoggingHandler; import java.util.ArrayList; import realityshard.container.network.ConnectionStateHandler; import realityshard.container.network.MessageDemuxDecoder; /** * Initializes a login shard channel... duh * * @author _rusty */ public class LoginShardChannelInitializer extends ChannelInitializer<Channel> { @Override protected void initChannel(Channel ch) { // inbound handlers ch.pipeline().addLast( + new LoggingHandler(), new ConnectionStateHandler(), HandshakeHandler.produceLoginHandshake(), new LoginServerCodec(), - new MessageDemuxDecoder(), - new LoggingHandler()); + new MessageDemuxDecoder()); } }
false
true
protected void initChannel(Channel ch) { // inbound handlers ch.pipeline().addLast( new ConnectionStateHandler(), HandshakeHandler.produceLoginHandshake(), new LoginServerCodec(), new MessageDemuxDecoder(), new LoggingHandler()); }
protected void initChannel(Channel ch) { // inbound handlers ch.pipeline().addLast( new LoggingHandler(), new ConnectionStateHandler(), HandshakeHandler.produceLoginHandshake(), new LoginServerCodec(), new MessageDemuxDecoder()); }
diff --git a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java index b95b3b5..a0c2818 100644 --- a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java +++ b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java @@ -1,661 +1,666 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.csstudio.swt.xygraph.linearscale; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Tick factory produces the different axis ticks. When specifying a format and * given the screen size parameters and range it will return a list of Ticks */ public class TickFactory { public enum TickFormatting { /** * Automatically adjust precision */ autoMode, /** * Rounded or chopped to the nearest decimal */ roundAndChopMode, /** * Use Exponent */ useExponent, /** * Use SI units (k,M,G,etc.) */ useSIunits, /** * Use external scale provider */ useCustom; } private TickFormatting formatOfTicks; private final static BigDecimal EPSILON = new BigDecimal("1.0E-20"); private static final int DIGITS_UPPER_LIMIT = 6; // limit for number of digits to display left of decimal point private static final int DIGITS_LOWER_LIMIT = -6; // limit for number of zeros to display right of decimal point private static final double ROUND_FRACTION = 2e-6; // fraction of denominator to round to private static final BigDecimal BREL_ERROR = new BigDecimal("1e-15"); private static final double REL_ERROR = BREL_ERROR.doubleValue(); private double graphMin; private double graphMax; private String tickFormat; private IScaleProvider scale; private int intervals; // number of intervals private boolean isReversed; /** * @param format */ public TickFactory(IScaleProvider scale) { this(TickFormatting.useCustom, scale); } /** * @param format */ public TickFactory(TickFormatting format, IScaleProvider scale) { formatOfTicks = format; this.scale = scale; } private String getTickString(double value) { if (scale!=null) value = scale.getLabel(value); String returnString = ""; if (Double.isNaN(value)) return returnString; switch (formatOfTicks) { case autoMode: returnString = String.format(tickFormat, value); break; case useExponent: returnString = String.format(tickFormat, value); break; case roundAndChopMode: returnString = String.format("%d", Math.round(value)); break; case useSIunits: double absValue = Math.abs(value); if (absValue == 0.0) { returnString = String.format("%6.2f", value); } else if (absValue <= 1E-15) { returnString = String.format("%6.2ff", value * 1E15); } else if (absValue <= 1E-12) { returnString = String.format("%6.2fp", value * 1E12); } else if (absValue <= 1E-9) { returnString = String.format("%6.2fn", value * 1E9); } else if (absValue <= 1E-6) { returnString = String.format("%6.2fµ", value * 1E6); } else if (absValue <= 1E-3) { returnString = String.format("%6.2fm", value * 1E3); } else if (absValue < 1E3) { returnString = String.format("%6.2f", value); } else if (absValue < 1E6) { returnString = String.format("%6.2fk", value * 1E-3); } else if (absValue < 1E9) { returnString = String.format("%6.2fM", value * 1E-6); } else if (absValue < 1E12) { returnString = String.format("%6.2fG", value * 1E-9); } else if (absValue < 1E15) { returnString = String.format("%6.2fT", value * 1E-12); } else if (absValue < 1E18) returnString = String.format("%6.2fP", value * 1E-15); break; case useCustom: returnString = scale.format(value); break; } return returnString; } private void createFormatString(final int precision, final boolean b) { switch (formatOfTicks) { case autoMode: tickFormat = b ? String.format("%%.%de", precision) : String.format("%%.%df", precision); break; case useExponent: tickFormat = String.format("%%.%de", precision); break; default: tickFormat = null; break; } } /** * Round numerator down to multiples of denominators * @param n numerator * @param d denominator * @return */ protected static double roundDown(BigDecimal n, BigDecimal d) { final int ns = n.signum(); if (ns == 0) return 0; final int ds = d.signum(); if (ds == 0) throw new IllegalArgumentException("Zero denominator is not allowed"); n = n.abs(); d = d.abs(); final BigDecimal[] x = n.divideAndRemainder(d); double rx = x[1].doubleValue(); if (rx > (1-ROUND_FRACTION)*d.doubleValue()) { // trim up if close to denominator x[1] = BigDecimal.ZERO; x[0] = x[0].add(BigDecimal.ONE); } else if (rx < ROUND_FRACTION*d.doubleValue()) { x[1] = BigDecimal.ZERO; } final int xs = x[1].signum(); if (xs == 0) { return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue(); } else if (xs < 0) { throw new IllegalStateException("Cannot happen!"); } if (ns != ds) return x[0].signum() == 0 ? -d.doubleValue() : -x[0].add(BigDecimal.ONE).multiply(d).doubleValue(); return x[0].multiply(d).doubleValue(); } /** * Round numerator up to multiples of denominators * @param n numerator * @param d denominator * @return */ protected static double roundUp(BigDecimal n, BigDecimal d) { final int ns = n.signum(); if (ns == 0) return 0; final int ds = d.signum(); if (ds == 0) throw new IllegalArgumentException("Zero denominator is not allowed"); n = n.abs(); d = d.abs(); final BigDecimal[] x = n.divideAndRemainder(d); double rx = x[1].doubleValue(); if (rx != 0) { if (rx < ROUND_FRACTION*d.doubleValue()) { // trim down if close to zero x[1] = BigDecimal.ZERO; } else if (rx > (1-ROUND_FRACTION)*d.doubleValue()) { x[1] = BigDecimal.ZERO; x[0] = x[0].add(BigDecimal.ONE); } } final int xs = x[1].signum(); if (xs == 0) { return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue(); } else if (xs < 0) { throw new IllegalStateException("Cannot happen!"); } if (ns != ds) return x[0].signum() == 0 ? 0 : -x[0].multiply(d).doubleValue(); return x[0].add(BigDecimal.ONE).multiply(d).doubleValue(); } /** * @param x * @return floor of log 10 */ private static int log10(BigDecimal x) { int c = x.compareTo(BigDecimal.ONE); int e = 0; while (c < 0) { e--; x = x.scaleByPowerOfTen(1); c = x.compareTo(BigDecimal.ONE); } c = x.compareTo(BigDecimal.TEN); while (c >= 0) { e++; x = x.scaleByPowerOfTen(-1); c = x.compareTo(BigDecimal.TEN); } return e; } /** * @param x * @param round if true, then round else take ceiling * @return a nice number */ protected static BigDecimal nicenum(BigDecimal x, boolean round) { int expv; /* exponent of x */ double f; /* fractional part of x */ double nf; /* nice, rounded number */ BigDecimal bf; expv = log10(x); bf = x.scaleByPowerOfTen(-expv); f = bf.doubleValue(); /* between 1 and 10 */ if (round) { if (f < 1.5) nf = 1; else if (f < 2.25) nf = 2; else if (f < 3.25) nf = 2.5; else if (f < 7.5) nf = 5; else nf = 10; } else if (f <= 1.) nf = 1; else if (f <= 2.) nf = 2; else if (f <= 5.) nf = 5; else nf = 10; return BigDecimal.valueOf(BigDecimal.valueOf(nf).scaleByPowerOfTen(expv).doubleValue()); } private double determineNumTicks(double min, double max, int maxTicks, boolean allowMinMaxOver) { BigDecimal bMin = BigDecimal.valueOf(min); BigDecimal bMax = BigDecimal.valueOf(max); BigDecimal bRange = bMax.subtract(bMin); if (bRange.signum() < 0) { BigDecimal bt = bMin; bMin = bMax; bMax = bt; bRange = bRange.negate(); isReversed = true; } else { isReversed = false; } BigDecimal magnitude = BigDecimal.valueOf(Math.max(Math.abs(min), Math.abs(max))); // tick points too dense to do anything if (bRange.compareTo(EPSILON.multiply(magnitude)) < 0) { return 0; } bRange = nicenum(bRange, false); BigDecimal bUnit; int nTicks = maxTicks - 1; if (Math.signum(min)*Math.signum(max) < 0) { // straddle case nTicks++; } do { long n; do { // ensure number of ticks is less or equal to number requested bUnit = nicenum(BigDecimal.valueOf(bRange.doubleValue() / nTicks), true); n = bRange.divideToIntegralValue(bUnit).longValue(); } while (n > maxTicks && --nTicks > 0); if (allowMinMaxOver) { graphMin = roundDown(bMin, bUnit); if (graphMin == 0) // ensure positive zero graphMin = 0; graphMax = roundUp(bMax, bUnit); if (graphMax == 0) graphMax = 0; } else { if (isReversed) { graphMin = max; graphMax = min; } else { graphMin = min; graphMax = max; } } if (bUnit.compareTo(BREL_ERROR.multiply(magnitude)) <= 0) { intervals = -1; // signal that we hit the limit of precision } else { intervals = (int) Math.round((graphMax - graphMin) / bUnit.doubleValue()); } } while (intervals > maxTicks && --nTicks > 0); if (isReversed) { double t = graphMin; graphMin = graphMax; graphMax = t; } double tickUnit = isReversed ? -bUnit.doubleValue() : bUnit.doubleValue(); /** * We get the labelled max and min for determining the precision which * the ticks should be shown at. */ int d = bUnit.scale() == bUnit.precision() ? -bUnit.scale() : bUnit.precision() - bUnit.scale() - 1; int p = (int) Math.max(Math.floor(Math.log10(Math.abs(graphMin))), Math.floor(Math.log10(Math.abs(graphMax)))); // System.err.println("P: " + bUnit.precision() + ", S: " + // bUnit.scale() + " => " + d + ", " + p); if (p <= DIGITS_LOWER_LIMIT || p >= DIGITS_UPPER_LIMIT) { createFormatString(Math.max(p - d, 0), true); } else { createFormatString(Math.max(-d, 0), false); } return tickUnit; } private boolean inRange(double x, double min, double max) { if (isReversed) { return x >= max && x <= min; } return x >= min && x <= max; } /** * Generate a list of ticks that span range given by min and max. The maximum number of * ticks is exceed by one in the case where the range straddles zero. * @param min * @param max * @param maxTicks * @param allowMinMaxOver allow min/maximum overwrite * @param tight if true then remove ticks outside range * @return a list of the ticks for the axis */ public List<Tick> generateTicks(double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumTicks(min, max, maxTicks, allowMinMaxOver); if (tickUnit == 0) return ticks; for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; if (Math.abs(p/tickUnit) < REL_ERROR) p = 0; // ensure positive zero boolean r = inRange(p, min, max); if (!tight || r) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } } int imax = ticks.size(); if (imax > 1) { if (!tight && allowMinMaxOver) { Tick t = ticks.get(imax - 1); if (!isReversed && t.getValue() < max) { // last is >= max t.setValue(graphMax); t.setText(getTickString(graphMax)); } } } else if (maxTicks > 1) { if (imax == 0) { imax++; Tick newTick = new Tick(); newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); if (isReversed) { newTick.setPosition(1); } else { newTick.setPosition(0); } ticks.add(newTick); } if (imax == 1) { Tick t = ticks.get(0); Tick newTick = new Tick(); if (t.getText().equals(getTickString(graphMax))) { newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); ticks.add(0, newTick); } else { newTick.setValue(graphMax); newTick.setText(getTickString(graphMax)); ticks.add(newTick); } imax++; } } double lo = tight ? min : ticks.get(0).getValue(); double hi = tight ? max : (imax > 1 ? ticks.get(imax - 1).getValue() : lo); double range = imax > 1 ? hi - lo : 1; if (isReversed) { for (Tick t : ticks) { t.setPosition(1 - (t.getValue() - lo) / range); } } else { for (Tick t : ticks) { t.setPosition((t.getValue() - lo) / range); } } return ticks; } private static final DecimalFormat CUSTOM_FORMAT = new DecimalFormat("#####0.000"); private static final DecimalFormat INDEX_FORMAT = new DecimalFormat("0"); /** * Generate a list of ticks that span range given by min and max. * @param min * @param max * @param maxTicks * @param tight if true then remove ticks outside range * @return a list of the ticks for the axis */ public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) { isReversed = min > max; if (isReversed) { double t = max; max = min; min = t; } List<Tick> ticks = new ArrayList<Tick>(); double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue(); - double tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange/(maxTicks - 1)), true).doubleValue()); - tickUnit = Math.floor(tickUnit); // make integer - graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit); - graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit); - intervals = (int) Math.floor((graphMax - graphMin) / tickUnit); + double tickUnit = 1; + intervals = 0; + int it = maxTicks - 1; + while (intervals < 1) { + tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange / it++), true).doubleValue()); + tickUnit = Math.floor(tickUnit); // make integer + graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit); + graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit); + intervals = (int) Math.floor((graphMax - graphMin) / tickUnit); + } switch (formatOfTicks) { case autoMode: tickFormat = "%g"; break; case useExponent: tickFormat = "%e"; break; default: tickFormat = null; break; } for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } int imax = ticks.size(); double range = imax > 1 ? max - min : 1; for (Tick t : ticks) { t.setPosition((t.getValue() - min) / range); } if (isReversed) { Collections.reverse(ticks); } if (formatOfTicks == TickFormatting.autoMode) { // override labels if (scale.areLabelCustomised()) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; boolean allInts = true; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (Double.isNaN(v)) continue; if (allInts) { allInts = Math.abs(v - Math.floor(v)) == 0; } v = Math.abs(v); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } if (allInts) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(INDEX_FORMAT.format(v)); } } else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(CUSTOM_FORMAT.format(v)); } } } else { for (Tick t : ticks) { t.setText(INDEX_FORMAT.format(t.getValue())); } } } return ticks; } private double determineNumLogTicks(double min, double max, int maxTicks, boolean allowMinMaxOver) { final boolean isReverse = min > max; final int loDecade; // lowest decade (or power of ten) final int hiDecade; if (isReverse) { loDecade = (int) Math.floor(Math.log10(max)); hiDecade = (int) Math.ceil(Math.log10(min)); } else { loDecade = (int) Math.floor(Math.log10(min)); hiDecade = (int) Math.ceil(Math.log10(max)); } int decades = hiDecade - loDecade; int unit = 0; int n; do { n = decades/++unit; } while (n > maxTicks); double tickUnit = isReverse ? Math.pow(10, -unit) : Math.pow(10, unit); if (allowMinMaxOver) { graphMin = Math.pow(10, loDecade); graphMax = Math.pow(10, hiDecade); } else { graphMin = min; graphMax = max; } if (isReverse) { double t = graphMin; graphMin = graphMax; graphMax = t; } createFormatString((int) Math.max(-Math.floor(loDecade), 0), false); return tickUnit; } /** * @param min * @param max * @param maxTicks * @param allowMinMaxOver allow min/maximum overwrite * @param tight if true then remove ticks outside range * @return a list of the ticks for the axis */ public List<Tick> generateLogTicks(double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumLogTicks(min, max, maxTicks, allowMinMaxOver); double p = graphMin; if (tickUnit > 1) { final double pmax = graphMax * Math.sqrt(tickUnit); while (p < pmax) { if (!tight || (p >= min && p <= max)) if (allowMinMaxOver || p <= max) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } double newTickValue = p * tickUnit; if (p == newTickValue) break; p = newTickValue; } final int imax = ticks.size(); if (imax == 1) { ticks.get(0).setPosition(0.5); } else if (imax > 1) { double lo = Math.log(tight ? min : ticks.get(0).getValue()); double hi = Math.log(tight ? max : ticks.get(imax - 1).getValue()); double range = hi - lo; for (Tick t : ticks) { t.setPosition((Math.log(t.getValue()) - lo) / range); } } } else { final double pmin = graphMax * Math.sqrt(tickUnit); while (p > pmin) { if (!tight || (p >= max && p <= min)) if (allowMinMaxOver || p <= max) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); } double newTickValue = p * tickUnit; if (p == newTickValue) break; p = newTickValue; } final int imax = ticks.size(); if (imax == 1) { ticks.get(0).setPosition(0.5); } else if (imax > 1) { double lo = Math.log(tight ? max : ticks.get(0).getValue()); double hi = Math.log(tight ? min : ticks.get(imax - 1).getValue()); double range = hi - lo; for (Tick t : ticks) { t.setPosition(1 - (Math.log(t.getValue()) - lo) / range); } } } return ticks; } }
true
true
public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) { isReversed = min > max; if (isReversed) { double t = max; max = min; min = t; } List<Tick> ticks = new ArrayList<Tick>(); double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue(); double tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange/(maxTicks - 1)), true).doubleValue()); tickUnit = Math.floor(tickUnit); // make integer graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit); graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit); intervals = (int) Math.floor((graphMax - graphMin) / tickUnit); switch (formatOfTicks) { case autoMode: tickFormat = "%g"; break; case useExponent: tickFormat = "%e"; break; default: tickFormat = null; break; } for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } int imax = ticks.size(); double range = imax > 1 ? max - min : 1; for (Tick t : ticks) { t.setPosition((t.getValue() - min) / range); } if (isReversed) { Collections.reverse(ticks); } if (formatOfTicks == TickFormatting.autoMode) { // override labels if (scale.areLabelCustomised()) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; boolean allInts = true; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (Double.isNaN(v)) continue; if (allInts) { allInts = Math.abs(v - Math.floor(v)) == 0; } v = Math.abs(v); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } if (allInts) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(INDEX_FORMAT.format(v)); } } else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(CUSTOM_FORMAT.format(v)); } } } else { for (Tick t : ticks) { t.setText(INDEX_FORMAT.format(t.getValue())); } } } return ticks; }
public List<Tick> generateIndexBasedTicks(double min, double max, int maxTicks, boolean tight) { isReversed = min > max; if (isReversed) { double t = max; max = min; min = t; } List<Tick> ticks = new ArrayList<Tick>(); double gRange = nicenum(BigDecimal.valueOf(max - min), false).doubleValue(); double tickUnit = 1; intervals = 0; int it = maxTicks - 1; while (intervals < 1) { tickUnit = Math.max(1, nicenum(BigDecimal.valueOf(gRange / it++), true).doubleValue()); tickUnit = Math.floor(tickUnit); // make integer graphMin = Math.ceil(Math.ceil(min / tickUnit) * tickUnit); graphMax = Math.floor(Math.floor(max / tickUnit) * tickUnit); intervals = (int) Math.floor((graphMax - graphMin) / tickUnit); } switch (formatOfTicks) { case autoMode: tickFormat = "%g"; break; case useExponent: tickFormat = "%e"; break; default: tickFormat = null; break; } for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } int imax = ticks.size(); double range = imax > 1 ? max - min : 1; for (Tick t : ticks) { t.setPosition((t.getValue() - min) / range); } if (isReversed) { Collections.reverse(ticks); } if (formatOfTicks == TickFormatting.autoMode) { // override labels if (scale.areLabelCustomised()) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; boolean allInts = true; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (Double.isNaN(v)) continue; if (allInts) { allInts = Math.abs(v - Math.floor(v)) == 0; } v = Math.abs(v); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } if (allInts) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(INDEX_FORMAT.format(v)); } } else if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) { for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); if (!Double.isNaN(v)) t.setText(CUSTOM_FORMAT.format(v)); } } } else { for (Tick t : ticks) { t.setText(INDEX_FORMAT.format(t.getValue())); } } } return ticks; }
diff --git a/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java b/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java index 048ae33a..b68d4433 100644 --- a/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java +++ b/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java @@ -1,508 +1,513 @@ /* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.utilities.install; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; public class InstallOptions { public static final String INSTALL_TYPE = "install.type"; public static final String FEDORA_HOME = "fedora.home"; public static final String FEDORA_SERVERHOST = "fedora.serverHost"; public static final String FEDORA_APP_SERVER_CONTEXT = "fedora.serverContext"; public static final String APIA_AUTH_REQUIRED = "apia.auth.required"; public static final String UPSTREAM_AUTH_ENABLED = "upstream.auth.enabled"; public static final String SSL_AVAILABLE = "ssl.available"; public static final String APIA_SSL_REQUIRED = "apia.ssl.required"; public static final String APIM_SSL_REQUIRED = "apim.ssl.required"; public static final String SERVLET_ENGINE = "servlet.engine"; public static final String TOMCAT_HOME = "tomcat.home"; public static final String FEDORA_ADMIN_PASS = "fedora.admin.pass"; public static final String TOMCAT_SHUTDOWN_PORT = "tomcat.shutdown.port"; public static final String TOMCAT_HTTP_PORT = "tomcat.http.port"; public static final String TOMCAT_SSL_PORT = "tomcat.ssl.port"; public static final String KEYSTORE_FILE = "keystore.file"; public static final String KEYSTORE_PASSWORD = "keystore.password"; public static final String KEYSTORE_TYPE = "keystore.type"; public static final String DATABASE = "database"; public static final String DATABASE_DRIVER = "database.driver"; public static final String DATABASE_JDBCURL = "database.jdbcURL"; public static final String DATABASE_DRIVERCLASS = "database.jdbcDriverClass"; public static final String EMBEDDED_DATABASE_DRIVERCLASSNAME = "org.apache.derby.jdbc.EmbeddedDriver"; public static final String DATABASE_USERNAME = "database.username"; public static final String DATABASE_PASSWORD = "database.password"; public static final String XACML_ENABLED = "xacml.enabled"; public static final String FESL_AUTHN_ENABLED = "fesl.authn.enabled"; public static final String FESL_AUTHZ_ENABLED = "fesl.authz.enabled"; public static final String LLSTORE_TYPE = "llstore.type"; public static final String RI_ENABLED = "ri.enabled"; public static final String MESSAGING_ENABLED = "messaging.enabled"; public static final String MESSAGING_URI = "messaging.uri"; public static final String DEPLOY_LOCAL_SERVICES = "deploy.local.services"; public static final String TEST_SPRING_CONFIGS = "test.spring.configs"; public static final String UNATTENDED = "unattended"; public static final String DATABASE_UPDATE = "database.update"; public static final String DEFAULT = "default"; public static final String INSTALL_QUICK = "quick"; public static final String INSTALL_CLIENT = "client"; public static final String INCLUDED = "included"; public static final String DERBY = "derby"; public static final String MYSQL = "mysql"; public static final String ORACLE = "oracle"; public static final String POSTGRESQL = "postgresql"; public static final String OTHER = "other"; public static final String EXISTING_TOMCAT = "existingTomcat"; private final Map<String, String> _map; private final Distribution _dist; /** * Initialize options from the given map of String values, keyed by option * id. */ public InstallOptions(Distribution dist, Map<String, String> map) throws OptionValidationException { _dist = dist; _map = map; applyDefaults(); validateAll(); } /** * Initialize options interactively, via input from the console. */ public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<String, String>(); System.out.println(); System.out.println("***********************"); System.out.println(" Fedora Installation "); System.out.println("***********************"); checkJavaVersion(); System.out.println(); System.out.println("To install Fedora, please answer the following questions."); System.out.println("Enter CANCEL at any time to abort the installation."); System.out.println("Detailed installation instructions are available online:\n"); System.out.println(" https://wiki.duraspace.org/display/FEDORA/All+Documentation\n"); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); if (getValue(INSTALL_TYPE).equals(INSTALL_CLIENT)) { return; } inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)) .getAbsolutePath(); String includedJDBCURL = "jdbc:derby:" + fedoraHome + File.separator + "derby/fedora3;create=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(FEDORA_APP_SERVER_CONTEXT, null); _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 _map.put(DATABASE, INCLUDED); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); _map.put(XACML_ENABLED, Boolean.toString(false)); + _map.put(UPSTREAM_AUTH_ENABLED, Boolean.toString(false)); _map.put(FESL_AUTHN_ENABLED, Boolean.toString(true)); _map.put(FESL_AUTHZ_ENABLED, Boolean.toString(false)); _map.put(LLSTORE_TYPE, null); // akubra-fs _map.put(RI_ENABLED, null); // false _map.put(MESSAGING_ENABLED, null); // false _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(FEDORA_APP_SERVER_CONTEXT); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); if (!getValue(KEYSTORE_FILE).equals(INCLUDED)) { inputOption(KEYSTORE_PASSWORD); inputOption(KEYSTORE_TYPE); } } } } // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if (getValue(DATABASE).equals(INCLUDED)) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(UPSTREAM_AUTH_ENABLED); + if (getBooleanValue(UPSTREAM_AUTH_ENABLED,false)) { + // disable FESL authN if upstream authN is enabled + _map.put(FESL_AUTHN_ENABLED, Boolean.toString(false)); + } inputOption(FESL_AUTHZ_ENABLED); if (getValue(FESL_AUTHZ_ENABLED).equals(Boolean.toString(true))) { // Disable legacy authz if FeSL is enabled _map.put(XACML_ENABLED, Boolean.toString(false)); } else { inputOption(XACML_ENABLED); } inputOption(LLSTORE_TYPE); inputOption(RI_ENABLED); inputOption(MESSAGING_ENABLED); if (getValue(MESSAGING_ENABLED).equals(Boolean.toString(true))) { inputOption(MESSAGING_URI); } inputOption(DEPLOY_LOCAL_SERVICES); } private static void checkJavaVersion() throws InstallationCancelledException { String v = System.getProperty("java.version"); if (v.startsWith("1.3") || v.startsWith("1.4") || v.startsWith("1.5")) { System.err.println("ERROR: Java " + v + " is too old; This version" + " of Fedora requires Java 1.6 or above."); throw new InstallationCancelledException(); } } private String dashes(int len) { StringBuffer out = new StringBuffer(); for (int i = 0; i < len; i++) { out.append('-'); } return out.toString(); } /** * Get the indicated option from the console. Continue prompting until the * value is valid, or the user has indicated they want to cancel the * installation. */ private void inputOption(String optionId) throws InstallationCancelledException { OptionDefinition opt = OptionDefinition.get(optionId, this); if (opt.getLabel() == null || opt.getLabel().length() == 0) { throw new InstallationCancelledException(optionId + " is missing label (check OptionDefinition.properties?)"); } System.out.println(opt.getLabel()); System.out.println(dashes(opt.getLabel().length())); System.out.println(opt.getDescription()); System.out.println(); String[] valids = opt.getValidValues(); if (valids != null) { System.out.print("Options : "); for (int i = 0; i < valids.length; i++) { if (i > 0) { System.out.print(", "); } System.out.print(valids[i]); } System.out.println(); } String defaultVal = opt.getDefaultValue(); if (valids != null || defaultVal != null) { System.out.println(); } boolean gotValidValue = false; while (!gotValidValue) { System.out.print("Enter a value "); if (defaultVal != null) { System.out.print("[default is " + defaultVal + "] "); } System.out.print("==> "); String value = readLine().trim(); if (value.length() == 0 && defaultVal != null) { value = defaultVal; } System.out.println(); if (value.equalsIgnoreCase("cancel")) { throw new InstallationCancelledException("Cancelled by user."); } try { opt.validateValue(value); gotValidValue = true; _map.put(optionId, value); System.out.println(); } catch (OptionValidationException e) { System.out.println("Error: " + e.getMessage()); } } } private String readLine() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); return reader.readLine(); } catch (Exception e) { throw new RuntimeException("Error: Unable to read from STDIN"); } } /** * Dump all options (including any defaults that were applied) to the given * stream, in java properties file format. The output stream remains open * after this method returns. */ public void dump(OutputStream out) throws IOException { Properties props = new Properties(); Iterator<String> iter = _map.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); props.setProperty(key, getValue(key)); } props.store(out, "Install Options"); } /** * Get the value of the given option, or <code>null</code> if it doesn't * exist. */ public String getValue(String name) { return System.getProperty(name, _map.get(name)); } public String getValue(String name, String defaultVal) { String value = getValue(name); if (value == null) { return defaultVal; } else { return value; } } /** * Get the value of the given option as an integer, or the given default * value if unspecified. * * @throws NumberFormatException * if the value is specified, but cannot be parsed as an integer. */ public int getIntValue(String name, int defaultValue) throws NumberFormatException { String value = getValue(name); if (value == null) { return defaultValue; } else { return Integer.parseInt(value); } } /** * Get the value of the given option as a boolean, or the given default * value if unspecified. If specified, the value is assumed to be * <code>true</code> if given as "true", regardless of case. All other * values are assumed to be <code>false</code>. */ public boolean getBooleanValue(String name, boolean defaultValue) { String value = getValue(name); if (value == null) { return defaultValue; } else { return value.equals("true"); } } /** * Get an iterator of the names of all specified options. */ public Collection<String> getOptionNames() { return _map.keySet(); } /** * Apply defaults to the options, where possible. */ private void applyDefaults() { for (String name : getOptionNames()) { String val = _map.get(name); if (val == null || val.length() == 0) { OptionDefinition opt = OptionDefinition.get(name, this); _map.put(name, opt.getDefaultValue()); } } } /** * Validate the options, assuming defaults have already been applied. * Validation for a given option might entail more than a syntax check. It * might check whether a given directory exists, for example. * */ private void validateAll() throws OptionValidationException { boolean unattended = getBooleanValue(UNATTENDED, false); for (String optionId : getOptionNames()) { OptionDefinition opt = OptionDefinition.get(optionId, this); if (opt == null) { throw new OptionValidationException("Option is not defined", optionId); } opt.validateValue(getValue(optionId), unattended); } } private boolean validateDatabaseConnection() { String database = getValue(DATABASE); if (database.equals(InstallOptions.INCLUDED)) { return true; } Database db = new Database(_dist, this); try { // validate the user input by attempting a database connection System.out.print("Validating database connection..."); db.test(); // check if we need to update old table if (db.usesDOTable()) { inputOption(DATABASE_UPDATE); } db.close(); System.out.println("OK\n"); return true; } catch (Exception e) { System.out.println("FAILED\n"); e.printStackTrace(); System.out.println(e.getClass().getName() + ": " + e.getMessage() + "\n"); System.out.println("ERROR validating database connection; see above.\n"); return false; } } }
false
true
public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<String, String>(); System.out.println(); System.out.println("***********************"); System.out.println(" Fedora Installation "); System.out.println("***********************"); checkJavaVersion(); System.out.println(); System.out.println("To install Fedora, please answer the following questions."); System.out.println("Enter CANCEL at any time to abort the installation."); System.out.println("Detailed installation instructions are available online:\n"); System.out.println(" https://wiki.duraspace.org/display/FEDORA/All+Documentation\n"); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); if (getValue(INSTALL_TYPE).equals(INSTALL_CLIENT)) { return; } inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)) .getAbsolutePath(); String includedJDBCURL = "jdbc:derby:" + fedoraHome + File.separator + "derby/fedora3;create=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(FEDORA_APP_SERVER_CONTEXT, null); _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 _map.put(DATABASE, INCLUDED); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); _map.put(XACML_ENABLED, Boolean.toString(false)); _map.put(FESL_AUTHN_ENABLED, Boolean.toString(true)); _map.put(FESL_AUTHZ_ENABLED, Boolean.toString(false)); _map.put(LLSTORE_TYPE, null); // akubra-fs _map.put(RI_ENABLED, null); // false _map.put(MESSAGING_ENABLED, null); // false _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(FEDORA_APP_SERVER_CONTEXT); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); if (!getValue(KEYSTORE_FILE).equals(INCLUDED)) { inputOption(KEYSTORE_PASSWORD); inputOption(KEYSTORE_TYPE); } } } } // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if (getValue(DATABASE).equals(INCLUDED)) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(UPSTREAM_AUTH_ENABLED); inputOption(FESL_AUTHZ_ENABLED); if (getValue(FESL_AUTHZ_ENABLED).equals(Boolean.toString(true))) { // Disable legacy authz if FeSL is enabled _map.put(XACML_ENABLED, Boolean.toString(false)); } else { inputOption(XACML_ENABLED); } inputOption(LLSTORE_TYPE); inputOption(RI_ENABLED); inputOption(MESSAGING_ENABLED); if (getValue(MESSAGING_ENABLED).equals(Boolean.toString(true))) { inputOption(MESSAGING_URI); } inputOption(DEPLOY_LOCAL_SERVICES); }
public InstallOptions(Distribution dist) throws InstallationCancelledException { _dist = dist; _map = new HashMap<String, String>(); System.out.println(); System.out.println("***********************"); System.out.println(" Fedora Installation "); System.out.println("***********************"); checkJavaVersion(); System.out.println(); System.out.println("To install Fedora, please answer the following questions."); System.out.println("Enter CANCEL at any time to abort the installation."); System.out.println("Detailed installation instructions are available online:\n"); System.out.println(" https://wiki.duraspace.org/display/FEDORA/All+Documentation\n"); inputOption(INSTALL_TYPE); inputOption(FEDORA_HOME); if (getValue(INSTALL_TYPE).equals(INSTALL_CLIENT)) { return; } inputOption(FEDORA_ADMIN_PASS); String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)) .getAbsolutePath(); String includedJDBCURL = "jdbc:derby:" + fedoraHome + File.separator + "derby/fedora3;create=true"; if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) { // See the defaultValues defined in OptionDefinition.properties // for the null values below _map.put(FEDORA_SERVERHOST, null); // localhost _map.put(FEDORA_APP_SERVER_CONTEXT, null); _map.put(APIA_AUTH_REQUIRED, null); // false _map.put(SSL_AVAILABLE, Boolean.toString(false)); _map.put(APIM_SSL_REQUIRED, Boolean.toString(false)); _map.put(SERVLET_ENGINE, null); // included _map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat"); _map.put(TOMCAT_HTTP_PORT, null); // 8080 _map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005 _map.put(DATABASE, INCLUDED); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); _map.put(XACML_ENABLED, Boolean.toString(false)); _map.put(UPSTREAM_AUTH_ENABLED, Boolean.toString(false)); _map.put(FESL_AUTHN_ENABLED, Boolean.toString(true)); _map.put(FESL_AUTHZ_ENABLED, Boolean.toString(false)); _map.put(LLSTORE_TYPE, null); // akubra-fs _map.put(RI_ENABLED, null); // false _map.put(MESSAGING_ENABLED, null); // false _map.put(DEPLOY_LOCAL_SERVICES, null); // true applyDefaults(); return; } inputOption(FEDORA_SERVERHOST); inputOption(FEDORA_APP_SERVER_CONTEXT); inputOption(APIA_AUTH_REQUIRED); inputOption(SSL_AVAILABLE); boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true); if (sslAvailable) { inputOption(APIA_SSL_REQUIRED); inputOption(APIM_SSL_REQUIRED); } inputOption(SERVLET_ENGINE); if (!getValue(SERVLET_ENGINE).equals(OTHER)) { inputOption(TOMCAT_HOME); inputOption(TOMCAT_HTTP_PORT); inputOption(TOMCAT_SHUTDOWN_PORT); if (sslAvailable) { inputOption(TOMCAT_SSL_PORT); if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) { inputOption(KEYSTORE_FILE); if (!getValue(KEYSTORE_FILE).equals(INCLUDED)) { inputOption(KEYSTORE_PASSWORD); inputOption(KEYSTORE_TYPE); } } } } // Database selection // Ultimately we want to provide the following properties: // database, database.username, database.password, // database.driver, database.jdbcURL, database.jdbcDriverClass inputOption(DATABASE); String db = DATABASE + "." + getValue(DATABASE); // The following lets us use the database-specific OptionDefinition.properties // for the user prompts and defaults String driver = db + ".driver"; String jdbcURL = db + ".jdbcURL"; String jdbcDriverClass = db + ".jdbcDriverClass"; if (getValue(DATABASE).equals(INCLUDED)) { _map.put(DATABASE_USERNAME, "fedoraAdmin"); _map.put(DATABASE_PASSWORD, "fedoraAdmin"); _map.put(DATABASE_DRIVER, INCLUDED); _map.put(DATABASE_JDBCURL, includedJDBCURL); _map.put(DATABASE_DRIVERCLASS, EMBEDDED_DATABASE_DRIVERCLASSNAME); } else { boolean dbValidated = false; while (!dbValidated) { inputOption(driver); _map.put(DATABASE_DRIVER, getValue(driver)); inputOption(DATABASE_USERNAME); inputOption(DATABASE_PASSWORD); inputOption(jdbcURL); _map.put(DATABASE_JDBCURL, getValue(jdbcURL)); inputOption(jdbcDriverClass); _map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass)); dbValidated = validateDatabaseConnection(); } } inputOption(UPSTREAM_AUTH_ENABLED); if (getBooleanValue(UPSTREAM_AUTH_ENABLED,false)) { // disable FESL authN if upstream authN is enabled _map.put(FESL_AUTHN_ENABLED, Boolean.toString(false)); } inputOption(FESL_AUTHZ_ENABLED); if (getValue(FESL_AUTHZ_ENABLED).equals(Boolean.toString(true))) { // Disable legacy authz if FeSL is enabled _map.put(XACML_ENABLED, Boolean.toString(false)); } else { inputOption(XACML_ENABLED); } inputOption(LLSTORE_TYPE); inputOption(RI_ENABLED); inputOption(MESSAGING_ENABLED); if (getValue(MESSAGING_ENABLED).equals(Boolean.toString(true))) { inputOption(MESSAGING_URI); } inputOption(DEPLOY_LOCAL_SERVICES); }
diff --git a/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java b/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java index a718ef510..eb6bb13ea 100644 --- a/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java +++ b/plugins-dev/ais/pt/up/fe/dceg/neptus/plugins/ais/AisOverlay.java @@ -1,404 +1,404 @@ /* * Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia * Laboratório de Sistemas e Tecnologia Subaquática (LSTS) * All rights reserved. * Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal * * This file is part of Neptus, Command and Control Framework. * * Commercial Licence Usage * Licencees holding valid commercial Neptus licences may use this file * in accordance with the commercial licence agreement provided with the * Software or, alternatively, in accordance with the terms contained in a * written agreement between you and Universidade do Porto. For licensing * terms, conditions, and further information contact [email protected]. * * European Union Public Licence - EUPL v.1.1 Usage * Alternatively, this file may be used under the terms of the EUPL, * Version 1.1 only (the "Licence"), appearing in the file LICENCE.md * included in the packaging of this file. You may not use this work * except in compliance with the Licence. Unless required by applicable * law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the Licence for the specific * language governing permissions and limitations at * https://www.lsts.pt/neptus/licence. * * For more information please see <http://lsts.fe.up.pt/neptus>. * * Author: José Pinto * Jul 12, 2012 */ package pt.up.fe.dceg.neptus.plugins.ais; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Vector; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.mozilla.javascript.edu.emory.mathcs.backport.java.util.Collections; import pt.up.fe.dceg.neptus.NeptusLog; import pt.up.fe.dceg.neptus.console.ConsoleLayout; import pt.up.fe.dceg.neptus.gui.PropertiesEditor; import pt.up.fe.dceg.neptus.planeditor.IEditorMenuExtension; import pt.up.fe.dceg.neptus.planeditor.IMapPopup; import pt.up.fe.dceg.neptus.plugins.NeptusProperty; import pt.up.fe.dceg.neptus.plugins.PluginDescription; import pt.up.fe.dceg.neptus.plugins.SimpleRendererInteraction; import pt.up.fe.dceg.neptus.plugins.update.IPeriodicUpdates; import pt.up.fe.dceg.neptus.plugins.update.PeriodicUpdatesService; import pt.up.fe.dceg.neptus.renderer2d.LayerPriority; import pt.up.fe.dceg.neptus.renderer2d.StateRenderer2D; import pt.up.fe.dceg.neptus.types.coord.LocationType; import pt.up.fe.dceg.neptus.util.GuiUtils; import com.google.gson.Gson; /** * @author zp * */ @PluginDescription(author = "ZP", name = "AIS Overlay", icon = "pt/up/fe/dceg/neptus/plugins/ais/mt.png") @LayerPriority(priority=-50) public class AisOverlay extends SimpleRendererInteraction implements IPeriodicUpdates, IEditorMenuExtension { private static final long serialVersionUID = 1L; @NeptusProperty(name = "Show vessel names") public boolean showNames = true; @NeptusProperty(name = "Show vessel speeds") public boolean showSpeeds = true; @NeptusProperty(name = "Milliseconds between vessel updates") public long updateMillis = 60000; @NeptusProperty(name = "Show only when selected") public boolean showOnlyWhenInteractionIsActive = true; @NeptusProperty(name = "Show stationary vessels") public boolean showStoppedShips = false; @NeptusProperty(name = "Interpolate and predict positions") public boolean interpolate = false; @NeptusProperty(name = "Moving vessel color") public Color movingColor = Color.blue.darker(); @NeptusProperty(name = "Stationary vessel color") public Color stationaryColor = Color.gray.darker(); @NeptusProperty(name = "Vessel label color") public Color labelColor = Color.black; @NeptusProperty(name = "Show speed in knots") public boolean useKnots = false; protected boolean active = false; protected Vector<AisShip> shipsOnMap = new Vector<AisShip>(); protected StateRenderer2D renderer = null; protected boolean updating = false; /** * @param console */ public AisOverlay(ConsoleLayout console) { super(console); } @Override public boolean isExclusive() { return true; } @Override public void setActive(boolean mode, StateRenderer2D source) { super.setActive(mode, source); active = mode; if (active) update(); } @Override public String getName() { return super.getName(); } @Override public long millisBetweenUpdates() { return updateMillis; } protected Thread lastThread = null; protected GeneralPath path = new GeneralPath(); { path.moveTo(0, 5); path.lineTo(-5, 3.5); path.lineTo(-5, -5); path.lineTo(5, -5); path.lineTo(5, 3.5); path.lineTo(0, 5); path.closePath(); } @Override public boolean update() { if (showOnlyWhenInteractionIsActive && !active) return true; // don't let more than one thread be running at a time if (lastThread != null) return true; lastThread = new Thread() { public void run() { updating = true; try { if (renderer == null) { lastThread = null; return; } LocationType topLeft = renderer.getTopLeftLocationType(); LocationType bottomRight = renderer.getBottomRightLocationType(); shipsOnMap = getShips(bottomRight.getLatitudeAsDoubleValue(), topLeft.getLongitudeAsDoubleValue(), topLeft.getLatitudeAsDoubleValue(), bottomRight.getLongitudeAsDoubleValue(), showStoppedShips); lastThread = null; renderer.repaint(); } finally { updating = false; } }; }; lastThread.setName("AIS Fetcher thread"); lastThread.setDaemon(true); lastThread.start(); return true; } private HttpClient client = new HttpClient(); private Gson gson = new Gson(); protected Vector<AisShip> getShips(double minLat, double minLon, double maxLat, double maxLon, boolean includeStationary) { Vector<AisShip> ships = new Vector<>(); // area is too large if (maxLat - minLat > 2) return ships; try { URL url = new URL("http://www.marinetraffic.com/ais/getjson.aspx?sw_x=" + minLon + "&sw_y=" + minLat + "&ne_x=" + maxLon + "&ne_y=" + maxLat + "&zoom=12" + "&fleet=&station=0&id=null"); GetMethod get = new GetMethod(url.toString()); get.setRequestHeader("Referer", "http://www.marinetraffic.com/ais/"); client.executeMethod(get); String json = get.getResponseBodyAsString(); String[][] res = gson.fromJson(json, String[][].class); for (int i = 0; i < res.length; i++) { double knots = Double.parseDouble(res[i][5]) / 10; if (!includeStationary && knots <= 0.2) continue; AisShip ship = new AisShip(); ship.setLatitude(Double.parseDouble(res[i][0])); ship.setLongitude(Double.parseDouble(res[i][1])); ship.setName(res[i][2]); ship.setMMSI(Integer.parseInt(res[i][7])); ship.setSpeed(knots); if (res[i][4] != null) ship.setCourse(Double.parseDouble(res[i][4])); if (res[i][6] != null) ship.setCountry(res[i][6]); if (res[i][8] != null) ship.setLength(Double.parseDouble(res[i][8])); ships.add(ship); } } catch (Exception e) { NeptusLog.pub().warn(e); } return ships; } @Override public void cleanSubPanel() { PeriodicUpdatesService.unregister(this); shipsOnMap.clear(); } @Override public void mouseClicked(MouseEvent event, StateRenderer2D source) { super.mouseClicked(event, source); JPopupMenu popup = new JPopupMenu(); popup.add("AIS settings").addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PropertiesEditor.editProperties(AisOverlay.this, getConsole(), true); } }); popup.add("Update ships").addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(); } }); popup.add(getShipInfoMenu()); popup.show(source, event.getX(), event.getY()); } @Override public void paint(Graphics2D g, StateRenderer2D renderer) { super.paint(g, renderer); this.renderer = renderer; if (showOnlyWhenInteractionIsActive && !active) return; if (lastThread != null) { g.drawString("Updating AIS layer...", 10, 15); } else { g.drawString(shipsOnMap.size() + " visible ships", 10, 15); } for (AisShip ship : shipsOnMap) { Graphics2D clone = (Graphics2D) g.create(); LocationType shipLoc = ship.getLocation(); if (interpolate) { double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0; double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps(); double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps(); shipLoc.translatePosition(tx, ty, 0); } Point2D pt = renderer.getScreenPosition(shipLoc); clone.translate(pt.getX(), pt.getY()); Graphics2D clone2 = (Graphics2D) clone.create(); Color c = movingColor; if (ship.getSpeedKnots() <= 0.2) c = stationaryColor; double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9; double scaleY = (renderer.getZoom() / 10) * ship.getLength(); - clone.rotate(Math.PI + ship.getHeadingRads()); + clone.rotate(Math.PI + ship.getHeadingRads() - renderer.getRotation()); clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128)); clone.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{3f, 10f}, 0.0f)); clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60 * renderer.getZoom())); clone.scale(scaleX, scaleY); clone.setColor(c); clone.fill(path); clone.dispose(); //clone2.rotate(-Math.PI/2 + ship.getHeadingRads()); clone2.setFont(new Font("Helvetica", Font.PLAIN, 8)); clone2.setColor(labelColor); clone2.drawLine(-3, 0, 3, 0); clone2.drawLine(0, -3, 0, 3); if (showNames) { clone2.drawString(ship.getName(), 5, 5); } if (showSpeeds && ship.getSpeedKnots() > 0.2) { if (useKnots) clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15); else clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15); } clone2.dispose(); } } protected JMenu getShipInfoMenu() { Vector<AisShip> ships = new Vector<>(); JMenu menu = new JMenu("Ship Info"); ships.addAll(shipsOnMap); Collections.sort(ships); if (ships.size() > 0 && Desktop.isDesktopSupported()) { for (final AisShip s : ships) { menu.add(s.getName()).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Desktop desktop = Desktop.getDesktop(); try { URI uri = new URI(s.getShipInfoURL()); desktop.browse(uri); } catch (IOException ex) { ex.printStackTrace(); } catch (URISyntaxException ex) { ex.printStackTrace(); } } }); } } else { menu.setEnabled(false); } return menu; } @Override public Collection<JMenuItem> getApplicableItems(LocationType loc, IMapPopup source) { Vector<JMenuItem> items = new Vector<>(); if (!shipsOnMap.isEmpty()) items.add(getShipInfoMenu()); return items; } @Override public void initSubPanel() { Vector<IMapPopup> r = getConsole().getSubPanelsOfInterface(IMapPopup.class); for (IMapPopup str2d : r) { str2d.addMenuExtension(this); } } }
true
true
public void paint(Graphics2D g, StateRenderer2D renderer) { super.paint(g, renderer); this.renderer = renderer; if (showOnlyWhenInteractionIsActive && !active) return; if (lastThread != null) { g.drawString("Updating AIS layer...", 10, 15); } else { g.drawString(shipsOnMap.size() + " visible ships", 10, 15); } for (AisShip ship : shipsOnMap) { Graphics2D clone = (Graphics2D) g.create(); LocationType shipLoc = ship.getLocation(); if (interpolate) { double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0; double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps(); double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps(); shipLoc.translatePosition(tx, ty, 0); } Point2D pt = renderer.getScreenPosition(shipLoc); clone.translate(pt.getX(), pt.getY()); Graphics2D clone2 = (Graphics2D) clone.create(); Color c = movingColor; if (ship.getSpeedKnots() <= 0.2) c = stationaryColor; double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9; double scaleY = (renderer.getZoom() / 10) * ship.getLength(); clone.rotate(Math.PI + ship.getHeadingRads()); clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128)); clone.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{3f, 10f}, 0.0f)); clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60 * renderer.getZoom())); clone.scale(scaleX, scaleY); clone.setColor(c); clone.fill(path); clone.dispose(); //clone2.rotate(-Math.PI/2 + ship.getHeadingRads()); clone2.setFont(new Font("Helvetica", Font.PLAIN, 8)); clone2.setColor(labelColor); clone2.drawLine(-3, 0, 3, 0); clone2.drawLine(0, -3, 0, 3); if (showNames) { clone2.drawString(ship.getName(), 5, 5); } if (showSpeeds && ship.getSpeedKnots() > 0.2) { if (useKnots) clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15); else clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15); } clone2.dispose(); } }
public void paint(Graphics2D g, StateRenderer2D renderer) { super.paint(g, renderer); this.renderer = renderer; if (showOnlyWhenInteractionIsActive && !active) return; if (lastThread != null) { g.drawString("Updating AIS layer...", 10, 15); } else { g.drawString(shipsOnMap.size() + " visible ships", 10, 15); } for (AisShip ship : shipsOnMap) { Graphics2D clone = (Graphics2D) g.create(); LocationType shipLoc = ship.getLocation(); if (interpolate) { double dT = (System.currentTimeMillis() - ship.lastUpdate) / 1000.0; double tx = Math.cos(ship.getHeadingRads()) * dT * ship.getSpeedMps(); double ty = Math.sin(ship.getHeadingRads()) * dT * ship.getSpeedMps(); shipLoc.translatePosition(tx, ty, 0); } Point2D pt = renderer.getScreenPosition(shipLoc); clone.translate(pt.getX(), pt.getY()); Graphics2D clone2 = (Graphics2D) clone.create(); Color c = movingColor; if (ship.getSpeedKnots() <= 0.2) c = stationaryColor; double scaleX = (renderer.getZoom() / 10) * ship.getLength() / 9; double scaleY = (renderer.getZoom() / 10) * ship.getLength(); clone.rotate(Math.PI + ship.getHeadingRads() - renderer.getRotation()); clone.setColor(c.brighter());//new Color(c.getRed(), c.getGreen(), c.getBlue(), 128)); clone.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{3f, 10f}, 0.0f)); clone.draw(new Line2D.Double(0, ship.getLength() / 1.99 * renderer.getZoom(), 0, ship.getSpeedMps() * 60 * renderer.getZoom())); clone.scale(scaleX, scaleY); clone.setColor(c); clone.fill(path); clone.dispose(); //clone2.rotate(-Math.PI/2 + ship.getHeadingRads()); clone2.setFont(new Font("Helvetica", Font.PLAIN, 8)); clone2.setColor(labelColor); clone2.drawLine(-3, 0, 3, 0); clone2.drawLine(0, -3, 0, 3); if (showNames) { clone2.drawString(ship.getName(), 5, 5); } if (showSpeeds && ship.getSpeedKnots() > 0.2) { if (useKnots) clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedKnots()) + " kn", 5, 15); else clone2.drawString(GuiUtils.getNeptusDecimalFormat(1).format(ship.getSpeedMps()) + " m/s", 5, 15); } clone2.dispose(); } }
diff --git a/xengine_less/src/com/xengine/android/utils/XFileUtil.java b/xengine_less/src/com/xengine/android/utils/XFileUtil.java index f0f0d9d..13a636c 100644 --- a/xengine_less/src/com/xengine/android/utils/XFileUtil.java +++ b/xengine_less/src/com/xengine/android/utils/XFileUtil.java @@ -1,348 +1,351 @@ package com.xengine.android.utils; import android.text.TextUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * Created with IntelliJ IDEA. * User: tujun * Date: 13-9-6 * Time: 下午5:45 * To change this template use File | Settings | File Templates. */ public class XFileUtil { /** * 复制文件 * @param oldFile * @param newFile * @return */ public static boolean copyFile(File oldFile, File newFile) { if (!oldFile.exists()) // 文件存在时 return false; InputStream is = null; FileOutputStream fs = null; try { is = new FileInputStream(oldFile); // 读入原文件 fs = new FileOutputStream(newFile); byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) != -1) { fs.write(buffer, 0, read); } return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); if (fs != null) fs.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } /** * 将File转换为byte[] * @param file * @return * @throws java.io.IOException */ public static byte[] file2byte(File file) throws IOException { if (file == null) return null; InputStream is = new FileInputStream(file); // 判断文件大小 long length = file.length(); if (length > Integer.MAX_VALUE) // 文件太大,无法读取 throw new IOException("File is to large "+file.getName()); // 创建一个数据来保存文件数据 byte[] bytes = new byte[(int)length]; // 读取数据到byte数组中 int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } is.close(); // 确保所有数据均被读取 if (offset < bytes.length) throw new IOException("Could not completely read file "+file.getName()); return bytes; } /** * 将byte[]转换为File * @param bytes * @param file * @return */ public static boolean byte2file(byte[] bytes, File file) { BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (bos != null) bos.close(); if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * String转换为File。 * 如果创建失败,会删除文件。 * @param res 字符内容 * @param file 文件 * @return 如果创建成功,返回true;否则返回false */ public static boolean string2File(String res, File file) { if (file == null || res == null) return false; BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file)); bufferedWriter.write(res); bufferedWriter.flush(); return true; } catch (IOException e) { e.printStackTrace(); if (file.exists()) file.delete(); return false; } finally { try { if (bufferedWriter != null) bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * File转换为String。 * @param file 文件 * @return 如果读取失败,返回null;否则返回字符串形式。 */ public static String file2String(File file) { FileInputStream fis = null; ByteArrayOutputStream baos = null; try { fis = new FileInputStream(file); baos = new ByteArrayOutputStream(); int i; while ((i = fis.read()) != -1) { baos.write(i); } String str = baos.toString(); return str; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { if (fis != null) fis.close(); if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 清空文件夹。 * @param dir 文件夹 * @param removeSelf 是否删除自身 */ public static void clearDirectory(File dir, boolean removeSelf) { if (dir == null || !dir.exists()) return; File[] files = dir.listFiles(); if (files != null) // 如果dir不是文件夹,files会为null for (File file : files) clearDirectory(file, true);// 递归 if (removeSelf) dir.delete(); } /** * 将多个文件压缩成一个.zip压缩文件 * @param originFilePaths 多个指定文件的路径 * @param zipFilePath 压缩生成的.zip文件的路径 * @return 压缩成功返回true;否则返回false */ public static boolean zipFile(List<String> originFilePaths, String zipFilePath) { // 防止外部修改列表 List<String> copyFilePaths = new ArrayList<String>(originFilePaths); // 创建.zip文件所在的文件夹(如果不存在),以及删除同名的.zip文件(如果存在) File zipFile = new File(zipFilePath); File zipFileDir = zipFile.getParentFile(); if (zipFileDir != null && !zipFileDir.exists()) { zipFileDir.mkdirs(); } if (zipFile.exists()) { zipFile.delete(); } FileOutputStream out = null; ZipOutputStream zipOut = null; try { out = new FileOutputStream(zipFilePath);// 根据文件路径构造一个文件输出流 zipOut = new ZipOutputStream(out);// 创建ZIP数据输出流对象 // 循环待压缩的文件列表 byte[] buffer = new byte[512]; for (String originFilePath : copyFilePaths) { if (TextUtils.isEmpty(originFilePath)) continue; File originFile = new File(originFilePath); if (!originFile.exists()) continue; // 创建文件输入流对象 FileInputStream in = new FileInputStream(originFile); // 创建指向压缩原始文件的入口 ZipEntry entry = new ZipEntry(originFile.getName()); + // 创建压缩文件的一项 zipOut.putNextEntry(entry); // 向压缩文件中输出数据 int nNumber = 0; while ((nNumber = in.read(buffer)) != -1) { zipOut.write(buffer, 0, nNumber); } + // 关闭这一项 + zipOut.closeEntry(); // 关闭创建的流对象 in.close(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (out != null) out.close(); if (zipOut != null) zipOut.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 解压.zip文件 * @param zipFile * @param dirPath * @param override * @return */ public static boolean unzipFile(String zipFile, String dirPath, boolean override) { if (TextUtils.isEmpty(zipFile)) return false; File file = new File(zipFile); if (!file.exists()) return false; try { InputStream is = new FileInputStream(file); return unzipFile(is, dirPath, override); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } /** * 解压.zip文件 * @param zipInput * @param dirPath * @param override * @return */ public static boolean unzipFile(InputStream zipInput, String dirPath, boolean override) { if (TextUtils.isEmpty(dirPath)) return false; File df = new File(dirPath); df.mkdirs(); if (!df.exists()) return false; ZipInputStream zis = null; BufferedInputStream bis = null; try { zis = new ZipInputStream(zipInput); bis = new BufferedInputStream(zis); File file = null; ZipEntry entry; while ((entry = zis.getNextEntry()) != null && !entry.isDirectory()) { file = new File(dirPath, entry.getName()); if (file.exists()) {// 如果文件存在,根据override字段决定是否要覆盖 if (override) file.delete();// 覆盖,先删除原先的文件 else continue;// 不覆盖,直接跳过 } FileOutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); byte buffer[] = new byte[512]; int realLength = 0; while ((realLength = bis.read(buffer)) != -1) { out.write(buffer, 0, realLength); } bos.flush(); bos.close(); out.close(); } return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (zis != null) zis.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } }
false
true
public static boolean zipFile(List<String> originFilePaths, String zipFilePath) { // 防止外部修改列表 List<String> copyFilePaths = new ArrayList<String>(originFilePaths); // 创建.zip文件所在的文件夹(如果不存在),以及删除同名的.zip文件(如果存在) File zipFile = new File(zipFilePath); File zipFileDir = zipFile.getParentFile(); if (zipFileDir != null && !zipFileDir.exists()) { zipFileDir.mkdirs(); } if (zipFile.exists()) { zipFile.delete(); } FileOutputStream out = null; ZipOutputStream zipOut = null; try { out = new FileOutputStream(zipFilePath);// 根据文件路径构造一个文件输出流 zipOut = new ZipOutputStream(out);// 创建ZIP数据输出流对象 // 循环待压缩的文件列表 byte[] buffer = new byte[512]; for (String originFilePath : copyFilePaths) { if (TextUtils.isEmpty(originFilePath)) continue; File originFile = new File(originFilePath); if (!originFile.exists()) continue; // 创建文件输入流对象 FileInputStream in = new FileInputStream(originFile); // 创建指向压缩原始文件的入口 ZipEntry entry = new ZipEntry(originFile.getName()); zipOut.putNextEntry(entry); // 向压缩文件中输出数据 int nNumber = 0; while ((nNumber = in.read(buffer)) != -1) { zipOut.write(buffer, 0, nNumber); } // 关闭创建的流对象 in.close(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (out != null) out.close(); if (zipOut != null) zipOut.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static boolean zipFile(List<String> originFilePaths, String zipFilePath) { // 防止外部修改列表 List<String> copyFilePaths = new ArrayList<String>(originFilePaths); // 创建.zip文件所在的文件夹(如果不存在),以及删除同名的.zip文件(如果存在) File zipFile = new File(zipFilePath); File zipFileDir = zipFile.getParentFile(); if (zipFileDir != null && !zipFileDir.exists()) { zipFileDir.mkdirs(); } if (zipFile.exists()) { zipFile.delete(); } FileOutputStream out = null; ZipOutputStream zipOut = null; try { out = new FileOutputStream(zipFilePath);// 根据文件路径构造一个文件输出流 zipOut = new ZipOutputStream(out);// 创建ZIP数据输出流对象 // 循环待压缩的文件列表 byte[] buffer = new byte[512]; for (String originFilePath : copyFilePaths) { if (TextUtils.isEmpty(originFilePath)) continue; File originFile = new File(originFilePath); if (!originFile.exists()) continue; // 创建文件输入流对象 FileInputStream in = new FileInputStream(originFile); // 创建指向压缩原始文件的入口 ZipEntry entry = new ZipEntry(originFile.getName()); // 创建压缩文件的一项 zipOut.putNextEntry(entry); // 向压缩文件中输出数据 int nNumber = 0; while ((nNumber = in.read(buffer)) != -1) { zipOut.write(buffer, 0, nNumber); } // 关闭这一项 zipOut.closeEntry(); // 关闭创建的流对象 in.close(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (out != null) out.close(); if (zipOut != null) zipOut.close(); } catch (IOException e) { e.printStackTrace(); } } }
diff --git a/src/main/java/us/camin/EconomyAPI.java b/src/main/java/us/camin/EconomyAPI.java index deaf059..226b25b 100644 --- a/src/main/java/us/camin/EconomyAPI.java +++ b/src/main/java/us/camin/EconomyAPI.java @@ -1,159 +1,159 @@ package us.camin; /* This file is part of Caminus Caminus is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Caminus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Caminus. If not, see <http://www.gnu.org/licenses/>. */ import java.io.IOException; import java.util.List; import java.util.ArrayList; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import net.milkbowl.vault.economy.EconomyResponse.ResponseType; import us.camin.api.BalanceAdjustResponse; public class EconomyAPI implements Economy { private Plugin m_p; public EconomyAPI(Plugin p) { m_p = p; } @Override public boolean isEnabled() { return true; } @Override public String getName() { return "Caminus"; } @Override public boolean hasBankSupport() { return false; } @Override public String format(double amount) { return amount+" grist"; } @Override public String currencyNamePlural() { return "grist"; } @Override public String currencyNameSingular() { return "grist"; } @Override public boolean hasAccount(String playerName) { return true; } @Override public double getBalance(String playerName) { try { return m_p.api().getBalance(playerName); } catch (IOException e) { return 0; } } @Override public boolean has(String playerName, double amount) { return getBalance(playerName) >= amount; } private EconomyResponse adjustPlayer(String playerName, double amount) { BalanceAdjustResponse resp; try { - resp = m_p.api().adjustBalance(playerName, -amount); + resp = m_p.api().adjustBalance(playerName, amount); } catch (IOException e) { return new EconomyResponse(0, 0, ResponseType.FAILURE, "Could not contact api.camin.us."); } if (resp.success) { return new EconomyResponse(amount, resp.newBalance, ResponseType.SUCCESS, resp.message); } else { return new EconomyResponse(0, resp.newBalance, ResponseType.FAILURE, resp.message); } } @Override public EconomyResponse withdrawPlayer(String playerName, double amount) { return adjustPlayer(playerName, amount); } @Override public EconomyResponse depositPlayer(String playerName, double amount) { return adjustPlayer(playerName, amount); } private static final EconomyResponse NO_IMPL_RESPONSE = new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "Not implemented."); @Override public EconomyResponse createBank(String name, String player) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse deleteBank(String name) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse bankBalance(String name) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse bankHas(String name, double amount) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse bankWithdraw(String name, double amount) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse bankDeposit(String name, double amount) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse isBankOwner(String name, String player) { return NO_IMPL_RESPONSE; } @Override public EconomyResponse isBankMember(String name, String player) { return NO_IMPL_RESPONSE; } @Override public boolean createPlayerAccount(String name) { return true; } @Override public List<String> getBanks() { return new ArrayList<String>(); } }
true
true
private EconomyResponse adjustPlayer(String playerName, double amount) { BalanceAdjustResponse resp; try { resp = m_p.api().adjustBalance(playerName, -amount); } catch (IOException e) { return new EconomyResponse(0, 0, ResponseType.FAILURE, "Could not contact api.camin.us."); } if (resp.success) { return new EconomyResponse(amount, resp.newBalance, ResponseType.SUCCESS, resp.message); } else { return new EconomyResponse(0, resp.newBalance, ResponseType.FAILURE, resp.message); } }
private EconomyResponse adjustPlayer(String playerName, double amount) { BalanceAdjustResponse resp; try { resp = m_p.api().adjustBalance(playerName, amount); } catch (IOException e) { return new EconomyResponse(0, 0, ResponseType.FAILURE, "Could not contact api.camin.us."); } if (resp.success) { return new EconomyResponse(amount, resp.newBalance, ResponseType.SUCCESS, resp.message); } else { return new EconomyResponse(0, resp.newBalance, ResponseType.FAILURE, resp.message); } }
diff --git a/uqcard/src/com/refnil/uqcard/BoardActivity.java b/uqcard/src/com/refnil/uqcard/BoardActivity.java index dfd61e3..0c70093 100644 --- a/uqcard/src/com/refnil/uqcard/BoardActivity.java +++ b/uqcard/src/com/refnil/uqcard/BoardActivity.java @@ -1,297 +1,299 @@ package com.refnil.uqcard; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.Gallery; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class BoardActivity extends Activity implements OnTouchListener { private ImageAdapter adapter; private float pointY; private int phase=1; private int selectedCard = 0; private OnClickListener c = new OnClickListener() { public void onClick(View v) { ImageView iv = (ImageView) v; if(phase == 0 && iv.getDrawable() != null && selectedCard != 0) { switch(iv.getId()) { case R.id.opponentGeneral : case R.id.opponentBack1 : case R.id.opponentBack2 : case R.id.opponentBack3 : case R.id.opponentFront1 : case R.id.opponentFront2 : case R.id.opponentFront3 : case R.id.opponentFront4 : case R.id.opponentFront5 : attackCard(iv); break; } } else { if((phase == 1 && iv.getDrawable() == null) || (phase == 0 && selectedCard == 0)) { switch(iv.getId()) { case R.id.playerPhenomenon : placeCard(iv); break; case R.id.playerBack1: case R.id.playerBack2: case R.id.playerBack3: case R.id.playerFront1: case R.id.playerFront2: case R.id.playerFront3: case R.id.playerFront4: case R.id.playerFront5 : if(phase == 0) selectedCard = iv.getId(); else placeCard(iv); break; } } } } }; private OnLongClickListener lc = new OnLongClickListener(){ public boolean onLongClick(View v) { ImageView iv = (ImageView) v; int vID = iv.getId(); if(vID != R.id.playerDeck && vID != R.id.opponentDeck && iv.getDrawable() != null) showCard(iv); return true; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.activity_board, null); setContentView(view); view.setOnTouchListener(this); TextView tv = (TextView) findViewById(R.id.opponentText); tv.setText("My opponent"); tv = (TextView) findViewById(R.id.playerText); tv.setText("Me"); //Opponent ImageView iv = (ImageView) findViewById(R.id.opponentBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setTag(R.drawable.carreau); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); //Player iv = (ImageView) findViewById(R.id.playerBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerPhenomenon); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); // Hand initialisation Gallery gallery = (Gallery)findViewById(R.id.Gallery); adapter = new ImageAdapter(this); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent i = new Intent(getApplicationContext(), FullCardActivity.class); int id = (int) adapter.getItemId(arg2); i.putExtra("id", id); startActivity(i); } }); SemiClosedSlidingDrawer slider = (SemiClosedSlidingDrawer) findViewById(R.id.mySlidingDrawer); slider.setOnDrawerOpenListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerOpenListener() { public void onDrawerOpened() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 2); gallery.setScaleX((float) 1.5); + gallery.setTranslationY(55); } }); slider.setOnDrawerCloseListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerCloseListener() { public void onDrawerClosed() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 0.9); gallery.setScaleX((float) 0.9); + gallery.setTranslationY(-7); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_board, menu); return true; } public void attackCard(ImageView iv) { if(selectedCard != 0) { Toast.makeText(getApplicationContext(), "Attack done", Toast.LENGTH_SHORT).show(); selectedCard = 0; //TEMP phase = 1; } } public void placeCard(ImageView iv) { if(selectedCard != 0) { iv.setImageResource(selectedCard); iv.setTag(selectedCard); selectedCard = 0; //TEMP phase = 0; } } public void showCard(ImageView image) { Intent i = new Intent(getApplicationContext(), FullCardActivity.class); int id=(Integer) image.getTag(); i.putExtra("id",id); startActivity(i); } public boolean onTouch(View arg0, MotionEvent event) { float eventY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: pointY=eventY; return true; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: SemiClosedSlidingDrawer slider = (SemiClosedSlidingDrawer) findViewById(R.id.mySlidingDrawer); Gallery gallery = (Gallery)findViewById(R.id.Gallery); if(eventY<pointY) { selectedCard = (int)gallery.getSelectedItemId(); slider.animateClose(); pointY =0; } break; default: return false; } return false; } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.activity_board, null); setContentView(view); view.setOnTouchListener(this); TextView tv = (TextView) findViewById(R.id.opponentText); tv.setText("My opponent"); tv = (TextView) findViewById(R.id.playerText); tv.setText("Me"); //Opponent ImageView iv = (ImageView) findViewById(R.id.opponentBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setTag(R.drawable.carreau); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); //Player iv = (ImageView) findViewById(R.id.playerBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerPhenomenon); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); // Hand initialisation Gallery gallery = (Gallery)findViewById(R.id.Gallery); adapter = new ImageAdapter(this); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent i = new Intent(getApplicationContext(), FullCardActivity.class); int id = (int) adapter.getItemId(arg2); i.putExtra("id", id); startActivity(i); } }); SemiClosedSlidingDrawer slider = (SemiClosedSlidingDrawer) findViewById(R.id.mySlidingDrawer); slider.setOnDrawerOpenListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerOpenListener() { public void onDrawerOpened() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 2); gallery.setScaleX((float) 1.5); } }); slider.setOnDrawerCloseListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerCloseListener() { public void onDrawerClosed() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 0.9); gallery.setScaleX((float) 0.9); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.activity_board, null); setContentView(view); view.setOnTouchListener(this); TextView tv = (TextView) findViewById(R.id.opponentText); tv.setText("My opponent"); tv = (TextView) findViewById(R.id.playerText); tv.setText("Me"); //Opponent ImageView iv = (ImageView) findViewById(R.id.opponentBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setTag(R.drawable.carreau); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.opponentCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); //Player iv = (ImageView) findViewById(R.id.playerBack1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerBack3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront1); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront2); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront3); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront4); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerFront5); iv.setTag(R.drawable.carreau); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerGeneral); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerPhenomenon); iv.setTag(R.drawable.coeur); iv.setOnClickListener(c); iv.setOnLongClickListener(lc); iv = (ImageView) findViewById(R.id.playerCemetery); iv.setTag(R.drawable.coeur); iv.setOnLongClickListener(lc); // Hand initialisation Gallery gallery = (Gallery)findViewById(R.id.Gallery); adapter = new ImageAdapter(this); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent i = new Intent(getApplicationContext(), FullCardActivity.class); int id = (int) adapter.getItemId(arg2); i.putExtra("id", id); startActivity(i); } }); SemiClosedSlidingDrawer slider = (SemiClosedSlidingDrawer) findViewById(R.id.mySlidingDrawer); slider.setOnDrawerOpenListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerOpenListener() { public void onDrawerOpened() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 2); gallery.setScaleX((float) 1.5); gallery.setTranslationY(55); } }); slider.setOnDrawerCloseListener(new com.refnil.uqcard.SemiClosedSlidingDrawer.OnDrawerCloseListener() { public void onDrawerClosed() { Gallery gallery = (Gallery)findViewById(R.id.Gallery); gallery.setScaleY((float) 0.9); gallery.setScaleX((float) 0.9); gallery.setTranslationY(-7); } }); }
diff --git a/app/controllers/Report.java b/app/controllers/Report.java index 2925f8a..03c0b2c 100644 --- a/app/controllers/Report.java +++ b/app/controllers/Report.java @@ -1,78 +1,78 @@ package controllers; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import models.Token; import play.Logger; import play.libs.Json; import play.libs.WS; import play.libs.WS.Response; import play.libs.WS.WSRequestHolder; import play.mvc.Controller; import play.mvc.Result; import util.AuthorizationUtil; import constants.APIConstants; /** * Report controller for generating reports * * @author tejawork * */ public class Report extends Controller{ //constants private static String PAGE_COUNT_PARAMETER_NAME = "page_count"; private static String PAGE_COUNT = "20"; //private static Token token = AuthorizationUtil.getNewToken(); /** * Route: /reports/topAudience * <p> * This creates a request to Lotame API to get a list of Top Audience Report * data. * * @return Returns Top Audience report as JSON object */ public static Result topAudiences() { Logger.trace("Getting the top audience from Lotame API"); Token token = AuthorizationUtil.getToken(); //setup the request with headers WSRequestHolder request = WS.url(APIConstants.LOTAME_TOP_AUDIENCE_URL); request.setHeader(APIConstants.ACCEPT_HEADER, APIConstants.JSON_HEADER_TYPE); request.setHeader(APIConstants.AUTHORIZATION_HEADER, token.tokenCode); request.setQueryParameter(PAGE_COUNT_PARAMETER_NAME, PAGE_COUNT); Logger.debug(String.format("Request being sent to %s", APIConstants.LOTAME_TOP_AUDIENCE_URL)); //extracting the response from the promise Response response = request.get().get(); //creating Jackson mapper ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = mapper.readValue(response.asJson(), JsonNode.class); } catch (Exception exception){ Logger.error("Json mapper has an error", exception); ObjectNode result = Json.newObject(); result.put(APIConstants.JSON_ERROR_KEY, APIConstants.JSON_500_MESSAGE); //returning a Http 500, when json mapper error occurs - return internalServerError(result); + return badRequest(result); } JsonNode array = rootNode.get(APIConstants.LOTAME_JSON_TOP_AUDIENCE_STAT_VAR); return ok(array); } }
true
true
public static Result topAudiences() { Logger.trace("Getting the top audience from Lotame API"); Token token = AuthorizationUtil.getToken(); //setup the request with headers WSRequestHolder request = WS.url(APIConstants.LOTAME_TOP_AUDIENCE_URL); request.setHeader(APIConstants.ACCEPT_HEADER, APIConstants.JSON_HEADER_TYPE); request.setHeader(APIConstants.AUTHORIZATION_HEADER, token.tokenCode); request.setQueryParameter(PAGE_COUNT_PARAMETER_NAME, PAGE_COUNT); Logger.debug(String.format("Request being sent to %s", APIConstants.LOTAME_TOP_AUDIENCE_URL)); //extracting the response from the promise Response response = request.get().get(); //creating Jackson mapper ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = mapper.readValue(response.asJson(), JsonNode.class); } catch (Exception exception){ Logger.error("Json mapper has an error", exception); ObjectNode result = Json.newObject(); result.put(APIConstants.JSON_ERROR_KEY, APIConstants.JSON_500_MESSAGE); //returning a Http 500, when json mapper error occurs return internalServerError(result); } JsonNode array = rootNode.get(APIConstants.LOTAME_JSON_TOP_AUDIENCE_STAT_VAR); return ok(array); }
public static Result topAudiences() { Logger.trace("Getting the top audience from Lotame API"); Token token = AuthorizationUtil.getToken(); //setup the request with headers WSRequestHolder request = WS.url(APIConstants.LOTAME_TOP_AUDIENCE_URL); request.setHeader(APIConstants.ACCEPT_HEADER, APIConstants.JSON_HEADER_TYPE); request.setHeader(APIConstants.AUTHORIZATION_HEADER, token.tokenCode); request.setQueryParameter(PAGE_COUNT_PARAMETER_NAME, PAGE_COUNT); Logger.debug(String.format("Request being sent to %s", APIConstants.LOTAME_TOP_AUDIENCE_URL)); //extracting the response from the promise Response response = request.get().get(); //creating Jackson mapper ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = mapper.readValue(response.asJson(), JsonNode.class); } catch (Exception exception){ Logger.error("Json mapper has an error", exception); ObjectNode result = Json.newObject(); result.put(APIConstants.JSON_ERROR_KEY, APIConstants.JSON_500_MESSAGE); //returning a Http 500, when json mapper error occurs return badRequest(result); } JsonNode array = rootNode.get(APIConstants.LOTAME_JSON_TOP_AUDIENCE_STAT_VAR); return ok(array); }
diff --git a/src/de/uxnr/amf/flex/msg/AbstractMessage.java b/src/de/uxnr/amf/flex/msg/AbstractMessage.java index 1f8df7f..f49013f 100644 --- a/src/de/uxnr/amf/flex/msg/AbstractMessage.java +++ b/src/de/uxnr/amf/flex/msg/AbstractMessage.java @@ -1,120 +1,121 @@ package de.uxnr.amf.flex.msg; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Vector; import de.uxnr.amf.AMF_Context; import de.uxnr.amf.AMF_Type; import de.uxnr.amf.v0.base.U8; import de.uxnr.amf.v3.AMF3_Type; import de.uxnr.amf.v3.base.UTF8; import de.uxnr.amf.v3.type.Object; public abstract class AbstractMessage extends Object { private static final UTF8[][] names = new UTF8[][] { { new UTF8("body"), new UTF8("clientId"), new UTF8("destination"), new UTF8("headers"), new UTF8("messageId"), new UTF8("timestamp"), new UTF8("timeToLive"), }, { new UTF8("clientId"), new UTF8("messageId"), } }; @Override public void write(AMF_Context context, DataOutputStream output) throws IOException { this.writeFields(context, output, AbstractMessage.names); } @Override public AMF_Type read(AMF_Context context, DataInputStream input) throws IOException { this.readFields(context, input, AbstractMessage.names); return this; } protected void writeFields(AMF_Context context, DataOutputStream output, UTF8[][] names) throws IOException { List<AMF3_Type> values = new Vector<AMF3_Type>(); List<Integer> flags = new Vector<Integer>(); for (UTF8[] name : names) { int flag = 0; for (int index = 0; index < name.length; index++) { AMF3_Type value = this.get(name[index]); if (value != null) { values.add(value); } } for (int index = name.length - 1; index >= 0; index--) { AMF3_Type value = this.get(name[index]); + flag <<= 1; if (value != null) { - flag = (flag << 1) | 1; + flag |= 1; } } flags.add(flag); } if (flags.isEmpty()) { flags.add(0x00); } this.writeFlags(context, output, flags); for (AMF3_Type value : values) { AMF3_Type.writeType(context, output, value); } } protected void readFields(AMF_Context context, DataInputStream input, UTF8[][] names) throws IOException { List<Integer> flags = this.readFlags(context, input); int index = 0; for (int flag : flags) { int reserved = 0; if (index < names.length) { for (UTF8 name : names[index++]) { if (((flag >> (reserved++)) & 1) == 1) { this.set(name, AMF3_Type.readType(context, input), true); } } } } } private void writeFlags(AMF_Context context, DataOutputStream output, List<Integer> flags) throws IOException { U8 ubyte = new U8(0x00); for (int index = 0; index < flags.size(); index++) { if (index == flags.size() - 1) { ubyte = new U8(flags.get(index)); } else { ubyte = new U8(flags.get(index) | 0x80); } ubyte.write(context, output); } } private List<Integer> readFlags(AMF_Context context, DataInputStream input) throws IOException { List<Integer> flags = new Vector<Integer>(); U8 ubyte = new U8(0x80); do { ubyte = new U8(context, input); flags.add(ubyte.get() & ~0x80); } while ((ubyte.get() & 0x80) == 0x80); return flags; } }
false
true
protected void writeFields(AMF_Context context, DataOutputStream output, UTF8[][] names) throws IOException { List<AMF3_Type> values = new Vector<AMF3_Type>(); List<Integer> flags = new Vector<Integer>(); for (UTF8[] name : names) { int flag = 0; for (int index = 0; index < name.length; index++) { AMF3_Type value = this.get(name[index]); if (value != null) { values.add(value); } } for (int index = name.length - 1; index >= 0; index--) { AMF3_Type value = this.get(name[index]); if (value != null) { flag = (flag << 1) | 1; } } flags.add(flag); } if (flags.isEmpty()) { flags.add(0x00); } this.writeFlags(context, output, flags); for (AMF3_Type value : values) { AMF3_Type.writeType(context, output, value); } }
protected void writeFields(AMF_Context context, DataOutputStream output, UTF8[][] names) throws IOException { List<AMF3_Type> values = new Vector<AMF3_Type>(); List<Integer> flags = new Vector<Integer>(); for (UTF8[] name : names) { int flag = 0; for (int index = 0; index < name.length; index++) { AMF3_Type value = this.get(name[index]); if (value != null) { values.add(value); } } for (int index = name.length - 1; index >= 0; index--) { AMF3_Type value = this.get(name[index]); flag <<= 1; if (value != null) { flag |= 1; } } flags.add(flag); } if (flags.isEmpty()) { flags.add(0x00); } this.writeFlags(context, output, flags); for (AMF3_Type value : values) { AMF3_Type.writeType(context, output, value); } }
diff --git a/src/tk/c4se/halt/ih31/nimunimu/controller/LoginController.java b/src/tk/c4se/halt/ih31/nimunimu/controller/LoginController.java index fb825dd..43de00c 100644 --- a/src/tk/c4se/halt/ih31/nimunimu/controller/LoginController.java +++ b/src/tk/c4se/halt/ih31/nimunimu/controller/LoginController.java @@ -1,81 +1,81 @@ /** * */ package tk.c4se.halt.ih31.nimunimu.controller; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import lombok.val; import tk.c4se.halt.ih31.nimunimu.exception.DBAccessException; import tk.c4se.halt.ih31.nimunimu.model.Member; import tk.c4se.halt.ih31.nimunimu.repository.SessionRepository; import tk.c4se.halt.ih31.nimunimu.validator.LoginValidator; /** * @author ne_Sachirou * */ @WebServlet("/login") public class LoginController extends Controller { /** * */ private static final long serialVersionUID = 41306642246590835L; private static final String JSP_PATH = "/resource/partial/login.jsp"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String urlRedirectAfterLogin = req.getParameter("redirect"); req.setAttribute("redirect", urlRedirectAfterLogin); forward(req, resp, "login", JSP_PATH); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (!checkCsrf(req, resp)) return; Map<String, Exception> errors = new LoginValidator().validate(req); if (!errors.isEmpty()) { showError(req, resp, errors); return; } final String id = req.getParameter("id").trim(); final String password = req.getParameter("password").trim(); Boolean isCorrectPassword = false; try { isCorrectPassword = Member.isCorrectPassword(id, password); } catch (DBAccessException e) { errors.put("DBAccess", e); } if (!isCorrectPassword) - errors.put("Login", new Exception("ID���p�X���[�h���قȂ�܂��B")); + errors.put("Login", new Exception("IDかパスワードが異なります。")); if (!errors.isEmpty()) { showError(req, resp, errors); return; } HttpSession session = new SessionRepository().getSession(req, true); session.setAttribute("memberId", id); resp.sendRedirect("/"); } private void showError(HttpServletRequest req, HttpServletResponse resp, Map<String, Exception> errors) throws ServletException, IOException { val id = req.getParameter("id"); val password = req.getParameter("password"); req.setAttribute("id", id); req.setAttribute("password", password); req.setAttribute("errors", errors); forward(req, resp, "login", JSP_PATH); } }
true
true
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (!checkCsrf(req, resp)) return; Map<String, Exception> errors = new LoginValidator().validate(req); if (!errors.isEmpty()) { showError(req, resp, errors); return; } final String id = req.getParameter("id").trim(); final String password = req.getParameter("password").trim(); Boolean isCorrectPassword = false; try { isCorrectPassword = Member.isCorrectPassword(id, password); } catch (DBAccessException e) { errors.put("DBAccess", e); } if (!isCorrectPassword) errors.put("Login", new Exception("ID���p�X���[�h���قȂ�܂��B")); if (!errors.isEmpty()) { showError(req, resp, errors); return; } HttpSession session = new SessionRepository().getSession(req, true); session.setAttribute("memberId", id); resp.sendRedirect("/"); }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (!checkCsrf(req, resp)) return; Map<String, Exception> errors = new LoginValidator().validate(req); if (!errors.isEmpty()) { showError(req, resp, errors); return; } final String id = req.getParameter("id").trim(); final String password = req.getParameter("password").trim(); Boolean isCorrectPassword = false; try { isCorrectPassword = Member.isCorrectPassword(id, password); } catch (DBAccessException e) { errors.put("DBAccess", e); } if (!isCorrectPassword) errors.put("Login", new Exception("IDかパスワードが異なります。")); if (!errors.isEmpty()) { showError(req, resp, errors); return; } HttpSession session = new SessionRepository().getSession(req, true); session.setAttribute("memberId", id); resp.sendRedirect("/"); }
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFile.java b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFile.java index 4734e075c..36b192d52 100644 --- a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFile.java +++ b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFile.java @@ -1,426 +1,427 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.core; import java.io.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.update.core.*; import org.eclipse.update.core.model.*; /** * Site on the File System */ public class SiteFile extends Site { /** * plugin entries */ private List pluginEntries = new ArrayList(0); /** * */ public ISiteContentConsumer createSiteContentConsumer(IFeature targetFeature) throws CoreException { SiteFileContentConsumer consumer = new SiteFileContentConsumer(targetFeature); consumer.setSite(this); return consumer; } /** */ public String getDefaultPackagedFeatureType() { return DEFAULT_INSTALLED_FEATURE_TYPE; } /* * @see ISite#install(IFeature, IVerifier, IProgressMonitor) */ public IFeatureReference install(IFeature sourceFeature, IVerificationListener verificationListener, IProgressMonitor progress) throws CoreException { return install(sourceFeature,null,verificationListener,progress); } /* * @see ISite#install(IFeature, IVerifier, IProgressMonitor) */ public IFeatureReference install(IFeature sourceFeature, IFeatureReference[] optionalfeatures, IVerificationListener verificationListener, IProgressMonitor progress) throws CoreException { if (sourceFeature == null) return null; // make sure we have an InstallMonitor InstallMonitor monitor; if (progress == null) monitor = null; else if (progress instanceof InstallMonitor) monitor = (InstallMonitor) progress; else monitor = new InstallMonitor(progress); // create new executable feature and install source content into it IFeature localFeature = createExecutableFeature(sourceFeature); IFeatureReference localFeatureReference = null; localFeatureReference = sourceFeature.install(localFeature, optionalfeatures, verificationListener, monitor); return localFeatureReference; } /* * @see ISite#install(IFeature,IFeatureContentConsumer, IVerifier,IVerificationLIstener, IProgressMonitor) */ public IFeatureReference install(IFeature sourceFeature, IFeatureReference[] optionalfeatures, IFeatureContentConsumer parentContentConsumer, IVerifier parentVerifier, IVerificationListener verificationListener, IProgressMonitor progress) throws InstallAbortedException, CoreException { if (sourceFeature == null) return null; // make sure we have an InstallMonitor InstallMonitor monitor; if (progress == null) monitor = null; else if (progress instanceof InstallMonitor) monitor = (InstallMonitor) progress; else monitor = new InstallMonitor(progress); // create new executable feature and install source content into it IFeature localFeature = createExecutableFeature(sourceFeature); parentContentConsumer.addChild(localFeature); // set the verifier IVerifier vr = sourceFeature.getFeatureContentProvider().getVerifier(); if (vr != null) vr.setParent(parentVerifier); IFeatureReference localFeatureReference = null; localFeatureReference = sourceFeature.install(localFeature, optionalfeatures, verificationListener, monitor); return localFeatureReference; } /* * @see ISite#remove(IFeature, IProgressMonitor) */ public void remove(IFeature feature, IProgressMonitor progress) throws CoreException { if (feature == null) { UpdateCore.warn("Feature to remove is null"); //$NON-NLS-1$ return; } ErrorRecoveryLog recoveryLog = ErrorRecoveryLog.getLog(); // make sure we have an InstallMonitor InstallMonitor monitor; if (progress == null) monitor = null; else if (progress instanceof InstallMonitor) monitor = (InstallMonitor) progress; else monitor = new InstallMonitor(progress); // Setup optional install handler InstallHandlerProxy handler = new InstallHandlerProxy(IInstallHandler.HANDLER_ACTION_UNINSTALL, feature, feature.getInstallHandlerEntry(), monitor); boolean success = false; Throwable originalException = null; try { // start log recoveryLog.open(ErrorRecoveryLog.START_REMOVE_LOG); aboutToRemove(feature); // log files have been downloaded recoveryLog.append(ErrorRecoveryLog.END_ABOUT_REMOVE); handler.uninstallInitiated(); // remove the feature and the plugins if they are not used and not activated // get the plugins from the feature IPluginEntry[] pluginsToRemove = getPluginEntriesOnlyReferencedBy(feature); if (monitor != null) { monitor.beginTask(Policy.bind("SiteFile.Removing") + feature.getLabel(), pluginsToRemove.length + 1); //$NON-NLS-1$ } // remove feature reference from the site ISiteFeatureReference[] featureReferences = getFeatureReferences(); if (featureReferences != null) { for (int indexRef = 0; indexRef < featureReferences.length; indexRef++) { IFeatureReference element = featureReferences[indexRef]; if (element.getVersionedIdentifier().equals(feature.getVersionedIdentifier())) { removeFeatureReferenceModel((FeatureReferenceModel) element); break; } } } if (InstallRegistry.getInstance().get("feature_"+feature.getVersionedIdentifier()) == null) { //$NON-NLS-1$ UpdateCore.log(Policy.bind("SiteFile.featureNotRemoved", feature.getVersionedIdentifier().toString()), null); //$NON-NLS-1$ //$NON-NLS-2$ } else { // remove the feature content ContentReference[] references = feature.getFeatureContentProvider().getFeatureEntryArchiveReferences(monitor); for (int i = 0; i < references.length; i++) { try { UpdateManagerUtils.removeFromFileSystem(references[i].asFile()); if (monitor != null) monitor.worked(1); } catch (IOException e) { throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemoveFeature", feature.getVersionedIdentifier().getIdentifier(), getURL().toExternalForm()), e); //$NON-NLS-1$ } } InstallRegistry.unregisterFeature(feature); } //finds the contentReferences for an IPluginEntry // and remove it for (int i = 0; i < pluginsToRemove.length; i++) { remove(feature, pluginsToRemove[i], monitor); } // remove any children feature IFeatureReference[] childrenRef = feature.getIncludedFeatureReferences(); for (int i = 0; i < childrenRef.length; i++) { IFeature childFeature = null; try { childFeature = childrenRef[i].getFeature(null); } catch (CoreException e) { UpdateCore.warn("Unable to retrieve feature to remove for:" + childrenRef[i]); //$NON-NLS-1$ } - if (childFeature != null) + // do not remove nested feature if configured (i.e. used by another configured feature) + if (childFeature != null && !getCurrentConfiguredSite().isConfigured(childFeature)) remove(childrenRef[i].getFeature(null), monitor); } // remove the feature from the site cache removeFeatureFromCache(feature.getURL()); handler.completeUninstall(); success = true; } catch (Throwable t) { originalException = t; } finally { Throwable newException = null; try { if (success) { // close the log recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); recoveryLog.delete(); } else { recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); } handler.uninstallCompleted(success); } catch (Throwable t) { newException = t; } if (originalException != null) // original exception wins throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), originalException); //$NON-NLS-1$ if (newException != null) throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), newException);//$NON-NLS-1$ } } /** * returns the download size * of the feature to be installed on the site. * If the site is <code>null</code> returns the maximum size * * If one plug-in entry has an unknown size. * then the download size is unknown. * */ public long getDownloadSizeFor(IFeature feature) { long result = 0; IPluginEntry[] entriesToInstall = feature.getPluginEntries(); IPluginEntry[] siteEntries = this.getPluginEntries(); entriesToInstall = UpdateManagerUtils.diff(entriesToInstall, siteEntries); //[18355] INonPluginEntry[] nonPluginEntriesToInstall = feature.getNonPluginEntries(); try { result = feature.getFeatureContentProvider().getDownloadSizeFor(entriesToInstall, nonPluginEntriesToInstall); } catch (CoreException e) { UpdateCore.warn(null, e); result = ContentEntryModel.UNKNOWN_SIZE; } return result; } /** * returns the download size * of the feature to be installed on the site. * If the site is <code>null</code> returns the maximum size * * If one plug-in entry has an unknown size. * then the download size is unknown. * * @see ISite#getDownloadSizeFor(IFeature) * */ public long getInstallSizeFor(IFeature feature) { long result = 0; try { List pluginsToInstall = new ArrayList(); // get all the plugins [17304] pluginsToInstall.addAll(Arrays.asList(feature.getPluginEntries())); IFeatureReference[] children = feature.getIncludedFeatureReferences(); IFeature currentFeature = null; for (int i = 0; i < children.length; i++) { currentFeature = children[i].getFeature(null); if (currentFeature != null) { pluginsToInstall.addAll(Arrays.asList(currentFeature.getPluginEntries())); } } IPluginEntry[] entriesToInstall = new IPluginEntry[0]; if (pluginsToInstall.size() > 0) { entriesToInstall = new IPluginEntry[pluginsToInstall.size()]; pluginsToInstall.toArray(entriesToInstall); } IPluginEntry[] siteEntries = this.getPluginEntries(); entriesToInstall = UpdateManagerUtils.diff(entriesToInstall, siteEntries); //[18355] INonPluginEntry[] nonPluginEntriesToInstall = feature.getNonPluginEntries(); result = feature.getFeatureContentProvider().getInstallSizeFor(entriesToInstall, nonPluginEntriesToInstall); } catch (CoreException e) { UpdateCore.warn(null, e); result = ContentEntryModel.UNKNOWN_SIZE; } return result; } /** * Adds a plugin entry * Either from parsing the file system or * installing a feature * * We cannot figure out the list of plugins by reading the Site.xml as * the archives tag are optionals */ public void addPluginEntry(IPluginEntry pluginEntry) { pluginEntries.add(pluginEntry); } public IPluginEntry[] getPluginEntries() { IPluginEntry[] result = new IPluginEntry[0]; if (!(pluginEntries == null || pluginEntries.isEmpty())) { result = new IPluginEntry[pluginEntries.size()]; pluginEntries.toArray(result); } return result; } public int getPluginEntryCount() { return getPluginEntries().length; } /** * */ private IFeature createExecutableFeature(IFeature sourceFeature) throws CoreException { IFeature result = null; IFeatureFactory factory = FeatureTypeFactory.getInstance().getFactory(DEFAULT_INSTALLED_FEATURE_TYPE); result = factory.createFeature(/*URL*/null, this, null); // at least set the version identifier to be the same ((FeatureModel) result).setFeatureIdentifier(sourceFeature.getVersionedIdentifier().getIdentifier()); ((FeatureModel) result).setFeatureVersion(sourceFeature.getVersionedIdentifier().getVersion().toString()); return result; } /** * */ private void remove(IFeature feature, IPluginEntry pluginEntry, InstallMonitor monitor) throws CoreException { if (pluginEntry == null) return; if (InstallRegistry.getInstance().get("plugin_"+pluginEntry.getVersionedIdentifier()) == null) { //$NON-NLS-1$ UpdateCore.log(Policy.bind("SiteFile.pluginNotRemoved", pluginEntry.getVersionedIdentifier().toString()), null); //$NON-NLS-1$ //$NON-NLS-2$ return; } ContentReference[] references = feature.getFeatureContentProvider().getPluginEntryArchiveReferences(pluginEntry, monitor); for (int i = 0; i < references.length; i++) { try { UpdateManagerUtils.removeFromFileSystem(references[i].asFile()); if (monitor != null) monitor.worked(1); } catch (IOException e) { throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemovePlugin", pluginEntry.getVersionedIdentifier().toString(), getURL().toExternalForm()), e);//$NON-NLS-1$ } } pluginEntries.remove(pluginEntry); InstallRegistry.unregisterPlugin(pluginEntry); } /* * */ private void aboutToRemove(IFeature feature) throws CoreException { ErrorRecoveryLog recoveryLog = ErrorRecoveryLog.getLog(); // if the recovery is not turned on if (!ErrorRecoveryLog.RECOVERY_ON) return; //logFeature if (feature != null) { // log feature URL ContentReference[] references = feature.getFeatureContentProvider().getFeatureEntryArchiveReferences(null); for (int i = 0; i < references.length; i++) { try { recoveryLog.appendPath(ErrorRecoveryLog.FEATURE_ENTRY, references[i].asFile().getAbsolutePath()); } catch (IOException e) { String id = UpdateCore.getPlugin().getBundle().getSymbolicName(); throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemoveFeature", feature.getVersionedIdentifier().getIdentifier(), getURL().toExternalForm()), e); //$NON-NLS-1$ } } // log pluginEntry URL IPluginEntry[] pluginsToRemove = getPluginEntriesOnlyReferencedBy(feature); for (int i = 0; i < pluginsToRemove.length; i++) { references = feature.getFeatureContentProvider().getPluginEntryArchiveReferences(pluginsToRemove[i], null); for (int j = 0; j < references.length; j++) { try { recoveryLog.appendPath(ErrorRecoveryLog.BUNDLE_JAR_ENTRY, references[j].asFile().getAbsolutePath()); } catch (IOException e) { throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemovePlugin", pluginsToRemove[i].getVersionedIdentifier().toString(), getURL().toExternalForm()), e); //$NON-NLS-1$ } } } } // call recursively for each children IFeatureReference[] childrenRef = feature.getIncludedFeatureReferences(); IFeature childFeature = null; for (int i = 0; i < childrenRef.length; i++) { try { childFeature = childrenRef[i].getFeature(null); } catch (CoreException e) { UpdateCore.warn("Unable to retrieve feature to remove for:" + childrenRef[i]); //$NON-NLS-1$ } aboutToRemove(childFeature); } } }
true
true
public void remove(IFeature feature, IProgressMonitor progress) throws CoreException { if (feature == null) { UpdateCore.warn("Feature to remove is null"); //$NON-NLS-1$ return; } ErrorRecoveryLog recoveryLog = ErrorRecoveryLog.getLog(); // make sure we have an InstallMonitor InstallMonitor monitor; if (progress == null) monitor = null; else if (progress instanceof InstallMonitor) monitor = (InstallMonitor) progress; else monitor = new InstallMonitor(progress); // Setup optional install handler InstallHandlerProxy handler = new InstallHandlerProxy(IInstallHandler.HANDLER_ACTION_UNINSTALL, feature, feature.getInstallHandlerEntry(), monitor); boolean success = false; Throwable originalException = null; try { // start log recoveryLog.open(ErrorRecoveryLog.START_REMOVE_LOG); aboutToRemove(feature); // log files have been downloaded recoveryLog.append(ErrorRecoveryLog.END_ABOUT_REMOVE); handler.uninstallInitiated(); // remove the feature and the plugins if they are not used and not activated // get the plugins from the feature IPluginEntry[] pluginsToRemove = getPluginEntriesOnlyReferencedBy(feature); if (monitor != null) { monitor.beginTask(Policy.bind("SiteFile.Removing") + feature.getLabel(), pluginsToRemove.length + 1); //$NON-NLS-1$ } // remove feature reference from the site ISiteFeatureReference[] featureReferences = getFeatureReferences(); if (featureReferences != null) { for (int indexRef = 0; indexRef < featureReferences.length; indexRef++) { IFeatureReference element = featureReferences[indexRef]; if (element.getVersionedIdentifier().equals(feature.getVersionedIdentifier())) { removeFeatureReferenceModel((FeatureReferenceModel) element); break; } } } if (InstallRegistry.getInstance().get("feature_"+feature.getVersionedIdentifier()) == null) { //$NON-NLS-1$ UpdateCore.log(Policy.bind("SiteFile.featureNotRemoved", feature.getVersionedIdentifier().toString()), null); //$NON-NLS-1$ //$NON-NLS-2$ } else { // remove the feature content ContentReference[] references = feature.getFeatureContentProvider().getFeatureEntryArchiveReferences(monitor); for (int i = 0; i < references.length; i++) { try { UpdateManagerUtils.removeFromFileSystem(references[i].asFile()); if (monitor != null) monitor.worked(1); } catch (IOException e) { throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemoveFeature", feature.getVersionedIdentifier().getIdentifier(), getURL().toExternalForm()), e); //$NON-NLS-1$ } } InstallRegistry.unregisterFeature(feature); } //finds the contentReferences for an IPluginEntry // and remove it for (int i = 0; i < pluginsToRemove.length; i++) { remove(feature, pluginsToRemove[i], monitor); } // remove any children feature IFeatureReference[] childrenRef = feature.getIncludedFeatureReferences(); for (int i = 0; i < childrenRef.length; i++) { IFeature childFeature = null; try { childFeature = childrenRef[i].getFeature(null); } catch (CoreException e) { UpdateCore.warn("Unable to retrieve feature to remove for:" + childrenRef[i]); //$NON-NLS-1$ } if (childFeature != null) remove(childrenRef[i].getFeature(null), monitor); } // remove the feature from the site cache removeFeatureFromCache(feature.getURL()); handler.completeUninstall(); success = true; } catch (Throwable t) { originalException = t; } finally { Throwable newException = null; try { if (success) { // close the log recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); recoveryLog.delete(); } else { recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); } handler.uninstallCompleted(success); } catch (Throwable t) { newException = t; } if (originalException != null) // original exception wins throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), originalException); //$NON-NLS-1$ if (newException != null) throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), newException);//$NON-NLS-1$ } }
public void remove(IFeature feature, IProgressMonitor progress) throws CoreException { if (feature == null) { UpdateCore.warn("Feature to remove is null"); //$NON-NLS-1$ return; } ErrorRecoveryLog recoveryLog = ErrorRecoveryLog.getLog(); // make sure we have an InstallMonitor InstallMonitor monitor; if (progress == null) monitor = null; else if (progress instanceof InstallMonitor) monitor = (InstallMonitor) progress; else monitor = new InstallMonitor(progress); // Setup optional install handler InstallHandlerProxy handler = new InstallHandlerProxy(IInstallHandler.HANDLER_ACTION_UNINSTALL, feature, feature.getInstallHandlerEntry(), monitor); boolean success = false; Throwable originalException = null; try { // start log recoveryLog.open(ErrorRecoveryLog.START_REMOVE_LOG); aboutToRemove(feature); // log files have been downloaded recoveryLog.append(ErrorRecoveryLog.END_ABOUT_REMOVE); handler.uninstallInitiated(); // remove the feature and the plugins if they are not used and not activated // get the plugins from the feature IPluginEntry[] pluginsToRemove = getPluginEntriesOnlyReferencedBy(feature); if (monitor != null) { monitor.beginTask(Policy.bind("SiteFile.Removing") + feature.getLabel(), pluginsToRemove.length + 1); //$NON-NLS-1$ } // remove feature reference from the site ISiteFeatureReference[] featureReferences = getFeatureReferences(); if (featureReferences != null) { for (int indexRef = 0; indexRef < featureReferences.length; indexRef++) { IFeatureReference element = featureReferences[indexRef]; if (element.getVersionedIdentifier().equals(feature.getVersionedIdentifier())) { removeFeatureReferenceModel((FeatureReferenceModel) element); break; } } } if (InstallRegistry.getInstance().get("feature_"+feature.getVersionedIdentifier()) == null) { //$NON-NLS-1$ UpdateCore.log(Policy.bind("SiteFile.featureNotRemoved", feature.getVersionedIdentifier().toString()), null); //$NON-NLS-1$ //$NON-NLS-2$ } else { // remove the feature content ContentReference[] references = feature.getFeatureContentProvider().getFeatureEntryArchiveReferences(monitor); for (int i = 0; i < references.length; i++) { try { UpdateManagerUtils.removeFromFileSystem(references[i].asFile()); if (monitor != null) monitor.worked(1); } catch (IOException e) { throw Utilities.newCoreException(Policy.bind("SiteFile.CannotRemoveFeature", feature.getVersionedIdentifier().getIdentifier(), getURL().toExternalForm()), e); //$NON-NLS-1$ } } InstallRegistry.unregisterFeature(feature); } //finds the contentReferences for an IPluginEntry // and remove it for (int i = 0; i < pluginsToRemove.length; i++) { remove(feature, pluginsToRemove[i], monitor); } // remove any children feature IFeatureReference[] childrenRef = feature.getIncludedFeatureReferences(); for (int i = 0; i < childrenRef.length; i++) { IFeature childFeature = null; try { childFeature = childrenRef[i].getFeature(null); } catch (CoreException e) { UpdateCore.warn("Unable to retrieve feature to remove for:" + childrenRef[i]); //$NON-NLS-1$ } // do not remove nested feature if configured (i.e. used by another configured feature) if (childFeature != null && !getCurrentConfiguredSite().isConfigured(childFeature)) remove(childrenRef[i].getFeature(null), monitor); } // remove the feature from the site cache removeFeatureFromCache(feature.getURL()); handler.completeUninstall(); success = true; } catch (Throwable t) { originalException = t; } finally { Throwable newException = null; try { if (success) { // close the log recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); recoveryLog.delete(); } else { recoveryLog.close(ErrorRecoveryLog.END_REMOVE_LOG); } handler.uninstallCompleted(success); } catch (Throwable t) { newException = t; } if (originalException != null) // original exception wins throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), originalException); //$NON-NLS-1$ if (newException != null) throw Utilities.newCoreException(Policy.bind("InstallHandler.error", feature.getLabel()), newException);//$NON-NLS-1$ } }
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java index 32507b490..b3b04f7a1 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java @@ -1,1005 +1,1005 @@ // ======================================================================== // Copyright (c) 2009 Intalio, Inc. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // Contributors: // Hugues Malphettes - initial API and implementation // ======================================================================== package org.eclipse.jetty.osgi.boot.internal.webapp; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import org.eclipse.jetty.deploy.AppProvider; import org.eclipse.jetty.deploy.ContextDeployer; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.deploy.WebAppDeployer; import org.eclipse.jetty.osgi.boot.JettyBootstrapActivator; import org.eclipse.jetty.osgi.boot.OSGiAppProvider; import org.eclipse.jetty.osgi.boot.OSGiWebappConstants; import org.eclipse.jetty.osgi.boot.internal.jsp.TldLocatableURLClassloader; import org.eclipse.jetty.osgi.boot.utils.BundleClassLoaderHelper; import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper; import org.eclipse.jetty.osgi.boot.utils.WebappRegistrationCustomizer; import org.eclipse.jetty.osgi.boot.utils.internal.DefaultBundleClassLoaderHelper; import org.eclipse.jetty.osgi.boot.utils.internal.DefaultFileLocatorHelper; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Bridges the jetty deployers with the OSGi lifecycle where applications are * managed inside OSGi-bundles. * <p> * This class should be called as a consequence of the activation of a new * service that is a ContextHandler.<br/> * This way the new webapps are exposed as OSGi services. * </p> * <p> * Helper methods to register a bundle that is a web-application or a context. * </p> * Limitations: * <ul> * <li>support for jarred webapps is somewhat limited.</li> * </ul> */ public class WebappRegistrationHelper { private static Logger __logger = Log.getLogger(WebappRegistrationHelper.class.getName()); private static boolean INITIALIZED = false; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. */ public static BundleClassLoaderHelper BUNDLE_CLASS_LOADER_HELPER = null; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. */ public static BundleFileLocatorHelper BUNDLE_FILE_LOCATOR_HELPER = null; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. * <p> * Several of those objects can be added here: For example we could have an optional fragment that setups * a specific implementation of JSF for the whole of jetty-osgi. * </p> */ public static Collection<WebappRegistrationCustomizer> JSP_REGISTRATION_HELPERS = new ArrayList<WebappRegistrationCustomizer>(); private Server _server; private ContextHandlerCollection _ctxtHandler; /** * this class loader loads the jars inside {$jetty.home}/lib/ext it is meant * as a migration path and for jars that are not OSGi ready. also gives * access to the jsp jars. */ // private URLClassLoader _libExtClassLoader; /** * This is the class loader that should be the parent classloader of any * webapp classloader. It is in fact the _libExtClassLoader with a trick to * let the TldScanner find the jars where the tld files are. */ private URLClassLoader _commonParentClassLoaderForWebapps; private DeploymentManager _deploymentManager; private OSGiAppProvider _provider; public WebappRegistrationHelper(Server server) { _server = server; staticInit(); } // Inject the customizing classes that might be defined in fragment bundles. private static synchronized void staticInit() { if (!INITIALIZED) { INITIALIZED = true; // setup the custom BundleClassLoaderHelper try { BUNDLE_CLASS_LOADER_HELPER = (BundleClassLoaderHelper)Class.forName(BundleClassLoaderHelper.CLASS_NAME).newInstance(); } catch (Throwable t) { // System.err.println("support for equinox and felix"); BUNDLE_CLASS_LOADER_HELPER = new DefaultBundleClassLoaderHelper(); } // setup the custom FileLocatorHelper try { BUNDLE_FILE_LOCATOR_HELPER = (BundleFileLocatorHelper)Class.forName(BundleFileLocatorHelper.CLASS_NAME).newInstance(); } catch (Throwable t) { // System.err.println("no jsp/jasper support"); BUNDLE_FILE_LOCATOR_HELPER = new DefaultFileLocatorHelper(); } } } /** * Removes quotes around system property values before we try to make them * into file pathes. */ public static String stripQuotesIfPresent(String filePath) { if (filePath == null) return null; if ((filePath.startsWith("\"") || filePath.startsWith("'")) && (filePath.endsWith("\"") || filePath.endsWith("'"))) return filePath.substring(1,filePath.length() - 1); return filePath; } /** * Look for the home directory of jetty as defined by the system property * 'jetty.home'. If undefined, look at the current bundle and uses its own * jettyhome folder for this feature. * <p> * Special case: inside eclipse-SDK:<br/> * If the bundle is jarred, see if we are inside eclipse-PDE itself. In that * case, look for the installation directory of eclipse-PDE, try to create a * jettyhome folder there and install the sample jettyhome folder at that * location. This makes the installation in eclipse-SDK easier. <br/> * This is a bit redundant with the work done by the jetty configuration * launcher. * </p> * * @param context * @throws Exception */ public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println(); - if (enUrls.hasMoreElements()) + if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (!bootBundleCanBeJarred && !_installLocation.isDirectory()) { String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = new File(jettyHome); URLClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); properties.put("jetty.home",jettyHome); properties.put("jetty.host",System.getProperty("jetty.host","")); properties.put("jetty.port",System.getProperty("jetty.port","8080")); properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile); if (!conffile.exists()) { __logger.warn("Unable to resolve the jetty/etc file " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { try { // Execute a Jetty configuration file XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile)); config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds()); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } } /** * Must be called after the server is configured. * * Locate the actual instance of the ContextDeployer and WebAppDeployer that * was created when configuring the server through jetty.xml. If there is no * such thing it won't be possible to deploy webapps from a context and we * throw IllegalStateExceptions. */ private void init() { // Get the context handler _ctxtHandler = (ContextHandlerCollection)_server.getChildHandlerByClass(ContextHandlerCollection.class); // get a deployerManager List<DeploymentManager> deployers = _server.getBeans(DeploymentManager.class); if (deployers != null && !deployers.isEmpty()) { _deploymentManager = deployers.get(0); for (AppProvider provider : _deploymentManager.getAppProviders()) { if (provider instanceof OSGiAppProvider) { _provider=(OSGiAppProvider)provider; break; } } if (_provider == null) { //create it on the fly with reasonable default values. try { _provider = new OSGiAppProvider(); _provider.setMonitoredDir( Resource.newResource(getDefaultOSGiContextsHome( new File(System.getProperty("jetty.home"))).toURI())); } catch (IOException e) { e.printStackTrace(); } _deploymentManager.addAppProvider(_provider); } } if (_ctxtHandler == null || _provider==null) throw new IllegalStateException("ERROR: No ContextHandlerCollection or OSGiAppProvider configured"); } /** * Deploy a new web application on the jetty server. * * @param bundle * The bundle * @param webappFolderPath * The path to the root of the webapp. Must be a path relative to * bundle; either an absolute path. * @param contextPath * The context path. Must start with "/" * @param extraClasspath * @param overrideBundleInstallLocation * @param webXmlPath * @param defaultWebXmlPath * TODO: parameter description * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerWebapplication(Bundle bundle, String webappFolderPath, String contextPath, String extraClasspath, String overrideBundleInstallLocation, String webXmlPath, String defaultWebXmlPath) throws Exception { File bundleInstall = overrideBundleInstallLocation == null?BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(bundle):new File( overrideBundleInstallLocation); File webapp = null; if (webappFolderPath != null && webappFolderPath.length() != 0 && !webappFolderPath.equals(".")) { if (webappFolderPath.startsWith("/") || webappFolderPath.startsWith("file:/")) { webapp = new File(webappFolderPath); } else { webapp = new File(bundleInstall,webappFolderPath); } } else { webapp = bundleInstall; } if (!webapp.exists()) { throw new IllegalArgumentException("Unable to locate " + webappFolderPath + " inside " + (bundleInstall != null?bundleInstall.getAbsolutePath():"unlocated bundle '" + bundle.getSymbolicName() + "'")); } return registerWebapplication(bundle,webapp,contextPath,extraClasspath,bundleInstall,webXmlPath,defaultWebXmlPath); } /** * TODO: refactor this into the createContext method of OSGiAppProvider. * @see WebAppDeployer#scan() * @param contributor * @param webapp * @param contextPath * @param extraClasspath * @param bundleInstall * @param webXmlPath * @param defaultWebXmlPath * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerWebapplication(Bundle contributor, File webapp, String contextPath, String extraClasspath, File bundleInstall, String webXmlPath, String defaultWebXmlPath) throws Exception { ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); String[] oldServerClasses = null; WebAppContext context = null; try { // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader composite = createWebappClassLoader(contributor); // configure with access to all jetty classes and also all the classes // that the contributor gives access to. Thread.currentThread().setContextClassLoader(composite); context = new WebAppContext(webapp.getAbsolutePath(),contextPath); context.setExtraClasspath(extraClasspath); if (webXmlPath != null && webXmlPath.length() != 0) { File webXml = null; if (webXmlPath.startsWith("/") || webXmlPath.startsWith("file:/")) { webXml = new File(webXmlPath); } else { webXml = new File(bundleInstall,webXmlPath); } if (webXml.exists()) { context.setDescriptor(webXml.getAbsolutePath()); } } if (defaultWebXmlPath == null || defaultWebXmlPath.length() == 0) { //use the one defined by the OSGiAppProvider. defaultWebXmlPath = _provider.getDefaultsDescriptor(); } if (defaultWebXmlPath != null && defaultWebXmlPath.length() != 0) { File defaultWebXml = null; if (defaultWebXmlPath.startsWith("/") || defaultWebXmlPath.startsWith("file:/")) { defaultWebXml = new File(webXmlPath); } else { defaultWebXml = new File(bundleInstall,defaultWebXmlPath); } if (defaultWebXml.exists()) { context.setDefaultsDescriptor(defaultWebXml.getAbsolutePath()); } } //other parameters that might be defines on the OSGiAppProvider: context.setParentLoaderPriority(_provider.isParentLoaderPriority()); configureWebAppContext(context,contributor); configureWebappClassLoader(contributor,context,composite); // @see // org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext) // during initialization of the webapp all the jetty packages are // visible // through the webapp classloader. oldServerClasses = context.getServerClasses(); context.setServerClasses(null); _provider.addContext(context); return context; } finally { if (context != null && oldServerClasses != null) { context.setServerClasses(oldServerClasses); } Thread.currentThread().setContextClassLoader(contextCl); } } /** * Stop a ContextHandler and remove it from the collection. * * @see ContextDeployer#undeploy * @param contextHandler * @throws Exception */ public void unregister(ContextHandler contextHandler) throws Exception { contextHandler.stop(); _ctxtHandler.removeHandler(contextHandler); } /** * @return The default folder in which the context files of the osgi bundles * are located and watched. Or null when the system property * "jetty.osgi.contexts.home" is not defined. * If the configuration file defines the OSGiAppProvider's context. * This will not be taken into account. */ File getDefaultOSGiContextsHome(File jettyHome) { String jettyContextsHome = System.getProperty("jetty.osgi.contexts.home"); if (jettyContextsHome != null) { File contextsHome = new File(jettyContextsHome); if (!contextsHome.exists() || !contextsHome.isDirectory()) { throw new IllegalArgumentException("the ${jetty.osgi.contexts.home} '" + jettyContextsHome + " must exist and be a folder"); } return contextsHome; } return new File(jettyHome, "/contexts"); } File getOSGiContextsHome() { return _provider.getContextXmlDirAsFile(); } /** * This type of registration relies on jetty's complete context xml file. * Context encompasses jndi and all other things. This makes the definition * of the webapp a lot more self-contained. * * @param contributor * @param contextFileRelativePath * @param extraClasspath * @param overrideBundleInstallLocation * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerContext(Bundle contributor, String contextFileRelativePath, String extraClasspath, String overrideBundleInstallLocation) throws Exception { File contextsHome = _provider.getContextXmlDirAsFile(); if (contextsHome != null) { File prodContextFile = new File(contextsHome,contributor.getSymbolicName() + "/" + contextFileRelativePath); if (prodContextFile.exists()) { return registerContext(contributor,prodContextFile,extraClasspath,overrideBundleInstallLocation); } } File contextFile = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation,contextFileRelativePath):new File( BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(contributor),contextFileRelativePath); if (contextFile.exists()) { return registerContext(contributor,contextFile,extraClasspath,overrideBundleInstallLocation); } else { if (contextFileRelativePath.startsWith("./")) { contextFileRelativePath = contextFileRelativePath.substring(1); } if (!contextFileRelativePath.startsWith("/")) { contextFileRelativePath = "/" + contextFileRelativePath; } if (overrideBundleInstallLocation == null) { URL contextURL = contributor.getEntry(contextFileRelativePath); if (contextURL != null) { return registerContext(contributor,contextURL.openStream(),extraClasspath,overrideBundleInstallLocation); } } else { JarFile zipFile = null; try { zipFile = new JarFile(overrideBundleInstallLocation); ZipEntry entry = zipFile.getEntry(contextFileRelativePath.substring(1)); return registerContext(contributor,zipFile.getInputStream(entry),extraClasspath,overrideBundleInstallLocation); } catch (Throwable t) { } finally { if (zipFile != null) try { zipFile.close(); } catch (IOException ioe) { } } } throw new IllegalArgumentException("Could not find the context " + "file " + contextFileRelativePath + " for the bundle " + contributor.getSymbolicName() + (overrideBundleInstallLocation != null?" using the install location " + overrideBundleInstallLocation:"")); } } /** * This type of registration relies on jetty's complete context xml file. * Context encompasses jndi and all other things. This makes the definition * of the webapp a lot more self-contained. * * @param webapp * @param contextPath * @param classInBundle * @throws Exception */ private ContextHandler registerContext(Bundle contributor, File contextFile, String extraClasspath, String overrideBundleInstallLocation) throws Exception { InputStream contextFileInputStream = null; try { contextFileInputStream = new BufferedInputStream(new FileInputStream(contextFile)); return registerContext(contributor,contextFileInputStream,extraClasspath,overrideBundleInstallLocation); } finally { if (contextFileInputStream != null) try { contextFileInputStream.close(); } catch (IOException ioe) { } } } /** * @param contributor * @param contextFileInputStream * @return The ContextHandler created and registered or null if it did not * happen. * @throws Exception */ private ContextHandler registerContext(Bundle contributor, InputStream contextFileInputStream, String extraClasspath, String overrideBundleInstallLocation) throws Exception { ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); String[] oldServerClasses = null; WebAppContext webAppContext = null; try { // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader composite = createWebappClassLoader(contributor); // configure with access to all jetty classes and also all the // classes // that the contributor gives access to. Thread.currentThread().setContextClassLoader(composite); ContextHandler context = createContextHandler(contributor,contextFileInputStream,extraClasspath,overrideBundleInstallLocation); if (context == null) { return null;// did not happen } // ok now register this webapp. we checked when we started jetty // that there // was at least one such handler for webapps. //the actual registration must happen via the new Deployment API. // _ctxtHandler.addHandler(context); configureWebappClassLoader(contributor,context,composite); if (context instanceof WebAppContext) { webAppContext = (WebAppContext)context; // @see // org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext) oldServerClasses = webAppContext.getServerClasses(); webAppContext.setServerClasses(null); } _provider.addContext(context); return context; } finally { if (webAppContext != null) { webAppContext.setServerClasses(oldServerClasses); } Thread.currentThread().setContextClassLoader(contextCl); } } /** * TODO: right now only the jetty-jsp bundle is scanned for common taglibs. * Should support a way to plug more bundles that contain taglibs. * * The jasper TldScanner expects a URLClassloader to parse a jar for the * /META-INF/*.tld it may contain. We place the bundles that we know contain * such tag-libraries. Please note that it will work if and only if the * bundle is a jar (!) Currently we just hardcode the bundle that contains * the jstl implemenation. * * A workaround when the tld cannot be parsed with this method is to copy * and paste it inside the WEB-INF of the webapplication where it is used. * * Support only 2 types of packaging for the bundle: - the bundle is a jar * (recommended for runtime.) - the bundle is a folder and contain jars in * the root and/or in the lib folder (nice for PDE developement situations) * Unsupported: the bundle is a jar that embeds more jars. * * @return * @throws Exception */ private URL[] getJarsWithTlds() throws Exception { ArrayList<URL> res = new ArrayList<URL>(); for (WebappRegistrationCustomizer regCustomizer : JSP_REGISTRATION_HELPERS) { URL[] urls = regCustomizer.getJarsWithTlds(_provider, BUNDLE_FILE_LOCATOR_HELPER); for (URL url : urls) { if (!res.contains(url)) res.add(url); } } if (!res.isEmpty()) return res.toArray(new URL[res.size()]); else return null; } /** * Applies the properties of WebAppDeployer as defined in jetty.xml. * * @see {WebAppDeployer#scan} around the comment * <code>// configure it</code> */ protected void configureWebAppContext(WebAppContext wah, Bundle contributor) { // rfc66 wah.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,contributor.getBundleContext()); //spring-dm-1.2.1 looks for the BundleContext as a different attribute. //not a spec... but if we want to support //org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext //then we need to do this to: wah.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(), contributor.getBundleContext()); } /** * @See {@link ContextDeployer#scan} * @param contextFile * @return */ protected ContextHandler createContextHandler(Bundle bundle, File contextFile, String extraClasspath, String overrideBundleInstallLocation) { try { return createContextHandler(bundle,new BufferedInputStream(new FileInputStream(contextFile)),extraClasspath,overrideBundleInstallLocation); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } /** * @See {@link ContextDeployer#scan} * @param contextFile * @return */ @SuppressWarnings("unchecked") protected ContextHandler createContextHandler(Bundle bundle, InputStream contextInputStream, String extraClasspath, String overrideBundleInstallLocation) { /* * Do something identical to what the ContextProvider would have done: * XmlConfiguration xmlConfiguration=new * XmlConfiguration(resource.getURL()); HashMap properties = new * HashMap(); properties.put("Server", _contexts.getServer()); if * (_configMgr!=null) properties.putAll(_configMgr.getProperties()); * * xmlConfiguration.setProperties(properties); ContextHandler * context=(ContextHandler)xmlConfiguration.configure(); * context.setAttributes(new AttributesMap(_contextAttributes)); */ try { XmlConfiguration xmlConfiguration = new XmlConfiguration(contextInputStream); HashMap properties = new HashMap(); properties.put("Server",_server); // insert the bundle's location as a property. setThisBundleHomeProperty(bundle,properties,overrideBundleInstallLocation); xmlConfiguration.setProperties(properties); ContextHandler context = (ContextHandler)xmlConfiguration.configure(); if (context instanceof WebAppContext) { ((WebAppContext)context).setExtraClasspath(extraClasspath); ((WebAppContext)context).setParentLoaderPriority(_provider.isParentLoaderPriority()); if (_provider.getDefaultsDescriptor() != null && _provider.getDefaultsDescriptor().length() != 0) { ((WebAppContext)context).setDefaultsDescriptor(_provider.getDefaultsDescriptor()); } } // rfc-66: context.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,bundle.getBundleContext()); //spring-dm-1.2.1 looks for the BundleContext as a different attribute. //not a spec... but if we want to support //org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext //then we need to do this to: context.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(), bundle.getBundleContext()); return context; } catch (FileNotFoundException e) { return null; } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (contextInputStream != null) try { contextInputStream.close(); } catch (IOException ioe) { } } return null; } /** * Configure a classloader onto the context. If the context is a * WebAppContext, build a WebAppClassLoader that has access to all the jetty * classes thanks to the classloader of the JettyBootStrapper bundle and * also has access to the classloader of the bundle that defines this * context. * <p> * If the context is not a WebAppContext, same but with a simpler * URLClassLoader. Note that the URLClassLoader is pretty much fake: it * delegate all actual classloading to the parent classloaders. * </p> * <p> * The URL[] returned by the URLClassLoader create contained specifically * the jars that some j2ee tools expect and look into. For example the jars * that contain tld files for jasper's jstl support. * </p> * <p> * Also as the jars in the lib folder and the classes in the classes folder * might already be in the OSGi classloader we filter them out of the * WebAppClassLoader * </p> * * @param context * @param contributor * @param webapp * @param contextPath * @param classInBundle * @throws Exception */ protected void configureWebappClassLoader(Bundle contributor, ContextHandler context, OSGiWebappClassLoader webappClassLoader) throws Exception { if (context instanceof WebAppContext) { WebAppContext webappCtxt = (WebAppContext)context; context.setClassLoader(webappClassLoader); webappClassLoader.setWebappContext(webappCtxt); } else { context.setClassLoader(webappClassLoader); } } /** * No matter what the type of webapp, we create a WebappClassLoader. */ protected OSGiWebappClassLoader createWebappClassLoader(Bundle contributor) throws Exception { // we use a temporary WebAppContext object. // if this is a real webapp we will set it on it a bit later: once we // know. OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(_commonParentClassLoaderForWebapps,new WebAppContext(),contributor); return webappClassLoader; } /** * Set the property &quot;this.bundle.install&quot; to point to the location * of the bundle. Useful when <SystemProperty name="this.bundle.home"/> is * used. */ private void setThisBundleHomeProperty(Bundle bundle, HashMap<String, Object> properties, String overrideBundleInstallLocation) { try { File location = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation):BUNDLE_FILE_LOCATOR_HELPER .getBundleInstallLocation(bundle); properties.put("this.bundle.install",location.getCanonicalPath()); } catch (Throwable t) { System.err.println("Unable to set 'this.bundle.install' " + " for the bundle " + bundle.getSymbolicName()); t.printStackTrace(); } } }
true
true
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println(); if (enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (!bootBundleCanBeJarred && !_installLocation.isDirectory()) { String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = new File(jettyHome); URLClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); properties.put("jetty.home",jettyHome); properties.put("jetty.host",System.getProperty("jetty.host","")); properties.put("jetty.port",System.getProperty("jetty.port","8080")); properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile); if (!conffile.exists()) { __logger.warn("Unable to resolve the jetty/etc file " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { try { // Execute a Jetty configuration file XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile)); config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds()); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } }
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false);System.err.println(); if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (!bootBundleCanBeJarred && !_installLocation.isDirectory()) { String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = new File(jettyHome); URLClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoaderHelper(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); properties.put("jetty.home",jettyHome); properties.put("jetty.host",System.getProperty("jetty.host","")); properties.put("jetty.port",System.getProperty("jetty.port","8080")); properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = etcFile.startsWith("/")?new File(etcFile):new File(jettyHomeF,etcFile); if (!conffile.exists()) { __logger.warn("Unable to resolve the jetty/etc file " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { try { // Execute a Jetty configuration file XmlConfiguration config = new XmlConfiguration(new FileInputStream(conffile)); config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,getJarsWithTlds()); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } }
diff --git a/slim3demo/src/slim3/demo/controller/AppRouter.java b/slim3demo/src/slim3/demo/controller/AppRouter.java index 68b6becf..e9c09649 100644 --- a/slim3demo/src/slim3/demo/controller/AppRouter.java +++ b/slim3demo/src/slim3/demo/controller/AppRouter.java @@ -1,11 +1,11 @@ package slim3.demo.controller; import org.slim3.controller.router.RouterImpl; public class AppRouter extends RouterImpl { public AppRouter() { - addRouting("/_ah/mail/{address}", "/mail/receive?address=${address}"); + addRouting("/_ah/mail/{address}", "/mail/receive?address={address}"); } }
true
true
public AppRouter() { addRouting("/_ah/mail/{address}", "/mail/receive?address=${address}"); }
public AppRouter() { addRouting("/_ah/mail/{address}", "/mail/receive?address={address}"); }
diff --git a/comic-manager/src/main/java/org/lazydog/comic/manager/phaselistener/Authenticate.java b/comic-manager/src/main/java/org/lazydog/comic/manager/phaselistener/Authenticate.java index 9556d68..4b2dc01 100644 --- a/comic-manager/src/main/java/org/lazydog/comic/manager/phaselistener/Authenticate.java +++ b/comic-manager/src/main/java/org/lazydog/comic/manager/phaselistener/Authenticate.java @@ -1,101 +1,101 @@ package org.lazydog.comic.manager.phaselistener; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import javax.naming.Context; import javax.naming.InitialContext; import org.lazydog.comic.ComicService; import org.lazydog.comic.model.UserPreference; import org.lazydog.comic.manager.utility.SessionKey; import org.lazydog.comic.manager.utility.SessionUtility; import org.lazydog.entry.EntryService; import org.lazydog.repository.criterion.ComparisonOperation; import org.lazydog.repository.Criteria; /** * Authenticate phase listener. * * @author Ron Rickard */ public class Authenticate implements PhaseListener { private static final long serialVersionUID = 1L; /** * Process after the phase. * * @param phaseEvent the phase event. */ @Override public void afterPhase(PhaseEvent phaseEvent) { try { // Check if the user is logged in and not stored on the session. if (FacesContext.getCurrentInstance().getExternalContext().getRemoteUser() != null && SessionUtility.getValue(SessionKey.UUID, String.class) == null) { // Declare. ComicService comicService; Context context; Criteria<UserPreference> criteria; EntryService entryService; String username; UserPreference userPreference; String uuid; // Get the comic service and entry service. context = new InitialContext(); // TODO: once this application is upgraded to JEE6, the lookup can use the non-FQ JNDI name. - comicService = (ComicService)context.lookup("java:global/org.lazydog.comic_comic-manager-ear_ear_1.7/comic-service-ejb-1.7/ejb/ComicService"); + comicService = (ComicService)context.lookup("java:global/comic-manager-ear-1.8/comic-service-ejb-1.8/ejb/ComicService"); entryService = (EntryService)context.lookup("ejb/EntryService"); // Get the username. username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); // Get the UUID. uuid = entryService.getUserProfile(username).getUuid(); // Put the UUID on the session. SessionUtility.putValue(SessionKey.UUID, uuid); // Get the user preference. criteria = comicService.getCriteria(UserPreference.class); criteria.add(ComparisonOperation.eq("uuid", uuid)); userPreference = comicService.find(UserPreference.class, criteria); // Put the user preference on the session. SessionUtility.putValue(SessionKey.USER_PREFERENCE, userPreference); } } catch(Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unable to authenticate user.")); } } /** * Process before the phase. * * @param phaseEvent the phase event. */ @Override public void beforePhase(PhaseEvent phaseEvent) { } /** * Get the phase ID. * * @return the phase ID (restore view.) */ @Override public PhaseId getPhaseId() { return PhaseId.RESTORE_VIEW; } }
true
true
public void afterPhase(PhaseEvent phaseEvent) { try { // Check if the user is logged in and not stored on the session. if (FacesContext.getCurrentInstance().getExternalContext().getRemoteUser() != null && SessionUtility.getValue(SessionKey.UUID, String.class) == null) { // Declare. ComicService comicService; Context context; Criteria<UserPreference> criteria; EntryService entryService; String username; UserPreference userPreference; String uuid; // Get the comic service and entry service. context = new InitialContext(); // TODO: once this application is upgraded to JEE6, the lookup can use the non-FQ JNDI name. comicService = (ComicService)context.lookup("java:global/org.lazydog.comic_comic-manager-ear_ear_1.7/comic-service-ejb-1.7/ejb/ComicService"); entryService = (EntryService)context.lookup("ejb/EntryService"); // Get the username. username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); // Get the UUID. uuid = entryService.getUserProfile(username).getUuid(); // Put the UUID on the session. SessionUtility.putValue(SessionKey.UUID, uuid); // Get the user preference. criteria = comicService.getCriteria(UserPreference.class); criteria.add(ComparisonOperation.eq("uuid", uuid)); userPreference = comicService.find(UserPreference.class, criteria); // Put the user preference on the session. SessionUtility.putValue(SessionKey.USER_PREFERENCE, userPreference); } } catch(Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unable to authenticate user.")); } }
public void afterPhase(PhaseEvent phaseEvent) { try { // Check if the user is logged in and not stored on the session. if (FacesContext.getCurrentInstance().getExternalContext().getRemoteUser() != null && SessionUtility.getValue(SessionKey.UUID, String.class) == null) { // Declare. ComicService comicService; Context context; Criteria<UserPreference> criteria; EntryService entryService; String username; UserPreference userPreference; String uuid; // Get the comic service and entry service. context = new InitialContext(); // TODO: once this application is upgraded to JEE6, the lookup can use the non-FQ JNDI name. comicService = (ComicService)context.lookup("java:global/comic-manager-ear-1.8/comic-service-ejb-1.8/ejb/ComicService"); entryService = (EntryService)context.lookup("ejb/EntryService"); // Get the username. username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); // Get the UUID. uuid = entryService.getUserProfile(username).getUuid(); // Put the UUID on the session. SessionUtility.putValue(SessionKey.UUID, uuid); // Get the user preference. criteria = comicService.getCriteria(UserPreference.class); criteria.add(ComparisonOperation.eq("uuid", uuid)); userPreference = comicService.find(UserPreference.class, criteria); // Put the user preference on the session. SessionUtility.putValue(SessionKey.USER_PREFERENCE, userPreference); } } catch(Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unable to authenticate user.")); } }
diff --git a/src/com/axelby/podax/PodcastDetailActivity.java b/src/com/axelby/podax/PodcastDetailActivity.java index 54fbe75..0b429a8 100644 --- a/src/com/axelby/podax/PodcastDetailActivity.java +++ b/src/com/axelby/podax/PodcastDetailActivity.java @@ -1,203 +1,206 @@ package com.axelby.podax; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class PodcastDetailActivity extends Activity { Podcast _podcast; TextView _titleView; TextView _subscriptionTitleView; WebView _descriptionView; Button _queueButton; TextView _queuePosition; ImageButton _restartButton; ImageButton _rewindButton; ImageButton _playButton; ImageButton _forwardButton; ImageButton _skipToEndButton; SeekBar _seekbar; boolean _seekbar_dragging; TextView _position; TextView _duration; DBAdapter _dbAdapter; PodaxApp _app; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.podcast_detail); _dbAdapter = DBAdapter.getInstance(this); _app = PodaxApp.getApp(); Intent intent = this.getIntent(); if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) _podcast = _dbAdapter.loadPodcast(intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1)); else _podcast = _dbAdapter.loadLastPlayedPodcast(); if (_podcast == null) { finish(); startActivity(new Intent(this, QueueActivity.class)); } _titleView = (TextView)findViewById(R.id.title); _titleView.setText(_podcast.getTitle()); _subscriptionTitleView = (TextView)findViewById(R.id.subscription_title); _subscriptionTitleView.setText(_podcast.getSubscription().getTitle()); _descriptionView = (WebView)findViewById(R.id.description); String html = _podcast.getDescription(); html = "<html><body style=\"background:black;color:white\">" + html + "</body></html>"; _descriptionView.loadData(html, "text/html", "utf-8"); _queuePosition = (TextView)findViewById(R.id.queue_position); _queueButton = (Button)findViewById(R.id.queue_btn); updateQueueViews(); _queueButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (_podcast.getQueuePosition() == null) _dbAdapter.addPodcastToQueue(_podcast.getId()); else _dbAdapter.removePodcastFromQueue(_podcast.getId()); _podcast = _dbAdapter.loadPodcast(_podcast.getId()); updateQueueViews(); } }); _restartButton = (ImageButton)findViewById(R.id.restart_btn); _restartButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.restart(); } }); _rewindButton = (ImageButton)findViewById(R.id.rewind_btn); _rewindButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipBack(); } }); _playButton = (ImageButton)findViewById(R.id.play_btn); _playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { - _app.play(_podcast); + if (PlayerService.isPlaying()) + _app.pause(); + else + _app.play(_podcast); } }); _forwardButton = (ImageButton)findViewById(R.id.forward_btn); _forwardButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipForward(); } }); _skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn); _skipToEndButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipToEnd(); } }); _seekbar = (SeekBar)findViewById(R.id.seekbar); _seekbar.setMax(_podcast.getDuration()); _seekbar.setProgress(_podcast.getLastPosition()); _seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { _position.setText(PlayerActivity.getTimeString(progress)); } public void onStartTrackingTouch(SeekBar seekBar) { _seekbar_dragging = true; } public void onStopTrackingTouch(SeekBar seekBar) { _seekbar_dragging = false; _app.skipTo(seekBar.getProgress() / 1000); } }); _seekbar_dragging = false; _position = (TextView)findViewById(R.id.position); _position.setText(PlayerActivity.getTimeString(_podcast.getLastPosition())); _duration = (TextView)findViewById(R.id.duration); _duration.setText(PlayerActivity.getTimeString(_podcast.getDuration())); PlayerActivity.injectPlayerFooter(this); updatePlayerControls(true); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { updatePlayerControls(false); handler.postDelayed(this, 250); } }, 250); } boolean _controlsEnabled = true; private void updatePlayerControls(boolean force) { Podcast p = DBAdapter.getInstance(this).loadLastPlayedPodcast(); if (PlayerService.isPlaying() && p.getId() == _podcast.getId()) { if (!_seekbar_dragging) { _position.setText(PlayerActivity.getTimeString(p.getLastPosition())); _duration.setText(PlayerActivity.getTimeString(p.getDuration())); _seekbar.setProgress(p.getLastPosition()); } if (!force && _controlsEnabled == true) return; _playButton.setImageResource(android.R.drawable.ic_media_pause); _restartButton.setEnabled(true); _rewindButton.setEnabled(true); _forwardButton.setEnabled(true); _skipToEndButton.setEnabled(true); _seekbar.setEnabled(true); _controlsEnabled = true; } else { if (!force && !_controlsEnabled) return; _playButton.setImageResource(android.R.drawable.ic_media_play); _restartButton.setEnabled(false); _rewindButton.setEnabled(false); _forwardButton.setEnabled(false); _skipToEndButton.setEnabled(false); _seekbar.setEnabled(false); _controlsEnabled = false; } } private void updateQueueViews() { if (_podcast.getQueuePosition() == null) { _queueButton.setText(R.string.add_to_queue); _queuePosition.setText(""); } else { _queueButton.setText(R.string.remove_from_queue); _queuePosition.setText("#" + String.valueOf(_podcast.getQueuePosition() + 1) + " in queue"); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.podcast_detail); _dbAdapter = DBAdapter.getInstance(this); _app = PodaxApp.getApp(); Intent intent = this.getIntent(); if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) _podcast = _dbAdapter.loadPodcast(intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1)); else _podcast = _dbAdapter.loadLastPlayedPodcast(); if (_podcast == null) { finish(); startActivity(new Intent(this, QueueActivity.class)); } _titleView = (TextView)findViewById(R.id.title); _titleView.setText(_podcast.getTitle()); _subscriptionTitleView = (TextView)findViewById(R.id.subscription_title); _subscriptionTitleView.setText(_podcast.getSubscription().getTitle()); _descriptionView = (WebView)findViewById(R.id.description); String html = _podcast.getDescription(); html = "<html><body style=\"background:black;color:white\">" + html + "</body></html>"; _descriptionView.loadData(html, "text/html", "utf-8"); _queuePosition = (TextView)findViewById(R.id.queue_position); _queueButton = (Button)findViewById(R.id.queue_btn); updateQueueViews(); _queueButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (_podcast.getQueuePosition() == null) _dbAdapter.addPodcastToQueue(_podcast.getId()); else _dbAdapter.removePodcastFromQueue(_podcast.getId()); _podcast = _dbAdapter.loadPodcast(_podcast.getId()); updateQueueViews(); } }); _restartButton = (ImageButton)findViewById(R.id.restart_btn); _restartButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.restart(); } }); _rewindButton = (ImageButton)findViewById(R.id.rewind_btn); _rewindButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipBack(); } }); _playButton = (ImageButton)findViewById(R.id.play_btn); _playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.play(_podcast); } }); _forwardButton = (ImageButton)findViewById(R.id.forward_btn); _forwardButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipForward(); } }); _skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn); _skipToEndButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipToEnd(); } }); _seekbar = (SeekBar)findViewById(R.id.seekbar); _seekbar.setMax(_podcast.getDuration()); _seekbar.setProgress(_podcast.getLastPosition()); _seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { _position.setText(PlayerActivity.getTimeString(progress)); } public void onStartTrackingTouch(SeekBar seekBar) { _seekbar_dragging = true; } public void onStopTrackingTouch(SeekBar seekBar) { _seekbar_dragging = false; _app.skipTo(seekBar.getProgress() / 1000); } }); _seekbar_dragging = false; _position = (TextView)findViewById(R.id.position); _position.setText(PlayerActivity.getTimeString(_podcast.getLastPosition())); _duration = (TextView)findViewById(R.id.duration); _duration.setText(PlayerActivity.getTimeString(_podcast.getDuration())); PlayerActivity.injectPlayerFooter(this); updatePlayerControls(true); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { updatePlayerControls(false); handler.postDelayed(this, 250); } }, 250); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.podcast_detail); _dbAdapter = DBAdapter.getInstance(this); _app = PodaxApp.getApp(); Intent intent = this.getIntent(); if (intent.hasExtra(Constants.EXTRA_PODCAST_ID)) _podcast = _dbAdapter.loadPodcast(intent.getIntExtra(Constants.EXTRA_PODCAST_ID, -1)); else _podcast = _dbAdapter.loadLastPlayedPodcast(); if (_podcast == null) { finish(); startActivity(new Intent(this, QueueActivity.class)); } _titleView = (TextView)findViewById(R.id.title); _titleView.setText(_podcast.getTitle()); _subscriptionTitleView = (TextView)findViewById(R.id.subscription_title); _subscriptionTitleView.setText(_podcast.getSubscription().getTitle()); _descriptionView = (WebView)findViewById(R.id.description); String html = _podcast.getDescription(); html = "<html><body style=\"background:black;color:white\">" + html + "</body></html>"; _descriptionView.loadData(html, "text/html", "utf-8"); _queuePosition = (TextView)findViewById(R.id.queue_position); _queueButton = (Button)findViewById(R.id.queue_btn); updateQueueViews(); _queueButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (_podcast.getQueuePosition() == null) _dbAdapter.addPodcastToQueue(_podcast.getId()); else _dbAdapter.removePodcastFromQueue(_podcast.getId()); _podcast = _dbAdapter.loadPodcast(_podcast.getId()); updateQueueViews(); } }); _restartButton = (ImageButton)findViewById(R.id.restart_btn); _restartButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.restart(); } }); _rewindButton = (ImageButton)findViewById(R.id.rewind_btn); _rewindButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipBack(); } }); _playButton = (ImageButton)findViewById(R.id.play_btn); _playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (PlayerService.isPlaying()) _app.pause(); else _app.play(_podcast); } }); _forwardButton = (ImageButton)findViewById(R.id.forward_btn); _forwardButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipForward(); } }); _skipToEndButton = (ImageButton)findViewById(R.id.skiptoend_btn); _skipToEndButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { _app.skipToEnd(); } }); _seekbar = (SeekBar)findViewById(R.id.seekbar); _seekbar.setMax(_podcast.getDuration()); _seekbar.setProgress(_podcast.getLastPosition()); _seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { _position.setText(PlayerActivity.getTimeString(progress)); } public void onStartTrackingTouch(SeekBar seekBar) { _seekbar_dragging = true; } public void onStopTrackingTouch(SeekBar seekBar) { _seekbar_dragging = false; _app.skipTo(seekBar.getProgress() / 1000); } }); _seekbar_dragging = false; _position = (TextView)findViewById(R.id.position); _position.setText(PlayerActivity.getTimeString(_podcast.getLastPosition())); _duration = (TextView)findViewById(R.id.duration); _duration.setText(PlayerActivity.getTimeString(_podcast.getDuration())); PlayerActivity.injectPlayerFooter(this); updatePlayerControls(true); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { updatePlayerControls(false); handler.postDelayed(this, 250); } }, 250); }
diff --git a/test/src/test/java/hudson/logging/LogRecorderManagerTest.java b/test/src/test/java/hudson/logging/LogRecorderManagerTest.java index af8cb977d..b7e2b1c9a 100644 --- a/test/src/test/java/hudson/logging/LogRecorderManagerTest.java +++ b/test/src/test/java/hudson/logging/LogRecorderManagerTest.java @@ -1,53 +1,53 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.logging; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.Url; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlForm; import java.util.logging.Logger; import java.util.logging.Level; /** * @author Kohsuke Kawaguchi */ public class LogRecorderManagerTest extends HudsonTestCase { /** * Makes sure that the logger configuration works. */ @Url("http://d.hatena.ne.jp/ssogabe/20090101/1230744150") public void testLoggerConfig() throws Exception { Logger logger = Logger.getLogger("foo.bar.zot"); - HtmlPage page = new WebClient().goTo("log/all"); + HtmlPage page = new WebClient().goTo("log/levels"); HtmlForm form = page.getFormByName("configLogger"); form.getInputByName("name").setValueAttribute("foo.bar.zot"); form.getSelectByName("level").getOptionByValue("finest").setSelected(true); submit(form); assertEquals(logger.getLevel(), Level.FINEST); } }
true
true
public void testLoggerConfig() throws Exception { Logger logger = Logger.getLogger("foo.bar.zot"); HtmlPage page = new WebClient().goTo("log/all"); HtmlForm form = page.getFormByName("configLogger"); form.getInputByName("name").setValueAttribute("foo.bar.zot"); form.getSelectByName("level").getOptionByValue("finest").setSelected(true); submit(form); assertEquals(logger.getLevel(), Level.FINEST); }
public void testLoggerConfig() throws Exception { Logger logger = Logger.getLogger("foo.bar.zot"); HtmlPage page = new WebClient().goTo("log/levels"); HtmlForm form = page.getFormByName("configLogger"); form.getInputByName("name").setValueAttribute("foo.bar.zot"); form.getSelectByName("level").getOptionByValue("finest").setSelected(true); submit(form); assertEquals(logger.getLevel(), Level.FINEST); }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/PayloadFactoryMediatorDeserializer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/PayloadFactoryMediatorDeserializer.java index fcbde481d..1f449c327 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/PayloadFactoryMediatorDeserializer.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/PayloadFactoryMediatorDeserializer.java @@ -1,73 +1,75 @@ package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer; import org.apache.synapse.mediators.AbstractMediator; import org.apache.synapse.mediators.transform.Argument; import org.apache.synapse.util.xpath.SynapseXPath; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.jaxen.JaxenException; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediaType; import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgument; import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgumentType; import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryMediator; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.*; public class PayloadFactoryMediatorDeserializer extends AbstractEsbNodeDeserializer<AbstractMediator, PayloadFactoryMediator>{ private static String XML_LITERAL = "xml"; private static String JSON_LITERAL = "json"; public PayloadFactoryMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.transform.PayloadFactoryMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.transform.PayloadFactoryMediator payloadFactoryMediator = (org.apache.synapse.mediators.transform.PayloadFactoryMediator)mediator; PayloadFactoryMediator visualPayloadFactoryMediator = (PayloadFactoryMediator) DeserializerUtils.createNode(part, EsbElementTypes.PayloadFactoryMediator_3597); setElementToEdit(visualPayloadFactoryMediator); executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__FORMAT, payloadFactoryMediator.getFormat()); - if(payloadFactoryMediator.getType().equals(XML_LITERAL)){ - executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.XML); - }else if(payloadFactoryMediator.getType().equals(JSON_LITERAL)){ - executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.JSON); + if (payloadFactoryMediator.getType() != null) { + if(payloadFactoryMediator.getType().equals(XML_LITERAL)){ + executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.XML); + } else if(payloadFactoryMediator.getType().equals(JSON_LITERAL)){ + executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.JSON); + } } EList<PayloadFactoryArgument> arguments=new BasicEList<PayloadFactoryArgument>(); for(Argument argument: payloadFactoryMediator.getXPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getExpression()!=null){ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(argument.getExpression())); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.XML); }else{ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_VALUE, argument.getValue()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.VALUE); } arguments.add(payloadFactoryArgument); } for(Argument argument: payloadFactoryMediator.getJsonPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getJsonPath()!=null){ try { SynapseXPath xpath = new SynapseXPath(argument.getJsonPath().getJsonPathExpression()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(xpath)); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.JSON); arguments.add(payloadFactoryArgument); } catch (Exception e) { e.printStackTrace(); } } } executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__ARGS, arguments); return visualPayloadFactoryMediator; } }
true
true
public PayloadFactoryMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.transform.PayloadFactoryMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.transform.PayloadFactoryMediator payloadFactoryMediator = (org.apache.synapse.mediators.transform.PayloadFactoryMediator)mediator; PayloadFactoryMediator visualPayloadFactoryMediator = (PayloadFactoryMediator) DeserializerUtils.createNode(part, EsbElementTypes.PayloadFactoryMediator_3597); setElementToEdit(visualPayloadFactoryMediator); executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__FORMAT, payloadFactoryMediator.getFormat()); if(payloadFactoryMediator.getType().equals(XML_LITERAL)){ executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.XML); }else if(payloadFactoryMediator.getType().equals(JSON_LITERAL)){ executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.JSON); } EList<PayloadFactoryArgument> arguments=new BasicEList<PayloadFactoryArgument>(); for(Argument argument: payloadFactoryMediator.getXPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getExpression()!=null){ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(argument.getExpression())); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.XML); }else{ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_VALUE, argument.getValue()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.VALUE); } arguments.add(payloadFactoryArgument); } for(Argument argument: payloadFactoryMediator.getJsonPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getJsonPath()!=null){ try { SynapseXPath xpath = new SynapseXPath(argument.getJsonPath().getJsonPathExpression()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(xpath)); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.JSON); arguments.add(payloadFactoryArgument); } catch (Exception e) { e.printStackTrace(); } } } executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__ARGS, arguments); return visualPayloadFactoryMediator; }
public PayloadFactoryMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.transform.PayloadFactoryMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.transform.PayloadFactoryMediator payloadFactoryMediator = (org.apache.synapse.mediators.transform.PayloadFactoryMediator)mediator; PayloadFactoryMediator visualPayloadFactoryMediator = (PayloadFactoryMediator) DeserializerUtils.createNode(part, EsbElementTypes.PayloadFactoryMediator_3597); setElementToEdit(visualPayloadFactoryMediator); executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__FORMAT, payloadFactoryMediator.getFormat()); if (payloadFactoryMediator.getType() != null) { if(payloadFactoryMediator.getType().equals(XML_LITERAL)){ executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.XML); } else if(payloadFactoryMediator.getType().equals(JSON_LITERAL)){ executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__MEDIA_TYPE, MediaType.JSON); } } EList<PayloadFactoryArgument> arguments=new BasicEList<PayloadFactoryArgument>(); for(Argument argument: payloadFactoryMediator.getXPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getExpression()!=null){ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(argument.getExpression())); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.XML); }else{ executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_VALUE, argument.getValue()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.VALUE); } arguments.add(payloadFactoryArgument); } for(Argument argument: payloadFactoryMediator.getJsonPathArgumentList()){ PayloadFactoryArgument payloadFactoryArgument= EsbFactory.eINSTANCE.createPayloadFactoryArgument(); if(argument.getJsonPath()!=null){ try { SynapseXPath xpath = new SynapseXPath(argument.getJsonPath().getJsonPathExpression()); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_EXPRESSION, createNamespacedProperty(xpath)); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__ARGUMENT_TYPE, PayloadFactoryArgumentType.EXPRESSION); executeSetValueCommand(payloadFactoryArgument,PAYLOAD_FACTORY_ARGUMENT__EVALUATOR, MediaType.JSON); arguments.add(payloadFactoryArgument); } catch (Exception e) { e.printStackTrace(); } } } executeSetValueCommand(PAYLOAD_FACTORY_MEDIATOR__ARGS, arguments); return visualPayloadFactoryMediator; }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/snippeteditor/JavaSnippetEditor.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/snippeteditor/JavaSnippetEditor.java index a13d46742..3bee0f8ae 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/snippeteditor/JavaSnippetEditor.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/snippeteditor/JavaSnippetEditor.java @@ -1,1487 +1,1488 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <[email protected]> - bug 38919 *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.snippeteditor; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventFilter; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IStackFrame; import org.eclipse.debug.core.model.IThread; import org.eclipse.debug.core.model.IValue; import org.eclipse.debug.internal.ui.views.expression.ExpressionInformationControl; import org.eclipse.debug.internal.ui.views.expression.PopupInformationControl; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugModelPresentation; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.debug.ui.IValueDetailListener; import org.eclipse.jdt.core.ICompletionRequestor; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.eval.IEvaluationContext; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.debug.core.IJavaStackFrame; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.core.IJavaValue; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.debug.eval.EvaluationManager; import org.eclipse.jdt.debug.eval.IClassFileEvaluationEngine; import org.eclipse.jdt.debug.eval.IEvaluationListener; import org.eclipse.jdt.debug.eval.IEvaluationResult; import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants; import org.eclipse.jdt.internal.debug.ui.JDIContentAssistPreference; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.internal.debug.ui.JDISourceViewer; import org.eclipse.jdt.internal.debug.ui.JavaDebugImages; import org.eclipse.jdt.internal.debug.ui.JavaDebugOptionsManager; import org.eclipse.jdt.internal.debug.ui.actions.PopupDisplayAction; import org.eclipse.jdt.internal.debug.ui.actions.PopupInspectAction; import org.eclipse.jdt.internal.debug.ui.display.JavaInspectExpression; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.TextOperationAction; import com.sun.jdi.InvocationException; import com.sun.jdi.ObjectReference; /** * An editor for Java snippets. */ public class JavaSnippetEditor extends AbstractTextEditor implements IDebugEventFilter, IEvaluationListener, IValueDetailListener { public static final String IMPORTS_CONTEXT = "SnippetEditor.imports"; //$NON-NLS-1$ public final static int RESULT_DISPLAY= 1; public final static int RESULT_RUN= 2; public final static int RESULT_INSPECT= 3; private int fResultMode; // one of the RESULT_* constants private IJavaProject fJavaProject; private IEvaluationContext fEvaluationContext; private IDebugTarget fVM; private String[] fLaunchedClassPath; private String fLaunchedWorkingDir; private String fLaunchedVMArgs; private IVMInstall fLaunchedVM; private List fSnippetStateListeners; private boolean fEvaluating; private IJavaThread fThread; private int fSnippetStart; private int fSnippetEnd; private String[] fImports= null; private Image fOldTitleImage= null; private IClassFileEvaluationEngine fEngine= null; /** * The debug model presentation used for computing toString */ private IDebugModelPresentation fPresentation= DebugUITools.newDebugModelPresentation(JDIDebugModel.getPluginIdentifier()); /** * The result of a toString evaluation returned asynchronously by the * debug model. */ private String fResult; /** * A thread that waits to have a * thread to perform an evaluation in. */ private static class WaitThread extends Thread { /** * The display used for event dispatching. */ private Display fDisplay; /** * Indicates whether to continue event queue dispatching. */ private volatile boolean fContinueEventDispatching = true; private Object fLock; /** * Creates a "wait" thread * * @param display the display to be used to read and dispatch events * @param lock the monitor to wait on */ private WaitThread(Display display, Object lock) { super("Snippet Wait Thread"); //$NON-NLS-1$ fDisplay = display; fLock= lock; } public void run() { try { synchronized (fLock) { //should be notified out of #setThread(IJavaThread) fLock.wait(10000); } } catch (InterruptedException e) { } finally { // Make sure that all events in the asynchronous event queue // are dispatched. fDisplay.syncExec(new Runnable() { public void run() { // do nothing } }); // Stop event dispatching fContinueEventDispatching= false; // Force the event loop to return from sleep () so that // it stops event dispatching. fDisplay.asyncExec(null); } } /** * Processes events. */ protected void block() { if (fDisplay == Display.getCurrent()) { while (fContinueEventDispatching) { if (!fDisplay.readAndDispatch()) fDisplay.sleep(); } } } } public JavaSnippetEditor() { super(); setDocumentProvider(JDIDebugUIPlugin.getDefault().getSnippetDocumentProvider()); setSourceViewerConfiguration(new JavaSnippetViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools(), this)); fSnippetStateListeners= new ArrayList(4); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setEditorContextMenuId("#JavaSnippetEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#JavaSnippetRulerContext"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetInput(org.eclipse.ui.IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); IFile file= getFile(); if (file != null) { String property= file.getPersistentProperty(new QualifiedName(JDIDebugUIPlugin.getUniqueIdentifier(), IMPORTS_CONTEXT)); if (property != null) { fImports = JavaDebugOptionsManager.parseList(property); } } } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ public void dispose() { shutDownVM(); fPresentation.dispose(); fSnippetStateListeners= null; ((JDISourceViewer) getSourceViewer()).dispose(); super.dispose(); } /** * Actions for the editor popup menu * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); if (getFile() != null) { Action action = new TextOperationAction(SnippetMessages.getBundle(), "SnippetEditor.ContentAssistProposal.", this, ISourceViewer.CONTENTASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action);//$NON-NLS-1$ setAction("ShowInPackageView", new ShowInPackageViewAction(this)); //$NON-NLS-1$ setAction("Stop", new StopAction(this)); //$NON-NLS-1$ setAction("SelectImports", new SelectImportsAction(this)); //$NON-NLS-1$ } } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager) */ protected void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); addGroup(menu, ITextEditorActionConstants.GROUP_EDIT, IContextMenuConstants.GROUP_GENERATE); addGroup(menu, ITextEditorActionConstants.GROUP_FIND, IContextMenuConstants.GROUP_SEARCH); addGroup(menu, IContextMenuConstants.GROUP_SEARCH, IContextMenuConstants.GROUP_SHOW); if (getFile() != null) { addAction(menu, IContextMenuConstants.GROUP_SHOW, "ShowInPackageView"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "Run"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "Stop"); //$NON-NLS-1$ addAction(menu, IContextMenuConstants.GROUP_ADDITIONS, "SelectImports"); //$NON-NLS-1$ } } protected boolean isVMLaunched() { return fVM != null; } public boolean isEvaluating() { return fEvaluating; } public void evalSelection(int resultMode) { if (!isInJavaProject()) { reportNotInJavaProjectError(); return; } if (isEvaluating()) { return; } checkCurrentProject(); evaluationStarts(); fResultMode= resultMode; buildAndLaunch(); if (fVM == null) { evaluationEnds(); return; } fireEvalStateChanged(); ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); String snippet= selection.getText(); fSnippetStart= selection.getOffset(); fSnippetEnd= fSnippetStart + selection.getLength(); evaluate(snippet); } /** * Checks if the page has been copied/moved to a different project or the project has been renamed. * Updates the launch configuration template if a copy/move/rename has occurred. */ protected void checkCurrentProject() { IFile file= getFile(); if (file == null) { return; } try { ILaunchConfiguration config = ScrapbookLauncher.getLaunchConfigurationTemplate(file); if (config != null) { String projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null); IJavaProject pro = JavaCore.create(file.getProject()); if (!pro.getElementName().equals(projectName)) { //the page has been moved to a "different" project ScrapbookLauncher.setLaunchConfigMemento(file, null); } } } catch (CoreException ce) { JDIDebugUIPlugin.log(ce); ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.evaluating"), null, ce.getStatus()); //$NON-NLS-1$ evaluationEnds(); return; } } protected void buildAndLaunch() { IJavaProject javaProject= getJavaProject(); if (javaProject == null) { return; } boolean build = !javaProject.getProject().getWorkspace().isAutoBuilding() || !javaProject.hasBuildState(); if (build) { if (!performIncrementalBuild()) { return; } } boolean changed= classPathHasChanged(); if (!changed) { changed = workingDirHasChanged(); } if (!changed) { changed = vmHasChanged(); } if (!changed) { changed = vmArgsChanged(); } boolean launch= fVM == null || changed; if (changed) { shutDownVM(); } if (fVM == null) { checkMultipleEditors(); } if (launch && fVM == null) { launchVM(); fVM= ScrapbookLauncher.getDefault().getDebugTarget(getFile()); } } protected boolean performIncrementalBuild() { IRunnableWithProgress r= new IRunnableWithProgress() { public void run(IProgressMonitor pm) throws InvocationTargetException { try { getJavaProject().getProject().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, pm); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; try { PlatformUI.getWorkbench().getProgressService().run(true, false, r); } catch (InterruptedException e) { JDIDebugUIPlugin.log(e); evaluationEnds(); return false; } catch (InvocationTargetException e) { JDIDebugUIPlugin.log(e); evaluationEnds(); return false; } return true; } protected void checkMultipleEditors() { fVM= ScrapbookLauncher.getDefault().getDebugTarget(getFile()); //multiple editors are opened on the same page if (fVM != null) { DebugPlugin.getDefault().addDebugEventFilter(this); try { IThread[] threads= fVM.getThreads(); for (int i = 0; i < threads.length; i++) { IThread iThread = threads[i]; if (iThread.isSuspended()) { iThread.resume(); } } } catch (DebugException de) { JDIDebugUIPlugin.log(de); } } } protected void setImports(String[] imports) { fImports= imports; IFile file= getFile(); if (file == null) { return; } String serialized= null; if (imports != null) { serialized= JavaDebugOptionsManager.serializeList(imports); } // persist try { file.setPersistentProperty(new QualifiedName(JDIDebugUIPlugin.getUniqueIdentifier(), IMPORTS_CONTEXT), serialized); } catch (CoreException e) { JDIDebugUIPlugin.log(e); ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.imports"), null, e.getStatus()); //$NON-NLS-1$ } } protected String[] getImports() { return fImports; } protected IEvaluationContext getEvaluationContext() { if (fEvaluationContext == null) { IJavaProject project= getJavaProject(); if (project != null) { fEvaluationContext= project.newEvaluationContext(); } } if (fEvaluationContext != null) { if (getImports() != null) { fEvaluationContext.setImports(getImports()); } else { fEvaluationContext.setImports(new String[]{}); } } return fEvaluationContext; } protected IJavaProject getJavaProject() { if (fJavaProject == null) { try { fJavaProject = findJavaProject(); } catch (JavaModelException e) { JDIDebugUIPlugin.log(e); showError(e.getStatus()); } } return fJavaProject; } protected void shutDownVM() { DebugPlugin.getDefault().removeDebugEventFilter(this); // The real shut down IDebugTarget target= fVM; if (fVM != null) { try { IBreakpoint bp = ScrapbookLauncher.getDefault().getMagicBreakpoint(fVM); if (bp != null) { fVM.breakpointRemoved(bp, null); } if (getThread() != null) { getThread().resume(); } fVM.terminate(); } catch (DebugException e) { JDIDebugUIPlugin.log(e); ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.shutdown"), null, e.getStatus()); //$NON-NLS-1$ return; } vmTerminated(); ScrapbookLauncher.getDefault().cleanup(target); } } /** * The VM has terminated, update state */ protected void vmTerminated() { fVM= null; fThread= null; fEvaluationContext= null; fLaunchedClassPath= null; if (fEngine != null) { fEngine.dispose(); } fEngine= null; fireEvalStateChanged(); } public void addSnippetStateChangedListener(ISnippetStateChangedListener listener) { if (fSnippetStateListeners != null && !fSnippetStateListeners.contains(listener)) { fSnippetStateListeners.add(listener); } } public void removeSnippetStateChangedListener(ISnippetStateChangedListener listener) { if (fSnippetStateListeners != null) { fSnippetStateListeners.remove(listener); } } protected void fireEvalStateChanged() { Runnable r= new Runnable() { public void run() { Shell shell= getShell(); if (fSnippetStateListeners != null && shell != null && !shell.isDisposed()) { List v= new ArrayList(fSnippetStateListeners); for (int i= 0; i < v.size(); i++) { ISnippetStateChangedListener l= (ISnippetStateChangedListener) v.get(i); l.snippetStateChanged(JavaSnippetEditor.this); } } } }; Shell shell= getShell(); if (shell != null) { getShell().getDisplay().asyncExec(r); } } protected void evaluate(String snippet) { if (getThread() == null) { WaitThread eThread= new WaitThread(Display.getCurrent(), this); eThread.start(); eThread.block(); } if (getThread() == null) { IStatus status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR, SnippetMessages.getString("SnippetEditor.error.nocontext"), null); //$NON-NLS-1$ ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.evaluating"), null, status); //$NON-NLS-1$ evaluationEnds(); return; } boolean hitBreakpoints= JDIDebugModel.getPreferences().getBoolean(JDIDebugModel.PREF_SUSPEND_FOR_BREAKPOINTS_DURING_EVALUATION); try { getEvaluationEngine().evaluate(snippet,getThread(), this, hitBreakpoints); } catch (DebugException e) { JDIDebugUIPlugin.log(e); ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.evaluating"), null, e.getStatus()); //$NON-NLS-1$ evaluationEnds(); } } /* (non-Javadoc) * @see org.eclipse.jdt.debug.eval.IEvaluationListener#evaluationComplete(org.eclipse.jdt.debug.eval.IEvaluationResult) */ public void evaluationComplete(IEvaluationResult result) { boolean severeErrors = false; if (result.hasErrors()) { String[] errors = result.getErrorMessages(); severeErrors = errors.length > 0; if (result.getException() != null) { showException(result.getException()); } showAllErrors(errors); } IJavaValue value= result.getValue(); if (value != null && !severeErrors) { switch (fResultMode) { case RESULT_DISPLAY: displayResult(value); break; case RESULT_INSPECT: String snippet= result.getSnippet().trim(); int snippetLength= snippet.length(); if (snippetLength > 30) { snippet = snippet.substring(0, 15) + SnippetMessages.getString("SnippetEditor.ellipsis") + snippet.substring(snippetLength - 15, snippetLength); //$NON-NLS-1$ } snippet= snippet.replace('\n', ' '); snippet= snippet.replace('\r', ' '); snippet= snippet.replace('\t', ' '); JavaInspectExpression exp = new JavaInspectExpression(snippet, value); showExpression(exp); break; case RESULT_RUN: // no action break; } } evaluationEnds(); } /** * Make the expression view visible or open one * if required. */ protected void showExpressionView() { Runnable r = new Runnable() { public void run() { IWorkbenchPage page = JDIDebugUIPlugin.getActivePage(); if (page != null) { IViewPart part = page.findView(IDebugUIConstants.ID_EXPRESSION_VIEW); if (part == null) { try { page.showView(IDebugUIConstants.ID_EXPRESSION_VIEW); } catch (PartInitException e) { JDIDebugUIPlugin.log(e); showError(e.getStatus()); } } else { page.bringToTop(part); } } } }; async(r); } protected void codeComplete(ICompletionRequestor requestor) throws JavaModelException { ITextSelection selection= (ITextSelection)getSelectionProvider().getSelection(); int start= selection.getOffset(); String snippet= getSourceViewer().getDocument().get(); IEvaluationContext e= getEvaluationContext(); if (e != null) { e.codeComplete(snippet, start, requestor); } } protected IJavaElement[] codeResolve() throws JavaModelException { ISourceViewer viewer= getSourceViewer(); if (viewer == null) { return null; } ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); int start= selection.getOffset(); int len= selection.getLength(); String snippet= viewer.getDocument().get(); IEvaluationContext e= getEvaluationContext(); if (e != null) { return e.codeSelect(snippet, start, len); } return null; } protected void showError(IStatus status) { evaluationEnds(); if (!status.isOK()) { ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.evaluating2"), null, status); //$NON-NLS-1$ } } protected void showError(String message) { Status status= new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, message, null); showError(status); } protected void displayResult(IJavaValue result) { StringBuffer resultString= new StringBuffer(); try { IJavaType type = result.getJavaType(); if (type != null) { String sig= type.getSignature(); if ("V".equals(sig)) { //$NON-NLS-1$ resultString.append(SnippetMessages.getString("SnippetEditor.noreturnvalue")); //$NON-NLS-1$ } else { if (sig != null) { resultString.append(SnippetMessages.getFormattedString("SnippetEditor.typename", result.getReferenceTypeName())); //$NON-NLS-1$ } else { resultString.append(" "); //$NON-NLS-1$ } resultString.append(evaluateToString(result)); } } else { resultString.append(result.getValueString()); } } catch(DebugException e) { JDIDebugUIPlugin.log(e); ErrorDialog.openError(getShell(), SnippetMessages.getString("SnippetEditor.error.toString"), null, e.getStatus()); //$NON-NLS-1$ } final String message = resultString.toString(); Runnable r = new Runnable() { public void run() { DisplayPopup popup = new DisplayPopup(getShell(), SnippetMessages.getString("JavaSnippetEditor.46"), PopupDisplayAction.ACTION_DEFINITION_ID); //$NON-NLS-1$ popup.setInformation(message); showPopup(popup); } }; async(r); } /** * Returns the result of evaluating 'toString' on the given * value. * * @param value object or primitive data type the 'toString' * is required for * @return the result of evaluating toString * @exception DebugException if an exception occurs during the * evaluation. */ protected synchronized String evaluateToString(IJavaValue value) { fResult= null; fPresentation.computeDetail(value, this); if (fResult == null) { try { wait(10000); } catch (InterruptedException e) { return SnippetMessages.getString("SnippetEditor.error.interrupted"); //$NON-NLS-1$ } } return fResult; } /* (non-Javadoc) * @see org.eclipse.debug.ui.IValueDetailListener#detailComputed(org.eclipse.debug.core.model.IValue, java.lang.String) */ public synchronized void detailComputed(IValue value, final String result) { fResult= result; this.notifyAll(); } protected void showAllErrors(final String[] errors) { IDocument document = getSourceViewer().getDocument(); String delimiter = document.getLegalLineDelimiters()[0]; final StringBuffer errorString = new StringBuffer(); for (int i = 0; i < errors.length; i++) { errorString.append(errors[i] + delimiter); } Runnable r = new Runnable() { public void run() { ErrorPopup adapter = new ErrorPopup(getShell(), SnippetMessages.getString("JavaSnippetEditor.49"), PopupDisplayAction.ACTION_DEFINITION_ID); //$NON-NLS-1$ adapter.setInformation(errorString.toString()); showPopup(adapter); } }; async(r); } private void showPopup(final SnippetPopup popup) { IDocument document = getSourceViewer().getDocument(); InformationPresenter infoPresenter = new InformationPresenter(new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { return popup; } }); try { String contentType = document.getContentType(fSnippetStart); IInformationProvider infoProvider = new IInformationProvider(){ public IRegion getSubject(ITextViewer textViewer, int offset) { return new Region(fSnippetStart, fSnippetEnd-fSnippetStart); } public String getInformation(ITextViewer textViewer, IRegion subject) { return popup.getInformation(); //$NON-NLS-1$ } }; infoPresenter.setInformationProvider(infoProvider, contentType); infoPresenter.install(getSourceViewer()); infoPresenter.showInformation(); } catch (BadLocationException e) { return; } } private void showExpression(final JavaInspectExpression expression) { Runnable r = new Runnable() { public void run() { InformationPresenter infoPresenter = new InformationPresenter(new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { IWorkbenchPage page = JDIDebugUIPlugin.getActivePage(); return new ExpressionInformationControl(page, expression, PopupInspectAction.ACTION_DEFININIITION_ID); } }); IInformationProvider provider = new IInformationProvider() { public IRegion getSubject(ITextViewer textViewer, int offset) { return new Region(fSnippetStart, fSnippetEnd-fSnippetStart); } public String getInformation(ITextViewer textViewer, IRegion subject) { return "nothing"; //$NON-NLS-1$ } }; try { infoPresenter.setInformationProvider(provider, getSourceViewer().getDocument().getContentType(fSnippetStart)); infoPresenter.install(getSourceViewer()); infoPresenter.showInformation(); } catch (BadLocationException e) { return; } } }; async(r); } protected void showException(Throwable exception) { if (exception instanceof DebugException) { DebugException de = (DebugException)exception; Throwable t= de.getStatus().getException(); if (t != null) { // show underlying exception showUnderlyingException(t); return; } } ByteArrayOutputStream bos= new ByteArrayOutputStream(); PrintStream ps= new PrintStream(bos, true); exception.printStackTrace(ps); final String message = bos.toString(); Runnable r = new Runnable() { public void run() { ExceptionPopup adapter = new ExceptionPopup(getShell(), SnippetMessages.getString("JavaSnippetEditor.51"), PopupDisplayAction.ACTION_DEFINITION_ID); //$NON-NLS-1$ adapter.setInformation(message); showPopup(adapter); } }; async(r); } protected void showUnderlyingException(Throwable t) { if (t instanceof InvocationException) { InvocationException ie= (InvocationException)t; ObjectReference ref= ie.exception(); String eName= ref.referenceType().name(); final String message= SnippetMessages.getFormattedString("SnippetEditor.exception", eName); //$NON-NLS-1$ Runnable r = new Runnable() { public void run() { ExceptionPopup adapter = new ExceptionPopup(getShell(), SnippetMessages.getString("JavaSnippetEditor.51"), PopupDisplayAction.ACTION_DEFINITION_ID); //$NON-NLS-1$ adapter.setInformation(message); showPopup(adapter); } }; async(r); } else { showException(t); } } protected IJavaProject findJavaProject() throws JavaModelException { Object input= getEditorInput(); if (input instanceof IFileEditorInput) { IFileEditorInput file= (IFileEditorInput)input; IProject p= file.getFile().getProject(); try { if (p.getNature(JavaCore.NATURE_ID) != null) { return JavaCore.create(p); } } catch (CoreException ce) { throw new JavaModelException(ce); } } return null; } protected boolean classPathHasChanged() { String[] classpath= getClassPath(getJavaProject()); if (fLaunchedClassPath != null && !classPathsEqual(fLaunchedClassPath, classpath)) { MessageDialog.openWarning(getShell(), SnippetMessages.getString("SnippetEditor.warning"), SnippetMessages.getString("SnippetEditor.warning.cpchange")); //$NON-NLS-2$ //$NON-NLS-1$ return true; } return false; } protected boolean workingDirHasChanged() { String wd = getWorkingDirectoryAttribute(); boolean changed = false; if (wd == null || fLaunchedWorkingDir == null) { if (wd != fLaunchedWorkingDir) { changed = true; } } else { if (!wd.equals(fLaunchedWorkingDir)) { changed = true; } } if (changed && fVM != null) { MessageDialog.openWarning(getShell(), SnippetMessages.getString("SnippetEditor.Warning_1"), SnippetMessages.getString("SnippetEditor.The_working_directory_has_changed._Restarting_the_evaluation_context._2")); //$NON-NLS-1$ //$NON-NLS-2$ } return changed; } protected boolean vmArgsChanged() { String args = getVMArgsAttribute(); boolean changed = false; if (args == null || fLaunchedVMArgs == null) { if (args != fLaunchedVMArgs) { changed = true; } } else { if (!args.equals(fLaunchedVMArgs)) { changed = true; } } if (changed && fVM != null) { MessageDialog.openWarning(getShell(), SnippetMessages.getString("SnippetEditor.Warning_1"), SnippetMessages.getString("SnippetEditor.1")); //$NON-NLS-1$ //$NON-NLS-2$ } return changed; } protected boolean vmHasChanged() { IVMInstall vm = getVMInstall(); boolean changed = false; if (vm == null || fLaunchedVM == null) { if (vm != fLaunchedVM) { changed = true; } } else { if (!vm.equals(fLaunchedVM)) { changed = true; } } if (changed && fVM != null) { MessageDialog.openWarning(getShell(), SnippetMessages.getString("SnippetEditor.Warning_1"), SnippetMessages.getString("SnippetEditor.The_JRE_has_changed._Restarting_the_evaluation_context._2")); //$NON-NLS-1$ //$NON-NLS-2$ } return changed; } protected boolean classPathsEqual(String[] path1, String[] path2) { if (path1.length != path2.length) { return false; } for (int i= 0; i < path1.length; i++) { if (!path1[i].equals(path2[i])) { return false; } } return true; } protected synchronized void evaluationStarts() { if (fThread != null) { try { IThread thread = fThread; fThread = null; thread.resume(); } catch (DebugException e) { JDIDebugUIPlugin.log(e); showException(e); return; } } fEvaluating = true; setTitleImage(); fireEvalStateChanged(); showStatus(SnippetMessages.getString("SnippetEditor.evaluating")); //$NON-NLS-1$ getSourceViewer().setEditable(false); } /** * Sets the tab image to indicate whether in the process of * evaluating or not. */ protected void setTitleImage() { Image image=null; if (fEvaluating) { fOldTitleImage= getTitleImage(); image= JavaDebugImages.get(JavaDebugImages.IMG_OBJS_SNIPPET_EVALUATING); } else { image= fOldTitleImage; fOldTitleImage= null; } if (image != null) { setTitleImage(image); } } protected void evaluationEnds() { Runnable r = new Runnable() { public void run() { fEvaluating= false; setTitleImage(); fireEvalStateChanged(); showStatus(""); //$NON-NLS-1$ getSourceViewer().setEditable(true); } }; async(r); } protected void showStatus(String message) { IEditorSite site=(IEditorSite)getSite(); EditorActionBarContributor contributor= (EditorActionBarContributor)site.getActionBarContributor(); contributor.getActionBars().getStatusLineManager().setMessage(message); } protected String[] getClassPath(IJavaProject project) { try { return JavaRuntime.computeDefaultRuntimeClassPath(project); } catch (CoreException e) { JDIDebugUIPlugin.log(e); return new String[0]; } } protected Shell getShell() { return getSite().getShell(); } /** * @see IDebugEventFilter#filterDebugEvents(DebugEvent[]) */ public DebugEvent[] filterDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent e = events[i]; Object source = e.getSource(); if (source instanceof IDebugElement) { IDebugElement de = (IDebugElement)source; if (de instanceof IDebugTarget) { if (de.getDebugTarget().equals(fVM)) { if (e.getKind() == DebugEvent.TERMINATE) { setThread(null); Runnable r = new Runnable() { public void run() { vmTerminated(); } }; getShell().getDisplay().asyncExec(r); } } } else if (de instanceof IJavaThread) { if (e.getKind() == DebugEvent.SUSPEND) { IJavaThread jt = (IJavaThread)de; try { if (jt.equals(getThread()) && e.getDetail() == DebugEvent.EVALUATION) { return null; } IJavaStackFrame f= (IJavaStackFrame)jt.getTopStackFrame(); if (f != null) { IBreakpoint[] bps = jt.getBreakpoints(); //last line of the eval method in ScrapbookMain1? - if (e.getDetail() == DebugEvent.STEP_END && f.getLineNumber() == 20 + int lineNumber = f.getLineNumber(); + if (e.getDetail() == DebugEvent.STEP_END && (lineNumber == 20 || lineNumber == 21) && f.getDeclaringTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") //$NON-NLS-1$ && jt.getDebugTarget() == fVM) { setThread(jt); return null; } else if (e.getDetail() == DebugEvent.BREAKPOINT && bps.length > 0 && bps[0].equals(ScrapbookLauncher.getDefault().getMagicBreakpoint(jt.getDebugTarget()))) { // locate the 'eval' method and step over IStackFrame[] frames = jt.getStackFrames(); for (int j = 0; j < frames.length; j++) { IJavaStackFrame frame = (IJavaStackFrame)frames[j]; if (frame.getReceivingTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") && frame.getName().equals("eval")) { //$NON-NLS-1$ //$NON-NLS-2$ frame.stepOver(); return null; } } } } } catch (DebugException ex) { JDIDebugUIPlugin.log(ex); } } } } } return events; } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(org.eclipse.jface.util.PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { JDISourceViewer isv= (JDISourceViewer) getSourceViewer(); if (isv != null) { IContentAssistant assistant= isv.getContentAssistant(); if (assistant instanceof ContentAssistant) { JDIContentAssistPreference.changeConfiguration((ContentAssistant) assistant, event); } super.handlePreferenceStoreChanged(event); } } protected IJavaThread getThread() { return fThread; } /** * Sets the thread to perform any evaluations in. * Notifies the WaitThread waiting on getting an evaluation thread * to perform an evaluation. */ protected synchronized void setThread(IJavaThread thread) { fThread= thread; notifyAll(); } protected void launchVM() { DebugPlugin.getDefault().addDebugEventFilter(this); fLaunchedClassPath = getClassPath(getJavaProject()); fLaunchedWorkingDir = getWorkingDirectoryAttribute(); fLaunchedVMArgs = getVMArgsAttribute(); fLaunchedVM = getVMInstall(); Runnable r = new Runnable() { public void run() { ScrapbookLauncher.getDefault().launch(getFile()); } }; BusyIndicator.showWhile(getShell().getDisplay(), r); } /** * Return the <code>IFile</code> associated with the current * editor input. Will return <code>null</code> if the current * editor input is for an external file */ public IFile getFile() { IEditorInput input= getEditorInput(); if (input instanceof IFileEditorInput) { return ((IFileEditorInput)input).getFile(); } return null; } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#updateSelectionDependentActions() */ protected void updateSelectionDependentActions() { super.updateSelectionDependentActions(); fireEvalStateChanged(); } /** * Terminates existing VM on a rename of the editor * @see org.eclipse.ui.part.WorkbenchPart#setTitle(java.lang.String) */ protected void setTitle(String title) { cleanupOnRenameOrMove(); super.setTitle(title); } /** * If the launch configuration has been copied, moved or * renamed, shut down any running VM and clear the relevant cached information. */ protected void cleanupOnRenameOrMove() { if(isVMLaunched()) { shutDownVM(); } else { fThread= null; fEvaluationContext= null; fLaunchedClassPath= null; if (fEngine != null) { fEngine.dispose(); fEngine= null; } } fJavaProject= null; } /** * Returns whether this editor has been opened on a resource that * is in a Java project. */ protected boolean isInJavaProject() { try { return findJavaProject() != null; } catch (JavaModelException jme) { JDIDebugUIPlugin.log(jme); } return false; } /** * Displays an error dialog indicating that evaluation * cannot occur outside of a Java Project. */ protected void reportNotInJavaProjectError() { String projectName= null; Object input= getEditorInput(); if (input instanceof IFileEditorInput) { IFileEditorInput file= (IFileEditorInput)input; IProject p= file.getFile().getProject(); projectName= p.getName(); } String message= ""; //$NON-NLS-1$ if (projectName != null) { message = projectName + SnippetMessages.getString("JavaSnippetEditor._is_not_a_Java_Project._n_1"); //$NON-NLS-1$ } showError(message + SnippetMessages.getString("JavaSnippetEditor.Unable_to_perform_evaluation_outside_of_a_Java_Project_2")); //$NON-NLS-1$ } /** * Asks the user for the workspace path * of a file resource and saves the document there. * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSaveAs(org.eclipse.core.runtime.IProgressMonitor) */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); SaveAsDialog dialog= new SaveAsDialog(shell); dialog.open(); IPath path= dialog.getResult(); if (path == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspace workspace= ResourcesPlugin.getWorkspace(); IFile file= workspace.getRoot().getFile(path); final IEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { IDocumentProvider dp= getDocumentProvider(); dp.saveDocument(monitor, newInput, dp.getDocument(getEditorInput()), true); } }; boolean success= false; try { getDocumentProvider().aboutToChange(newInput); PlatformUI.getWorkbench().getProgressService().run(false, true, op); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { JDIDebugUIPlugin.log(x); String title= SnippetMessages.getString("JavaSnippetEditor.Problems_During_Save_As..._3"); //$NON-NLS-1$ String msg= SnippetMessages.getString("JavaSnippetEditor.Save_could_not_be_completed.__4") + x.getTargetException().getMessage(); //$NON-NLS-1$ MessageDialog.openError(shell, title, msg); } finally { getDocumentProvider().changed(newInput); if (success) { setInput(newInput); } } if (progressMonitor != null) { progressMonitor.setCanceled(!success); } } /* (non-Javadoc) * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed() */ public boolean isSaveAsAllowed() { return true; } protected IClassFileEvaluationEngine getEvaluationEngine() { if (fEngine == null) { IPath outputLocation = getJavaProject().getProject().getPluginWorkingLocation(JDIDebugUIPlugin.getDefault().getDescriptor()); java.io.File f = new java.io.File(outputLocation.toOSString()); fEngine = EvaluationManager.newClassFileEvaluationEngine(getJavaProject(), (IJavaDebugTarget)getThread().getDebugTarget(), f); } if (getImports() != null) { fEngine.setImports(getImports()); } else { fEngine.setImports(new String[]{}); } return fEngine; } /* (non-Javadoc) * @see org.eclipse.ui.texteditor.AbstractTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, int) */ protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new JDISourceViewer(parent, ruler, styles); } /** * Returns the working directory attribute for this scrapbook */ protected String getWorkingDirectoryAttribute() { IFile file= getFile(); if (file != null) { try { return ScrapbookLauncher.getWorkingDirectoryAttribute(file); } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } return null; } /** * Returns the working directory attribute for this scrapbook */ protected String getVMArgsAttribute() { IFile file= getFile(); if (file != null) { try { return ScrapbookLauncher.getVMArgsAttribute(file); } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } return null; } /** * Returns the vm install for this scrapbook */ protected IVMInstall getVMInstall() { IFile file= getFile(); if (file != null) { try { return ScrapbookLauncher.getVMInstall(file); } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } return null; } /** * Executes the given runnable in the Display thread */ protected void async(Runnable r) { Control control= getVerticalRuler().getControl(); if (!control.isDisposed()) { control.getDisplay().asyncExec(r); } } protected void showAndSelect(final String text, final int offset) { Runnable r = new Runnable() { public void run() { try { getSourceViewer().getDocument().replace(offset, 0, text); } catch (BadLocationException e) { JDIDebugUIPlugin.log(e); } selectAndReveal(offset, text.length()); } }; async(r); } /* (non-Javadoc) * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class required) { if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(required); } private class SnippetPopup extends PopupInformationControl { protected String fInformation; private Text fText; SnippetPopup(Shell parent, String label, String actionDefinitionId) { super(parent, label, actionDefinitionId); } public String getInformation() { return fInformation; } public boolean hasContents() { return fText != null; } public void setInformation(String information) { fInformation = information; fText.setText(fInformation); } public Control createControl(Composite parent) { Composite comp = new Composite(parent, parent.getStyle()); comp.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); comp.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); comp.setLayout(new GridLayout()); fText = new Text(comp, SWT.NONE); fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); Dialog.applyDialogFont(comp); fText.setLayoutData(new GridData(GridData.FILL_BOTH)); return fText; } public IDialogSettings getDialogSettings() { return JDIDebugUIPlugin.getDefault().getDialogSettings(); } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.PopupInformationControl#performCommand() */ protected void performCommand() { try { getSourceViewer().getDocument().replace(fSnippetEnd, 0, fInformation); } catch (BadLocationException e) { } selectAndReveal(fSnippetEnd, fInformation.length()); } } //subclasses are used to persist Popup sizes separately from other SnippetPopupAdapter's sizes private class ExceptionPopup extends SnippetPopup { public ExceptionPopup(Shell parent, String label, String actionDefinitionId) { super(parent, label, actionDefinitionId); } } private class DisplayPopup extends SnippetPopup { public DisplayPopup(Shell parent, String label, String actionDefinitionId) { super(parent, label, actionDefinitionId); } } private class ErrorPopup extends SnippetPopup { public ErrorPopup(Shell parent, String label, String actionDefinitionId) { super(parent, label, actionDefinitionId); } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.PopupInformationControl#performCommand() */ protected void performCommand() { try { getSourceViewer().getDocument().replace(fSnippetStart, 0, fInformation.toString()); } catch (BadLocationException e) { } selectAndReveal(fSnippetStart, fInformation.length()); } } }
true
true
public DebugEvent[] filterDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent e = events[i]; Object source = e.getSource(); if (source instanceof IDebugElement) { IDebugElement de = (IDebugElement)source; if (de instanceof IDebugTarget) { if (de.getDebugTarget().equals(fVM)) { if (e.getKind() == DebugEvent.TERMINATE) { setThread(null); Runnable r = new Runnable() { public void run() { vmTerminated(); } }; getShell().getDisplay().asyncExec(r); } } } else if (de instanceof IJavaThread) { if (e.getKind() == DebugEvent.SUSPEND) { IJavaThread jt = (IJavaThread)de; try { if (jt.equals(getThread()) && e.getDetail() == DebugEvent.EVALUATION) { return null; } IJavaStackFrame f= (IJavaStackFrame)jt.getTopStackFrame(); if (f != null) { IBreakpoint[] bps = jt.getBreakpoints(); //last line of the eval method in ScrapbookMain1? if (e.getDetail() == DebugEvent.STEP_END && f.getLineNumber() == 20 && f.getDeclaringTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") //$NON-NLS-1$ && jt.getDebugTarget() == fVM) { setThread(jt); return null; } else if (e.getDetail() == DebugEvent.BREAKPOINT && bps.length > 0 && bps[0].equals(ScrapbookLauncher.getDefault().getMagicBreakpoint(jt.getDebugTarget()))) { // locate the 'eval' method and step over IStackFrame[] frames = jt.getStackFrames(); for (int j = 0; j < frames.length; j++) { IJavaStackFrame frame = (IJavaStackFrame)frames[j]; if (frame.getReceivingTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") && frame.getName().equals("eval")) { //$NON-NLS-1$ //$NON-NLS-2$ frame.stepOver(); return null; } } } } } catch (DebugException ex) { JDIDebugUIPlugin.log(ex); } } } } } return events; }
public DebugEvent[] filterDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent e = events[i]; Object source = e.getSource(); if (source instanceof IDebugElement) { IDebugElement de = (IDebugElement)source; if (de instanceof IDebugTarget) { if (de.getDebugTarget().equals(fVM)) { if (e.getKind() == DebugEvent.TERMINATE) { setThread(null); Runnable r = new Runnable() { public void run() { vmTerminated(); } }; getShell().getDisplay().asyncExec(r); } } } else if (de instanceof IJavaThread) { if (e.getKind() == DebugEvent.SUSPEND) { IJavaThread jt = (IJavaThread)de; try { if (jt.equals(getThread()) && e.getDetail() == DebugEvent.EVALUATION) { return null; } IJavaStackFrame f= (IJavaStackFrame)jt.getTopStackFrame(); if (f != null) { IBreakpoint[] bps = jt.getBreakpoints(); //last line of the eval method in ScrapbookMain1? int lineNumber = f.getLineNumber(); if (e.getDetail() == DebugEvent.STEP_END && (lineNumber == 20 || lineNumber == 21) && f.getDeclaringTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") //$NON-NLS-1$ && jt.getDebugTarget() == fVM) { setThread(jt); return null; } else if (e.getDetail() == DebugEvent.BREAKPOINT && bps.length > 0 && bps[0].equals(ScrapbookLauncher.getDefault().getMagicBreakpoint(jt.getDebugTarget()))) { // locate the 'eval' method and step over IStackFrame[] frames = jt.getStackFrames(); for (int j = 0; j < frames.length; j++) { IJavaStackFrame frame = (IJavaStackFrame)frames[j]; if (frame.getReceivingTypeName().equals("org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1") && frame.getName().equals("eval")) { //$NON-NLS-1$ //$NON-NLS-2$ frame.stepOver(); return null; } } } } } catch (DebugException ex) { JDIDebugUIPlugin.log(ex); } } } } } return events; }
diff --git a/src/state/GameState.java b/src/state/GameState.java index a974b5d..7cb7015 100644 --- a/src/state/GameState.java +++ b/src/state/GameState.java @@ -1,237 +1,237 @@ package state; import helper.LevelHelper; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import org.lwjgl.input.Keyboard; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import other.LevelController; import other.Translator; import app.Game; import entity.Level; import entity.Menu; import entity.MenuItem; import entity.MessageBox; public class GameState extends BasicGameState { private int stateId; private Level level = null; private boolean showMenu = false; private boolean showGameOverMenu = false; private Menu menu = null; private Menu gameOverMenu = null; private Translator translator; private LevelController levelController; private MessageBox messageBox; private boolean wasFinished = false; public GameState(int stateId) { this.stateId = stateId; this.translator = Translator.getInstance(); this.levelController = LevelController.getInstance(); } @Override public void init(final GameContainer container, final StateBasedGame game) throws SlickException { this.messageBox = new MessageBox(container); this.messageBox.setBackgroundColor(Color.lightGray); MenuItem continueItem = new MenuItem(this.translator.translate("Continue"), new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { GameState.this.showMenu = false; GameState.this.showGameOverMenu = false; } }); MenuItem repeatLevel = new MenuItem(this.translator.translate("Repeat level"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.initLevel(container, game); GameState.this.showMenu = false; GameState.this.showGameOverMenu = false; } }); MenuItem subMenu = new MenuItem(this.translator.translate("Sub menu"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.showMenu = false; GameState.this.showGameOverMenu = false; game.enterState(Game.MENU_FOR_GAME_STATE); } }); MenuItem mainMenu = new MenuItem(this.translator.translate("Main menu"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.showMenu = false; GameState.this.showGameOverMenu = false; game.enterState(Game.MENU_STATE); } }); List<MenuItem> menuItems = new ArrayList<MenuItem>(); menuItems.add(continueItem); menuItems.add(repeatLevel); menuItems.add(subMenu); menuItems.add(mainMenu); for (MenuItem item : menuItems) { item.setMargin(30); } this.menu = new Menu(menuItems, container); this.menu.setBackgroundColor(Color.lightGray); List<MenuItem> gameOverMenuItems = new ArrayList<MenuItem>(); gameOverMenuItems.add(repeatLevel); gameOverMenuItems.add(subMenu); gameOverMenuItems.add(mainMenu); for (MenuItem item : gameOverMenuItems) { item.setMargin(30); } this.gameOverMenu = new Menu(gameOverMenuItems, container); this.gameOverMenu.setBackgroundColor(Color.lightGray); this.initLevel(container, game); } private void initLevel(GameContainer container, final StateBasedGame game) { try { this.wasFinished = false; this.level = this.levelController.getCurrentLevel(); int itemSize = this.level.getOriginalImageSize(); float scale = LevelHelper.computeScale(container, this.level.getOriginalImageSize(), new Dimension(this.level.getWidth(), this.level.getHeight())); this.level.setScale(scale); int width = this.level.getWidth() * (int) (itemSize * scale); int height = this.level.getHeight() * (int) (itemSize * scale); this.level.setMarginLeft((container.getWidth() - width) / 2); this.level.setMarginTop((container.getHeight() - height) / 2); if (!this.level.isValid()) { this.messageBox.showConfirm(this.translator .translate("Level is not valid. Do you wanna edit this level?"), new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { game.enterState(Game.EDITOR_STATE); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_FOR_GAME_STATE); } }); } } catch (Exception e) { e.printStackTrace(); } } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { this.level.render(container, game, g); if (this.showMenu) { this.menu.render(container, game, g); } if (this.showGameOverMenu) { this.gameOverMenu.render(container, game, g); } this.messageBox.render(container, game, g); } @Override public void update(final GameContainer container, final StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); if (input.isKeyPressed(Input.KEY_ESCAPE) && !this.level.isFinished() && !this.level.isOver()) { this.showMenu = true; } if (this.level.isOver()) { this.showGameOverMenu = true; if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.initLevel(container, game); this.showMenu = false; this.showGameOverMenu = false; } } if (this.level.isFinished()) { if (this.levelController.nextLevelExist()) { + if (!this.wasFinished) { + this.wasFinished = true; + this.levelController.updateProgress(); + } this.messageBox.showConfirm(this.translator .translate("Level was finished. Do you wanna continue to next level?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.levelController.loadNextLevel(); GameState.this.initLevel(container, game); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.levelController.loadNextLevel(); this.initLevel(container, game); this.messageBox.close(); } } else { this.messageBox .showConfirm( this.translator .translate("Congratulation!!! Package was finished. Do you wanna continue?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_FOR_GAME_STATE); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); } - if (!this.wasFinished) { - this.wasFinished = true; - this.levelController.updateProgress(); - } } if (this.showMenu) { this.menu.update(container, game, delta); } else if (this.showGameOverMenu) { this.gameOverMenu.update(container, game, delta); } else { this.level.update(container, game, delta); } this.messageBox.update(container, game, delta); input.clearKeyPressedRecord(); } @Override public int getID() { return this.stateId; } }
false
true
public void update(final GameContainer container, final StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); if (input.isKeyPressed(Input.KEY_ESCAPE) && !this.level.isFinished() && !this.level.isOver()) { this.showMenu = true; } if (this.level.isOver()) { this.showGameOverMenu = true; if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.initLevel(container, game); this.showMenu = false; this.showGameOverMenu = false; } } if (this.level.isFinished()) { if (this.levelController.nextLevelExist()) { this.messageBox.showConfirm(this.translator .translate("Level was finished. Do you wanna continue to next level?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.levelController.loadNextLevel(); GameState.this.initLevel(container, game); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.levelController.loadNextLevel(); this.initLevel(container, game); this.messageBox.close(); } } else { this.messageBox .showConfirm( this.translator .translate("Congratulation!!! Package was finished. Do you wanna continue?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_FOR_GAME_STATE); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); } if (!this.wasFinished) { this.wasFinished = true; this.levelController.updateProgress(); } } if (this.showMenu) { this.menu.update(container, game, delta); } else if (this.showGameOverMenu) { this.gameOverMenu.update(container, game, delta); } else { this.level.update(container, game, delta); } this.messageBox.update(container, game, delta); input.clearKeyPressedRecord(); }
public void update(final GameContainer container, final StateBasedGame game, int delta) throws SlickException { Input input = container.getInput(); if (input.isKeyPressed(Input.KEY_ESCAPE) && !this.level.isFinished() && !this.level.isOver()) { this.showMenu = true; } if (this.level.isOver()) { this.showGameOverMenu = true; if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.initLevel(container, game); this.showMenu = false; this.showGameOverMenu = false; } } if (this.level.isFinished()) { if (this.levelController.nextLevelExist()) { if (!this.wasFinished) { this.wasFinished = true; this.levelController.updateProgress(); } this.messageBox.showConfirm(this.translator .translate("Level was finished. Do you wanna continue to next level?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GameState.this.levelController.loadNextLevel(); GameState.this.initLevel(container, game); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); if (input.isKeyPressed(Keyboard.KEY_RETURN)) { this.levelController.loadNextLevel(); this.initLevel(container, game); this.messageBox.close(); } } else { this.messageBox .showConfirm( this.translator .translate("Congratulation!!! Package was finished. Do you wanna continue?"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_FOR_GAME_STATE); } }, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { game.enterState(Game.MENU_STATE); } }); } } if (this.showMenu) { this.menu.update(container, game, delta); } else if (this.showGameOverMenu) { this.gameOverMenu.update(container, game, delta); } else { this.level.update(container, game, delta); } this.messageBox.update(container, game, delta); input.clearKeyPressedRecord(); }
diff --git a/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java b/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java index 256190b..c4ab31c 100644 --- a/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java +++ b/editor/src/main/java/kkckkc/jsourcepad/model/bundle/EnvironmentProvider.java @@ -1,126 +1,124 @@ package kkckkc.jsourcepad.model.bundle; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import kkckkc.jsourcepad.action.ActionContextKeys; import kkckkc.jsourcepad.model.Doc; import kkckkc.jsourcepad.model.Window; import kkckkc.jsourcepad.util.Config; import kkckkc.jsourcepad.util.Cygwin; import kkckkc.jsourcepad.util.action.ActionManager; import kkckkc.jsourcepad.util.io.SystemEnvironmentHelper; import kkckkc.syntaxpane.model.Interval; import kkckkc.utils.Os; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class EnvironmentProvider { private static final Function<? super File,String> FILE_TO_STRING = new Function<File, String>() { @Override public String apply(File file) { return formatPath(file.toString()); } }; public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) { Map<String, String> systemEnvironment = SystemEnvironmentHelper.getSystemEnvironment(); Map<String, String> environment = new HashMap<String, String>(systemEnvironment); Doc activeDoc = window.getDocList().getActiveDoc(); if (activeDoc != null) { environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath()); environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex())); environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1)); environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine())); String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord()); if (s != null) { environment.put("TM_CURRENT_WORD", s); } if (activeDoc.getFile() != null) { environment.put("TM_FILENAME", activeDoc.getFile().getName()); environment.put("TM_DIRECTORY", formatPath(activeDoc.getFile().getParentFile().getPath())); environment.put("TM_FILEPATH", formatPath(activeDoc.getFile().getPath())); } System.out.println("selection = " + activeDoc.getActiveBuffer().getSelection()); Interval selection = activeDoc.getActiveBuffer().getSelection(); if (selection != null && ! selection.isEmpty()) { String text = activeDoc.getActiveBuffer().getText(selection); if (text.length() > 60000) text = text.substring(0, 60000); environment.put("TM_SELECTED_TEXT", text); } } if (window.getProject() != null) { environment.put("TM_PROJECT_DIRECTORY", formatPath(window.getProject().getProjectDir().getPath())); } List<File> paths = Lists.newArrayList(); if (bundleItemSupplier != null) { environment.put("TM_BUNDLE_SUPPORT", formatPath(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath())); paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin")); } - if (System.getProperty("supportPath") != null) { - environment.put("TM_SUPPORT_PATH", formatPath(Config.getSupportFolder().getPath())); - paths.add(new File(Config.getSupportFolder(), "bin")); - paths.add(new File(Config.getSupportFolder(), System.getProperty("os.name") + "/bin")); + environment.put("TM_SUPPORT_PATH", formatPath(Config.getSupportFolder().getPath())); + paths.add(new File(Config.getSupportFolder(), "bin")); + paths.add(new File(Config.getSupportFolder(), System.getProperty("os.name") + "/bin")); - // TODO: This is a hack. Add binary with proper error message - environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2"); - } + // TODO: This is a hack. Add binary with proper error message + environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2"); List<File> files = Lists.newArrayList(); ActionManager actionManager = window.getActionManager(); if (! (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc)) { if (window.getProject() != null) { files = window.getProject().getSelectedFiles(); } } else { if (activeDoc != null && activeDoc.getFile() != null) { files = Collections.singletonList(activeDoc.getFile()); } } if (files.isEmpty()) { environment.put("TM_SELECTED_FILE", ""); environment.put("TM_SELECTED_FILES", ""); } else { environment.put("TM_SELECTED_FILE", "\"" + formatPath(files.get(0).toString()) + "\""); environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(Collections2.transform(files, FILE_TO_STRING))); } if (activeDoc != null) { environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false"); environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize())); } environment.put("PATH", systemEnvironment.get("PATH") + File.pathSeparator + Joiner.on(File.pathSeparator).join(Collections2.transform(paths, FILE_TO_STRING))); return environment; } private static String formatPath(String s) { if (Os.isWindows()) { return Cygwin.makePathForEnvironmentUsage(s); } return s; } }
false
true
public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) { Map<String, String> systemEnvironment = SystemEnvironmentHelper.getSystemEnvironment(); Map<String, String> environment = new HashMap<String, String>(systemEnvironment); Doc activeDoc = window.getDocList().getActiveDoc(); if (activeDoc != null) { environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath()); environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex())); environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1)); environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine())); String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord()); if (s != null) { environment.put("TM_CURRENT_WORD", s); } if (activeDoc.getFile() != null) { environment.put("TM_FILENAME", activeDoc.getFile().getName()); environment.put("TM_DIRECTORY", formatPath(activeDoc.getFile().getParentFile().getPath())); environment.put("TM_FILEPATH", formatPath(activeDoc.getFile().getPath())); } System.out.println("selection = " + activeDoc.getActiveBuffer().getSelection()); Interval selection = activeDoc.getActiveBuffer().getSelection(); if (selection != null && ! selection.isEmpty()) { String text = activeDoc.getActiveBuffer().getText(selection); if (text.length() > 60000) text = text.substring(0, 60000); environment.put("TM_SELECTED_TEXT", text); } } if (window.getProject() != null) { environment.put("TM_PROJECT_DIRECTORY", formatPath(window.getProject().getProjectDir().getPath())); } List<File> paths = Lists.newArrayList(); if (bundleItemSupplier != null) { environment.put("TM_BUNDLE_SUPPORT", formatPath(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath())); paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin")); } if (System.getProperty("supportPath") != null) { environment.put("TM_SUPPORT_PATH", formatPath(Config.getSupportFolder().getPath())); paths.add(new File(Config.getSupportFolder(), "bin")); paths.add(new File(Config.getSupportFolder(), System.getProperty("os.name") + "/bin")); // TODO: This is a hack. Add binary with proper error message environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2"); } List<File> files = Lists.newArrayList(); ActionManager actionManager = window.getActionManager(); if (! (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc)) { if (window.getProject() != null) { files = window.getProject().getSelectedFiles(); } } else { if (activeDoc != null && activeDoc.getFile() != null) { files = Collections.singletonList(activeDoc.getFile()); } } if (files.isEmpty()) { environment.put("TM_SELECTED_FILE", ""); environment.put("TM_SELECTED_FILES", ""); } else { environment.put("TM_SELECTED_FILE", "\"" + formatPath(files.get(0).toString()) + "\""); environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(Collections2.transform(files, FILE_TO_STRING))); } if (activeDoc != null) { environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false"); environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize())); } environment.put("PATH", systemEnvironment.get("PATH") + File.pathSeparator + Joiner.on(File.pathSeparator).join(Collections2.transform(paths, FILE_TO_STRING))); return environment; }
public static Map<String, String> getEnvironment(Window window, BundleItemSupplier bundleItemSupplier) { Map<String, String> systemEnvironment = SystemEnvironmentHelper.getSystemEnvironment(); Map<String, String> environment = new HashMap<String, String>(systemEnvironment); Doc activeDoc = window.getDocList().getActiveDoc(); if (activeDoc != null) { environment.put("TM_SCOPE", activeDoc.getActiveBuffer().getInsertionPoint().getScope().getPath()); environment.put("TM_LINE_INDEX", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineIndex())); environment.put("TM_LINE_NUMBER", Integer.toString(activeDoc.getActiveBuffer().getInsertionPoint().getLineNumber() + 1)); environment.put("TM_CURRENT_LINE", activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentLine())); String s = activeDoc.getActiveBuffer().getText(activeDoc.getActiveBuffer().getCurrentWord()); if (s != null) { environment.put("TM_CURRENT_WORD", s); } if (activeDoc.getFile() != null) { environment.put("TM_FILENAME", activeDoc.getFile().getName()); environment.put("TM_DIRECTORY", formatPath(activeDoc.getFile().getParentFile().getPath())); environment.put("TM_FILEPATH", formatPath(activeDoc.getFile().getPath())); } System.out.println("selection = " + activeDoc.getActiveBuffer().getSelection()); Interval selection = activeDoc.getActiveBuffer().getSelection(); if (selection != null && ! selection.isEmpty()) { String text = activeDoc.getActiveBuffer().getText(selection); if (text.length() > 60000) text = text.substring(0, 60000); environment.put("TM_SELECTED_TEXT", text); } } if (window.getProject() != null) { environment.put("TM_PROJECT_DIRECTORY", formatPath(window.getProject().getProjectDir().getPath())); } List<File> paths = Lists.newArrayList(); if (bundleItemSupplier != null) { environment.put("TM_BUNDLE_SUPPORT", formatPath(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support").getPath())); paths.add(new File(bundleItemSupplier.getFile().getParentFile().getParentFile(), "Support/bin")); } environment.put("TM_SUPPORT_PATH", formatPath(Config.getSupportFolder().getPath())); paths.add(new File(Config.getSupportFolder(), "bin")); paths.add(new File(Config.getSupportFolder(), System.getProperty("os.name") + "/bin")); // TODO: This is a hack. Add binary with proper error message environment.put("DIALOG", "/Applications/Installed/TextMate.app/Contents/PlugIns/Dialog2.tmplugin/Contents/Resources/tm_dialog2"); List<File> files = Lists.newArrayList(); ActionManager actionManager = window.getActionManager(); if (! (actionManager.getActionContext().get(ActionContextKeys.FOCUSED_COMPONENT) instanceof Doc)) { if (window.getProject() != null) { files = window.getProject().getSelectedFiles(); } } else { if (activeDoc != null && activeDoc.getFile() != null) { files = Collections.singletonList(activeDoc.getFile()); } } if (files.isEmpty()) { environment.put("TM_SELECTED_FILE", ""); environment.put("TM_SELECTED_FILES", ""); } else { environment.put("TM_SELECTED_FILE", "\"" + formatPath(files.get(0).toString()) + "\""); environment.put("TM_SELECTED_FILES", Joiner.on("\"").join(Collections2.transform(files, FILE_TO_STRING))); } if (activeDoc != null) { environment.put("TM_SOFT_TABS", activeDoc.getTabManager().isSoftTabs() ? "true" : "false"); environment.put("TM_TAB_SIZE", Integer.toString(activeDoc.getTabManager().getTabSize())); } environment.put("PATH", systemEnvironment.get("PATH") + File.pathSeparator + Joiner.on(File.pathSeparator).join(Collections2.transform(paths, FILE_TO_STRING))); return environment; }
diff --git a/src/main/java/de/cismet/commons/cismap/io/AddGeometriesToMapWizardAction.java b/src/main/java/de/cismet/commons/cismap/io/AddGeometriesToMapWizardAction.java index 09cc0eaa..2b16d2d8 100644 --- a/src/main/java/de/cismet/commons/cismap/io/AddGeometriesToMapWizardAction.java +++ b/src/main/java/de/cismet/commons/cismap/io/AddGeometriesToMapWizardAction.java @@ -1,505 +1,506 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.commons.cismap.io; import com.vividsolutions.jts.geom.Geometry; import org.apache.log4j.Logger; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import org.jdom.Element; import org.openide.DialogDisplayer; import org.openide.WizardDescriptor; import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.NbBundle; import java.awt.Component; import java.awt.Dialog; import java.awt.EventQueue; import java.awt.Frame; import java.awt.event.ActionEvent; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.logging.Level; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import de.cismet.cismap.commons.Crs; import de.cismet.cismap.commons.features.Feature; import de.cismet.cismap.commons.features.PureNewFeature; import de.cismet.cismap.commons.features.PureNewFeature.geomTypes; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.commons.raster.wms.simple.SimpleWmsGetMapUrl; import de.cismet.commons.cismap.io.converters.GeometryConverter; import de.cismet.commons.cismap.io.converters.TextToGeometryConverter; import de.cismet.commons.converter.ConversionException; import de.cismet.commons.converter.Converter; import de.cismet.commons.gui.wizard.converter.AbstractConverterChooseWizardPanel; import de.cismet.commons.gui.wizard.converter.ConverterPreselectionMode; import de.cismet.tools.configuration.Configurable; import de.cismet.tools.configuration.NoWriteError; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.WaitingDialogThread; /** * DOCUMENT ME! * * @author [email protected] * @version 1.0 */ public final class AddGeometriesToMapWizardAction extends AbstractAction implements Configurable { //~ Static fields/initializers --------------------------------------------- public static final String PROP_AVAILABLE_CONVERTERS = "__prop_available_converters__"; // NOI18N public static final String PROP_INPUT_FILE = "__prop_input_file__"; // NOI18N public static final String PROP_CURRENT_CRS = "__prop_current_epsg_code__"; // NOI18N public static final String PROP_PREVIEW_GETMAP_URL = "__prop_preview_getmap_url__"; // NOI18N public static final String PROP_CONVERTER_PRESELECT_MODE = "__prop_converter_preselect_mode__"; // NOI18N public static final String CONF_SECTION = "addGeometriesToMapWizardAction"; // NOI18N public static final String CONF_CONV_PRESELECT = "converterPreselectionMode"; // NOI18N public static final String CONF_PREVIEW_GETMAP_URL = "previewGetMapUrl"; // NOI18N /** LOGGER. */ private static final transient Logger LOG = Logger.getLogger(AddGeometriesToMapWizardAction.class); //~ Instance fields -------------------------------------------------------- private transient Converter selectedConverter; private transient WizardDescriptor.Panel<WizardDescriptor>[] panels; private transient ConverterPreselectionMode converterPreselectionMode; private transient String previewGetMapUrl; private transient File inputFile; private transient String inputData; //~ Constructors ----------------------------------------------------------- /** * Creates a new AddGeometriesToMapWizardAction object. */ public AddGeometriesToMapWizardAction() { super( "", // NOI18N ImageUtilities.loadImageIcon( AddGeometriesToMapWizardAction.class.getPackage().getName().replace('.', '/') + "/new_geom_wiz_22.png", // NOI18N false)); putValue( Action.SHORT_DESCRIPTION, NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.<init>.action.shortDescription")); // NOI18N setConverterPreselectionMode(getDefaultConverterPreselectionMode()); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @SuppressWarnings("unchecked") private WizardDescriptor.Panel<WizardDescriptor>[] getPanels() { assert EventQueue.isDispatchThread() : "can only be called from EDT"; // NOI18N if (panels == null) { panels = new WizardDescriptor.Panel[] { new AddGeometriesToMapEnterDataWizardPanel(), new AddGeometriesToMapChooseConverterWizardPanel(), new AddGeometriesToMapPreviewWizardPanel() }; final String[] steps = new String[panels.length]; for (int i = 0; i < panels.length; i++) { final Component c = panels[i].getComponent(); // Default step name to component name of panel. Mainly useful // for getting the name of the target chooser to appear in the // list of steps. steps[i] = c.getName(); if (c instanceof JComponent) { // assume Swing components final JComponent jc = (JComponent)c; // Sets step number of a component jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, Integer.valueOf(i)); // Sets steps names for a panel jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps); // Turn on subtitle creation on each step jc.putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, Boolean.TRUE); // Show steps on the left side with the image on the // background jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, Boolean.TRUE); // Turn on numbering of all steps jc.putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, Boolean.TRUE); } } } return panels; } @Override public void actionPerformed(final ActionEvent e) { final WizardDescriptor wizard = new WizardDescriptor(getPanels()); wizard.setTitleFormat(new MessageFormat("{0}")); // NOI18N wizard.setTitle(NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).wizard.title")); // NOI18N final Collection<? extends TextToGeometryConverter> availableConverters = Lookup.getDefault() .lookupAll(TextToGeometryConverter.class); final ConverterPreselectionMode preselectionMode; if (ConverterPreselectionMode.DEFAULT == getConverterPreselectionMode()) { preselectionMode = getDefaultConverterPreselectionMode(); } else { preselectionMode = getConverterPreselectionMode(); } wizard.putProperty(AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER, selectedConverter); wizard.putProperty(PROP_PREVIEW_GETMAP_URL, getPreviewGetMapUrl()); wizard.putProperty(PROP_AVAILABLE_CONVERTERS, new ArrayList<Converter>(availableConverters)); wizard.putProperty(PROP_CURRENT_CRS, CismapBroker.getInstance().getSrs()); wizard.putProperty(PROP_CONVERTER_PRESELECT_MODE, preselectionMode); wizard.putProperty(PROP_INPUT_FILE, getInputFile()); wizard.putProperty(AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA, getInputData()); final Frame parent = StaticSwingTools.getParentFrame(CismapBroker.getInstance().getMappingComponent()); final Dialog dialog = DialogDisplayer.getDefault().createDialog(wizard); dialog.pack(); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); dialog.toFront(); // after wizard execution the input file and data is cleared from the action so that it won't be reused // NOTE: this can be changed so that the action may remember previous entries setInputFile(null); setInputData(null); if (wizard.getValue() == WizardDescriptor.FINISH_OPTION) { // remember the selected converter if ((ConverterPreselectionMode.SESSION_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.PERMANENT_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.CONFIGURE_AND_MEMORY == converterPreselectionMode)) { setSelectedConverter((Converter)wizard.getProperty( AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER)); } else { setSelectedConverter(null); } final WaitingDialogThread<Geometry> wdt = new WaitingDialogThread<Geometry>( parent, true, NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.message"), // NOI18N null, 50) { @Override @SuppressWarnings("unchecked") protected Geometry doInBackground() throws Exception { Geometry geometry = (Geometry)wizard.getProperty( AddGeometriesToMapPreviewWizardPanel.PROP_GEOMETRY); if (geometry == null) { final Converter converter = (Converter)wizard.getProperty( AbstractConverterChooseWizardPanel.PROP_CONVERTER); final Object data = wizard.getProperty( AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA); final Crs crs = (Crs)wizard.getProperty(AddGeometriesToMapWizardAction.PROP_CURRENT_CRS); assert converter instanceof GeometryConverter : "illegal wizard initialisation"; // NOI18N final GeometryConverter geomConverter = (GeometryConverter)converter; geometry = geomConverter.convertForward(data, crs.getCode()); } return geometry; } @Override protected void done() { try { final Geometry geom = get(); final PureNewFeature feature = new PureNewFeature(geom); feature.setGeometryType(getGeomType(geom)); + feature.setEditable(true); final MappingComponent map = CismapBroker.getInstance().getMappingComponent(); map.getFeatureCollection().addFeature(feature); map.getFeatureCollection().holdFeature(feature); // fixed extent means, don't move map at all if (!map.isFixedMapExtent()) { map.zoomToAFeatureCollection(Arrays.asList((Feature)feature), true, map.isFixedMapScale()); } } catch (final Exception ex) { final ErrorInfo errorInfo; final StringWriter stacktraceWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stacktraceWriter)); if (ex instanceof ConversionException) { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } else { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } JXErrorPane.showDialog(parent, errorInfo); } } // cannot map to ellipse private geomTypes getGeomType(final Geometry geom) { final String jtsGeomType = geom.getGeometryType(); // JTS v1.12 strings if ("Polygon".equals(jtsGeomType)) { // NOI18N if (geom.isRectangle()) { return geomTypes.RECTANGLE; } else { return geomTypes.POLYGON; } } else if ("Point".equals(jtsGeomType)) { // NOI18N return geomTypes.POINT; } else if ("LineString".equals(jtsGeomType)) { // NOI18N return geomTypes.LINESTRING; } else if ("MultiPolygon".equals(jtsGeomType)) { // NOI18N return geomTypes.MULTIPOLYGON; } else { return geomTypes.UNKNOWN; } } }; // FIXME: the WaitingDialogThread only works properly when using start, thus cannot be put in an executor wdt.start(); } } @Override public void configure(final Element parent) { // only properties that are directly changable by the user shall be configured here, currently there are non } @Override public void masterConfigure(final Element parent) { if (parent == null) { // no configuration section present, simply leave return; } final Element actionConfigElement = parent.getChild(CONF_SECTION); // NOI18N if (actionConfigElement == null) { // no configuration section present, simply leave return; } final Element convPreselectModeElement = actionConfigElement.getChild(CONF_CONV_PRESELECT); if (convPreselectModeElement == null) { setConverterPreselectionMode(ConverterPreselectionMode.DEFAULT); } else { final String convPreselectModeString = convPreselectModeElement.getText(); try { final ConverterPreselectionMode convPreselectMode = ConverterPreselectionMode.valueOf( convPreselectModeString); setConverterPreselectionMode(convPreselectMode); } catch (final IllegalArgumentException e) { LOG.warn("illegal value for " + CONF_CONV_PRESELECT + ", configuring DEFAULT", e); // NOI18N setConverterPreselectionMode(ConverterPreselectionMode.DEFAULT); } } final Element convPreviewGetMapUrlElement = actionConfigElement.getChild(CONF_PREVIEW_GETMAP_URL); if (convPreviewGetMapUrlElement == null) { setPreviewGetMapUrl(null); } else { setPreviewGetMapUrl(convPreviewGetMapUrlElement.getText().trim()); } } @Override public Element getConfiguration() throws NoWriteError { final Element sectionElement = new Element(CONF_SECTION); final Element convPreselectModeElement = new Element(CONF_CONV_PRESELECT); convPreselectModeElement.setText(getConverterPreselectionMode().toString()); final Element convPreviewGetMapUrlElement = new Element(CONF_PREVIEW_GETMAP_URL); convPreviewGetMapUrlElement.setText(getPreviewGetMapUrl()); sectionElement.addContent(convPreselectModeElement); sectionElement.addContent(convPreviewGetMapUrlElement); return sectionElement; } /** * Gets the current <code>ConverterPreselectionMode</code> that will be used in the wizard. * * @return the current <code>ConverterPreselectionMode</code> that will be used in the wizard */ public ConverterPreselectionMode getConverterPreselectionMode() { return converterPreselectionMode; } /** * Sets the <code>ConverterPreselectionMode</code> that will be used in the wizard. * * @param converterPreselectionMode the <code>ConverterPreselectionMode</code> to use * * @throws IllegalArgumentException if the given <code>ConverterPreselectionMode</code> is not supported by the * wizard (currently CONFIGURE, CONFIGURE_AND_MEMORY and PREMANENT_MEMORY) */ public void setConverterPreselectionMode(final ConverterPreselectionMode converterPreselectionMode) { switch (converterPreselectionMode) { case CONFIGURE: // fall-through case CONFIGURE_AND_MEMORY: // fall-through case PERMANENT_MEMORY: { throw new IllegalArgumentException("mode not supported yet: " + converterPreselectionMode); // NOI18N } default: { this.converterPreselectionMode = converterPreselectionMode; } } } /** * Gets the default <code>ConverterPreselectionMode</code>, currently <i>SESSION_MEMORY</i>. * * @return the default <code>ConverterPreselectionMode</code>, currently <i>SESSION_MEMORY</i> */ public ConverterPreselectionMode getDefaultConverterPreselectionMode() { return ConverterPreselectionMode.SESSION_MEMORY; } /** * Gets the current map preview url that will be used by the wizard as a background layer for the newly created * geometry. The preview url shall be a string that can be used with {@link SimpleWmsGetMapUrl}. * * @return the current map preview url */ public String getPreviewGetMapUrl() { return previewGetMapUrl; } /** * Sets the map preview url that will be used by the wizard as a background layer for the newly created geometry. * The preview url shall be a string that can be used with {@link SimpleWmsGetMapUrl}. * * @param previewGetMapUrl the new map preview url */ public void setPreviewGetMapUrl(final String previewGetMapUrl) { this.previewGetMapUrl = previewGetMapUrl; } /** * Gets the currently selected converter that will be used for the next wizard invocation. * * @return the currently selected converter that will for the next wizard invocation */ public Converter getSelectedConverter() { return selectedConverter; } /** * Sets the selected converter that will be used for the next wizard invocation. * * @param selectedConverter the new selected converter */ public void setSelectedConverter(final Converter selectedConverter) { this.selectedConverter = selectedConverter; } /** * Gets the input file that will be used for the next wizard invocation. * * @return the input file that will be used for the next wizard invocation */ public File getInputFile() { return inputFile; } /** * Sets input file that may be used for the next wizard invocation. After an invocation of the wizard the file is * cleared again. * * @param inputFile the input file to be used for the next wizard invocation */ public void setInputFile(final File inputFile) { this.inputFile = inputFile; } /** * Gets the input data that will be used for the next wizard invocation. * * @return the input data that will be used for the next wizard invocation */ public String getInputData() { return inputData; } /** * Sets input data that may be used for the next wizard invocation. After an invocation of the wizard the data is * cleared again. * * @param inputData the input data to be used for the next wizard invocation */ public void setInputData(final String inputData) { this.inputData = inputData; } }
true
true
public void actionPerformed(final ActionEvent e) { final WizardDescriptor wizard = new WizardDescriptor(getPanels()); wizard.setTitleFormat(new MessageFormat("{0}")); // NOI18N wizard.setTitle(NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).wizard.title")); // NOI18N final Collection<? extends TextToGeometryConverter> availableConverters = Lookup.getDefault() .lookupAll(TextToGeometryConverter.class); final ConverterPreselectionMode preselectionMode; if (ConverterPreselectionMode.DEFAULT == getConverterPreselectionMode()) { preselectionMode = getDefaultConverterPreselectionMode(); } else { preselectionMode = getConverterPreselectionMode(); } wizard.putProperty(AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER, selectedConverter); wizard.putProperty(PROP_PREVIEW_GETMAP_URL, getPreviewGetMapUrl()); wizard.putProperty(PROP_AVAILABLE_CONVERTERS, new ArrayList<Converter>(availableConverters)); wizard.putProperty(PROP_CURRENT_CRS, CismapBroker.getInstance().getSrs()); wizard.putProperty(PROP_CONVERTER_PRESELECT_MODE, preselectionMode); wizard.putProperty(PROP_INPUT_FILE, getInputFile()); wizard.putProperty(AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA, getInputData()); final Frame parent = StaticSwingTools.getParentFrame(CismapBroker.getInstance().getMappingComponent()); final Dialog dialog = DialogDisplayer.getDefault().createDialog(wizard); dialog.pack(); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); dialog.toFront(); // after wizard execution the input file and data is cleared from the action so that it won't be reused // NOTE: this can be changed so that the action may remember previous entries setInputFile(null); setInputData(null); if (wizard.getValue() == WizardDescriptor.FINISH_OPTION) { // remember the selected converter if ((ConverterPreselectionMode.SESSION_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.PERMANENT_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.CONFIGURE_AND_MEMORY == converterPreselectionMode)) { setSelectedConverter((Converter)wizard.getProperty( AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER)); } else { setSelectedConverter(null); } final WaitingDialogThread<Geometry> wdt = new WaitingDialogThread<Geometry>( parent, true, NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.message"), // NOI18N null, 50) { @Override @SuppressWarnings("unchecked") protected Geometry doInBackground() throws Exception { Geometry geometry = (Geometry)wizard.getProperty( AddGeometriesToMapPreviewWizardPanel.PROP_GEOMETRY); if (geometry == null) { final Converter converter = (Converter)wizard.getProperty( AbstractConverterChooseWizardPanel.PROP_CONVERTER); final Object data = wizard.getProperty( AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA); final Crs crs = (Crs)wizard.getProperty(AddGeometriesToMapWizardAction.PROP_CURRENT_CRS); assert converter instanceof GeometryConverter : "illegal wizard initialisation"; // NOI18N final GeometryConverter geomConverter = (GeometryConverter)converter; geometry = geomConverter.convertForward(data, crs.getCode()); } return geometry; } @Override protected void done() { try { final Geometry geom = get(); final PureNewFeature feature = new PureNewFeature(geom); feature.setGeometryType(getGeomType(geom)); final MappingComponent map = CismapBroker.getInstance().getMappingComponent(); map.getFeatureCollection().addFeature(feature); map.getFeatureCollection().holdFeature(feature); // fixed extent means, don't move map at all if (!map.isFixedMapExtent()) { map.zoomToAFeatureCollection(Arrays.asList((Feature)feature), true, map.isFixedMapScale()); } } catch (final Exception ex) { final ErrorInfo errorInfo; final StringWriter stacktraceWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stacktraceWriter)); if (ex instanceof ConversionException) { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } else { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } JXErrorPane.showDialog(parent, errorInfo); } } // cannot map to ellipse private geomTypes getGeomType(final Geometry geom) { final String jtsGeomType = geom.getGeometryType(); // JTS v1.12 strings if ("Polygon".equals(jtsGeomType)) { // NOI18N if (geom.isRectangle()) { return geomTypes.RECTANGLE; } else { return geomTypes.POLYGON; } } else if ("Point".equals(jtsGeomType)) { // NOI18N return geomTypes.POINT; } else if ("LineString".equals(jtsGeomType)) { // NOI18N return geomTypes.LINESTRING; } else if ("MultiPolygon".equals(jtsGeomType)) { // NOI18N return geomTypes.MULTIPOLYGON; } else { return geomTypes.UNKNOWN; } } }; // FIXME: the WaitingDialogThread only works properly when using start, thus cannot be put in an executor wdt.start(); } }
public void actionPerformed(final ActionEvent e) { final WizardDescriptor wizard = new WizardDescriptor(getPanels()); wizard.setTitleFormat(new MessageFormat("{0}")); // NOI18N wizard.setTitle(NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).wizard.title")); // NOI18N final Collection<? extends TextToGeometryConverter> availableConverters = Lookup.getDefault() .lookupAll(TextToGeometryConverter.class); final ConverterPreselectionMode preselectionMode; if (ConverterPreselectionMode.DEFAULT == getConverterPreselectionMode()) { preselectionMode = getDefaultConverterPreselectionMode(); } else { preselectionMode = getConverterPreselectionMode(); } wizard.putProperty(AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER, selectedConverter); wizard.putProperty(PROP_PREVIEW_GETMAP_URL, getPreviewGetMapUrl()); wizard.putProperty(PROP_AVAILABLE_CONVERTERS, new ArrayList<Converter>(availableConverters)); wizard.putProperty(PROP_CURRENT_CRS, CismapBroker.getInstance().getSrs()); wizard.putProperty(PROP_CONVERTER_PRESELECT_MODE, preselectionMode); wizard.putProperty(PROP_INPUT_FILE, getInputFile()); wizard.putProperty(AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA, getInputData()); final Frame parent = StaticSwingTools.getParentFrame(CismapBroker.getInstance().getMappingComponent()); final Dialog dialog = DialogDisplayer.getDefault().createDialog(wizard); dialog.pack(); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); dialog.toFront(); // after wizard execution the input file and data is cleared from the action so that it won't be reused // NOTE: this can be changed so that the action may remember previous entries setInputFile(null); setInputData(null); if (wizard.getValue() == WizardDescriptor.FINISH_OPTION) { // remember the selected converter if ((ConverterPreselectionMode.SESSION_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.PERMANENT_MEMORY == converterPreselectionMode) || (ConverterPreselectionMode.CONFIGURE_AND_MEMORY == converterPreselectionMode)) { setSelectedConverter((Converter)wizard.getProperty( AddGeometriesToMapChooseConverterWizardPanel.PROP_CONVERTER)); } else { setSelectedConverter(null); } final WaitingDialogThread<Geometry> wdt = new WaitingDialogThread<Geometry>( parent, true, NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.message"), // NOI18N null, 50) { @Override @SuppressWarnings("unchecked") protected Geometry doInBackground() throws Exception { Geometry geometry = (Geometry)wizard.getProperty( AddGeometriesToMapPreviewWizardPanel.PROP_GEOMETRY); if (geometry == null) { final Converter converter = (Converter)wizard.getProperty( AbstractConverterChooseWizardPanel.PROP_CONVERTER); final Object data = wizard.getProperty( AddGeometriesToMapEnterDataWizardPanel.PROP_COORDINATE_DATA); final Crs crs = (Crs)wizard.getProperty(AddGeometriesToMapWizardAction.PROP_CURRENT_CRS); assert converter instanceof GeometryConverter : "illegal wizard initialisation"; // NOI18N final GeometryConverter geomConverter = (GeometryConverter)converter; geometry = geomConverter.convertForward(data, crs.getCode()); } return geometry; } @Override protected void done() { try { final Geometry geom = get(); final PureNewFeature feature = new PureNewFeature(geom); feature.setGeometryType(getGeomType(geom)); feature.setEditable(true); final MappingComponent map = CismapBroker.getInstance().getMappingComponent(); map.getFeatureCollection().addFeature(feature); map.getFeatureCollection().holdFeature(feature); // fixed extent means, don't move map at all if (!map.isFixedMapExtent()) { map.zoomToAFeatureCollection(Arrays.asList((Feature)feature), true, map.isFixedMapScale()); } } catch (final Exception ex) { final ErrorInfo errorInfo; final StringWriter stacktraceWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stacktraceWriter)); if (ex instanceof ConversionException) { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.conversionError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } else { errorInfo = new ErrorInfo( NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.title"), // NOI18N NbBundle.getMessage( AddGeometriesToMapWizardAction.class, "AddGeometriesToMapWizardAction.actionPerformed(ActionEvent).waitingDialogThread.genericError.message"), // NOI18N stacktraceWriter.toString(), "WARNING", // NOI18N ex, Level.WARNING, null); } JXErrorPane.showDialog(parent, errorInfo); } } // cannot map to ellipse private geomTypes getGeomType(final Geometry geom) { final String jtsGeomType = geom.getGeometryType(); // JTS v1.12 strings if ("Polygon".equals(jtsGeomType)) { // NOI18N if (geom.isRectangle()) { return geomTypes.RECTANGLE; } else { return geomTypes.POLYGON; } } else if ("Point".equals(jtsGeomType)) { // NOI18N return geomTypes.POINT; } else if ("LineString".equals(jtsGeomType)) { // NOI18N return geomTypes.LINESTRING; } else if ("MultiPolygon".equals(jtsGeomType)) { // NOI18N return geomTypes.MULTIPOLYGON; } else { return geomTypes.UNKNOWN; } } }; // FIXME: the WaitingDialogThread only works properly when using start, thus cannot be put in an executor wdt.start(); } }
diff --git a/src/com/android/phone/BluetoothHandsfree.java b/src/com/android/phone/BluetoothHandsfree.java index d507b665..7ab69efc 100644 --- a/src/com/android/phone/BluetoothHandsfree.java +++ b/src/com/android/phone/BluetoothHandsfree.java @@ -1,2844 +1,2842 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.bluetooth.AtCommandHandler; import android.bluetooth.AtCommandResult; import android.bluetooth.AtParser; import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothAssignedNumbers; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.bluetooth.HeadsetBase; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.SystemProperties; import android.telephony.PhoneNumberUtils; import android.telephony.ServiceState; import android.telephony.SignalStrength; import android.util.Log; import com.android.internal.telephony.Call; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.CallManager; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; /** * Bluetooth headset manager for the Phone app. * @hide */ public class BluetoothHandsfree { private static final String TAG = "Bluetooth HS/HF"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // even more logging public static final int TYPE_UNKNOWN = 0; public static final int TYPE_HEADSET = 1; public static final int TYPE_HANDSFREE = 2; private final Context mContext; private final BluetoothAdapter mAdapter; private final CallManager mCM; private BluetoothA2dp mA2dp; private BluetoothDevice mA2dpDevice; private int mA2dpState; private boolean mPendingAudioState; private int mAudioState; private ServiceState mServiceState; private HeadsetBase mHeadset; // null when not connected private BluetoothHeadset mBluetoothHeadset; private int mHeadsetType; private boolean mAudioPossible; private BluetoothSocket mConnectedSco; private IncomingScoAcceptThread mIncomingScoThread = null; private ScoSocketConnectThread mConnectScoThread = null; private SignalScoCloseThread mSignalScoCloseThread = null; private Object mScoLock = new Object(); private AudioManager mAudioManager; private PowerManager mPowerManager; private boolean mPendingSco; // waiting for a2dp sink to suspend before establishing SCO private boolean mA2dpSuspended; private boolean mUserWantsAudio; private WakeLock mStartCallWakeLock; // held while waiting for the intent to start call private WakeLock mStartVoiceRecognitionWakeLock; // held while waiting for voice recognition // AT command state private static final int GSM_MAX_CONNECTIONS = 6; // Max connections allowed by GSM private static final int CDMA_MAX_CONNECTIONS = 2; // Max connections allowed by CDMA private long mBgndEarliestConnectionTime = 0; private boolean mClip = false; // Calling Line Information Presentation private boolean mIndicatorsEnabled = false; private boolean mCmee = false; // Extended Error reporting private long[] mClccTimestamps; // Timestamps associated with each clcc index private boolean[] mClccUsed; // Is this clcc index in use private boolean mWaitingForCallStart; private boolean mWaitingForVoiceRecognition; // do not connect audio until service connection is established // for 3-way supported devices, this is after AT+CHLD // for non-3-way supported devices, this is after AT+CMER (see spec) private boolean mServiceConnectionEstablished; private final BluetoothPhoneState mBluetoothPhoneState; // for CIND and CIEV updates private final BluetoothAtPhonebook mPhonebook; private Phone.State mPhoneState = Phone.State.IDLE; CdmaPhoneCallState.PhoneCallState mCdmaThreeWayCallState = CdmaPhoneCallState.PhoneCallState.IDLE; private DebugThread mDebugThread; private int mScoGain = Integer.MIN_VALUE; private static Intent sVoiceCommandIntent; // Audio parameters private static final String HEADSET_NREC = "bt_headset_nrec"; private static final String HEADSET_NAME = "bt_headset_name"; private int mRemoteBrsf = 0; private int mLocalBrsf = 0; // CDMA specific flag used in context with BT devices having display capabilities // to show which Caller is active. This state might not be always true as in CDMA // networks if a caller drops off no update is provided to the Phone. // This flag is just used as a toggle to provide a update to the BT device to specify // which caller is active. private boolean mCdmaIsSecondCallActive = false; /* Constants from Bluetooth Specification Hands-Free profile version 1.5 */ private static final int BRSF_AG_THREE_WAY_CALLING = 1 << 0; private static final int BRSF_AG_EC_NR = 1 << 1; private static final int BRSF_AG_VOICE_RECOG = 1 << 2; private static final int BRSF_AG_IN_BAND_RING = 1 << 3; private static final int BRSF_AG_VOICE_TAG_NUMBE = 1 << 4; private static final int BRSF_AG_REJECT_CALL = 1 << 5; private static final int BRSF_AG_ENHANCED_CALL_STATUS = 1 << 6; private static final int BRSF_AG_ENHANCED_CALL_CONTROL = 1 << 7; private static final int BRSF_AG_ENHANCED_ERR_RESULT_CODES = 1 << 8; private static final int BRSF_HF_EC_NR = 1 << 0; private static final int BRSF_HF_CW_THREE_WAY_CALLING = 1 << 1; private static final int BRSF_HF_CLIP = 1 << 2; private static final int BRSF_HF_VOICE_REG_ACT = 1 << 3; private static final int BRSF_HF_REMOTE_VOL_CONTROL = 1 << 4; private static final int BRSF_HF_ENHANCED_CALL_STATUS = 1 << 5; private static final int BRSF_HF_ENHANCED_CALL_CONTROL = 1 << 6; // VirtualCall - true if Virtual Call is active, false otherwise private boolean mVirtualCallStarted = false; public static String typeToString(int type) { switch (type) { case TYPE_UNKNOWN: return "unknown"; case TYPE_HEADSET: return "headset"; case TYPE_HANDSFREE: return "handsfree"; } return null; } public BluetoothHandsfree(Context context, CallManager cm) { mCM = cm; mContext = context; mAdapter = BluetoothAdapter.getDefaultAdapter(); boolean bluetoothCapable = (mAdapter != null); mHeadset = null; // nothing connected yet if (bluetoothCapable) { mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.A2DP); } mA2dpState = BluetoothA2dp.STATE_DISCONNECTED; mA2dpDevice = null; mA2dpSuspended = false; mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":StartCall"); mStartCallWakeLock.setReferenceCounted(false); mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":VoiceRecognition"); mStartVoiceRecognitionWakeLock.setReferenceCounted(false); mLocalBrsf = BRSF_AG_THREE_WAY_CALLING | BRSF_AG_EC_NR | BRSF_AG_REJECT_CALL | BRSF_AG_ENHANCED_CALL_STATUS; if (sVoiceCommandIntent == null) { sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND); sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } if (mContext.getPackageManager().resolveActivity(sVoiceCommandIntent, 0) != null && BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) { mLocalBrsf |= BRSF_AG_VOICE_RECOG; } mBluetoothPhoneState = new BluetoothPhoneState(); mUserWantsAudio = true; mVirtualCallStarted = false; mPhonebook = new BluetoothAtPhonebook(mContext, this); mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); cdmaSetSecondCallState(false); if (bluetoothCapable) { resetAtState(); } } /** * A thread that runs in the background waiting for a Sco Server Socket to * accept a connection. Even after a connection has been accepted, the Sco Server * continues to listen for new connections. */ private class IncomingScoAcceptThread extends Thread{ private final BluetoothServerSocket mIncomingServerSocket; private BluetoothSocket mIncomingSco; private boolean stopped = false; public IncomingScoAcceptThread() { BluetoothServerSocket serverSocket = null; try { serverSocket = BluetoothAdapter.listenUsingScoOn(); } catch (IOException e) { Log.e(TAG, "Could not create BluetoothServerSocket"); stopped = true; } mIncomingServerSocket = serverSocket; } @Override public void run() { while (!stopped) { try { mIncomingSco = mIncomingServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "BluetoothServerSocket could not accept connection"); } if (mIncomingSco != null) { connectSco(); } } } private void connectSco() { synchronized (mScoLock) { if (isHeadsetConnected() && (mAudioPossible || allowAudioAnytime()) && mConnectedSco == null) { Log.i(TAG, "Routing audio for incoming SCO connection"); mConnectedSco = mIncomingSco; mAudioManager.setBluetoothScoOn(true); setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTED, mHeadset.getRemoteDevice()); if (mSignalScoCloseThread == null) { mSignalScoCloseThread = new SignalScoCloseThread(); mSignalScoCloseThread.setName("SignalScoCloseThread"); mSignalScoCloseThread.start(); } } else { Log.i(TAG, "Rejecting incoming SCO connection"); try { mIncomingSco.close(); }catch (IOException e) { Log.e(TAG, "Error when closing incoming Sco socket"); } mIncomingSco = null; } } } void shutdown() { try { mIncomingServerSocket.close(); } catch (IOException e) { Log.w(TAG, "Error when closing server socket"); } stopped = true; interrupt(); } } /** * A thread that runs in the background waiting for a Sco Socket to * connect.Once the socket is connected, this thread shall be * shutdown. */ private class ScoSocketConnectThread extends Thread{ private BluetoothSocket mOutgoingSco; public ScoSocketConnectThread(BluetoothDevice device) { try { mOutgoingSco = device.createScoSocket(); } catch (IOException e) { Log.w(TAG, "Could not create BluetoothSocket"); failedScoConnect(); } } @Override public void run() { try { mOutgoingSco.connect(); }catch (IOException connectException) { Log.e(TAG, "BluetoothSocket could not connect"); mOutgoingSco = null; failedScoConnect(); } if (mOutgoingSco != null) { connectSco(); } } private void connectSco() { synchronized (mScoLock) { if (isHeadsetConnected() && mConnectedSco == null) { if (VDBG) log("Routing audio for outgoing SCO conection"); mConnectedSco = mOutgoingSco; mAudioManager.setBluetoothScoOn(true); setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTED, mHeadset.getRemoteDevice()); if (mSignalScoCloseThread == null) { mSignalScoCloseThread = new SignalScoCloseThread(); mSignalScoCloseThread.setName("SignalScoCloseThread"); mSignalScoCloseThread.start(); } } else { if (VDBG) log("Rejecting new connected outgoing SCO socket"); try { mOutgoingSco.close(); }catch (IOException e) { Log.e(TAG, "Error when closing Sco socket"); } mOutgoingSco = null; failedScoConnect(); } } } private void failedScoConnect() { // Wait for couple of secs before sending AUDIO_STATE_DISCONNECTED, // since an incoming SCO connection can happen immediately with // certain headsets. Message msg = Message.obtain(mHandler, SCO_AUDIO_STATE); msg.obj = mHeadset.getRemoteDevice(); mHandler.sendMessageDelayed(msg, 2000); } void shutdown() { closeConnectedSco(); interrupt(); } } /* * Signals when a Sco connection has been closed */ private class SignalScoCloseThread extends Thread{ private boolean stopped = false; @Override public void run() { while (!stopped) { if (mConnectedSco != null) { byte b[] = new byte[1]; InputStream inStream = null; try { inStream = mConnectedSco.getInputStream(); } catch (IOException e) {} if (inStream != null) { try { // inStream.read is a blocking call that won't ever // return anything, but will throw an exception if the // connection is closed int ret = inStream.read(b, 0, 1); }catch (IOException connectException) { // call a message to close this thread and turn off audio // we can't call audioOff directly because then // the thread would try to close itself Message msg = Message.obtain(mHandler, SCO_CLOSED); mHandler.sendMessage(msg); break; } } } } } void shutdown() { stopped = true; closeConnectedSco(); interrupt(); } } private void connectScoThread(){ if (mConnectScoThread == null) { BluetoothDevice device = mHeadset.getRemoteDevice(); if (getAudioState(device) == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) { setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTING, device); } mConnectScoThread = new ScoSocketConnectThread(mHeadset.getRemoteDevice()); mConnectScoThread.setName("HandsfreeScoSocketConnectThread"); mConnectScoThread.start(); } } private void closeConnectedSco() { if (mConnectedSco != null) { try { mConnectedSco.close(); } catch (IOException e) { Log.e(TAG, "Error when closing Sco socket"); } BluetoothDevice device = null; if (mHeadset != null) { device = mHeadset.getRemoteDevice(); } mAudioManager.setBluetoothScoOn(false); setAudioState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, device); mConnectedSco = null; } } /* package */ synchronized void onBluetoothEnabled() { /* Bluez has a bug where it will always accept and then orphan * incoming SCO connections, regardless of whether we have a listening * SCO socket. So the best thing to do is always run a listening socket * while bluetooth is on so that at least we can disconnect it * immediately when we don't want it. */ if (mIncomingScoThread == null) { mIncomingScoThread = new IncomingScoAcceptThread(); mIncomingScoThread.setName("incomingScoAcceptThread"); mIncomingScoThread.start(); } } /* package */ synchronized void onBluetoothDisabled() { // Close off the SCO sockets audioOff(); if (mIncomingScoThread != null) { try { mIncomingScoThread.shutdown(); mIncomingScoThread.join(); mIncomingScoThread = null; }catch (InterruptedException ex) { Log.w(TAG, "mIncomingScoThread close error " + ex); } } } private boolean isHeadsetConnected() { if (mHeadset == null) { return false; } return mHeadset.isConnected(); } /* package */ synchronized void connectHeadset(HeadsetBase headset, int headsetType) { mHeadset = headset; mHeadsetType = headsetType; if (mHeadsetType == TYPE_HEADSET) { initializeHeadsetAtParser(); } else { initializeHandsfreeAtParser(); } // Headset vendor-specific commands registerAllVendorSpecificCommands(); headset.startEventThread(); configAudioParameters(); if (inDebug()) { startDebug(); } if (isIncallAudio()) { audioOn(); } } /* returns true if there is some kind of in-call audio we may wish to route * bluetooth to */ private boolean isIncallAudio() { Call.State state = mCM.getActiveFgCallState(); return (state == Call.State.ACTIVE || state == Call.State.ALERTING); } /* package */ synchronized void disconnectHeadset() { audioOff(); mHeadset = null; stopDebug(); resetAtState(); } /* package */ synchronized void resetAtState() { mClip = false; mIndicatorsEnabled = false; mServiceConnectionEstablished = false; mCmee = false; mClccTimestamps = new long[GSM_MAX_CONNECTIONS]; mClccUsed = new boolean[GSM_MAX_CONNECTIONS]; for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { mClccUsed[i] = false; } mRemoteBrsf = 0; mPhonebook.resetAtState(); } private void configAudioParameters() { String name = mHeadset.getRemoteDevice().getName(); if (name == null) { name = "<unknown>"; } mAudioManager.setParameters(HEADSET_NAME+"="+name+";"+HEADSET_NREC+"=on"); } /** Represents the data that we send in a +CIND or +CIEV command to the HF */ private class BluetoothPhoneState { // 0: no service // 1: service private int mService; // 0: no active call // 1: active call (where active means audio is routed - not held call) private int mCall; // 0: not in call setup // 1: incoming call setup // 2: outgoing call setup // 3: remote party being alerted in an outgoing call setup private int mCallsetup; // 0: no calls held // 1: held call and active call // 2: held call only private int mCallheld; // cellular signal strength of AG: 0-5 private int mSignal; // cellular signal strength in CSQ rssi scale private int mRssi; // for CSQ // 0: roaming not active (home) // 1: roaming active private int mRoam; // battery charge of AG: 0-5 private int mBattchg; // 0: not registered // 1: registered, home network // 5: registered, roaming private int mStat; // for CREG private String mRingingNumber; // Context for in-progress RING's private int mRingingType; private boolean mIgnoreRing = false; private boolean mStopRing = false; private static final int SERVICE_STATE_CHANGED = 1; private static final int PRECISE_CALL_STATE_CHANGED = 2; private static final int RING = 3; private static final int PHONE_CDMA_CALL_WAITING = 4; private Handler mStateChangeHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case RING: AtCommandResult result = ring(); if (result != null) { sendURC(result.toString()); } break; case SERVICE_STATE_CHANGED: ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result; updateServiceState(sendUpdate(), state); break; case PRECISE_CALL_STATE_CHANGED: case PHONE_CDMA_CALL_WAITING: Connection connection = null; if (((AsyncResult) msg.obj).result instanceof Connection) { connection = (Connection) ((AsyncResult) msg.obj).result; } handlePreciseCallStateChange(sendUpdate(), connection); break; } } }; private BluetoothPhoneState() { // init members // TODO May consider to repalce the default phone's state and signal // by CallManagter's state and signal updateServiceState(false, mCM.getDefaultPhone().getServiceState()); handlePreciseCallStateChange(false, null); mBattchg = 5; // There is currently no API to get battery level // on demand, so set to 5 and wait for an update mSignal = asuToSignal(mCM.getDefaultPhone().getSignalStrength()); // register for updates // Use the service state of default phone as BT service state to // avoid situation such as no cell or wifi connection but still // reporting in service (since SipPhone always reports in service). mCM.getDefaultPhone().registerForServiceStateChanged(mStateChangeHandler, SERVICE_STATE_CHANGED, null); mCM.registerForPreciseCallStateChanged(mStateChangeHandler, PRECISE_CALL_STATE_CHANGED, null); mCM.registerForCallWaiting(mStateChangeHandler, PHONE_CDMA_CALL_WAITING, null); IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); filter.addAction(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED); filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); mContext.registerReceiver(mStateReceiver, filter); } private void updateBtPhoneStateAfterRadioTechnologyChange() { if(VDBG) Log.d(TAG, "updateBtPhoneStateAfterRadioTechnologyChange..."); //Unregister all events from the old obsolete phone mCM.getDefaultPhone().unregisterForServiceStateChanged(mStateChangeHandler); mCM.unregisterForPreciseCallStateChanged(mStateChangeHandler); mCM.unregisterForCallWaiting(mStateChangeHandler); //Register all events new to the new active phone mCM.getDefaultPhone().registerForServiceStateChanged(mStateChangeHandler, SERVICE_STATE_CHANGED, null); mCM.registerForPreciseCallStateChanged(mStateChangeHandler, PRECISE_CALL_STATE_CHANGED, null); mCM.registerForCallWaiting(mStateChangeHandler, PHONE_CDMA_CALL_WAITING, null); } private boolean sendUpdate() { return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mIndicatorsEnabled; } private boolean sendClipUpdate() { return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mClip; } private void stopRing() { mStopRing = true; } /* convert [0,31] ASU signal strength to the [0,5] expected by * bluetooth devices. Scale is similar to status bar policy */ private int gsmAsuToSignal(SignalStrength signalStrength) { int asu = signalStrength.getGsmSignalStrength(); if (asu >= 16) return 5; else if (asu >= 8) return 4; else if (asu >= 4) return 3; else if (asu >= 2) return 2; else if (asu >= 1) return 1; else return 0; } /** * Convert the cdma / evdo db levels to appropriate icon level. * The scale is similar to the one used in status bar policy. * * @param signalStrength * @return the icon level */ private int cdmaDbmEcioToSignal(SignalStrength signalStrength) { int levelDbm = 0; int levelEcio = 0; int cdmaIconLevel = 0; int evdoIconLevel = 0; int cdmaDbm = signalStrength.getCdmaDbm(); int cdmaEcio = signalStrength.getCdmaEcio(); if (cdmaDbm >= -75) levelDbm = 4; else if (cdmaDbm >= -85) levelDbm = 3; else if (cdmaDbm >= -95) levelDbm = 2; else if (cdmaDbm >= -100) levelDbm = 1; else levelDbm = 0; // Ec/Io are in dB*10 if (cdmaEcio >= -90) levelEcio = 4; else if (cdmaEcio >= -110) levelEcio = 3; else if (cdmaEcio >= -130) levelEcio = 2; else if (cdmaEcio >= -150) levelEcio = 1; else levelEcio = 0; cdmaIconLevel = (levelDbm < levelEcio) ? levelDbm : levelEcio; if (mServiceState != null && (mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_0 || mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_A)) { int evdoEcio = signalStrength.getEvdoEcio(); int evdoSnr = signalStrength.getEvdoSnr(); int levelEvdoEcio = 0; int levelEvdoSnr = 0; // Ec/Io are in dB*10 if (evdoEcio >= -650) levelEvdoEcio = 4; else if (evdoEcio >= -750) levelEvdoEcio = 3; else if (evdoEcio >= -900) levelEvdoEcio = 2; else if (evdoEcio >= -1050) levelEvdoEcio = 1; else levelEvdoEcio = 0; if (evdoSnr > 7) levelEvdoSnr = 4; else if (evdoSnr > 5) levelEvdoSnr = 3; else if (evdoSnr > 3) levelEvdoSnr = 2; else if (evdoSnr > 1) levelEvdoSnr = 1; else levelEvdoSnr = 0; evdoIconLevel = (levelEvdoEcio < levelEvdoSnr) ? levelEvdoEcio : levelEvdoSnr; } // TODO(): There is a bug open regarding what should be sent. return (cdmaIconLevel > evdoIconLevel) ? cdmaIconLevel : evdoIconLevel; } private int asuToSignal(SignalStrength signalStrength) { if (signalStrength.isGsm()) { return gsmAsuToSignal(signalStrength); } else { return cdmaDbmEcioToSignal(signalStrength); } } /* convert [0,5] signal strength to a rssi signal strength for CSQ * which is [0,31]. Despite the same scale, this is not the same value * as ASU. */ private int signalToRssi(int signal) { // using C4A suggested values switch (signal) { case 0: return 0; case 1: return 4; case 2: return 8; case 3: return 13; case 4: return 19; case 5: return 31; } return 0; } private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { updateBatteryState(intent); } else if (intent.getAction().equals( TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED)) { updateSignalState(intent); } else if (intent.getAction().equals( BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) { int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED); int oldState = intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, BluetoothProfile.STATE_DISCONNECTED); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // We are only concerned about Connected sinks to suspend and resume // them. We can safely ignore SINK_STATE_CHANGE for other devices. if (mA2dpDevice != null && !device.equals(mA2dpDevice)) return; synchronized (BluetoothHandsfree.this) { mA2dpState = state; if (state == BluetoothProfile.STATE_DISCONNECTED) { mA2dpDevice = null; } else { mA2dpDevice = device; } if (oldState == BluetoothA2dp.STATE_PLAYING && mA2dpState == BluetoothProfile.STATE_CONNECTED) { if (mA2dpSuspended) { if (mPendingSco) { mHandler.removeMessages(MESSAGE_CHECK_PENDING_SCO); if (DBG) log("A2DP suspended, completing SCO"); connectScoThread(); mPendingSco = false; } } } } } } }; private synchronized void updateBatteryState(Intent intent) { int batteryLevel = intent.getIntExtra("level", -1); int scale = intent.getIntExtra("scale", -1); if (batteryLevel == -1 || scale == -1) { return; // ignore } batteryLevel = batteryLevel * 5 / scale; if (mBattchg != batteryLevel) { mBattchg = batteryLevel; if (sendUpdate()) { sendURC("+CIEV: 7," + mBattchg); } } } private synchronized void updateSignalState(Intent intent) { // NOTE this function is called by the BroadcastReceiver mStateReceiver after intent // ACTION_SIGNAL_STRENGTH_CHANGED and by the DebugThread mDebugThread if (mHeadset == null) { return; } SignalStrength signalStrength = SignalStrength.newFromBundle(intent.getExtras()); int signal; if (signalStrength != null) { signal = asuToSignal(signalStrength); mRssi = signalToRssi(signal); // no unsolicited CSQ if (signal != mSignal) { mSignal = signal; if (sendUpdate()) { sendURC("+CIEV: 5," + mSignal); } } } else { Log.e(TAG, "Signal Strength null"); } } private synchronized void updateServiceState(boolean sendUpdate, ServiceState state) { int service = state.getState() == ServiceState.STATE_IN_SERVICE ? 1 : 0; int roam = state.getRoaming() ? 1 : 0; int stat; AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); mServiceState = state; if (service == 0) { stat = 0; } else { stat = (roam == 1) ? 5 : 1; } if (service != mService) { mService = service; if (sendUpdate) { result.addResponse("+CIEV: 1," + mService); } } if (roam != mRoam) { mRoam = roam; if (sendUpdate) { result.addResponse("+CIEV: 6," + mRoam); } } if (stat != mStat) { mStat = stat; if (sendUpdate) { result.addResponse(toCregString()); } } sendURC(result.toString()); } private synchronized void handlePreciseCallStateChange(boolean sendUpdate, Connection connection) { int call = 0; int callsetup = 0; int callheld = 0; int prevCallsetup = mCallsetup; AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); Call foregroundCall = mCM.getActiveFgCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); Call ringingCall = mCM.getFirstActiveRingingCall(); if (VDBG) log("updatePhoneState()"); // This function will get called when the Precise Call State // {@link Call.State} changes. Hence, we might get this update // even if the {@link Phone.state} is same as before. // Check for the same. Phone.State newState = mCM.getState(); if (newState != mPhoneState) { mPhoneState = newState; switch (mPhoneState) { case IDLE: mUserWantsAudio = true; // out of call - reset state audioOff(); break; default: callStarted(); } } switch(foregroundCall.getState()) { case ACTIVE: call = 1; mAudioPossible = true; break; case DIALING: callsetup = 2; mAudioPossible = true; // We also need to send a Call started indication // for cases where the 2nd MO was initiated was // from a *BT hands free* and is waiting for a // +BLND: OK response // There is a special case handling of the same case // for CDMA below if (mCM.getFgPhone().getPhoneType() == Phone.PHONE_TYPE_GSM) { callStarted(); } break; case ALERTING: callsetup = 3; // Open the SCO channel for the outgoing call. audioOn(); mAudioPossible = true; break; case DISCONNECTING: // This is a transient state, we don't want to send // any AT commands during this state. call = mCall; callsetup = mCallsetup; callheld = mCallheld; break; default: mAudioPossible = false; } switch(ringingCall.getState()) { case INCOMING: case WAITING: callsetup = 1; break; case DISCONNECTING: // This is a transient state, we don't want to send // any AT commands during this state. call = mCall; callsetup = mCallsetup; callheld = mCallheld; break; } switch(backgroundCall.getState()) { case HOLDING: if (call == 1) { callheld = 1; } else { call = 1; callheld = 2; } break; case DISCONNECTING: // This is a transient state, we don't want to send // any AT commands during this state. call = mCall; callsetup = mCallsetup; callheld = mCallheld; break; } if (mCall != call) { if (call == 1) { // This means that a call has transitioned from NOT ACTIVE to ACTIVE. // Switch on audio. audioOn(); } mCall = call; if (sendUpdate) { result.addResponse("+CIEV: 2," + mCall); } } if (mCallsetup != callsetup) { mCallsetup = callsetup; if (sendUpdate) { // If mCall = 0, send CIEV // mCall = 1, mCallsetup = 0, send CIEV // mCall = 1, mCallsetup = 1, send CIEV after CCWA, // if 3 way supported. // mCall = 1, mCallsetup = 2 / 3 -> send CIEV, // if 3 way is supported if (mCall != 1 || mCallsetup == 0 || mCallsetup != 1 && (mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CIEV: 3," + mCallsetup); } } } if (mCM.getDefaultPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA) { PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); callheld = getCdmaCallHeldStatus(currCdmaThreeWayCallState, prevCdmaThreeWayCallState); if (mCdmaThreeWayCallState != currCdmaThreeWayCallState) { // In CDMA, the network does not provide any feedback // to the phone when the 2nd MO call goes through the // stages of DIALING > ALERTING -> ACTIVE we fake the // sequence if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { mAudioPossible = true; if (sendUpdate) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CIEV: 3,2"); result.addResponse("+CIEV: 3,3"); result.addResponse("+CIEV: 3,0"); } } // We also need to send a Call started indication // for cases where the 2nd MO was initiated was // from a *BT hands free* and is waiting for a // +BLND: OK response callStarted(); } // In CDMA, the network does not provide any feedback to // the phone when a user merges a 3way call or swaps // between two calls we need to send a CIEV response // indicating that a call state got changed which should // trigger a CLCC update request from the BT client. if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { mAudioPossible = true; if (sendUpdate) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CIEV: 2,1"); result.addResponse("+CIEV: 3,0"); } } } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } boolean callsSwitched = (callheld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); if (mCallheld != callheld || callsSwitched) { mCallheld = callheld; if (sendUpdate) { result.addResponse("+CIEV: 4," + mCallheld); } } if (callsetup == 1 && callsetup != prevCallsetup) { // new incoming call String number = null; int type = 128; // find incoming phone number and type if (connection == null) { connection = ringingCall.getEarliestConnection(); if (connection == null) { Log.e(TAG, "Could not get a handle on Connection object for new " + "incoming call"); } } if (connection != null) { number = connection.getAddress(); if (number != null) { type = PhoneNumberUtils.toaFromString(number); } } if (number == null) { number = ""; } if ((call != 0 || callheld != 0) && sendUpdate) { // call waiting if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) { result.addResponse("+CCWA: \"" + number + "\"," + type); result.addResponse("+CIEV: 3," + callsetup); } } else { // regular new incoming call mRingingNumber = number; mRingingType = type; mIgnoreRing = false; mStopRing = false; if ((mLocalBrsf & BRSF_AG_IN_BAND_RING) != 0x0) { audioOn(); } result.addResult(ring()); } } sendURC(result.toString()); } private int getCdmaCallHeldStatus(CdmaPhoneCallState.PhoneCallState currState, CdmaPhoneCallState.PhoneCallState prevState) { int callheld; // Update the Call held information if (currState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (prevState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { callheld = 0; //0: no calls held, as now *both* the caller are active } else { callheld = 1; //1: held call and active call, as on answering a // Call Waiting, one of the caller *is* put on hold } } else if (currState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { callheld = 1; //1: held call and active call, as on make a 3 Way Call // the first caller *is* put on hold } else { callheld = 0; //0: no calls held as this is a SINGLE_ACTIVE call } return callheld; } private AtCommandResult ring() { if (!mIgnoreRing && !mStopRing && mCM.getFirstActiveRingingCall().isRinging()) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("RING"); if (sendClipUpdate()) { result.addResponse("+CLIP: \"" + mRingingNumber + "\"," + mRingingType); } Message msg = mStateChangeHandler.obtainMessage(RING); mStateChangeHandler.sendMessageDelayed(msg, 3000); return result; } return null; } private synchronized String toCregString() { return new String("+CREG: 1," + mStat); } private synchronized AtCommandResult toCindResult() { AtCommandResult result = new AtCommandResult(AtCommandResult.OK); int call, call_setup; // Handsfree carkits expect that +CIND is properly responded to. // Hence we ensure that a proper response is sent for the virtual call too. if (isVirtualCallInProgress()) { call = 1; call_setup = 0; } else { // regular phone call call = mCall; call_setup = mCallsetup; } mSignal = asuToSignal(mCM.getDefaultPhone().getSignalStrength()); String status = "+CIND: " + mService + "," + call + "," + call_setup + "," + mCallheld + "," + mSignal + "," + mRoam + "," + mBattchg; result.addResponse(status); return result; } private synchronized AtCommandResult toCsqResult() { AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String status = "+CSQ: " + mRssi + ",99"; result.addResponse(status); return result; } private synchronized AtCommandResult getCindTestResult() { return new AtCommandResult("+CIND: (\"service\",(0-1))," + "(\"call\",(0-1))," + "(\"callsetup\",(0-3)),(\"callheld\",(0-2)),(\"signal\",(0-5))," + "(\"roam\",(0-1)),(\"battchg\",(0-5))"); } private synchronized void ignoreRing() { mCallsetup = 0; mIgnoreRing = true; if (sendUpdate()) { sendURC("+CIEV: 3," + mCallsetup); } } }; private static final int SCO_CLOSED = 3; private static final int CHECK_CALL_STARTED = 4; private static final int CHECK_VOICE_RECOGNITION_STARTED = 5; private static final int MESSAGE_CHECK_PENDING_SCO = 6; private static final int SCO_AUDIO_STATE = 7; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { synchronized (BluetoothHandsfree.this) { switch (msg.what) { case SCO_CLOSED: audioOff(); break; case CHECK_CALL_STARTED: if (mWaitingForCallStart) { mWaitingForCallStart = false; Log.e(TAG, "Timeout waiting for call to start"); sendURC("ERROR"); if (mStartCallWakeLock.isHeld()) { mStartCallWakeLock.release(); } } break; case CHECK_VOICE_RECOGNITION_STARTED: if (mWaitingForVoiceRecognition) { mWaitingForVoiceRecognition = false; Log.e(TAG, "Timeout waiting for voice recognition to start"); sendURC("ERROR"); } break; case MESSAGE_CHECK_PENDING_SCO: if (mPendingSco && isA2dpMultiProfile()) { Log.w(TAG, "Timeout suspending A2DP for SCO (mA2dpState = " + mA2dpState + "). Starting SCO anyway"); connectScoThread(); mPendingSco = false; } break; case SCO_AUDIO_STATE: BluetoothDevice device = (BluetoothDevice) msg.obj; if (getAudioState(device) == BluetoothHeadset.STATE_AUDIO_CONNECTING) { setAudioState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, device); } break; } } } }; private synchronized void setAudioState(int state, BluetoothDevice device) { if (VDBG) log("setAudioState(" + state + ")"); if (mBluetoothHeadset == null) { mAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET); mPendingAudioState = true; mAudioState = state; return; } mBluetoothHeadset.setAudioState(device, state); } private synchronized int getAudioState(BluetoothDevice device) { if (mBluetoothHeadset == null) return BluetoothHeadset.STATE_AUDIO_DISCONNECTED; return mBluetoothHeadset.getAudioState(device); } private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { public void onServiceConnected(int profile, BluetoothProfile proxy) { if (profile == BluetoothProfile.HEADSET) { mBluetoothHeadset = (BluetoothHeadset) proxy; synchronized(BluetoothHandsfree.this) { if (mPendingAudioState) { mBluetoothHeadset.setAudioState(mHeadset.getRemoteDevice(), mAudioState); mPendingAudioState = false; } } } else if (profile == BluetoothProfile.A2DP) { mA2dp = (BluetoothA2dp) proxy; } } public void onServiceDisconnected(int profile) { if (profile == BluetoothProfile.HEADSET) { mBluetoothHeadset = null; } else if (profile == BluetoothProfile.A2DP) { mA2dp = null; } } }; /* * Put the AT command, company ID, arguments, and device in an Intent and broadcast it. */ private void broadcastVendorSpecificEventIntent(String command, int companyId, int commandType, Object[] arguments, BluetoothDevice device) { if (VDBG) log("broadcastVendorSpecificEventIntent(" + command + ")"); Intent intent = new Intent(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT); intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD, command); intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD_TYPE, commandType); // assert: all elements of args are Serializable intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS, arguments); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "." + Integer.toString(companyId)); mContext.sendBroadcast(intent, android.Manifest.permission.BLUETOOTH); } void updateBtHandsfreeAfterRadioTechnologyChange() { if (VDBG) Log.d(TAG, "updateBtHandsfreeAfterRadioTechnologyChange..."); mBluetoothPhoneState.updateBtPhoneStateAfterRadioTechnologyChange(); } /** Request to establish SCO (audio) connection to bluetooth * headset/handsfree, if one is connected. Does not block. * Returns false if the user has requested audio off, or if there * is some other immediate problem that will prevent BT audio. */ /* package */ synchronized boolean audioOn() { if (VDBG) log("audioOn()"); if (!isHeadsetConnected()) { if (DBG) log("audioOn(): headset is not connected!"); return false; } if (mHeadsetType == TYPE_HANDSFREE && !mServiceConnectionEstablished) { if (DBG) log("audioOn(): service connection not yet established!"); return false; } if (mConnectedSco != null) { if (DBG) log("audioOn(): audio is already connected"); return true; } if (!mUserWantsAudio) { if (DBG) log("audioOn(): user requested no audio, ignoring"); return false; } if (mPendingSco) { if (DBG) log("audioOn(): SCO already pending"); return true; } mA2dpSuspended = false; mPendingSco = false; if (isA2dpMultiProfile() && mA2dpState == BluetoothA2dp.STATE_PLAYING) { if (DBG) log("suspending A2DP stream for SCO"); mA2dpSuspended = mA2dp.suspendSink(mA2dpDevice); if (mA2dpSuspended) { mPendingSco = true; Message msg = mHandler.obtainMessage(MESSAGE_CHECK_PENDING_SCO); mHandler.sendMessageDelayed(msg, 2000); } else { Log.w(TAG, "Could not suspend A2DP stream for SCO, going ahead with SCO"); } } if (!mPendingSco) { connectScoThread(); } return true; } /** Used to indicate the user requested BT audio on. * This will establish SCO (BT audio), even if the user requested it off * previously on this call. */ /* package */ synchronized void userWantsAudioOn() { mUserWantsAudio = true; audioOn(); } /** Used to indicate the user requested BT audio off. * This will prevent us from establishing BT audio again during this call * if audioOn() is called. */ /* package */ synchronized void userWantsAudioOff() { mUserWantsAudio = false; audioOff(); } /** Request to disconnect SCO (audio) connection to bluetooth * headset/handsfree, if one is connected. Does not block. */ /* package */ synchronized void audioOff() { if (VDBG) log("audioOff(): mPendingSco: " + mPendingSco + ", mConnectedSco: " + mConnectedSco + ", mA2dpState: " + mA2dpState + ", mA2dpSuspended: " + mA2dpSuspended); if (mA2dpSuspended) { if (isA2dpMultiProfile()) { if (DBG) log("resuming A2DP stream after disconnecting SCO"); mA2dp.resumeSink(mA2dpDevice); } mA2dpSuspended = false; } mPendingSco = false; if (mSignalScoCloseThread != null) { try { mSignalScoCloseThread.shutdown(); mSignalScoCloseThread.join(); mSignalScoCloseThread = null; }catch (InterruptedException ex) { Log.w(TAG, "mSignalScoCloseThread close error " + ex); } } if (mConnectScoThread != null) { try { mConnectScoThread.shutdown(); mConnectScoThread.join(); mConnectScoThread = null; }catch (InterruptedException ex) { Log.w(TAG, "mConnectScoThread close error " + ex); } } closeConnectedSco(); // Should be closed already, but just in case } /* package */ boolean isAudioOn() { return (mConnectedSco != null); } private boolean isA2dpMultiProfile() { return mA2dp != null && mHeadset != null && mA2dpDevice != null && mA2dpDevice.equals(mHeadset.getRemoteDevice()); } /* package */ void ignoreRing() { mBluetoothPhoneState.ignoreRing(); } private void sendURC(String urc) { if (isHeadsetConnected()) { mHeadset.sendURC(urc); } } /** helper to redial last dialled number */ private AtCommandResult redial() { String number = mPhonebook.getLastDialledNumber(); if (number == null) { // spec seems to suggest sending ERROR if we dont have a // number to redial if (VDBG) log("Bluetooth redial requested (+BLDN), but no previous " + "outgoing calls found. Ignoring"); return new AtCommandResult(AtCommandResult.ERROR); } // Outgoing call initiated by the handsfree device // Send terminateVirtualVoiceCall terminateVirtualVoiceCall(); Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", number, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); // We do not immediately respond OK, wait until we get a phone state // update. If we return OK now and the handsfree immeidately requests // our phone state it will say we are not in call yet which confuses // some devices expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } /** Build the +CLCC result * The complexity arises from the fact that we need to maintain the same * CLCC index even as a call moves between states. */ private synchronized AtCommandResult gsmGetClccResult() { // Collect all known connections Connection[] clccConnections = new Connection[GSM_MAX_CONNECTIONS]; // indexed by CLCC index LinkedList<Connection> newConnections = new LinkedList<Connection>(); LinkedList<Connection> connections = new LinkedList<Connection>(); Call foregroundCall = mCM.getActiveFgCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); Call ringingCall = mCM.getFirstActiveRingingCall(); if (ringingCall.getState().isAlive()) { connections.addAll(ringingCall.getConnections()); } if (foregroundCall.getState().isAlive()) { connections.addAll(foregroundCall.getConnections()); } if (backgroundCall.getState().isAlive()) { connections.addAll(backgroundCall.getConnections()); } // Mark connections that we already known about boolean clccUsed[] = new boolean[GSM_MAX_CONNECTIONS]; for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { clccUsed[i] = mClccUsed[i]; mClccUsed[i] = false; } for (Connection c : connections) { boolean found = false; long timestamp = c.getCreateTime(); for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { if (clccUsed[i] && timestamp == mClccTimestamps[i]) { mClccUsed[i] = true; found = true; clccConnections[i] = c; break; } } if (!found) { newConnections.add(c); } } // Find a CLCC index for new connections while (!newConnections.isEmpty()) { // Find lowest empty index int i = 0; while (mClccUsed[i]) i++; // Find earliest connection long earliestTimestamp = newConnections.get(0).getCreateTime(); Connection earliestConnection = newConnections.get(0); for (int j = 0; j < newConnections.size(); j++) { long timestamp = newConnections.get(j).getCreateTime(); if (timestamp < earliestTimestamp) { earliestTimestamp = timestamp; earliestConnection = newConnections.get(j); } } // update mClccUsed[i] = true; mClccTimestamps[i] = earliestTimestamp; clccConnections[i] = earliestConnection; newConnections.remove(earliestConnection); } // Build CLCC AtCommandResult result = new AtCommandResult(AtCommandResult.OK); for (int i = 0; i < clccConnections.length; i++) { if (mClccUsed[i]) { String clccEntry = connectionToClccEntry(i, clccConnections[i]); if (clccEntry != null) { result.addResponse(clccEntry); } } } return result; } /** Convert a Connection object into a single +CLCC result */ private String connectionToClccEntry(int index, Connection c) { int state; switch (c.getState()) { case ACTIVE: state = 0; break; case HOLDING: state = 1; break; case DIALING: state = 2; break; case ALERTING: state = 3; break; case INCOMING: state = 4; break; case WAITING: state = 5; break; default: return null; // bad state } int mpty = 0; Call call = c.getCall(); if (call != null) { mpty = call.isMultiparty() ? 1 : 0; } int direction = c.isIncoming() ? 1 : 0; String number = c.getAddress(); int type = -1; if (number != null) { type = PhoneNumberUtils.toaFromString(number); } String result = "+CLCC: " + (index + 1) + "," + direction + "," + state + ",0," + mpty; if (number != null) { result += ",\"" + number + "\"," + type; } return result; } /** Build the +CLCC result for CDMA * The complexity arises from the fact that we need to maintain the same * CLCC index even as a call moves between states. */ private synchronized AtCommandResult cdmaGetClccResult() { // In CDMA at one time a user can have only two live/active connections Connection[] clccConnections = new Connection[CDMA_MAX_CONNECTIONS];// indexed by CLCC index Call foregroundCall = mCM.getActiveFgCall(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call.State ringingCallState = ringingCall.getState(); // If the Ringing Call state is INCOMING, that means this is the very first call // hence there should not be any Foreground Call if (ringingCallState == Call.State.INCOMING) { if (VDBG) log("Filling clccConnections[0] for INCOMING state"); clccConnections[0] = ringingCall.getLatestConnection(); } else if (foregroundCall.getState().isAlive()) { // Getting Foreground Call connection based on Call state if (ringingCall.isRinging()) { if (VDBG) log("Filling clccConnections[0] & [1] for CALL WAITING state"); clccConnections[0] = foregroundCall.getEarliestConnection(); clccConnections[1] = ringingCall.getLatestConnection(); } else { if (foregroundCall.getConnections().size() <= 1) { // Single call scenario if (VDBG) log("Filling clccConnections[0] with ForgroundCall latest connection"); clccConnections[0] = foregroundCall.getLatestConnection(); } else { // Multiple Call scenario. This would be true for both // CONF_CALL and THRWAY_ACTIVE state if (VDBG) log("Filling clccConnections[0] & [1] with ForgroundCall connections"); clccConnections[0] = foregroundCall.getEarliestConnection(); clccConnections[1] = foregroundCall.getLatestConnection(); } } } // Update the mCdmaIsSecondCallActive flag based on the Phone call state if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) { cdmaSetSecondCallState(false); } else if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { cdmaSetSecondCallState(true); } // Build CLCC AtCommandResult result = new AtCommandResult(AtCommandResult.OK); for (int i = 0; (i < clccConnections.length) && (clccConnections[i] != null); i++) { String clccEntry = cdmaConnectionToClccEntry(i, clccConnections[i]); if (clccEntry != null) { result.addResponse(clccEntry); } } return result; } /** Convert a Connection object into a single +CLCC result for CDMA phones */ private String cdmaConnectionToClccEntry(int index, Connection c) { int state; PhoneApp app = PhoneApp.getInstance(); CdmaPhoneCallState.PhoneCallState currCdmaCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaCallState = app.cdmaPhoneCallState.getPreviousCallState(); if ((prevCdmaCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL)) { // If the current state is reached after merging two calls // we set the state of all the connections as ACTIVE state = 0; } else { switch (c.getState()) { case ACTIVE: // For CDMA since both the connections are set as active by FW after accepting // a Call waiting or making a 3 way call, we need to set the state specifically // to ACTIVE/HOLDING based on the mCdmaIsSecondCallActive flag. This way the // CLCC result will allow BT devices to enable the swap or merge options if (index == 0) { // For the 1st active connection state = mCdmaIsSecondCallActive ? 1 : 0; } else { // for the 2nd active connection state = mCdmaIsSecondCallActive ? 0 : 1; } break; case HOLDING: state = 1; break; case DIALING: state = 2; break; case ALERTING: state = 3; break; case INCOMING: state = 4; break; case WAITING: state = 5; break; default: return null; // bad state } } int mpty = 0; if (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { mpty = 1; } else { mpty = 0; } int direction = c.isIncoming() ? 1 : 0; String number = c.getAddress(); int type = -1; if (number != null) { type = PhoneNumberUtils.toaFromString(number); } String result = "+CLCC: " + (index + 1) + "," + direction + "," + state + ",0," + mpty; if (number != null) { result += ",\"" + number + "\"," + type; } return result; } /* * Register a vendor-specific command. * @param commandName the name of the command. For example, if the expected * incoming command is <code>AT+FOO=bar,baz</code>, the value of this should be * <code>"+FOO"</code>. * @param companyId the Bluetooth SIG Company Identifier * @param parser the AtParser on which to register the command */ private void registerVendorSpecificCommand(String commandName, int companyId, AtParser parser) { parser.register(commandName, new VendorSpecificCommandHandler(commandName, companyId)); } /* * Register all vendor-specific commands here. */ private void registerAllVendorSpecificCommands() { AtParser parser = mHeadset.getAtParser(); // Plantronics-specific headset events go here registerVendorSpecificCommand("+XEVENT", BluetoothAssignedNumbers.PLANTRONICS, parser); } /** * Register AT Command handlers to implement the Headset profile */ private void initializeHeadsetAtParser() { if (VDBG) log("Registering Headset AT commands"); AtParser parser = mHeadset.getAtParser(); // Headsets usually only have one button, which is meant to cause the // HS to send us AT+CKPD=200 or AT+CKPD. parser.register("+CKPD", new AtCommandHandler() { private AtCommandResult headsetButtonPress() { if (mCM.getFirstActiveRingingCall().isRinging()) { // Answer the call mBluetoothPhoneState.stopRing(); sendURC("OK"); PhoneUtils.answerCall(mCM.getFirstActiveRingingCall()); // If in-band ring tone is supported, SCO connection will already // be up and the following call will just return. audioOn(); return new AtCommandResult(AtCommandResult.UNSOLICITED); } else if (mCM.hasActiveFgCall()) { if (!isAudioOn()) { // Transfer audio from AG to HS audioOn(); } else { if (mHeadset.getDirection() == HeadsetBase.DIRECTION_INCOMING && (System.currentTimeMillis() - mHeadset.getConnectTimestamp()) < 5000) { // Headset made a recent ACL connection to us - and // made a mandatory AT+CKPD request to connect // audio which races with our automatic audio // setup. ignore } else { // Hang up the call audioOff(); PhoneUtils.hangup(PhoneApp.getInstance().mCM); } } return new AtCommandResult(AtCommandResult.OK); } else { // No current call - redial last number return redial(); } } @Override public AtCommandResult handleActionCommand() { return headsetButtonPress(); } @Override public AtCommandResult handleSetCommand(Object[] args) { return headsetButtonPress(); } }); } /** * Register AT Command handlers to implement the Handsfree profile */ private void initializeHandsfreeAtParser() { if (VDBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); final Phone phone = mCM.getDefaultPhone(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { sendURC("OK"); mBluetoothPhoneState.stopRing(); PhoneUtils.answerCall(mCM.getFirstActiveRingingCall()); return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Send terminateVirtualVoiceCall terminateVirtualVoiceCall(); // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { sendURC("OK"); if (isVirtualCallInProgress()) { - //TODO(): Need a way to inform the audio manager. terminateVirtualVoiceCall(); } else { if (mCM.hasActiveFgCall()) { PhoneUtils.hangupActiveCall(mCM.getActiveFgCall()); } else if (mCM.hasActiveRingingCall()) { PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall()); } else if (mCM.hasActiveBgCall()) { PhoneUtils.hangupHoldingCall(mCM.getFirstActiveBgCall()); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mBluetoothPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mBluetoothPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mBluetoothPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mBluetoothPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { phone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int phoneType = phone.getPhoneType(); // Handsfree carkits expect that +CLCC is properly responded to. // Hence we ensure that a proper response is sent for the virtual call too. if (isVirtualCallInProgress()) { String number = phone.getLine1Number(); AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String args; if (number == null) { args = "+CLCC: 1,0,0,0,0,\"\",0"; } else { args = "+CLCC: 1,0,0,0,0,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number); } result.addResponse(args); return result; } if (phoneType == Phone.PHONE_TYPE_CDMA) { return cdmaGetClccResult(); } else if (phoneType == Phone.PHONE_TYPE_GSM) { return gsmGetClccResult(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { int phoneType = phone.getPhoneType(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (ringingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(ringingCall); } else { result = PhoneUtils.hangupHoldingCall(backgroundCall); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { if (ringingCall.isRinging()) { // If there is Call waiting then answer the call and // put the first call on hold. if (VDBG) log("CHLD:1 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else { // If there is no Call waiting then just hangup // the active call. In CDMA this mean that the complete // call session would be ended if (VDBG) log("CHLD:1 Hangup Call"); PhoneUtils.hangup(PhoneApp.getInstance().mCM); } return new AtCommandResult(AtCommandResult.OK); } else if (phoneType == Phone.PHONE_TYPE_GSM) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive( PhoneApp.getInstance().mCM, ringingCall)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else if (args[0].equals(2)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, the way we switch to a new incoming call is by // calling PhoneUtils.answerCall(). switchAndHoldActive() won't // properly update the call state within telephony. // If the Phone state is already in CONF_CALL then we simply send // a flash cmd by calling switchHoldingAndActive() if (ringingCall.isRinging()) { if (VDBG) log("CHLD:2 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else if (PhoneApp.getInstance().cdmaPhoneCallState .getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (VDBG) log("CHLD:2 Swap Calls"); PhoneUtils.switchHoldingAndActive(backgroundCall); // Toggle the second callers active state flag cdmaSwapSecondCallState(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { PhoneUtils.switchHoldingAndActive(backgroundCall); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, we need to check if the call is in THRWAY_ACTIVE state if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { if (VDBG) log("CHLD:3 Merge Calls"); PhoneUtils.mergeCalls(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { if (mCM.hasActiveFgCall() && mCM.hasActiveBgCall()) { PhoneUtils.mergeCalls(); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; sendURC("+CHLD: (0,1,2,3)"); sendURC("OK"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = phone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = phone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // phone will not be NULL at this point. return new AtCommandResult("+CGSN: " + phone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameters(HEADSET_NREC+"=off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameters(HEADSET_NREC+"=on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (!BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) { return new AtCommandResult(AtCommandResult.ERROR); } - // Send terminateVirtualVoiceCall - // TODO(): Need a way to inform the audio manager. - terminateVirtualVoiceCall(); if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { - if (!mWaitingForVoiceRecognition) { + if (!mWaitingForVoiceRecognition && + !isCellularCallInProgress() && + !isVirtualCallInProgress()) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = phone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mCM.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); } public void sendScoGainUpdate(int gain) { if (mScoGain != gain && (mRemoteBrsf & BRSF_HF_REMOTE_VOL_CONTROL) != 0x0) { sendURC("+VGS:" + gain); mScoGain = gain; } } public AtCommandResult reportCmeError(int error) { if (mCmee) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("+CME ERROR: " + error); return result; } else { return new AtCommandResult(AtCommandResult.ERROR); } } private static final int START_CALL_TIMEOUT = 10000; // ms private synchronized void expectCallStart() { mWaitingForCallStart = true; Message msg = Message.obtain(mHandler, CHECK_CALL_STARTED); mHandler.sendMessageDelayed(msg, START_CALL_TIMEOUT); if (!mStartCallWakeLock.isHeld()) { mStartCallWakeLock.acquire(START_CALL_TIMEOUT); } } private synchronized void callStarted() { if (mWaitingForCallStart) { mWaitingForCallStart = false; sendURC("OK"); if (mStartCallWakeLock.isHeld()) { mStartCallWakeLock.release(); } } } private static final int START_VOICE_RECOGNITION_TIMEOUT = 5000; // ms private synchronized void expectVoiceRecognition() { mWaitingForVoiceRecognition = true; Message msg = Message.obtain(mHandler, CHECK_VOICE_RECOGNITION_STARTED); mHandler.sendMessageDelayed(msg, START_VOICE_RECOGNITION_TIMEOUT); if (!mStartVoiceRecognitionWakeLock.isHeld()) { mStartVoiceRecognitionWakeLock.acquire(START_VOICE_RECOGNITION_TIMEOUT); } } /* package */ synchronized boolean startVoiceRecognition() { if (mWaitingForVoiceRecognition) { // HF initiated mWaitingForVoiceRecognition = false; sendURC("OK"); } else { // AG initiated sendURC("+BVRA: 1"); } boolean ret = audioOn(); if (mStartVoiceRecognitionWakeLock.isHeld()) { mStartVoiceRecognitionWakeLock.release(); } return ret; } /* package */ synchronized boolean stopVoiceRecognition() { sendURC("+BVRA: 0"); audioOff(); return true; } /* * This class broadcasts vendor-specific commands + arguments to interested receivers. */ private class VendorSpecificCommandHandler extends AtCommandHandler { private String mCommandName; private int mCompanyId; private VendorSpecificCommandHandler(String commandName, int companyId) { mCommandName = commandName; mCompanyId = companyId; } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleActionCommand() { return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleSetCommand(Object[] arguments) { broadcastVendorSpecificEventIntent(mCommandName, mCompanyId, BluetoothHeadset.AT_CMD_TYPE_SET, arguments, mHeadset.getRemoteDevice()); return new AtCommandResult(AtCommandResult.OK); } } private boolean inDebug() { return DBG && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE, false); } private boolean allowAudioAnytime() { return inDebug() && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE_AUDIO_ANYTIME, false); } private void startDebug() { if (DBG && mDebugThread == null) { mDebugThread = new DebugThread(); mDebugThread.start(); } } private void stopDebug() { if (mDebugThread != null) { mDebugThread.interrupt(); mDebugThread = null; } } // VirtualCall SCO support // // Cellular call in progress private boolean isCellularCallInProgress() { if (mCM.hasActiveFgCall() || mCM.hasActiveRingingCall()) return true; return false; } // Virtual Call in Progress private boolean isVirtualCallInProgress() { return mVirtualCallStarted; } //NOTE: Currently the VirtualCall API does not allow the application to initiate a call // transfer. Call transfer may be initiated from the handsfree device and this is handled by // the VirtualCall API synchronized boolean initiateVirtualVoiceCall() { if (DBG) log("initiateVirtualVoiceCall: Received"); // 1. Check if the SCO state is idle if ((isCellularCallInProgress()) || (isVirtualCallInProgress())) { Log.e(TAG, "initiateVirtualVoiceCall: Call in progress"); return false; } // 1.5. Set mVirtualCallStarted to true mVirtualCallStarted = true; // 2. Perform outgoing call setup procedure if (mBluetoothPhoneState.sendUpdate()) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); // outgoing call result.addResponse("+CIEV: 3,2"); result.addResponse("+CIEV: 2,1"); result.addResponse("+CIEV: 3,0"); sendURC(result.toString()); if (DBG) Log.d(TAG, "initiateVirtualVoiceCall: Sent Call-setup procedure"); } // 3. Open the Audio Connection if (audioOn() == false) { log("initiateVirtualVoiceCall: audioON failed"); terminateVirtualVoiceCall(); return false; } mAudioPossible = true; // Done if (DBG) log("initiateVirtualVoiceCall: Done"); return true; } synchronized boolean terminateVirtualVoiceCall() { if (DBG) log("terminateVirtualVoiceCall: Received"); // 1. Check if a virtual call is in progress if (!isVirtualCallInProgress()) { if (DBG) log("terminateVirtualVoiceCall: VirtualCall is not in progress"); return false; } // 2. Release audio connection audioOff(); // 3. Reset mVirtualCallStarted to false mVirtualCallStarted = false; // 4. terminate call-setup if (mBluetoothPhoneState.sendUpdate()) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); // outgoing call result.addResponse("+CIEV: 2,0"); sendURC(result.toString()); if (DBG) log("terminateVirtualVoiceCall: Sent Call-setup procedure"); } mAudioPossible = false; // Done if (DBG) log("terminateVirtualVoiceCall: Done"); return true; } /** Debug thread to read debug properties - runs when debug.bt.hfp is true * at the time a bluetooth handsfree device is connected. Debug properties * are polled and mock updates sent every 1 second */ private class DebugThread extends Thread { /** Turns on/off handsfree profile debugging mode */ private static final String DEBUG_HANDSFREE = "debug.bt.hfp"; /** Mock battery level change - use 0 to 5 */ private static final String DEBUG_HANDSFREE_BATTERY = "debug.bt.hfp.battery"; /** Mock no cellular service when false */ private static final String DEBUG_HANDSFREE_SERVICE = "debug.bt.hfp.service"; /** Mock cellular roaming when true */ private static final String DEBUG_HANDSFREE_ROAM = "debug.bt.hfp.roam"; /** false to true transition will force an audio (SCO) connection to * be established. true to false will force audio to be disconnected */ private static final String DEBUG_HANDSFREE_AUDIO = "debug.bt.hfp.audio"; /** true allows incoming SCO connection out of call. */ private static final String DEBUG_HANDSFREE_AUDIO_ANYTIME = "debug.bt.hfp.audio_anytime"; /** Mock signal strength change in ASU - use 0 to 31 */ private static final String DEBUG_HANDSFREE_SIGNAL = "debug.bt.hfp.signal"; /** Debug AT+CLCC: print +CLCC result */ private static final String DEBUG_HANDSFREE_CLCC = "debug.bt.hfp.clcc"; /** Debug AT+BSIR - Send In Band Ringtones Unsolicited AT command. * debug.bt.unsol.inband = 0 => AT+BSIR = 0 sent by the AG * debug.bt.unsol.inband = 1 => AT+BSIR = 0 sent by the AG * Other values are ignored. */ private static final String DEBUG_UNSOL_INBAND_RINGTONE = "debug.bt.unsol.inband"; @Override public void run() { boolean oldService = true; boolean oldRoam = false; boolean oldAudio = false; while (!isInterrupted() && inDebug()) { int batteryLevel = SystemProperties.getInt(DEBUG_HANDSFREE_BATTERY, -1); if (batteryLevel >= 0 && batteryLevel <= 5) { Intent intent = new Intent(); intent.putExtra("level", batteryLevel); intent.putExtra("scale", 5); mBluetoothPhoneState.updateBatteryState(intent); } boolean serviceStateChanged = false; if (SystemProperties.getBoolean(DEBUG_HANDSFREE_SERVICE, true) != oldService) { oldService = !oldService; serviceStateChanged = true; } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_ROAM, false) != oldRoam) { oldRoam = !oldRoam; serviceStateChanged = true; } if (serviceStateChanged) { Bundle b = new Bundle(); b.putInt("state", oldService ? 0 : 1); b.putBoolean("roaming", oldRoam); mBluetoothPhoneState.updateServiceState(true, ServiceState.newFromBundle(b)); } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_AUDIO, false) != oldAudio) { oldAudio = !oldAudio; if (oldAudio) { audioOn(); } else { audioOff(); } } int signalLevel = SystemProperties.getInt(DEBUG_HANDSFREE_SIGNAL, -1); if (signalLevel >= 0 && signalLevel <= 31) { SignalStrength signalStrength = new SignalStrength(signalLevel, -1, -1, -1, -1, -1, -1, true); Intent intent = new Intent(); Bundle data = new Bundle(); signalStrength.fillInNotifierBundle(data); intent.putExtras(data); mBluetoothPhoneState.updateSignalState(intent); } if (SystemProperties.getBoolean(DEBUG_HANDSFREE_CLCC, false)) { log(gsmGetClccResult().toString()); } try { sleep(1000); // 1 second } catch (InterruptedException e) { break; } int inBandRing = SystemProperties.getInt(DEBUG_UNSOL_INBAND_RINGTONE, -1); if (inBandRing == 0 || inBandRing == 1) { AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED); result.addResponse("+BSIR: " + inBandRing); sendURC(result.toString()); } } } } public void cdmaSwapSecondCallState() { if (VDBG) log("cdmaSetSecondCallState: Toggling mCdmaIsSecondCallActive"); mCdmaIsSecondCallActive = !mCdmaIsSecondCallActive; } public void cdmaSetSecondCallState(boolean state) { if (VDBG) log("cdmaSetSecondCallState: Setting mCdmaIsSecondCallActive to " + state); mCdmaIsSecondCallActive = state; } private static void log(String msg) { Log.d(TAG, msg); } }
false
true
private void initializeHandsfreeAtParser() { if (VDBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); final Phone phone = mCM.getDefaultPhone(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { sendURC("OK"); mBluetoothPhoneState.stopRing(); PhoneUtils.answerCall(mCM.getFirstActiveRingingCall()); return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Send terminateVirtualVoiceCall terminateVirtualVoiceCall(); // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { sendURC("OK"); if (isVirtualCallInProgress()) { //TODO(): Need a way to inform the audio manager. terminateVirtualVoiceCall(); } else { if (mCM.hasActiveFgCall()) { PhoneUtils.hangupActiveCall(mCM.getActiveFgCall()); } else if (mCM.hasActiveRingingCall()) { PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall()); } else if (mCM.hasActiveBgCall()) { PhoneUtils.hangupHoldingCall(mCM.getFirstActiveBgCall()); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mBluetoothPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mBluetoothPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mBluetoothPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mBluetoothPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { phone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int phoneType = phone.getPhoneType(); // Handsfree carkits expect that +CLCC is properly responded to. // Hence we ensure that a proper response is sent for the virtual call too. if (isVirtualCallInProgress()) { String number = phone.getLine1Number(); AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String args; if (number == null) { args = "+CLCC: 1,0,0,0,0,\"\",0"; } else { args = "+CLCC: 1,0,0,0,0,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number); } result.addResponse(args); return result; } if (phoneType == Phone.PHONE_TYPE_CDMA) { return cdmaGetClccResult(); } else if (phoneType == Phone.PHONE_TYPE_GSM) { return gsmGetClccResult(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { int phoneType = phone.getPhoneType(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (ringingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(ringingCall); } else { result = PhoneUtils.hangupHoldingCall(backgroundCall); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { if (ringingCall.isRinging()) { // If there is Call waiting then answer the call and // put the first call on hold. if (VDBG) log("CHLD:1 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else { // If there is no Call waiting then just hangup // the active call. In CDMA this mean that the complete // call session would be ended if (VDBG) log("CHLD:1 Hangup Call"); PhoneUtils.hangup(PhoneApp.getInstance().mCM); } return new AtCommandResult(AtCommandResult.OK); } else if (phoneType == Phone.PHONE_TYPE_GSM) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive( PhoneApp.getInstance().mCM, ringingCall)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else if (args[0].equals(2)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, the way we switch to a new incoming call is by // calling PhoneUtils.answerCall(). switchAndHoldActive() won't // properly update the call state within telephony. // If the Phone state is already in CONF_CALL then we simply send // a flash cmd by calling switchHoldingAndActive() if (ringingCall.isRinging()) { if (VDBG) log("CHLD:2 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else if (PhoneApp.getInstance().cdmaPhoneCallState .getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (VDBG) log("CHLD:2 Swap Calls"); PhoneUtils.switchHoldingAndActive(backgroundCall); // Toggle the second callers active state flag cdmaSwapSecondCallState(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { PhoneUtils.switchHoldingAndActive(backgroundCall); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, we need to check if the call is in THRWAY_ACTIVE state if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { if (VDBG) log("CHLD:3 Merge Calls"); PhoneUtils.mergeCalls(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { if (mCM.hasActiveFgCall() && mCM.hasActiveBgCall()) { PhoneUtils.mergeCalls(); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; sendURC("+CHLD: (0,1,2,3)"); sendURC("OK"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = phone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = phone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // phone will not be NULL at this point. return new AtCommandResult("+CGSN: " + phone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameters(HEADSET_NREC+"=off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameters(HEADSET_NREC+"=on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (!BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) { return new AtCommandResult(AtCommandResult.ERROR); } // Send terminateVirtualVoiceCall // TODO(): Need a way to inform the audio manager. terminateVirtualVoiceCall(); if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { if (!mWaitingForVoiceRecognition) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = phone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mCM.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); }
private void initializeHandsfreeAtParser() { if (VDBG) log("Registering Handsfree AT commands"); AtParser parser = mHeadset.getAtParser(); final Phone phone = mCM.getDefaultPhone(); // Answer parser.register('A', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { sendURC("OK"); mBluetoothPhoneState.stopRing(); PhoneUtils.answerCall(mCM.getFirstActiveRingingCall()); return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); parser.register('D', new AtCommandHandler() { @Override public AtCommandResult handleBasicCommand(String args) { if (args.length() > 0) { if (args.charAt(0) == '>') { // Yuck - memory dialling requested. // Just dial last number for now if (args.startsWith(">9999")) { // for PTS test return new AtCommandResult(AtCommandResult.ERROR); } return redial(); } else { // Send terminateVirtualVoiceCall terminateVirtualVoiceCall(); // Remove trailing ';' if (args.charAt(args.length() - 1) == ';') { args = args.substring(0, args.length() - 1); } Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", args, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); expectCallStart(); return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing } } return new AtCommandResult(AtCommandResult.ERROR); } }); // Hang-up command parser.register("+CHUP", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { sendURC("OK"); if (isVirtualCallInProgress()) { terminateVirtualVoiceCall(); } else { if (mCM.hasActiveFgCall()) { PhoneUtils.hangupActiveCall(mCM.getActiveFgCall()); } else if (mCM.hasActiveRingingCall()) { PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall()); } else if (mCM.hasActiveBgCall()) { PhoneUtils.hangupHoldingCall(mCM.getFirstActiveBgCall()); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Bluetooth Retrieve Supported Features command parser.register("+BRSF", new AtCommandHandler() { private AtCommandResult sendBRSF() { return new AtCommandResult("+BRSF: " + mLocalBrsf); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+BRSF=<handsfree supported features bitmap> // Handsfree is telling us which features it supports. We // send the features we support if (args.length == 1 && (args[0] instanceof Integer)) { mRemoteBrsf = (Integer) args[0]; } else { Log.w(TAG, "HF didn't sent BRSF assuming 0"); } return sendBRSF(); } @Override public AtCommandResult handleActionCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } @Override public AtCommandResult handleReadCommand() { // This seems to be out of spec, but lets do the nice thing return sendBRSF(); } }); // Call waiting notification on/off parser.register("+CCWA", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Seems to be out of spec, but lets return nicely return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { // Call waiting is always on return new AtCommandResult("+CCWA: 1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CCWA=<n> // Handsfree is trying to enable/disable call waiting. We // cannot disable in the current implementation. return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleTestCommand() { // Request for range of supported CCWA paramters return new AtCommandResult("+CCWA: (\"n\",(1))"); } }); // Mobile Equipment Event Reporting enable/disable command // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we // only support paramter ind (disable/enable evert reporting using // +CDEV) parser.register("+CMER", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult( "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length < 4) { // This is a syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if (args[0].equals(3) && args[1].equals(0) && args[2].equals(0)) { boolean valid = false; if (args[3].equals(0)) { mIndicatorsEnabled = false; valid = true; } else if (args[3].equals(1)) { mIndicatorsEnabled = true; valid = true; } if (valid) { if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) { mServiceConnectionEstablished = true; sendURC("OK"); // send immediately, then initiate audio if (isIncallAudio()) { audioOn(); } // only send OK once return new AtCommandResult(AtCommandResult.UNSOLICITED); } else { return new AtCommandResult(AtCommandResult.OK); } } } return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CMER: (3),(0),(0),(0-1)"); } }); // Mobile Equipment Error Reporting enable/disable parser.register("+CMEE", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // out of spec, assume they want to enable mCmee = true; return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0")); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CMEE=<n> if (args.length == 0) { // <n> ommitted - default to 0 mCmee = false; return new AtCommandResult(AtCommandResult.OK); } else if (!(args[0] instanceof Integer)) { // Syntax error return new AtCommandResult(AtCommandResult.ERROR); } else { mCmee = ((Integer)args[0] == 1); return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Probably not required but spec, but no harm done return new AtCommandResult("+CMEE: (0-1)"); } }); // Bluetooth Last Dialled Number parser.register("+BLDN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return redial(); } }); // Indicator Update command parser.register("+CIND", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return mBluetoothPhoneState.toCindResult(); } @Override public AtCommandResult handleTestCommand() { return mBluetoothPhoneState.getCindTestResult(); } }); // Query Signal Quality (legacy) parser.register("+CSQ", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { return mBluetoothPhoneState.toCsqResult(); } }); // Query network registration state parser.register("+CREG", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult(mBluetoothPhoneState.toCregString()); } }); // Send DTMF. I don't know if we are also expected to play the DTMF tone // locally, right now we don't parser.register("+VTS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args.length >= 1) { char c; if (args[0] instanceof Integer) { c = ((Integer) args[0]).toString().charAt(0); } else { c = ((String) args[0]).charAt(0); } if (isValidDtmf(c)) { phone.sendDtmf(c); return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } private boolean isValidDtmf(char c) { switch (c) { case '#': case '*': return true; default: if (Character.digit(c, 14) != -1) { return true; // 0-9 and A-D } return false; } } }); // List calls parser.register("+CLCC", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int phoneType = phone.getPhoneType(); // Handsfree carkits expect that +CLCC is properly responded to. // Hence we ensure that a proper response is sent for the virtual call too. if (isVirtualCallInProgress()) { String number = phone.getLine1Number(); AtCommandResult result = new AtCommandResult(AtCommandResult.OK); String args; if (number == null) { args = "+CLCC: 1,0,0,0,0,\"\",0"; } else { args = "+CLCC: 1,0,0,0,0,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number); } result.addResponse(args); return result; } if (phoneType == Phone.PHONE_TYPE_CDMA) { return cdmaGetClccResult(); } else if (phoneType == Phone.PHONE_TYPE_GSM) { return gsmGetClccResult(); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } }); // Call Hold and Multiparty Handling command parser.register("+CHLD", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { int phoneType = phone.getPhoneType(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); if (args.length >= 1) { if (args[0].equals(0)) { boolean result; if (ringingCall.isRinging()) { result = PhoneUtils.hangupRingingCall(ringingCall); } else { result = PhoneUtils.hangupHoldingCall(backgroundCall); } if (result) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else if (args[0].equals(1)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { if (ringingCall.isRinging()) { // If there is Call waiting then answer the call and // put the first call on hold. if (VDBG) log("CHLD:1 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else { // If there is no Call waiting then just hangup // the active call. In CDMA this mean that the complete // call session would be ended if (VDBG) log("CHLD:1 Hangup Call"); PhoneUtils.hangup(PhoneApp.getInstance().mCM); } return new AtCommandResult(AtCommandResult.OK); } else if (phoneType == Phone.PHONE_TYPE_GSM) { // Hangup active call, answer held call if (PhoneUtils.answerAndEndActive( PhoneApp.getInstance().mCM, ringingCall)) { return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } else if (args[0].equals(2)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, the way we switch to a new incoming call is by // calling PhoneUtils.answerCall(). switchAndHoldActive() won't // properly update the call state within telephony. // If the Phone state is already in CONF_CALL then we simply send // a flash cmd by calling switchHoldingAndActive() if (ringingCall.isRinging()) { if (VDBG) log("CHLD:2 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); } else if (PhoneApp.getInstance().cdmaPhoneCallState .getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (VDBG) log("CHLD:2 Swap Calls"); PhoneUtils.switchHoldingAndActive(backgroundCall); // Toggle the second callers active state flag cdmaSwapSecondCallState(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { PhoneUtils.switchHoldingAndActive(backgroundCall); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(3)) { if (phoneType == Phone.PHONE_TYPE_CDMA) { // For CDMA, we need to check if the call is in THRWAY_ACTIVE state if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { if (VDBG) log("CHLD:3 Merge Calls"); PhoneUtils.mergeCalls(); } } else if (phoneType == Phone.PHONE_TYPE_GSM) { if (mCM.hasActiveFgCall() && mCM.hasActiveBgCall()) { PhoneUtils.mergeCalls(); } } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } return new AtCommandResult(AtCommandResult.OK); } } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { mServiceConnectionEstablished = true; sendURC("+CHLD: (0,1,2,3)"); sendURC("OK"); // send reply first, then connect audio if (isIncallAudio()) { audioOn(); } // already replied return new AtCommandResult(AtCommandResult.UNSOLICITED); } }); // Get Network operator name parser.register("+COPS", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { String operatorName = phone.getServiceState().getOperatorAlphaLong(); if (operatorName != null) { if (operatorName.length() > 16) { operatorName = operatorName.substring(0, 16); } return new AtCommandResult( "+COPS: 0,0,\"" + operatorName + "\""); } else { return new AtCommandResult( "+COPS: 0,0,\"UNKNOWN\",0"); } } @Override public AtCommandResult handleSetCommand(Object[] args) { // Handsfree only supports AT+COPS=3,0 if (args.length != 2 || !(args[0] instanceof Integer) || !(args[1] instanceof Integer)) { // syntax error return new AtCommandResult(AtCommandResult.ERROR); } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) { return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED); } else { return new AtCommandResult(AtCommandResult.OK); } } @Override public AtCommandResult handleTestCommand() { // Out of spec, but lets be friendly return new AtCommandResult("+COPS: (3),(0)"); } }); // Mobile PIN // AT+CPIN is not in the handsfree spec (although it is in 3GPP) parser.register("+CPIN", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { return new AtCommandResult("+CPIN: READY"); } }); // Bluetooth Response and Hold // Only supported on PDC (Japan) and CDMA networks. parser.register("+BTRH", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Replying with just OK indicates no response and hold // features in use now return new AtCommandResult(AtCommandResult.OK); } @Override public AtCommandResult handleSetCommand(Object[] args) { // Neeed PDC or CDMA return new AtCommandResult(AtCommandResult.ERROR); } }); // Request International Mobile Subscriber Identity (IMSI) // Not in bluetooth handset spec parser.register("+CIMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // AT+CIMI String imsi = phone.getSubscriberId(); if (imsi == null || imsi.length() == 0) { return reportCmeError(BluetoothCmeError.SIM_FAILURE); } else { return new AtCommandResult(imsi); } } }); // Calling Line Identification Presentation parser.register("+CLIP", new AtCommandHandler() { @Override public AtCommandResult handleReadCommand() { // Currently assumes the network is provisioned for CLIP return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1"); } @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+CLIP=<n> if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) { mClip = args[0].equals(1); return new AtCommandResult(AtCommandResult.OK); } else { return new AtCommandResult(AtCommandResult.ERROR); } } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+CLIP: (0-1)"); } }); // AT+CGSN - Returns the device IMEI number. parser.register("+CGSN", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Get the IMEI of the device. // phone will not be NULL at this point. return new AtCommandResult("+CGSN: " + phone.getDeviceId()); } }); // AT+CGMM - Query Model Information parser.register("+CGMM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String model = SystemProperties.get("ro.product.model"); if (model != null) { return new AtCommandResult("+CGMM: " + model); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // AT+CGMI - Query Manufacturer Information parser.register("+CGMI", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { // Return the Model Information. String manuf = SystemProperties.get("ro.product.manufacturer"); if (manuf != null) { return new AtCommandResult("+CGMI: " + manuf); } else { return new AtCommandResult(AtCommandResult.ERROR); } } }); // Noise Reduction and Echo Cancellation control parser.register("+NREC", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (args[0].equals(0)) { mAudioManager.setParameters(HEADSET_NREC+"=off"); return new AtCommandResult(AtCommandResult.OK); } else if (args[0].equals(1)) { mAudioManager.setParameters(HEADSET_NREC+"=on"); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } }); // Voice recognition (dialing) parser.register("+BVRA", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { if (!BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) { return new AtCommandResult(AtCommandResult.ERROR); } if (args.length >= 1 && args[0].equals(1)) { synchronized (BluetoothHandsfree.this) { if (!mWaitingForVoiceRecognition && !isCellularCallInProgress() && !isVirtualCallInProgress()) { try { mContext.startActivity(sVoiceCommandIntent); } catch (ActivityNotFoundException e) { return new AtCommandResult(AtCommandResult.ERROR); } expectVoiceRecognition(); } } return new AtCommandResult(AtCommandResult.UNSOLICITED); // send nothing yet } else if (args.length >= 1 && args[0].equals(0)) { audioOff(); return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult(AtCommandResult.ERROR); } @Override public AtCommandResult handleTestCommand() { return new AtCommandResult("+BVRA: (0-1)"); } }); // Retrieve Subscriber Number parser.register("+CNUM", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { String number = phone.getLine1Number(); if (number == null) { return new AtCommandResult(AtCommandResult.OK); } return new AtCommandResult("+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); } }); // Microphone Gain parser.register("+VGM", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGM=<gain> in range [0,15] // Headset/Handsfree is reporting its current gain setting return new AtCommandResult(AtCommandResult.OK); } }); // Speaker Gain parser.register("+VGS", new AtCommandHandler() { @Override public AtCommandResult handleSetCommand(Object[] args) { // AT+VGS=<gain> in range [0,15] if (args.length != 1 || !(args[0] instanceof Integer)) { return new AtCommandResult(AtCommandResult.ERROR); } mScoGain = (Integer) args[0]; int flag = mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0; mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag); return new AtCommandResult(AtCommandResult.OK); } }); // Phone activity status parser.register("+CPAS", new AtCommandHandler() { @Override public AtCommandResult handleActionCommand() { int status = 0; switch (mCM.getState()) { case IDLE: status = 0; break; case RINGING: status = 3; break; case OFFHOOK: status = 4; break; } return new AtCommandResult("+CPAS: " + status); } }); mPhonebook.register(parser); }
diff --git a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AttributesVerifier.java b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AttributesVerifier.java index 29e5f97..a22b4eb 100644 --- a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AttributesVerifier.java +++ b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AttributesVerifier.java @@ -1,209 +1,208 @@ package org.apache.maven.doxia.siterenderer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlHeader2; import com.gargoylesoftware.htmlunit.html.HtmlHeader3; import com.gargoylesoftware.htmlunit.html.HtmlImage; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlParagraph; import com.gargoylesoftware.htmlunit.html.HtmlTable; import com.gargoylesoftware.htmlunit.html.HtmlTableDataCell; import com.gargoylesoftware.htmlunit.html.HtmlTableHeaderCell; import com.gargoylesoftware.htmlunit.html.HtmlTableRow; import com.gargoylesoftware.htmlunit.html.UnknownHtmlElement; import java.util.Iterator; /** * * * @author ltheussl * @version $Id$ */ public class AttributesVerifier extends AbstractVerifier { /** {@inheritDoc} */ public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "section", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertNotNull( a ); assertEquals( "section", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "ID", p.getAttributeValue( "id" ) ); assertEquals( "CLASS", p.getAttributeValue( "class" ) ); assertEquals( "TITLE", p.getAttributeValue( "title" ) ); assertEquals( "STYLE", p.getAttributeValue( "style" ) ); assertEquals( "LANG", p.getAttributeValue( "lang" ) ); HtmlImage img = (HtmlImage) elementIterator.next(); assertNotNull( img ); assertEquals( "project.png", img.getAttributeValue( "src" ) ); assertEquals( "150", img.getAttributeValue( "width" ) ); assertEquals( "93", img.getAttributeValue( "height" ) ); assertEquals( "border: 1px solid silver", img.getAttributeValue( "style" ) ); assertEquals( "Project", img.getAttributeValue( "alt" ) ); // test object identity to distinguish the case ATTRIBUTE_VALUE_EMPTY assertTrue( img.getAttributeValue( "dummy" ) == HtmlElement.ATTRIBUTE_NOT_DEFINED ); HtmlTable table = (HtmlTable) elementIterator.next(); assertEquals( "1", table.getAttributeValue( "border" ) ); assertEquals( "none", table.getAttributeValue( "class" ) ); element = (HtmlElement) elementIterator.next(); // this is a htmlunit bug assertEquals( "tbody", element.getTagName() ); HtmlTableRow tr = (HtmlTableRow) elementIterator.next(); HtmlTableHeaderCell th = (HtmlTableHeaderCell) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); assertEquals( "center", th.getAttributeValue( "align" ) ); assertEquals( "2", th.getAttributeValue( "colspan" ) ); assertEquals( "50%", th.getAttributeValue( "width" ) ); tr = (HtmlTableRow) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); - assertEquals( "left", th.getAttributeValue( "align" ) ); assertEquals( "2", th.getAttributeValue( "rowspan" ) ); assertEquals( "middle", th.getAttributeValue( "valign" ) ); HtmlTableDataCell td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); tr = (HtmlTableRow) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); UnknownHtmlElement unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "u", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "s", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sub", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sup", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "color: red; margin-left: 20px", p.getAttributeValue( "style" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.pdf", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.txt", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section without id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_without_id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection without id", h3.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Subsection_without_id", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "section-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section with id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "subsection-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection with id", h3.asText().trim() ); assertFalse( elementIterator.hasNext() ); } }
true
true
public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "section", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertNotNull( a ); assertEquals( "section", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "ID", p.getAttributeValue( "id" ) ); assertEquals( "CLASS", p.getAttributeValue( "class" ) ); assertEquals( "TITLE", p.getAttributeValue( "title" ) ); assertEquals( "STYLE", p.getAttributeValue( "style" ) ); assertEquals( "LANG", p.getAttributeValue( "lang" ) ); HtmlImage img = (HtmlImage) elementIterator.next(); assertNotNull( img ); assertEquals( "project.png", img.getAttributeValue( "src" ) ); assertEquals( "150", img.getAttributeValue( "width" ) ); assertEquals( "93", img.getAttributeValue( "height" ) ); assertEquals( "border: 1px solid silver", img.getAttributeValue( "style" ) ); assertEquals( "Project", img.getAttributeValue( "alt" ) ); // test object identity to distinguish the case ATTRIBUTE_VALUE_EMPTY assertTrue( img.getAttributeValue( "dummy" ) == HtmlElement.ATTRIBUTE_NOT_DEFINED ); HtmlTable table = (HtmlTable) elementIterator.next(); assertEquals( "1", table.getAttributeValue( "border" ) ); assertEquals( "none", table.getAttributeValue( "class" ) ); element = (HtmlElement) elementIterator.next(); // this is a htmlunit bug assertEquals( "tbody", element.getTagName() ); HtmlTableRow tr = (HtmlTableRow) elementIterator.next(); HtmlTableHeaderCell th = (HtmlTableHeaderCell) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); assertEquals( "center", th.getAttributeValue( "align" ) ); assertEquals( "2", th.getAttributeValue( "colspan" ) ); assertEquals( "50%", th.getAttributeValue( "width" ) ); tr = (HtmlTableRow) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); assertEquals( "left", th.getAttributeValue( "align" ) ); assertEquals( "2", th.getAttributeValue( "rowspan" ) ); assertEquals( "middle", th.getAttributeValue( "valign" ) ); HtmlTableDataCell td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); tr = (HtmlTableRow) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); UnknownHtmlElement unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "u", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "s", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sub", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sup", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "color: red; margin-left: 20px", p.getAttributeValue( "style" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.pdf", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.txt", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section without id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_without_id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection without id", h3.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Subsection_without_id", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "section-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section with id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "subsection-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection with id", h3.asText().trim() ); assertFalse( elementIterator.hasNext() ); }
public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "section", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertNotNull( a ); assertEquals( "section", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "ID", p.getAttributeValue( "id" ) ); assertEquals( "CLASS", p.getAttributeValue( "class" ) ); assertEquals( "TITLE", p.getAttributeValue( "title" ) ); assertEquals( "STYLE", p.getAttributeValue( "style" ) ); assertEquals( "LANG", p.getAttributeValue( "lang" ) ); HtmlImage img = (HtmlImage) elementIterator.next(); assertNotNull( img ); assertEquals( "project.png", img.getAttributeValue( "src" ) ); assertEquals( "150", img.getAttributeValue( "width" ) ); assertEquals( "93", img.getAttributeValue( "height" ) ); assertEquals( "border: 1px solid silver", img.getAttributeValue( "style" ) ); assertEquals( "Project", img.getAttributeValue( "alt" ) ); // test object identity to distinguish the case ATTRIBUTE_VALUE_EMPTY assertTrue( img.getAttributeValue( "dummy" ) == HtmlElement.ATTRIBUTE_NOT_DEFINED ); HtmlTable table = (HtmlTable) elementIterator.next(); assertEquals( "1", table.getAttributeValue( "border" ) ); assertEquals( "none", table.getAttributeValue( "class" ) ); element = (HtmlElement) elementIterator.next(); // this is a htmlunit bug assertEquals( "tbody", element.getTagName() ); HtmlTableRow tr = (HtmlTableRow) elementIterator.next(); HtmlTableHeaderCell th = (HtmlTableHeaderCell) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); assertEquals( "center", th.getAttributeValue( "align" ) ); assertEquals( "2", th.getAttributeValue( "colspan" ) ); assertEquals( "50%", th.getAttributeValue( "width" ) ); tr = (HtmlTableRow) elementIterator.next(); th = (HtmlTableHeaderCell) elementIterator.next(); assertEquals( "2", th.getAttributeValue( "rowspan" ) ); assertEquals( "middle", th.getAttributeValue( "valign" ) ); HtmlTableDataCell td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); tr = (HtmlTableRow) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); td = (HtmlTableDataCell) elementIterator.next(); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); UnknownHtmlElement unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "u", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "s", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sub", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "sup", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unk.getTagName() ); unk = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unk.getTagName() ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); assertEquals( "color: red; margin-left: 20px", p.getAttributeValue( "style" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.pdf", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.txt", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section without id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_without_id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection without id", h3.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Subsection_without_id", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "section-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertEquals( "Section with id", h2.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "subsection-id", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h3 = (HtmlHeader3) elementIterator.next(); assertEquals( "Subsection with id", h3.asText().trim() ); assertFalse( elementIterator.hasNext() ); }
diff --git a/java/target/src/test/testrt/PeriodicUnrel.java b/java/target/src/test/testrt/PeriodicUnrel.java index 89001151..ea4bb3bb 100644 --- a/java/target/src/test/testrt/PeriodicUnrel.java +++ b/java/target/src/test/testrt/PeriodicUnrel.java @@ -1,63 +1,61 @@ package testrt; import util.*; import joprt.*; import com.jopdesign.sys.*; // use differnet (unrelated) period to find WC Jitter public class PeriodicUnrel { static class Busy extends RtThread { private int c; Busy(int per, int ch) { super(5, per); c = ch; } public void run() { for (;;) { // Dbg.wr(c); waitForNextPeriod(); } } } public static void main(String[] args) { Dbg.initSer(); // use serial line for debug output RtThread rt = new RtThread(10, 100000) { public void run() { waitForNextPeriod(); int ts_old = Native.rd(Const.IO_US_CNT); for (;;) { waitForNextPeriod(); int ts = Native.rd(Const.IO_US_CNT); Result.printPeriod(ts_old, ts); ts_old = ts; } } }; int i; for (i=0; i<10; ++i) { new Busy(2345+456*i, i+'a'); } RtThread.startMission(); -RtThread.debug(); // sleep for (;;) { -// RtThread.debug(); -Dbg.wr('M'); + Dbg.wr('M'); Timer.wd(); -for (;;) ; + for (;;) ; // try { Thread.sleep(1200); } catch (Exception e) {} } } }
false
true
public static void main(String[] args) { Dbg.initSer(); // use serial line for debug output RtThread rt = new RtThread(10, 100000) { public void run() { waitForNextPeriod(); int ts_old = Native.rd(Const.IO_US_CNT); for (;;) { waitForNextPeriod(); int ts = Native.rd(Const.IO_US_CNT); Result.printPeriod(ts_old, ts); ts_old = ts; } } }; int i; for (i=0; i<10; ++i) { new Busy(2345+456*i, i+'a'); } RtThread.startMission(); RtThread.debug(); // sleep for (;;) { // RtThread.debug(); Dbg.wr('M'); Timer.wd(); for (;;) ; // try { Thread.sleep(1200); } catch (Exception e) {} } }
public static void main(String[] args) { Dbg.initSer(); // use serial line for debug output RtThread rt = new RtThread(10, 100000) { public void run() { waitForNextPeriod(); int ts_old = Native.rd(Const.IO_US_CNT); for (;;) { waitForNextPeriod(); int ts = Native.rd(Const.IO_US_CNT); Result.printPeriod(ts_old, ts); ts_old = ts; } } }; int i; for (i=0; i<10; ++i) { new Busy(2345+456*i, i+'a'); } RtThread.startMission(); // sleep for (;;) { Dbg.wr('M'); Timer.wd(); for (;;) ; // try { Thread.sleep(1200); } catch (Exception e) {} } }
diff --git a/connectors/cherrysms/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java b/connectors/cherrysms/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java index fd171a36..2cd37a3f 100644 --- a/connectors/cherrysms/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java +++ b/connectors/cherrysms/src/de/ub0r/android/websms/connector/cherrysms/ConnectorCherrySMS.java @@ -1,231 +1,233 @@ /* * Copyright (C) 2010 Felix Bechstein * * This file is part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; If not, see <http://www.gnu.org/licenses/>. */ package de.ub0r.android.websms.connector.cherrysms; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URLEncoder; import org.apache.http.HttpResponse; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import de.ub0r.android.websms.connector.common.Connector; import de.ub0r.android.websms.connector.common.ConnectorCommand; import de.ub0r.android.websms.connector.common.ConnectorSpec; import de.ub0r.android.websms.connector.common.Utils; import de.ub0r.android.websms.connector.common.WebSMSException; import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec; /** * AsyncTask to manage IO to cherry-sms.com API. * * @author flx */ public class ConnectorCherrySMS extends Connector { /** Tag for output. */ private static final String TAG = "WebSMS.cherry"; /** {@link SubConnectorSpec} ID: with sender. */ private static final String ID_W_SENDER = "w_sender"; /** {@link SubConnectorSpec} ID: without sender. */ private static final String ID_WO_SENDER = "wo_sender"; /** CherrySMS Gateway URL. */ private static final String URL = "https://gw.cherry-sms.com/"; /** * {@inheritDoc} */ @Override public final ConnectorSpec initSpec(final Context context) { final String name = context .getString(R.string.connector_cherrysms_name); ConnectorSpec c = new ConnectorSpec(TAG, name); c.setAuthor(// . context.getString(R.string.connector_cherrysms_author)); c.setBalance(null); c.setPrefsTitle(context .getString(R.string.connector_cherrysms_preferences)); c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE | ConnectorSpec.CAPABILITIES_SEND | ConnectorSpec.CAPABILITIES_PREFS); c.addSubConnector(ID_WO_SENDER, context.getString(R.string.wo_sender), SubConnectorSpec.FEATURE_MULTIRECIPIENTS); c.addSubConnector(ID_W_SENDER, context.getString(R.string.w_sender), SubConnectorSpec.FEATURE_MULTIRECIPIENTS); return c; } /** * {@inheritDoc} */ @Override public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (p.getBoolean(Preferences.PREFS_ENABLED, false)) { if (p.getString(Preferences.PREFS_PASSWORD, "").length() > 0) { connectorSpec.setReady(); } else { connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED); } } else { connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE); } return connectorSpec; } /** * Check return code from cherry-sms.com. * * @param context * {@link Context} * @param ret * return code * @return true if no error code * @throws WebSMSException * WebSMSException */ private static boolean checkReturnCode(final Context context, final int ret) throws WebSMSException { Log.d(TAG, "ret=" + ret); switch (ret) { case 100: return true; case 10: throw new WebSMSException(context, R.string.error_cherry_10); case 20: throw new WebSMSException(context, R.string.error_cherry_20); case 30: throw new WebSMSException(context, R.string.error_cherry_30); case 31: throw new WebSMSException(context, R.string.error_cherry_31); case 40: throw new WebSMSException(context, R.string.error_cherry_40); case 50: throw new WebSMSException(context, R.string.error_cherry_50); case 60: throw new WebSMSException(context, R.string.error_cherry_60); case 70: throw new WebSMSException(context, R.string.error_cherry_70); case 71: throw new WebSMSException(context, R.string.error_cherry_71); case 80: throw new WebSMSException(context, R.string.error_cherry_80); case 90: throw new WebSMSException(context, R.string.error_cherry_90); default: throw new WebSMSException(context, R.string.error, " code: " + ret); } } /** * Send data. * * @param context * {@link Context} * @param command * {@link ConnectorCommand} * @throws WebSMSException * WebSMSException */ private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); url.append(URLEncoder.encode(text, "ISO-8859-15")); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } Log.d(TAG, "--HTTP GET--"); Log.d(TAG, url.toString()); Log.d(TAG, "--HTTP GET--"); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; - cs.setBalance(lines[l - 1].trim()); - if (l > 1) { + if (l > 0) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } + if (l > 1) { + cs.setBalance(lines[l - 1].trim()); + } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } } /** * {@inheritDoc} */ @Override protected final void doUpdate(final Context context, final Intent intent) throws WebSMSException { this.sendData(context, new ConnectorCommand(intent)); } /** * {@inheritDoc} */ @Override protected final void doSend(final Context context, final Intent intent) throws WebSMSException { this.sendData(context, new ConnectorCommand(intent)); } }
false
true
private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); url.append(URLEncoder.encode(text, "ISO-8859-15")); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } Log.d(TAG, "--HTTP GET--"); Log.d(TAG, url.toString()); Log.d(TAG, "--HTTP GET--"); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; cs.setBalance(lines[l - 1].trim()); if (l > 1) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
private void sendData(final Context context, final ConnectorCommand command) throws WebSMSException { // do IO try { // get Connection final StringBuilder url = new StringBuilder(URL); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); url.append("?user="); url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender()))); url.append("&password="); url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, ""))); final String text = command.getText(); if (text != null && text.length() > 0) { boolean sendWithSender = false; final String sub = command.getSelectedSubConnector(); if (sub != null && sub.equals(ID_W_SENDER)) { sendWithSender = true; } Log.d(TAG, "send with sender = " + sendWithSender); if (sendWithSender) { url.append("&from=1"); } url.append("&message="); url.append(URLEncoder.encode(text, "ISO-8859-15")); url.append("&to="); url.append(Utils.joinRecipientsNumbers(command.getRecipients(), ";", true)); } else { url.append("&check=guthaben"); } Log.d(TAG, "--HTTP GET--"); Log.d(TAG, url.toString()); Log.d(TAG, "--HTTP GET--"); // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str( response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; int l = lines.length; if (l > 0) { final int ret = Integer.parseInt(lines[0].trim()); checkReturnCode(context, ret); } if (l > 1) { cs.setBalance(lines[l - 1].trim()); } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
diff --git a/src/main/java/com/soebes/maven/plugins/itexin/ExecutorMojo.java b/src/main/java/com/soebes/maven/plugins/itexin/ExecutorMojo.java index b9c723c..ffa7fc0 100644 --- a/src/main/java/com/soebes/maven/plugins/itexin/ExecutorMojo.java +++ b/src/main/java/com/soebes/maven/plugins/itexin/ExecutorMojo.java @@ -1,213 +1,213 @@ package com.soebes.maven.plugins.itexin; import java.util.ArrayList; import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.twdata.maven.mojoexecutor.MojoExecutor; import org.twdata.maven.mojoexecutor.PlexusConfigurationUtils; /** * Executor will execute a given plugin by iterating throught the given items. * * @author Karl-Heinz Marbaise <a href="mailto:[email protected]">[email protected]</a> * */ @Mojo(name = "executor", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true) public class ExecutorMojo extends AbstractMojo { /** * The plugin to be executed. * <pre>{@code * <plugin> * <groupId>..</groupId> * <artifactId>..</artifactId> * <version>..</version> * </plugin> * }</pre> */ @Parameter(required = true) private Plugin plugin; /** * The plugin goal to be executed. * */ @Parameter(required = true) private String goal; /** * Plugin configuration to use in the execution. * <pre>{@code * <configuration> * Plugin Configuration * </configuration> * }</pre> */ @Parameter private XmlPlexusConfiguration configuration; /** * The project currently being build. * */ @Parameter(required = true, readonly = true, defaultValue = "${project}") private MavenProject mavenProject; /** * The current Maven session. * */ @Parameter(required = true, readonly = true, defaultValue = "${session}") private MavenSession mavenSession; /** * Here you can define the items which will be iterated through. * <pre>{@code * <items> * <item>one</item> * <item>two</item> * <item>three</item> * .. * </items>}</pre> */ @Parameter private List<String> items; /** * The list of items which will be iterated through. * * {@code <content>one, two, three</content>} */ @Parameter private String content; /** * The delimiter which will be used to split the * {@link #content}. */ @Parameter(defaultValue = ",") private String delimiter; /** * The token the iterator placeholder begins with. */ @Parameter(required = true, defaultValue = "@") private String beginToken; /** * The token the iterator placeholder ends with. */ @Parameter(required = true, defaultValue = "@") private String endToken; /** * The name of the iterator variable. */ @Parameter(required = true, defaultValue = "item") private String iteratorName; /** * The Maven BuildPluginManager component. * */ @Component private BuildPluginManager pluginManager; @Component // for Maven 3 only private PluginDescriptor pluginDescriptor; /** * This will copy the configuration from src to the result whereas the * placeholder will be replaced with the current value. * */ private PlexusConfiguration copyConfiguration(PlexusConfiguration src, String iteratorName, String value) { XmlPlexusConfiguration dom = new XmlPlexusConfiguration(src.getName()); if (src.getValue() != null) { if (src.getValue().contains(iteratorName)) { dom.setValue(src.getValue().replaceAll(iteratorName, value)); } else { dom.setValue(src.getValue()); } } else { dom.setValue(src.getValue(null)); } for (String attributeName : src.getAttributeNames()) { dom.setAttribute(attributeName, src.getAttribute(attributeName, null)); } for (PlexusConfiguration child : src.getChildren()) { dom.addChild(copyConfiguration(child, iteratorName, value)); } return dom; } private List<String> getContentAsList() { List<String> result = new ArrayList<String>(); String[] resultArray = content.split(delimiter); for (String item : resultArray) { result.add(item.trim()); } return result; } private List<String> getItems() throws MojoExecutionException { List<String> result = new ArrayList<String>(); if (!items.isEmpty()) { result = items; } else if (content != null && content.trim().length() > 0) { result = getContentAsList(); } return result; } public void execute() throws MojoExecutionException { if (items == null && content == null) { throw new MojoExecutionException("You have to use at least one. Either items element or content element!"); } - if (!items.isEmpty() && content != null & content.trim().length() > 0) { + if (!items.isEmpty() && content != null && content.trim().length() > 0) { throw new MojoExecutionException("You can use only one element. Either items element or content element but not both!"); } for (String item : getItems()) { getLog().debug("Configuration(before): " + configuration.toString()); PlexusConfiguration plexusConfiguration = copyConfiguration(configuration, beginToken + iteratorName + endToken, item); getLog().debug("plexusConfiguration(after): " + plexusConfiguration.toString()); StringBuilder sb = new StringBuilder("]] "); // --- maven-jar-plugin:2.3.2:jar (default-jar) @ basic-test --- sb.append(plugin.getKey()); sb.append(":"); sb.append(plugin.getVersion()); getLog().info(sb.toString()); // Put the value of the current iteration into the properties mavenProject.getProperties().put(iteratorName, item); MojoExecutor.executeMojo(plugin, goal, PlexusConfigurationUtils.toXpp3Dom(plexusConfiguration), MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager)); } } }
true
true
public void execute() throws MojoExecutionException { if (items == null && content == null) { throw new MojoExecutionException("You have to use at least one. Either items element or content element!"); } if (!items.isEmpty() && content != null & content.trim().length() > 0) { throw new MojoExecutionException("You can use only one element. Either items element or content element but not both!"); } for (String item : getItems()) { getLog().debug("Configuration(before): " + configuration.toString()); PlexusConfiguration plexusConfiguration = copyConfiguration(configuration, beginToken + iteratorName + endToken, item); getLog().debug("plexusConfiguration(after): " + plexusConfiguration.toString()); StringBuilder sb = new StringBuilder("]] "); // --- maven-jar-plugin:2.3.2:jar (default-jar) @ basic-test --- sb.append(plugin.getKey()); sb.append(":"); sb.append(plugin.getVersion()); getLog().info(sb.toString()); // Put the value of the current iteration into the properties mavenProject.getProperties().put(iteratorName, item); MojoExecutor.executeMojo(plugin, goal, PlexusConfigurationUtils.toXpp3Dom(plexusConfiguration), MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager)); } }
public void execute() throws MojoExecutionException { if (items == null && content == null) { throw new MojoExecutionException("You have to use at least one. Either items element or content element!"); } if (!items.isEmpty() && content != null && content.trim().length() > 0) { throw new MojoExecutionException("You can use only one element. Either items element or content element but not both!"); } for (String item : getItems()) { getLog().debug("Configuration(before): " + configuration.toString()); PlexusConfiguration plexusConfiguration = copyConfiguration(configuration, beginToken + iteratorName + endToken, item); getLog().debug("plexusConfiguration(after): " + plexusConfiguration.toString()); StringBuilder sb = new StringBuilder("]] "); // --- maven-jar-plugin:2.3.2:jar (default-jar) @ basic-test --- sb.append(plugin.getKey()); sb.append(":"); sb.append(plugin.getVersion()); getLog().info(sb.toString()); // Put the value of the current iteration into the properties mavenProject.getProperties().put(iteratorName, item); MojoExecutor.executeMojo(plugin, goal, PlexusConfigurationUtils.toXpp3Dom(plexusConfiguration), MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager)); } }
diff --git a/src/main/java/ShpToOsmConverter.java b/src/main/java/ShpToOsmConverter.java index 138fa7d..2c0ecda 100644 --- a/src/main/java/ShpToOsmConverter.java +++ b/src/main/java/ShpToOsmConverter.java @@ -1,400 +1,401 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.geotools.data.DataStoreFinder; import org.geotools.data.FeatureSource; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.geometry.jts.JTS; import org.geotools.referencing.CRS; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.geometry.MismatchedDimensionException; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import osm.output.OSMOutputter; import osm.primitive.Primitive; import osm.primitive.Tag; import osm.primitive.node.Node; import osm.primitive.relation.Member; import osm.primitive.relation.Relation; import osm.primitive.way.Way; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class ShpToOsmConverter { private static final int MAX_NODES_IN_WAY = 2000; private File inputFile; private RuleSet ruleset; private boolean onlyIncludeTaggedPrimitives; private OSMOutputter outputter; public ShpToOsmConverter(File shpFile, RuleSet rules, boolean onlyIncludeTaggedPrim, OSMOutputter out) { inputFile = shpFile; outputter = out; ruleset = rules; onlyIncludeTaggedPrimitives = onlyIncludeTaggedPrim; } public void convert() { CoordinateReferenceSystem targetCRS = null; try { targetCRS = CRS .parseWKT("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]"); } catch (NoSuchAuthorityCodeException e1) { e1.printStackTrace(); } catch (FactoryException e1) { e1.printStackTrace(); } try { // Connection parameters Map<String, Serializable> connectParameters = new HashMap<String, Serializable>(); connectParameters.put("url", inputFile.toURI().toURL()); + connectParameters.put("create spatial index", false); ShapefileDataStore dataStore = (ShapefileDataStore) DataStoreFinder.getDataStore(connectParameters); CoordinateReferenceSystem sourceCRS = dataStore.getSchema().getCoordinateReferenceSystem(); if (sourceCRS == null) { System.err .println("Could not determine the shapefile's projection. More than likely, the .prj file was not included."); System.exit(-1); } else { System.err.println("Converting from " + sourceCRS + " to " + targetCRS); } outputter.start(); // we are now connected String[] typeNames = dataStore.getTypeNames(); for (String typeName : typeNames) { System.err.println(typeName); FeatureSource<SimpleFeatureType, SimpleFeature> featureSource; FeatureCollection<SimpleFeatureType, SimpleFeature> collection; FeatureIterator<SimpleFeature> iterator; featureSource = dataStore.getFeatureSource(typeName); collection = featureSource.getFeatures(); iterator = collection.features(); try { while (iterator.hasNext()) { try { SimpleFeature feature = iterator.next(); Geometry rawGeom = (Geometry) feature.getDefaultGeometry(); String geometryType = rawGeom.getGeometryType(); // Transform to spherical mercator Geometry geometry = null; try { MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, true); geometry = JTS.transform(rawGeom, transform); } catch (FactoryException e) { e.printStackTrace(); } catch (TransformException e) { e.printStackTrace(); } // geometry = rawGeom; System.err.println("Geometry type: " + geometryType); if ("MultiLineString".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { LineString geometryN = (LineString) geometry .getGeometryN(i); List<Way> ways = linestringToWays(geometryN); applyRulesList(feature, geometryType, ways, ruleset.getLineRules()); for (Way way : ways) { if (shouldInclude(way)) { outputter.addWay(way); } } } } else if ("MultiPolygon".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Polygon geometryN = (Polygon) geometry.getGeometryN(i); // Get the outer ring of the polygon LineString outerLine = geometryN.getExteriorRing(); List<Way> outerWays = polygonToWays(outerLine); if (geometryN.getNumInteriorRing() > 0) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); // Tags go on the relation for multipolygons applyRulesList(feature, geometryType, Arrays.asList(r), ruleset.getOuterPolygonRules()); for (Primitive outerWay : outerWays) { // Always include every outer way r.addMember(new Member(outerWay, "outer")); } // Then the inner ones, if any for (int j = 0; j < geometryN.getNumInteriorRing(); j++) { LineString innerLine = geometryN.getInteriorRingN(j); List<Way> innerWays = polygonToWays(innerLine); applyRulesList(feature, geometryType, innerWays, ruleset .getInnerPolygonRules()); for (Way innerWay : innerWays) { r.addMember(new Member(innerWay, "inner")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there's more than one way, then it // needs to be a multipolygon and the // tags need to be applied to the // relation if(outerWays.size() > 1) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); applyRulesList(feature, geometryType, r, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { r.addMember(new Member(outerWay, "outer")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there aren't any inner lines, then // just use the outer one as a way. applyRulesList(feature, geometryType, outerWays, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { outputter.addWay(outerWay); } } } } } } else if ("Point".equals(geometryType)) { List<Node> nodes = new ArrayList<Node>(geometry.getNumGeometries()); for (int i = 0; i < geometry.getNumGeometries(); i++) { Point geometryN = (Point) geometry.getGeometryN(i); Node n = pointToNode(geometryN); nodes.add(n); } applyRulesList(feature, geometryType, nodes, ruleset.getPointRules()); for (Node node : nodes) { if (shouldInclude(node)) { outputter.addNode(node); } } } } catch (IllegalArgumentException e) { System.err.println("Skipping a geometry becase:"); e.printStackTrace(); } } } catch (MismatchedDimensionException e) { e.printStackTrace(); } finally { if (iterator != null) { // YOU MUST CLOSE THE ITERATOR! iterator.close(); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } outputter.finish(); } private boolean shouldInclude(Primitive w) { if(onlyIncludeTaggedPrimitives) { return w.hasTags(); } else { return true; } } private Node pointToNode(Point geometryN) { Coordinate coord = geometryN.getCoordinate(); return new Node(coord.y, coord.x); } private void applyRulesList(SimpleFeature feature, String geometryType, List<? extends Primitive> features, List<Rule> rulelist) { Collection<Property> properties = feature.getProperties(); for (Property property : properties) { String srcKey = property.getType().getName().toString(); if (!geometryType.equals(srcKey)) { Object value = property.getValue(); if (value != null) { final String dirtyOriginalValue = value.toString().trim(); if (!StringUtils.isEmpty(dirtyOriginalValue)) { String escapedOriginalValue = StringEscapeUtils.escapeXml(dirtyOriginalValue); for (Rule rule : rulelist) { Tag t = rule.createTag(srcKey, escapedOriginalValue); if (t != null) { for (Primitive primitive : features) { primitive.addTag(t); } } } } } } } } private void applyRulesList(SimpleFeature feature, String geometryType, Primitive features, List<Rule> rulelist) { applyRulesList(feature, geometryType, Arrays.asList(features), rulelist); } private static void applyOriginalTagsTo(SimpleFeature feature, String geometryType, Primitive w) { Collection<Property> properties = feature.getProperties(); for (Property property : properties) { String name = property.getType().getName().toString(); if (!geometryType.equals(name)) { String value = property.getValue().toString(); value = StringEscapeUtils.escapeXml(value); w.addTag(new Tag(name, value)); } } } private static List<Way> linestringToWays(LineString geometryN) { Coordinate[] coordinates = geometryN.getCoordinates(); // Follow the 2000 nodes per way max rule int waysToCreate = coordinates.length / MAX_NODES_IN_WAY; waysToCreate += (coordinates.length % MAX_NODES_IN_WAY == 0) ? 0 : 1; List<Way> ways = new ArrayList<Way>(waysToCreate); Way way = new Way(); int nodeCount = 0; for (Coordinate coord : coordinates) { Node node = new Node(coord.y, coord.x); way.addNode(node); if(++nodeCount % MAX_NODES_IN_WAY == 0) { ways.add(way); way = new Way(); way.addNode(node); } } // Add the last way to the list of ways if(way.nodeCount() > 0) { ways.add(way); } return ways; } private static List<Way> polygonToWays(LineString geometryN) { Coordinate[] coordinates = geometryN.getCoordinates(); if(coordinates.length < 2) { throw new IllegalArgumentException("Way with less than 2 nodes."); } // Follow the 2000 max nodes per way rule int waysToCreate = coordinates.length / MAX_NODES_IN_WAY; waysToCreate += (coordinates.length % MAX_NODES_IN_WAY == 0) ? 0 : 1; List<Way> ways = new ArrayList<Way>(waysToCreate); Way way = new Way(); // First node for the polygon Coordinate firstCoord = coordinates[0]; Node firstNode = new Node(firstCoord.y, firstCoord.x); way.addNode(firstNode); // "middle" nodes for (int i = 1; i < coordinates.length-1; i++) { Coordinate coord = coordinates[i]; Node node = new Node(coord.y, coord.x); way.addNode(node); if(i % (MAX_NODES_IN_WAY - 1) == 0) { ways.add(way); way = new Way(); way.addNode(node); } } // Last node should be the same ID as the first one Coordinate lastCoord = coordinates[coordinates.length-1]; if(lastCoord.x == firstCoord.x && lastCoord.y == firstCoord.y) { way.addNode(firstNode); } // Add the last way to the list of ways if(way.nodeCount() > 0) { ways.add(way); } return ways; } }
true
true
public void convert() { CoordinateReferenceSystem targetCRS = null; try { targetCRS = CRS .parseWKT("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]"); } catch (NoSuchAuthorityCodeException e1) { e1.printStackTrace(); } catch (FactoryException e1) { e1.printStackTrace(); } try { // Connection parameters Map<String, Serializable> connectParameters = new HashMap<String, Serializable>(); connectParameters.put("url", inputFile.toURI().toURL()); ShapefileDataStore dataStore = (ShapefileDataStore) DataStoreFinder.getDataStore(connectParameters); CoordinateReferenceSystem sourceCRS = dataStore.getSchema().getCoordinateReferenceSystem(); if (sourceCRS == null) { System.err .println("Could not determine the shapefile's projection. More than likely, the .prj file was not included."); System.exit(-1); } else { System.err.println("Converting from " + sourceCRS + " to " + targetCRS); } outputter.start(); // we are now connected String[] typeNames = dataStore.getTypeNames(); for (String typeName : typeNames) { System.err.println(typeName); FeatureSource<SimpleFeatureType, SimpleFeature> featureSource; FeatureCollection<SimpleFeatureType, SimpleFeature> collection; FeatureIterator<SimpleFeature> iterator; featureSource = dataStore.getFeatureSource(typeName); collection = featureSource.getFeatures(); iterator = collection.features(); try { while (iterator.hasNext()) { try { SimpleFeature feature = iterator.next(); Geometry rawGeom = (Geometry) feature.getDefaultGeometry(); String geometryType = rawGeom.getGeometryType(); // Transform to spherical mercator Geometry geometry = null; try { MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, true); geometry = JTS.transform(rawGeom, transform); } catch (FactoryException e) { e.printStackTrace(); } catch (TransformException e) { e.printStackTrace(); } // geometry = rawGeom; System.err.println("Geometry type: " + geometryType); if ("MultiLineString".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { LineString geometryN = (LineString) geometry .getGeometryN(i); List<Way> ways = linestringToWays(geometryN); applyRulesList(feature, geometryType, ways, ruleset.getLineRules()); for (Way way : ways) { if (shouldInclude(way)) { outputter.addWay(way); } } } } else if ("MultiPolygon".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Polygon geometryN = (Polygon) geometry.getGeometryN(i); // Get the outer ring of the polygon LineString outerLine = geometryN.getExteriorRing(); List<Way> outerWays = polygonToWays(outerLine); if (geometryN.getNumInteriorRing() > 0) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); // Tags go on the relation for multipolygons applyRulesList(feature, geometryType, Arrays.asList(r), ruleset.getOuterPolygonRules()); for (Primitive outerWay : outerWays) { // Always include every outer way r.addMember(new Member(outerWay, "outer")); } // Then the inner ones, if any for (int j = 0; j < geometryN.getNumInteriorRing(); j++) { LineString innerLine = geometryN.getInteriorRingN(j); List<Way> innerWays = polygonToWays(innerLine); applyRulesList(feature, geometryType, innerWays, ruleset .getInnerPolygonRules()); for (Way innerWay : innerWays) { r.addMember(new Member(innerWay, "inner")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there's more than one way, then it // needs to be a multipolygon and the // tags need to be applied to the // relation if(outerWays.size() > 1) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); applyRulesList(feature, geometryType, r, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { r.addMember(new Member(outerWay, "outer")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there aren't any inner lines, then // just use the outer one as a way. applyRulesList(feature, geometryType, outerWays, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { outputter.addWay(outerWay); } } } } } } else if ("Point".equals(geometryType)) { List<Node> nodes = new ArrayList<Node>(geometry.getNumGeometries()); for (int i = 0; i < geometry.getNumGeometries(); i++) { Point geometryN = (Point) geometry.getGeometryN(i); Node n = pointToNode(geometryN); nodes.add(n); } applyRulesList(feature, geometryType, nodes, ruleset.getPointRules()); for (Node node : nodes) { if (shouldInclude(node)) { outputter.addNode(node); } } } } catch (IllegalArgumentException e) { System.err.println("Skipping a geometry becase:"); e.printStackTrace(); } } } catch (MismatchedDimensionException e) { e.printStackTrace(); } finally { if (iterator != null) { // YOU MUST CLOSE THE ITERATOR! iterator.close(); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } outputter.finish(); }
public void convert() { CoordinateReferenceSystem targetCRS = null; try { targetCRS = CRS .parseWKT("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]"); } catch (NoSuchAuthorityCodeException e1) { e1.printStackTrace(); } catch (FactoryException e1) { e1.printStackTrace(); } try { // Connection parameters Map<String, Serializable> connectParameters = new HashMap<String, Serializable>(); connectParameters.put("url", inputFile.toURI().toURL()); connectParameters.put("create spatial index", false); ShapefileDataStore dataStore = (ShapefileDataStore) DataStoreFinder.getDataStore(connectParameters); CoordinateReferenceSystem sourceCRS = dataStore.getSchema().getCoordinateReferenceSystem(); if (sourceCRS == null) { System.err .println("Could not determine the shapefile's projection. More than likely, the .prj file was not included."); System.exit(-1); } else { System.err.println("Converting from " + sourceCRS + " to " + targetCRS); } outputter.start(); // we are now connected String[] typeNames = dataStore.getTypeNames(); for (String typeName : typeNames) { System.err.println(typeName); FeatureSource<SimpleFeatureType, SimpleFeature> featureSource; FeatureCollection<SimpleFeatureType, SimpleFeature> collection; FeatureIterator<SimpleFeature> iterator; featureSource = dataStore.getFeatureSource(typeName); collection = featureSource.getFeatures(); iterator = collection.features(); try { while (iterator.hasNext()) { try { SimpleFeature feature = iterator.next(); Geometry rawGeom = (Geometry) feature.getDefaultGeometry(); String geometryType = rawGeom.getGeometryType(); // Transform to spherical mercator Geometry geometry = null; try { MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, true); geometry = JTS.transform(rawGeom, transform); } catch (FactoryException e) { e.printStackTrace(); } catch (TransformException e) { e.printStackTrace(); } // geometry = rawGeom; System.err.println("Geometry type: " + geometryType); if ("MultiLineString".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { LineString geometryN = (LineString) geometry .getGeometryN(i); List<Way> ways = linestringToWays(geometryN); applyRulesList(feature, geometryType, ways, ruleset.getLineRules()); for (Way way : ways) { if (shouldInclude(way)) { outputter.addWay(way); } } } } else if ("MultiPolygon".equals(geometryType)) { for (int i = 0; i < geometry.getNumGeometries(); i++) { Polygon geometryN = (Polygon) geometry.getGeometryN(i); // Get the outer ring of the polygon LineString outerLine = geometryN.getExteriorRing(); List<Way> outerWays = polygonToWays(outerLine); if (geometryN.getNumInteriorRing() > 0) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); // Tags go on the relation for multipolygons applyRulesList(feature, geometryType, Arrays.asList(r), ruleset.getOuterPolygonRules()); for (Primitive outerWay : outerWays) { // Always include every outer way r.addMember(new Member(outerWay, "outer")); } // Then the inner ones, if any for (int j = 0; j < geometryN.getNumInteriorRing(); j++) { LineString innerLine = geometryN.getInteriorRingN(j); List<Way> innerWays = polygonToWays(innerLine); applyRulesList(feature, geometryType, innerWays, ruleset .getInnerPolygonRules()); for (Way innerWay : innerWays) { r.addMember(new Member(innerWay, "inner")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there's more than one way, then it // needs to be a multipolygon and the // tags need to be applied to the // relation if(outerWays.size() > 1) { Relation r = new Relation(); r.addTag(new Tag("type", "multipolygon")); applyRulesList(feature, geometryType, r, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { r.addMember(new Member(outerWay, "outer")); } } if (shouldInclude(r)) { outputter.addRelation(r); } } else { // If there aren't any inner lines, then // just use the outer one as a way. applyRulesList(feature, geometryType, outerWays, ruleset .getOuterPolygonRules()); for (Way outerWay : outerWays) { if (shouldInclude(outerWay)) { outputter.addWay(outerWay); } } } } } } else if ("Point".equals(geometryType)) { List<Node> nodes = new ArrayList<Node>(geometry.getNumGeometries()); for (int i = 0; i < geometry.getNumGeometries(); i++) { Point geometryN = (Point) geometry.getGeometryN(i); Node n = pointToNode(geometryN); nodes.add(n); } applyRulesList(feature, geometryType, nodes, ruleset.getPointRules()); for (Node node : nodes) { if (shouldInclude(node)) { outputter.addNode(node); } } } } catch (IllegalArgumentException e) { System.err.println("Skipping a geometry becase:"); e.printStackTrace(); } } } catch (MismatchedDimensionException e) { e.printStackTrace(); } finally { if (iterator != null) { // YOU MUST CLOSE THE ITERATOR! iterator.close(); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } outputter.finish(); }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java index 6920a3fcc..da5b8a9e9 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java @@ -1,582 +1,587 @@ /* * BitsreamReader.java * * Version: $Revision: 1.5 $ * * Date: $Date: 2006/08/08 20:59:54 $ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.xmlui.cocoon; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.sql.SQLException; import java.util.Map; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletResponse; import org.apache.avalon.excalibur.pool.Recyclable; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.ResourceNotFoundException; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Response; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.environment.http.HttpEnvironment; import org.apache.cocoon.environment.http.HttpResponse; import org.apache.cocoon.reading.AbstractReader; import org.apache.cocoon.util.ByteRange; import org.dspace.app.xmlui.utils.AuthenticationUtil; import org.dspace.app.xmlui.utils.ContextUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.uri.ResolvableIdentifier; import org.dspace.uri.IdentifierService; import org.dspace.uri.IdentifierException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.xml.sax.SAXException; import org.apache.log4j.Logger; import org.dspace.core.LogManager; /** * The BitstreamReader will query DSpace for a particular bitstream and transmit * it to the user. There are several method of specifing the bitstream to be * develivered. You may refrence a bitstream by either it's id or attempt to * resolve the bitstream's name. * * /bitstream/{handle}/{sequence}/{name} * * &lt;map:read type="BitstreamReader"> * &lt;map:parameter name="handle" value="{1}/{2}"/&gt; * &lt;map:parameter name="sequence" value="{3}"/&gt; * &lt;map:parameter name="name" value="{4}"/&gt; * &lt;/map:read&gt; * * When no handle is assigned yet you can access a bistream * using it's internal ID. * * /bitstream/id/{bitstreamID}/{sequence}/{name} * * &lt;map:read type="BitstreamReader"> * &lt;map:parameter name="bitstreamID" value="{1}"/&gt; * &lt;map:parameter name="sequence" value="{2}"/&gt; * &lt;/map:read&gt; * * Alternativly, you can access the bitstream via a name instead * of directly through it's sequence. * * /html/{handle}/{name} * * &lt;map:read type="BitstreamReader"&gt; * &lt;map:parameter name="handle" value="{1}/{2}"/&gt; * &lt;map:parameter name="name" value="{3}"/&gt; * &lt;/map:read&gt; * * Again when no handle is available you can also access it * via an internal itemID & name. * * /html/id/{itemID}/{name} * * &lt;map:read type="BitstreamReader"&gt; * &lt;map:parameter name="itemID" value="{1}"/&gt; * &lt;map:parameter name="name" value="{2}"/&gt; * &lt;/map:read&gt; * * @author Scott Phillips */ public class BitstreamReader extends AbstractReader implements Recyclable { private static Logger log = Logger.getLogger(BitstreamReader.class); /** * Messages to be sent when the user is not authorized to view * a particular bitstream. They will be redirected to the login * where this message will be displayed. */ private final static String AUTH_REQUIRED_HEADER = "xmlui.BitstreamReader.auth_header"; private final static String AUTH_REQUIRED_MESSAGE = "xmlui.BitstreamReader.auth_message"; /** * How big of a buffer should we use when reading from the bitstream before * writting to the HTTP response? */ protected static final int BUFFER_SIZE = 8192; /** * When should a bitstream expire in milliseconds. This should be set to * some low value just to prevent someone hiting DSpace repeatily from * killing the server. Note: 60000 milliseconds are in a second. * * Format: minutes * seconds * milliseconds */ protected static final int expires = 60 * 60 * 60000; /** The Cocoon response */ protected Response response; /** The Cocoon request */ protected Request request; /** The bitstream file */ protected InputStream bitstreamInputStream; /** The bitstream's reported size */ protected long bitstreamSize; /** The bitstream's mime-type */ protected String bitstreamMimeType; /** The bitstream's name */ protected String bitstreamName; /** * Set up the bitstream reader. * * See the class description for information on configuration options. * * FIXME: This should use the parameter "uri" rather than "handle" to be * consistent with the JSPUI. Unfortunately, I have no idea how this works * right now, so I'll have to do that later. It should still work for now * though. --JR */ public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, par); try { this.request = ObjectModelHelper.getRequest(objectModel); this.response = ObjectModelHelper.getResponse(objectModel); Context context = ContextUtil.obtainContext(objectModel); // Get our parameters that identify the bitstream int itemID = par.getParameterAsInteger("itemID", -1); int bitstreamID = par.getParameterAsInteger("bitstreamID", -1); String handle = par.getParameter("handle", null); int sequence = par.getParameterAsInteger("sequence", -1); String name = par.getParameter("name", null); // Reslove the bitstream Bitstream bitstream = null; Item item = null; DSpaceObject dso = null; if (bitstreamID > -1) { // Direct refrence to the individual bitstream ID. bitstream = Bitstream.find(context, bitstreamID); } else if (itemID > -1) { // Referenced by internal itemID item = Item.find(context, itemID); if (sequence > -1) { bitstream = findBitstreamBySequence(item, sequence); } else if (name != null) { bitstream = findBitstreamByName(item, name); } } else if (handle != null) { // Reference by an item's handle. ResolvableIdentifier ri = IdentifierService.resolve(context, handle); dso = (DSpaceObject) IdentifierService.getResource(context, ri); if (dso instanceof Item && sequence > -1) { bitstream = findBitstreamBySequence((Item) dso,sequence); } else if (dso instanceof Item && name != null) { bitstream = findBitstreamByName((Item) dso,name); } } // Was a bitstream found? if (bitstream == null) { throw new ResourceNotFoundException("Unable to locate bitstream"); } // Is there a User logged in and does the user have access to read it? if (!AuthorizeManager.authorizeActionBoolean(context, bitstream, Constants.READ)) { if(this.request.getSession().getAttribute("dspace.current.user.id")!=null){ // A user is logged in, but they are not authorized to read this bitstream, // instead of asking them to login again we'll point them to a friendly error // message that tells them the bitstream is restricted. String redictURL = request.getContextPath() + "/handle/"; if (item!=null){ // redictURL += item.getHandle(); redictURL += IdentifierService.getCanonicalForm(item); } else if(dso!=null){ // redictURL += dso.getHandle(); redictURL += IdentifierService.getCanonicalForm(dso); } redictURL += "/restricted-resource?bitstreamId=" + bitstream.getID(); HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } else{ // The user does not have read access to this bitstream. Inturrupt this current request // and then forward them to the login page so that they can be authenticated. Once that is // successfull they will request will be resumed. AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); // Redirect String redictURL = request.getContextPath() + "/login"; HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } } // Success, bitstream found and the user has access to read it. // Store these for later retreval: this.bitstreamInputStream = bitstream.retrieve(); this.bitstreamSize = bitstream.getSize(); this.bitstreamMimeType = bitstream.getFormat().getMIMEType(); this.bitstreamName = bitstream.getName(); // Trim any path information from the bitstream - if (bitstreamName != null) - { - int finalSlashIndex = bitstreamName.lastIndexOf("/"); - if (finalSlashIndex > 0) - { - bitstreamName = bitstreamName.substring(finalSlashIndex+1); - } + if (bitstreamName != null && bitstreamName.length() >0 ) + { + int finalSlashIndex = bitstreamName.lastIndexOf("/"); + if (finalSlashIndex > 0) + { + bitstreamName = bitstreamName.substring(finalSlashIndex+1); + } + } + else + { + // In-case there is no bitstream name... + bitstreamName = "bitstream"; } // Log that the bitstream has been viewed. log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID())); } catch (SQLException sqle) { throw new ProcessingException("Unable to read bitstream.",sqle); } catch (IdentifierException e) { log.error("caught exception: ", e); throw new ProcessingException("Unable to read bitstream.", e); } catch (AuthorizeException ae) { throw new ProcessingException("Unable to read bitstream.",ae); } } /** * Find the bitstream identified by a sequence number on this item. * * @param item A DSpace item * @param sequence The sequence of the bitstream * @return The bitstream or null if none found. */ private Bitstream findBitstreamBySequence(Item item, int sequence) throws SQLException { if (item == null) return null; Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { if (bitstream.getSequenceID() == sequence) { return bitstream; } } } return null; } /** * Return the bitstream from the given item that is identified by the * given name. If the name has prepended directories they will be removed * one at a time until a bitstream is found. Note that if two bitstreams * have the same name then the first bitstream will be returned. * * @param item A DSpace item * @param name The name of the bitstream * @return The bitstream or null if none found. */ private Bitstream findBitstreamByName(Item item, String name) throws SQLException { if (name == null || item == null) return null; // Determine our the maximum number of directories that will be removed for a path. int maxDepthPathSearch = 3; if (ConfigurationManager.getProperty("xmlui.html.max-depth-guess") != null) maxDepthPathSearch = ConfigurationManager.getIntProperty("xmlui.html.max-depth-guess"); // Search for the named bitstream on this item. Each time through the loop // a directory is removed from the name until either our maximum depth is // reached or the bitstream is found. Note: an extra pass is added on to the // loop for a last ditch effort where all directory paths will be removed. for (int i = 0; i < maxDepthPathSearch+1; i++) { // Search through all the bitstreams and see // if the name can be found Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { if (name.equals(bitstream.getName())) { return bitstream; } } } // The bitstream was not found, so try removing a directory // off of the name and see if we lost some path information. int indexOfSlash = name.indexOf('/'); if (indexOfSlash < 0) // No more directories to remove from the path, so return null for no // bitstream found. return null; name = name.substring(indexOfSlash+1); // If this is our next to last time through the loop then // trim everything and only use the trailing filename. if (i == maxDepthPathSearch-1) { int indexOfLastSlash = name.lastIndexOf('/'); if (indexOfLastSlash > -1) name = name.substring(indexOfLastSlash+1); } } // The named bitstream was not found and we exausted our the maximum path depth that // we search. return null; } /** * Write the actual data out to the response. * * Some implementation notes, * * 1) We set a short expires time just in the hopes of preventing someone * from overloading the server by clicking reload a bunch of times. I * realize that this is nowhere near 100% effective but it may help in some * cases and shouldn't hurt anything. * * 2) We accept partial downloads, thus if you lose a connection half way * through most web browser will enable you to resume downloading the * bitstream. */ public void generate() throws IOException, SAXException, ProcessingException { if (this.bitstreamInputStream == null) return; byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; response.setDateHeader("Expires", System.currentTimeMillis() + expires); // If this is a large bitstream then tell the browser it should treat it as a download. int threshold = ConfigurationManager.getIntProperty("xmlui.content_disposition_threshold"); if (bitstreamSize > threshold && threshold != 0) { String name = bitstreamName; // Try and make the download file name formated for each browser. try { String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.contains("MSIE")) name = URLEncoder.encode(name,"UTF8"); else if (agent != null && agent.contains("Mozilla")) name = MimeUtility.encodeText(name, "UTF8", "B"); } catch (UnsupportedEncodingException see) { // do nothing } response.setHeader("Content-Disposition", "attachment;filename=" + name); } // Turn off partial downloads, they cause problems // and are only rarely used. Specifically some windows pdf // viewers are incapable of handling this request. By // uncommenting the following two lines you will turn this feature back on. // response.setHeader("Accept-Ranges", "bytes"); // String ranges = request.getHeader("Range"); String ranges = null; ByteRange byteRange = null; if (ranges != null) { try { ranges = ranges.substring(ranges.indexOf('=') + 1); byteRange = new ByteRange(ranges); } catch (NumberFormatException e) { byteRange = null; if (response instanceof HttpResponse) { // Respond with status 416 (Request range not // satisfiable) ((HttpResponse) response).setStatus(416); } } } if (byteRange != null) { String entityLength; String entityRange; if (this.bitstreamSize != -1) { entityLength = "" + this.bitstreamSize; entityRange = byteRange.intersection( new ByteRange(0, this.bitstreamSize)).toString(); } else { entityLength = "*"; entityRange = byteRange.toString(); } response.setHeader("Content-Range", entityRange + "/" + entityLength); if (response instanceof HttpResponse) { // Response with status 206 (Partial content) ((HttpResponse) response).setStatus(206); } int pos = 0; int posEnd; while ((length = this.bitstreamInputStream.read(buffer)) > -1) { posEnd = pos + length - 1; ByteRange intersection = byteRange .intersection(new ByteRange(pos, posEnd)); if (intersection != null) { out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length()); } pos += length; } } else { response.setHeader("Content-Length", String .valueOf(this.bitstreamSize)); while ((length = this.bitstreamInputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } /** * Returns the mime-type of the bitstream. */ public String getMimeType() { return this.bitstreamMimeType; } /** * Recycle */ public void recycle() { this.response = null; this.request = null; this.bitstreamInputStream = null; this.bitstreamSize = 0; this.bitstreamMimeType = null; } }
true
true
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, par); try { this.request = ObjectModelHelper.getRequest(objectModel); this.response = ObjectModelHelper.getResponse(objectModel); Context context = ContextUtil.obtainContext(objectModel); // Get our parameters that identify the bitstream int itemID = par.getParameterAsInteger("itemID", -1); int bitstreamID = par.getParameterAsInteger("bitstreamID", -1); String handle = par.getParameter("handle", null); int sequence = par.getParameterAsInteger("sequence", -1); String name = par.getParameter("name", null); // Reslove the bitstream Bitstream bitstream = null; Item item = null; DSpaceObject dso = null; if (bitstreamID > -1) { // Direct refrence to the individual bitstream ID. bitstream = Bitstream.find(context, bitstreamID); } else if (itemID > -1) { // Referenced by internal itemID item = Item.find(context, itemID); if (sequence > -1) { bitstream = findBitstreamBySequence(item, sequence); } else if (name != null) { bitstream = findBitstreamByName(item, name); } } else if (handle != null) { // Reference by an item's handle. ResolvableIdentifier ri = IdentifierService.resolve(context, handle); dso = (DSpaceObject) IdentifierService.getResource(context, ri); if (dso instanceof Item && sequence > -1) { bitstream = findBitstreamBySequence((Item) dso,sequence); } else if (dso instanceof Item && name != null) { bitstream = findBitstreamByName((Item) dso,name); } } // Was a bitstream found? if (bitstream == null) { throw new ResourceNotFoundException("Unable to locate bitstream"); } // Is there a User logged in and does the user have access to read it? if (!AuthorizeManager.authorizeActionBoolean(context, bitstream, Constants.READ)) { if(this.request.getSession().getAttribute("dspace.current.user.id")!=null){ // A user is logged in, but they are not authorized to read this bitstream, // instead of asking them to login again we'll point them to a friendly error // message that tells them the bitstream is restricted. String redictURL = request.getContextPath() + "/handle/"; if (item!=null){ // redictURL += item.getHandle(); redictURL += IdentifierService.getCanonicalForm(item); } else if(dso!=null){ // redictURL += dso.getHandle(); redictURL += IdentifierService.getCanonicalForm(dso); } redictURL += "/restricted-resource?bitstreamId=" + bitstream.getID(); HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } else{ // The user does not have read access to this bitstream. Inturrupt this current request // and then forward them to the login page so that they can be authenticated. Once that is // successfull they will request will be resumed. AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); // Redirect String redictURL = request.getContextPath() + "/login"; HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } } // Success, bitstream found and the user has access to read it. // Store these for later retreval: this.bitstreamInputStream = bitstream.retrieve(); this.bitstreamSize = bitstream.getSize(); this.bitstreamMimeType = bitstream.getFormat().getMIMEType(); this.bitstreamName = bitstream.getName(); // Trim any path information from the bitstream if (bitstreamName != null) { int finalSlashIndex = bitstreamName.lastIndexOf("/"); if (finalSlashIndex > 0) { bitstreamName = bitstreamName.substring(finalSlashIndex+1); } } // Log that the bitstream has been viewed. log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID())); } catch (SQLException sqle) { throw new ProcessingException("Unable to read bitstream.",sqle); } catch (IdentifierException e) { log.error("caught exception: ", e); throw new ProcessingException("Unable to read bitstream.", e); } catch (AuthorizeException ae) { throw new ProcessingException("Unable to read bitstream.",ae); } }
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, par); try { this.request = ObjectModelHelper.getRequest(objectModel); this.response = ObjectModelHelper.getResponse(objectModel); Context context = ContextUtil.obtainContext(objectModel); // Get our parameters that identify the bitstream int itemID = par.getParameterAsInteger("itemID", -1); int bitstreamID = par.getParameterAsInteger("bitstreamID", -1); String handle = par.getParameter("handle", null); int sequence = par.getParameterAsInteger("sequence", -1); String name = par.getParameter("name", null); // Reslove the bitstream Bitstream bitstream = null; Item item = null; DSpaceObject dso = null; if (bitstreamID > -1) { // Direct refrence to the individual bitstream ID. bitstream = Bitstream.find(context, bitstreamID); } else if (itemID > -1) { // Referenced by internal itemID item = Item.find(context, itemID); if (sequence > -1) { bitstream = findBitstreamBySequence(item, sequence); } else if (name != null) { bitstream = findBitstreamByName(item, name); } } else if (handle != null) { // Reference by an item's handle. ResolvableIdentifier ri = IdentifierService.resolve(context, handle); dso = (DSpaceObject) IdentifierService.getResource(context, ri); if (dso instanceof Item && sequence > -1) { bitstream = findBitstreamBySequence((Item) dso,sequence); } else if (dso instanceof Item && name != null) { bitstream = findBitstreamByName((Item) dso,name); } } // Was a bitstream found? if (bitstream == null) { throw new ResourceNotFoundException("Unable to locate bitstream"); } // Is there a User logged in and does the user have access to read it? if (!AuthorizeManager.authorizeActionBoolean(context, bitstream, Constants.READ)) { if(this.request.getSession().getAttribute("dspace.current.user.id")!=null){ // A user is logged in, but they are not authorized to read this bitstream, // instead of asking them to login again we'll point them to a friendly error // message that tells them the bitstream is restricted. String redictURL = request.getContextPath() + "/handle/"; if (item!=null){ // redictURL += item.getHandle(); redictURL += IdentifierService.getCanonicalForm(item); } else if(dso!=null){ // redictURL += dso.getHandle(); redictURL += IdentifierService.getCanonicalForm(dso); } redictURL += "/restricted-resource?bitstreamId=" + bitstream.getID(); HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } else{ // The user does not have read access to this bitstream. Inturrupt this current request // and then forward them to the login page so that they can be authenticated. Once that is // successfull they will request will be resumed. AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); // Redirect String redictURL = request.getContextPath() + "/login"; HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } } // Success, bitstream found and the user has access to read it. // Store these for later retreval: this.bitstreamInputStream = bitstream.retrieve(); this.bitstreamSize = bitstream.getSize(); this.bitstreamMimeType = bitstream.getFormat().getMIMEType(); this.bitstreamName = bitstream.getName(); // Trim any path information from the bitstream if (bitstreamName != null && bitstreamName.length() >0 ) { int finalSlashIndex = bitstreamName.lastIndexOf("/"); if (finalSlashIndex > 0) { bitstreamName = bitstreamName.substring(finalSlashIndex+1); } } else { // In-case there is no bitstream name... bitstreamName = "bitstream"; } // Log that the bitstream has been viewed. log.info(LogManager.getHeader(context, "view_bitstream", "bitstream_id=" + bitstream.getID())); } catch (SQLException sqle) { throw new ProcessingException("Unable to read bitstream.",sqle); } catch (IdentifierException e) { log.error("caught exception: ", e); throw new ProcessingException("Unable to read bitstream.", e); } catch (AuthorizeException ae) { throw new ProcessingException("Unable to read bitstream.",ae); } }
diff --git a/ini/trakem2/display/Display.java b/ini/trakem2/display/Display.java index 1fdc4faf..c4c46bf3 100644 --- a/ini/trakem2/display/Display.java +++ b/ini/trakem2/display/Display.java @@ -1,3755 +1,3755 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005, 2006 Albert Cardona and Rodney Douglas. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.display; import ij.*; import ij.io.*; import ij.gui.*; import ij.process.*; import ij.measure.Calibration; import ini.trakem2.Project; import ini.trakem2.ControlWindow; import ini.trakem2.persistence.DBObject; import ini.trakem2.persistence.Loader; import ini.trakem2.utils.IJError; import ini.trakem2.imaging.PatchStack; import ini.trakem2.imaging.LayerStack; import ini.trakem2.imaging.Registration; import ini.trakem2.imaging.StitchingTEM; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; import ini.trakem2.utils.DNDInsertImage; import ini.trakem2.utils.Search; import ini.trakem2.utils.Bureaucrat; import ini.trakem2.utils.Worker; import ini.trakem2.utils.Dispatcher; import ini.trakem2.utils.Lock; import ini.trakem2.tree.*; import javax.swing.*; import javax.swing.event.*; import mpicbg.trakem2.align.Align; import mpicbg.trakem2.align.AlignTask; import java.awt.*; import java.awt.event.*; import java.util.*; import java.lang.reflect.Method; import java.io.File; import java.io.Writer; /** A Display is a class to show a Layer and enable mouse and keyboard manipulation of all its components. */ public final class Display extends DBObject implements ActionListener, ImageListener { /** The Layer this Display is showing. */ private Layer layer; private Displayable active = null; /** All selected Displayable objects, including the active one. */ final private Selection selection = new Selection(this); private ImagePlus last_temp = null; private JFrame frame; private JTabbedPane tabs; private Hashtable<Class,JScrollPane> ht_tabs; private JScrollPane scroll_patches; private JPanel panel_patches; private JScrollPane scroll_profiles; private JPanel panel_profiles; private JScrollPane scroll_zdispl; private JPanel panel_zdispl; private JScrollPane scroll_channels; private JPanel panel_channels; private JScrollPane scroll_labels; private JPanel panel_labels; private JSlider transp_slider; private DisplayNavigator navigator; private JScrollBar scroller; private DisplayCanvas canvas; // WARNING this is an AWT component, since it extends ImageCanvas private JPanel canvas_panel; // and this is a workaround, to better (perhaps) integrate the awt canvas inside a JSplitPane private JSplitPane split; private JPopupMenu popup = null; /** Contains the packed alphas of every channel. */ private int c_alphas = 0xffffffff; // all 100 % visible private Channel[] channels; private Hashtable<Displayable,DisplayablePanel> ht_panels = new Hashtable<Displayable,DisplayablePanel>(); /** Handle drop events, to insert image files. */ private DNDInsertImage dnd; private boolean size_adjusted = false; private int scroll_step = 1; /** Keep track of all existing Display objects. */ static private ArrayList<Display> al_displays = new ArrayList<Display>(); /** The currently focused Display, if any. */ static private Display front = null; /** Displays to open when all objects have been reloaded from the database. */ static private final Hashtable ht_later = new Hashtable(); /** A thread to handle user actions, for example an event sent from a popup menu. */ private final Dispatcher dispatcher = new Dispatcher(); static private WindowAdapter window_listener = new WindowAdapter() { /** Unregister the closed Display. */ public void windowClosing(WindowEvent we) { final Object source = we.getSource(); for (Iterator it = al_displays.iterator(); it.hasNext(); ) { Display d = (Display)it.next(); if (source == d.frame) { it.remove(); if (d == front) front = null; d.remove(false); //calls destroy break; } } } /** Set the source Display as front. */ public void windowActivated(WindowEvent we) { // find which was it to make it be the front final Object source = we.getSource(); for (final Display d : al_displays) { if (source == d.frame) { front = d; // set toolbar ProjectToolbar.setProjectToolbar(); // now, select the layer in the LayerTree front.getProject().select(front.layer); // finally, set the virtual ImagePlus that ImageJ will see d.setTempCurrentImage(); // copied from ij.gui.ImageWindow, with modifications if (IJ.isMacintosh() && IJ.getInstance()!=null) { IJ.wait(10); // may be needed for Java 1.4 on OS X d.frame.setMenuBar(ij.Menus.getMenuBar()); } return; } } // else, restore the ImageJ toolbar for non-project images //if (!source.equals(IJ.getInstance())) { // ProjectToolbar.setImageJToolbar(); //} } /** Restore the ImageJ toolbar */ public void windowDeactivated(WindowEvent we) { // Can't, the user can never click the ProjectToolbar then. This has to be done in a different way, for example checking who is the WindowManager.getCurrentImage (and maybe setting a dummy image into it) //ProjectToolbar.setImageJToolbar(); } /** Call a pack() when the window is maximized to fit the canvas correctly. */ public void windowStateChanged(WindowEvent we) { final Object source = we.getSource(); for (final Display d : al_displays) { if (source != d.frame) continue; d.pack(); break; } } }; static private MouseListener frame_mouse_listener = new MouseAdapter() { public void mouseReleased(MouseEvent me) { Object source = me.getSource(); for (final Display d : al_displays) { if (d.frame == source) { if (d.size_adjusted) { d.pack(); d.size_adjusted = false; Utils.log2("mouse released on JFrame"); } break; } } } }; private int last_frame_state = frame.NORMAL; // THIS WHOLE SYSTEM OF LISTENERS IS BROKEN: // * when zooming in, the window growths in width a few pixels. // * when enlarging the window quickly, the canvas is not resized as large as it should. // -- the whole problem: swing threading, which I am not handling properly. It's hard. static private ComponentListener component_listener = new ComponentAdapter() { public void componentResized(ComponentEvent ce) { final Display d = getDisplaySource(ce); if (null != d) { d.size_adjusted = true; // works in combination with mouseReleased to call pack(), avoiding infinite loops. d.adjustCanvas(); int frame_state = d.frame.getExtendedState(); if (frame_state != d.last_frame_state) { // this setup avoids infinite loops (for pack() calls componentResized as well d.last_frame_state = frame_state; if (d.frame.ICONIFIED != frame_state) d.pack(); } } } public void componentMoved(ComponentEvent ce) { Display d = getDisplaySource(ce); if (null != d) d.updateInDatabase("position"); } private Display getDisplaySource(ComponentEvent ce) { final Object source = ce.getSource(); for (final Display d : al_displays) { if (source == d.frame) { return d; } } return null; } }; static private ChangeListener tabs_listener = new ChangeListener() { /** Listen to tab changes. */ public void stateChanged(final ChangeEvent ce) { final Object source = ce.getSource(); for (final Display d : al_displays) { if (source == d.tabs) { d.dispatcher.exec(new Runnable() { public void run() { // creating tabs fires the event!!! if (null == d.frame || null == d.canvas) return; final Container tab = (Container)d.tabs.getSelectedComponent(); if (tab == d.scroll_channels) { // find active channel if any for (int i=0; i<d.channels.length; i++) { if (d.channels[i].isActive()) { d.transp_slider.setValue((int)(d.channels[i].getAlpha() * 100)); break; } } } else { // recreate contents /* int count = tab.getComponentCount(); if (0 == count || (1 == count && tab.getComponent(0).getClass().equals(JLabel.class))) { */ // ALWAYS, because it could be the case that the user changes layer while on one specific tab, and then clicks on the other tab which may not be empty and shows totally the wrong contents (i.e. for another layer) String label = null; ArrayList al = null; JPanel p = null; if (tab == d.scroll_zdispl) { label = "Z-space objects"; al = d.layer.getParent().getZDisplayables(); p = d.panel_zdispl; } else if (tab == d.scroll_patches) { label = "Patches"; al = d.layer.getDisplayables(Patch.class); p = d.panel_patches; } else if (tab == d.scroll_labels) { label = "Labels"; al = d.layer.getDisplayables(DLabel.class); p = d.panel_labels; } else if (tab == d.scroll_profiles) { label = "Profiles"; al = d.layer.getDisplayables(Profile.class); p = d.panel_profiles; } d.updateTab(p, label, al); //Utils.updateComponent(d.tabs.getSelectedComponent()); //Utils.log2("updated tab: " + p + " with " + al.size() + " objects."); //} if (null != d.active) { // set the transp slider to the alpha value of the active Displayable if any d.transp_slider.setValue((int)(d.active.getAlpha() * 100)); DisplayablePanel dp = d.ht_panels.get(d.active); if (null != dp) dp.setActive(true); } } }}); break; } } } }; private final ScrollLayerListener scroller_listener = new ScrollLayerListener(); private class ScrollLayerListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent ae) { int index = scroller.getValue(); slt.set(layer.getParent().getLayer(index)); return; } } private final SetLayerThread slt = new SetLayerThread(); private class SetLayerThread extends Thread { private boolean go = true; private Layer layer; private final Lock lock = new Lock(); private final Lock lock2 = new Lock(); SetLayerThread() { setPriority(Thread.NORM_PRIORITY); setDaemon(true); start(); } public final void set(final Layer layer) { synchronized (lock) { this.layer = layer; } synchronized (this) { notify(); } } public final void setAndWait(final Layer layer) { lock2.lock(); set(layer); } public void run() { while (go) { while (null == this.layer) { synchronized (this) { try { wait(); } catch (InterruptedException ie) {} } } Layer layer = null; synchronized (lock) { layer = this.layer; this.layer = null; } // if (!go) return; // after nullifying layer // if (null != layer) { Display.this.setLayer(layer); Display.this.updateInDatabase("layer_id"); } // unlock any calls waiting on setAndWait synchronized (lock2) { lock2.unlock(); } } // cleanup: synchronized (lock2) { lock2.unlock(); } } public void waitForLayer() { while (null != layer && go) { try { Thread.sleep(10); } catch (Exception e) {} } } public void quit() { go = false; } } /** Creates a new Display with adjusted magnification to fit in the screen. */ static public void createDisplay(final Project project, final Layer layer) { SwingUtilities.invokeLater(new Runnable() { public void run() { Display display = new Display(project, layer); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight()); double mag = screen.width / layer.getLayerWidth(); if (mag * layer.getLayerHeight() > screen.height) mag = screen.height / layer.getLayerHeight(); mag = display.canvas.getLowerZoomLevel2(mag); if (mag > 1.0) mag = 1.0; //display.getCanvas().setup(mag, srcRect); // would call pack() at the wrong time! // ... so instead: manually display.getCanvas().setMagnification(mag); display.getCanvas().setSrcRect(srcRect.x, srcRect.y, srcRect.width, srcRect.height); display.getCanvas().setDrawingSize((int)Math.ceil(srcRect.width * mag), (int)Math.ceil(srcRect.height * mag)); // display.updateTitle(); ij.gui.GUI.center(display.frame); display.frame.pack(); }}); } /** A new Display from scratch, to show the given Layer. */ public Display(Project project, final Layer layer) { super(project); front = this; makeGUI(layer, null); ImagePlus.addImageListener(this); setLayer(layer); this.layer = layer; // after, or it doesn't update properly al_displays.add(this); addToDatabase(); } /** For reconstruction purposes. The Display will be stored in the ht_later.*/ public Display(Project project, long id, Layer layer, Object[] props) { super(project, id); synchronized (ht_later) { Display.ht_later.put(this, props); } this.layer = layer; } /** Open a new Display centered around the given Displayable. */ public Display(Project project, Layer layer, Displayable displ) { super(project); front = this; active = displ; makeGUI(layer, null); ImagePlus.addImageListener(this); setLayer(layer); this.layer = layer; // after set layer! al_displays.add(this); addToDatabase(); } /** Reconstruct a Display from an XML entry, to be opened when everything is ready. */ public Display(Project project, long id, Layer layer, HashMap ht_attributes) { super(project, id); if (null == layer) { Utils.log2("Display: need a non-null Layer for id=" + id); return; } Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight()); double magnification = 0.25; Point p = new Point(0, 0); int c_alphas = 0xffffffff; int c_alphas_state = 0xffffffff; for (Iterator it = ht_attributes.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); String key = (String)entry.getKey(); String data = (String)entry.getValue(); if (key.equals("srcrect_x")) { // reflection! Reflection! srcRect.x = Integer.parseInt(data); } else if (key.equals("srcrect_y")) { srcRect.y = Integer.parseInt(data); } else if (key.equals("srcrect_width")) { srcRect.width = Integer.parseInt(data); } else if (key.equals("srcrect_height")) { srcRect.height = Integer.parseInt(data); } else if (key.equals("magnification")) { magnification = Double.parseDouble(data); } else if (key.equals("x")) { p.x = Integer.parseInt(data); } else if (key.equals("y")) { p.y = Integer.parseInt(data); } else if (key.equals("c_alphas")) { try { c_alphas = Integer.parseInt(data); } catch (Exception ex) { c_alphas = 0xffffffff; } } else if (key.equals("c_alphas_state")) { try { c_alphas_state = Integer.parseInt(data); } catch (Exception ex) { IJError.print(ex); c_alphas_state = 0xffffffff; } } else if (key.equals("scroll_step")) { try { setScrollStep(Integer.parseInt(data)); } catch (Exception ex) { IJError.print(ex); setScrollStep(1); } } // TODO the above is insecure, in that data is not fully checked to be within bounds. } Object[] props = new Object[]{p, new Double(magnification), srcRect, new Long(layer.getId()), new Integer(c_alphas), new Integer(c_alphas_state)}; synchronized (ht_later) { Display.ht_later.put(this, props); } this.layer = layer; } /** After reloading a project from the database, open the Displays that the project had. */ static public Bureaucrat openLater() { final Hashtable ht_later_local; synchronized (ht_later) { if (0 == ht_later.size()) return null; ht_later_local = new Hashtable(ht_later); ht_later.keySet().removeAll(ht_later_local.keySet()); } final Worker worker = new Worker("Opening displays") { public void run() { startedWorking(); try { Thread.sleep(300); // waiting for Swing for (Enumeration e = ht_later_local.keys(); e.hasMoreElements(); ) { final Display d = (Display)e.nextElement(); front = d; // must be set before repainting any ZDisplayable! Object[] props = (Object[])ht_later_local.get(d); if (ControlWindow.isGUIEnabled()) d.makeGUI(d.layer, props); d.setLayerLater(d.layer, d.layer.get(((Long)props[3]).longValue())); //important to do it after makeGUI if (!ControlWindow.isGUIEnabled()) continue; ImagePlus.addImageListener(d); al_displays.add(d); d.updateTitle(); // force a repaint if a prePaint was done TODO this should be properly managed with repaints using always the invokeLater, but then it's DOG SLOW if (d.canvas.getMagnification() > 0.499) { SwingUtilities.invokeLater(new Runnable() { public void run() { d.repaint(d.layer); d.project.getLoader().setChanged(false); Utils.log2("A set to false"); }}); } d.project.getLoader().setChanged(false); Utils.log2("B set to false"); } if (null != front) front.getProject().select(front.layer); } catch (Throwable t) { IJError.print(t); } finally { finishedWorking(); } } }; return Bureaucrat.createAndStart(worker, ((Display)ht_later_local.keySet().iterator().next()).getProject()); // gets the project from the first Display } private void makeGUI(final Layer layer, final Object[] props) { // gather properties Point p = null; double mag = 1.0D; Rectangle srcRect = null; if (null != props) { p = (Point)props[0]; mag = ((Double)props[1]).doubleValue(); srcRect = (Rectangle)props[2]; } // transparency slider this.transp_slider = new JSlider(javax.swing.SwingConstants.HORIZONTAL, 0, 100, 100); this.transp_slider.setBackground(Color.white); this.transp_slider.setMinimumSize(new Dimension(250, 20)); this.transp_slider.setMaximumSize(new Dimension(250, 20)); this.transp_slider.setPreferredSize(new Dimension(250, 20)); TransparencySliderListener tsl = new TransparencySliderListener(); this.transp_slider.addChangeListener(tsl); this.transp_slider.addMouseListener(tsl); for (final KeyListener kl : this.transp_slider.getKeyListeners()) { this.transp_slider.removeKeyListener(kl); } // Tabbed pane on the left this.tabs = new JTabbedPane(); this.tabs.setMinimumSize(new Dimension(250, 300)); this.tabs.setBackground(Color.white); this.tabs.addChangeListener(tabs_listener); // Tab 1: Patches this.panel_patches = new JPanel(); BoxLayout patches_layout = new BoxLayout(panel_patches, BoxLayout.Y_AXIS); this.panel_patches.setLayout(patches_layout); this.panel_patches.add(new JLabel("No patches.")); this.scroll_patches = makeScrollPane(panel_patches); this.scroll_patches.setPreferredSize(new Dimension(250, 300)); this.scroll_patches.setMinimumSize(new Dimension(250, 300)); this.tabs.add("Patches", scroll_patches); // Tab 2: Profiles this.panel_profiles = new JPanel(); BoxLayout profiles_layout = new BoxLayout(panel_profiles, BoxLayout.Y_AXIS); this.panel_profiles.setLayout(profiles_layout); this.panel_profiles.add(new JLabel("No profiles.")); this.scroll_profiles = makeScrollPane(panel_profiles); this.scroll_profiles.setPreferredSize(new Dimension(250, 300)); this.scroll_profiles.setMinimumSize(new Dimension(250, 300)); this.tabs.add("Profiles", scroll_profiles); // Tab 3: pipes this.panel_zdispl = new JPanel(); BoxLayout pipes_layout = new BoxLayout(panel_zdispl, BoxLayout.Y_AXIS); this.panel_zdispl.setLayout(pipes_layout); this.panel_zdispl.add(new JLabel("No objects.")); this.scroll_zdispl = makeScrollPane(panel_zdispl); this.scroll_zdispl.setPreferredSize(new Dimension(250, 300)); this.scroll_zdispl.setMinimumSize(new Dimension(250, 300)); this.tabs.add("Z space", scroll_zdispl); // Tab 4: channels this.panel_channels = new JPanel(); BoxLayout channels_layout = new BoxLayout(panel_channels, BoxLayout.Y_AXIS); this.panel_channels.setLayout(channels_layout); this.scroll_channels = makeScrollPane(panel_channels); this.scroll_channels.setPreferredSize(new Dimension(250, 300)); this.scroll_channels.setMinimumSize(new Dimension(250, 300)); this.channels = new Channel[4]; this.channels[0] = new Channel(this, Channel.MONO); this.channels[1] = new Channel(this, Channel.RED); this.channels[2] = new Channel(this, Channel.GREEN); this.channels[3] = new Channel(this, Channel.BLUE); //this.panel_channels.add(this.channels[0]); this.panel_channels.add(this.channels[1]); this.panel_channels.add(this.channels[2]); this.panel_channels.add(this.channels[3]); this.tabs.add("Opacity", scroll_channels); // Tab 5: labels this.panel_labels = new JPanel(); BoxLayout labels_layout = new BoxLayout(panel_labels, BoxLayout.Y_AXIS); this.panel_labels.setLayout(labels_layout); this.panel_labels.add(new JLabel("No labels.")); this.scroll_labels = makeScrollPane(panel_labels); this.scroll_labels.setPreferredSize(new Dimension(250, 300)); this.scroll_labels.setMinimumSize(new Dimension(250, 300)); this.tabs.add("Labels", scroll_labels); this.ht_tabs = new Hashtable<Class,JScrollPane>(); this.ht_tabs.put(Patch.class, scroll_patches); this.ht_tabs.put(Profile.class, scroll_profiles); this.ht_tabs.put(ZDisplayable.class, scroll_zdispl); this.ht_tabs.put(AreaList.class, scroll_zdispl); this.ht_tabs.put(Pipe.class, scroll_zdispl); this.ht_tabs.put(Polyline.class, scroll_zdispl); this.ht_tabs.put(Ball.class, scroll_zdispl); this.ht_tabs.put(Dissector.class, scroll_zdispl); this.ht_tabs.put(DLabel.class, scroll_labels); // channels not included // Navigator this.navigator = new DisplayNavigator(this, layer.getLayerWidth(), layer.getLayerHeight()); // Layer scroller (to scroll slices) int extent = (int)(250.0 / layer.getParent().size()); if (extent < 10) extent = 10; this.scroller = new JScrollBar(JScrollBar.HORIZONTAL); updateLayerScroller(layer); this.scroller.addAdjustmentListener(scroller_listener); // Left panel, contains the transp slider, the tabbed pane, the navigation panel and the layer scroller JPanel left = new JPanel(); BoxLayout left_layout = new BoxLayout(left, BoxLayout.Y_AXIS); left.setLayout(left_layout); left.add(transp_slider); left.add(tabs); left.add(navigator); left.add(scroller); // Canvas this.canvas = new DisplayCanvas(this, (int)Math.ceil(layer.getLayerWidth()), (int)Math.ceil(layer.getLayerHeight())); this.canvas_panel = new JPanel(); GridBagLayout gb = new GridBagLayout(); this.canvas_panel.setLayout(gb); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.NORTHWEST; gb.setConstraints(this.canvas_panel, c); gb.setConstraints(this.canvas, c); // prevent new Displays from screweing up if input is globally disabled if (!project.isInputEnabled()) this.canvas.setReceivesInput(false); this.canvas_panel.add(canvas); this.navigator.addMouseWheelListener(canvas); this.transp_slider.addKeyListener(canvas); // Split pane to contain everything this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, canvas_panel); this.split.setOneTouchExpandable(true); // NOT present in all L&F (?) // fix gb.setConstraints(split.getRightComponent(), c); // JFrame to show the split pane this.frame = ControlWindow.createJFrame(layer.toString()); if (IJ.isMacintosh() && IJ.getInstance()!=null) { IJ.wait(10); // may be needed for Java 1.4 on OS X this.frame.setMenuBar(ij.Menus.getMenuBar()); } this.frame.addWindowListener(window_listener); this.frame.addComponentListener(component_listener); this.frame.getContentPane().add(split); this.frame.addMouseListener(frame_mouse_listener); //doesn't exist//this.frame.setMinimumSize(new Dimension(270, 600)); if (null != props) { // restore canvas canvas.setup(mag, srcRect); // restore visibility of each channel int cs = ((Integer)props[5]).intValue(); // aka c_alphas_state int[] sel = new int[4]; sel[0] = ((cs&0xff000000)>>24); sel[1] = ((cs&0xff0000)>>16); sel[2] = ((cs&0xff00)>>8); sel[3] = (cs&0xff); // restore channel alphas this.c_alphas = ((Integer)props[4]).intValue(); channels[0].setAlpha( (float)((c_alphas&0xff000000)>>24) / 255.0f , 0 != sel[0]); channels[1].setAlpha( (float)((c_alphas&0xff0000)>>16) / 255.0f , 0 != sel[1]); channels[2].setAlpha( (float)((c_alphas&0xff00)>>8) / 255.0f , 0 != sel[2]); channels[3].setAlpha( (float) (c_alphas&0xff) / 255.0f , 0 != sel[3]); // restore visibility in the working c_alphas this.c_alphas = ((0 != sel[0] ? (int)(255 * channels[0].getAlpha()) : 0)<<24) + ((0 != sel[1] ? (int)(255 * channels[1].getAlpha()) : 0)<<16) + ((0 != sel[2] ? (int)(255 * channels[2].getAlpha()) : 0)<<8) + (0 != sel[3] ? (int)(255 * channels[3].getAlpha()) : 0); } if (null != active && null != layer) { Rectangle r = active.getBoundingBox(); r.x -= r.width/2; r.y -= r.height/2; r.width += r.width; r.height += r.height; if (r.x < 0) r.x = 0; if (r.y < 0) r.y = 0; if (r.width > layer.getLayerWidth()) r.width = (int)layer.getLayerWidth(); if (r.height> layer.getLayerHeight())r.height= (int)layer.getLayerHeight(); double magn = layer.getLayerWidth() / (double)r.width; canvas.setup(magn, r); } // add keyListener to the whole frame this.tabs.addKeyListener(canvas); this.canvas_panel.addKeyListener(canvas); this.frame.addKeyListener(canvas); this.frame.pack(); ij.gui.GUI.center(this.frame); this.frame.setVisible(true); ProjectToolbar.setProjectToolbar(); // doesn't get it through events final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); if (null != props) { // fix positioning outside the screen (dual to single monitor) if (p.x >= 0 && p.x < screen.width - 50 && p.y >= 0 && p.y <= screen.height - 50) this.frame.setLocation(p); else frame.setLocation(0, 0); } // fix excessive size final Rectangle box = this.frame.getBounds(); int x = box.x; int y = box.y; int width = box.width; int height = box.height; if (box.width > screen.width) { x = 0; width = screen.width; } if (box.height > screen.height) { y = 0; height = screen.height; } if (x != box.x || y != box.y) { this.frame.setLocation(x, y + (0 == y ? 30 : 0)); // added insets for bad window managers updateInDatabase("position"); } if (width != box.width || height != box.height) { this.frame.setSize(new Dimension(width -10, height -30)); // added insets for bad window managers } if (null == props) { // try to optimize canvas dimensions and magn double magn = layer.getLayerHeight() / screen.height; if (magn > 1.0) magn = 1.0; long size = 0; // limit magnification if appropriate for (Iterator it = layer.getDisplayables(Patch.class).iterator(); it.hasNext(); ) { final Patch pa = (Patch)it.next(); final Rectangle ba = pa.getBoundingBox(); size += (long)(ba.width * ba.height); } if (size > 10000000) canvas.setInitialMagnification(0.25); // 10 Mb else { this.frame.setSize(new Dimension((int)(screen.width * 0.66), (int)(screen.height * 0.66))); } } Utils.updateComponent(tabs); // otherwise fails in FreeBSD java 1.4.2 when reconstructing // Set the calibration of the FakeImagePlus to that of the LayerSet ((FakeImagePlus)canvas.getFakeImagePlus()).setCalibrationSuper(layer.getParent().getCalibrationCopy()); // Set the FakeImagePlus as the current image setTempCurrentImage(); // create a drag and drop listener dnd = new DNDInsertImage(this); // start a repainting thread if (null != props) { canvas.repaint(true); // repaint() is unreliable } // Set the minimum size of the tabbed pane on the left, so it can be completely collapsed now that it has been properly displayed. This is a patch to the lack of respect for the setDividerLocation method. SwingUtilities.invokeLater(new Runnable() { public void run() { tabs.setMinimumSize(new Dimension(0, 100)); } }); } private JScrollPane makeScrollPane(Component c) { JScrollPane jsp = new JScrollPane(c); // adjust scrolling to use one DisplayablePanel as the minimal unit jsp.getVerticalScrollBar().setBlockIncrement(DisplayablePanel.HEIGHT); // clicking within the track jsp.getVerticalScrollBar().setUnitIncrement(DisplayablePanel.HEIGHT); // clicking on an arrow return jsp; } public JPanel getCanvasPanel() { return canvas_panel; } public DisplayCanvas getCanvas() { return canvas; } public void setLayer(final Layer layer) { if (null == layer || layer == this.layer) return; final boolean set_zdispl = null == Display.this.layer || layer.getParent() != Display.this.layer.getParent(); if (selection.isTransforming()) { Utils.log("Can't browse layers while transforming.\nCANCEL the transform first with the ESCAPE key or right-click -> cancel."); scroller.setValue(Display.this.layer.getParent().getLayerIndex(Display.this.layer.getId())); return; } this.layer = layer; scroller.setValue(layer.getParent().getLayerIndex(layer.getId())); // update the current Layer pointer in ZDisplayable objects for (Iterator it = layer.getParent().getZDisplayables().iterator(); it.hasNext(); ) { ((ZDisplayable)it.next()).setLayer(layer); // the active layer } updateVisibleTab(set_zdispl); // see if a lot has to be reloaded, put the relevant ones at the end project.getLoader().prepare(layer); updateTitle(); // to show the new 'z' // select the Layer in the LayerTree project.select(Display.this.layer); // does so in a separate thread // update active Displayable: // deselect all except ZDisplayables final ArrayList sel = selection.getSelected(); final Displayable last_active = Display.this.active; int sel_next = -1; for (Iterator it = sel.iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); if (!(d instanceof ZDisplayable)) { it.remove(); selection.remove(d); if (d == last_active && sel.size() > 0) { // select the last one of the remaining, if any sel_next = sel.size()-1; } } } if (-1 != sel_next && sel.size() > 0) select((Displayable)sel.get(sel_next), true); else if (null != last_active && last_active.getClass() == Patch.class && null != last_temp && last_temp instanceof PatchStack) { Displayable d = ((PatchStack)last_temp).getPatch(layer, (Patch)last_active); if (null != d) selection.add(d); } // TODO last_temp doesn't remain the PatchStack // Utils.log2("last_temp is: " + last_temp.getClass().getName()); // Keep Profile chain selected, for best ease of use: if (null != last_active && last_active.getClass() == Profile.class && last_active.isLinked(Profile.class)) { Displayable other = null; for (final Displayable prof : last_active.getLinked(Profile.class)) { if (prof.getLayer() == layer) { other = prof; break; } } if (null != other) selection.add(other); } // repaint everything navigator.repaint(true); canvas.repaint(true); // repaint tabs (hard as hell) Utils.updateComponent(tabs); // @#$%^! The above works half the times, so explicit repaint as well: Component c = tabs.getSelectedComponent(); if (null == c) { c = scroll_patches; tabs.setSelectedComponent(scroll_patches); } Utils.updateComponent(c); project.getLoader().setMassiveMode(false); // resetting if it was set true // update the coloring in the ProjectTree project.getProjectTree().updateUILater(); setTempCurrentImage(); } static public void updateVisibleTabs() { for (final Display d : al_displays) { d.updateVisibleTab(true); } } /** Recreate the tab that is being shown. */ public void updateVisibleTab(boolean set_zdispl) { // update only the visible tab switch (tabs.getSelectedIndex()) { case 0: ht_panels.clear(); updateTab(panel_patches, "Patches", layer.getDisplayables(Patch.class)); break; case 1: ht_panels.clear(); updateTab(panel_profiles, "Profiles", layer.getDisplayables(Profile.class)); break; case 2: if (set_zdispl) { ht_panels.clear(); updateTab(panel_zdispl, "Z-space objects", layer.getParent().getZDisplayables()); } break; // case 3: channel opacities case 4: ht_panels.clear(); updateTab(panel_labels, "Labels", layer.getDisplayables(DLabel.class)); break; } } private void setLayerLater(final Layer layer, final Displayable active) { if (null == layer) return; this.layer = layer; if (!ControlWindow.isGUIEnabled()) return; SwingUtilities.invokeLater(new Runnable() { public void run() { // empty the tabs, except channels and pipes clearTab(panel_profiles, "Profiles"); clearTab(panel_patches, "Patches"); clearTab(panel_labels, "Labels"); // distribute Displayable to the tabs. Ignore LayerSet instances. if (null == ht_panels) ht_panels = new Hashtable<Displayable,DisplayablePanel>(); else ht_panels.clear(); Iterator it = layer.getDisplayables().iterator(); while (it.hasNext()) { add((Displayable)it.next(), false, false); } it = layer.getParent().getZDisplayables().iterator(); // the pipes, that live in the LayerSet while (it.hasNext()) { add((Displayable)it.next(), false, false); } navigator.repaint(true); // was not done when adding Utils.updateComponent(tabs.getSelectedComponent()); // setActive(active); }}); // swing issues: /* new Thread() { public void run() { setPriority(Thread.NORM_PRIORITY); try { Thread.sleep(1000); } catch (Exception e) {} setActive(active); } }.start(); */ } /** Remove all components from the tab and add a "No [label]" label to each. */ private void clearTab(final Container c, final String label) { c.removeAll(); c.add(new JLabel("No " + label + ".")); // magic cocktail: if (tabs.getSelectedComponent() == c) { Utils.updateComponent(c); } } /** A class to listen to the transparency_slider of the DisplayablesSelectorWindow. */ private class TransparencySliderListener extends MouseAdapter implements ChangeListener { public void stateChanged(ChangeEvent ce) { //change the transparency value of the current active displayable float new_value = (float)((JSlider)ce.getSource()).getValue(); setTransparency(new_value / 100.0f); } public void mousePressed(MouseEvent me) { JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (scroll != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"}); } public void mouseReleased(MouseEvent me) { // update navigator window navigator.repaint(true); JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (scroll != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"}); } } /** Context-sensitive: to a Displayable, or to a channel. */ private void setTransparency(final float value) { JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (scroll == scroll_channels) { for (int i=0; i<4; i++) { if (channels[i].getBackground() == Color.cyan) { channels[i].setAlpha(value); // will call back and repaint the Display return; } } } else if (null != active) { if (value != active.getAlpha()) { // because there's a callback from setActive that would then affect all other selected Displayable without having dragged the slider, i.e. just by being selected. canvas.invalidateVolatile(); selection.setAlpha(value); } } } public void setTransparencySlider(final float transp) { if (transp >= 0.0f && transp <= 1.0f) { // fire event transp_slider.setValue((int)(transp * 100)); } } /** Mark the canvas for updating the offscreen images if the given Displayable is NOT the active. */ // Used by the Displayable.setVisible for example. static public void setUpdateGraphics(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer && null != d.active && d.active != displ) { d.canvas.setUpdateGraphics(true); } } } /** Flag the DisplayCanvas of Displays showing the given Layer to update their offscreen images.*/ static public void setUpdateGraphics(final Layer layer, final boolean update) { for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update); } } } /** Whether to update the offscreen images or not. */ public void setUpdateGraphics(boolean b) { canvas.setUpdateGraphics(b); } /** Find all Display instances that contain the layer and repaint them, in the Swing GUI thread. */ static public void update(final Layer layer) { if (null == layer) return; SwingUtilities.invokeLater(new Runnable() { public void run() { for (final Display d : al_displays) { if (d.isShowing(layer)) { d.repaintAll(); } } }}); } static public void update(final LayerSet set) { update(set, true); } /** Find all Display instances showing a Layer of this LayerSet, and update the dimensions of the navigator and canvas and snapshots, and repaint, in the Swing GUI thread. */ static public void update(final LayerSet set, final boolean update_canvas_dimensions) { if (null == set) return; SwingUtilities.invokeLater(new Runnable() { public void run() { for (final Display d : al_displays) { if (set.contains(d.layer)) { d.updateSnapshots(); if (update_canvas_dimensions) d.canvas.setDimensions(set.getLayerWidth(), set.getLayerHeight()); d.repaintAll(); } } }}); } /** Release all resources held by this Display and close the frame. */ protected void destroy() { dispatcher.quit(); canvas.setReceivesInput(false); slt.quit(); // update the coloring in the ProjectTree and LayerTree if (!project.isBeingDestroyed()) { try { project.getProjectTree().updateUILater(); project.getLayerTree().updateUILater(); } catch (Exception e) { Utils.log2("updateUI failed at Display.destroy()"); } } frame.removeComponentListener(component_listener); frame.removeWindowListener(window_listener); frame.removeWindowFocusListener(window_listener); frame.removeWindowStateListener(window_listener); frame.removeKeyListener(canvas); frame.removeMouseListener(frame_mouse_listener); canvas_panel.removeKeyListener(canvas); canvas.removeKeyListener(canvas); tabs.removeChangeListener(tabs_listener); tabs.removeKeyListener(canvas); ImagePlus.removeImageListener(this); bytypelistener = null; canvas.destroy(); navigator.destroy(); scroller.removeAdjustmentListener(scroller_listener); frame.setVisible(false); //no need, and throws exception//frame.dispose(); active = null; if (null != selection) selection.clear(); //Utils.log2("destroying selection"); // below, need for SetLayerThread threads to quit slt.quit(); // set a new front if any if (null == front && al_displays.size() > 0) { front = (Display)al_displays.get(al_displays.size() -1); } // repaint layer tree (to update the label color) try { project.getLayerTree().updateUILater(); // works only after setting the front above } catch (Exception e) {} // ignore swing sync bullshit when closing everything too fast // remove the drag and drop listener dnd.destroy(); } /** Find all Display instances that contain a Layer of the given project and close them without removing the Display entries from the database. */ static synchronized public void close(final Project project) { /* // concurrent modifications if more than 1 Display are being removed asynchronously for (final Display d : al_displays) { if (d.getLayer().getProject().equals(project)) { it.remove(); d.destroy(); } } */ Display[] d = new Display[al_displays.size()]; al_displays.toArray(d); for (int i=0; i<d.length; i++) { if (d[i].getProject() == project) { al_displays.remove(d[i]); d[i].destroy(); } } } /** Find all Display instances that contain the layer and close them and remove the Display from the database. */ static public void close(final Layer layer) { for (Iterator it = al_displays.iterator(); it.hasNext(); ) { Display d = (Display)it.next(); if (d.isShowing(layer)) { d.remove(false); it.remove(); } } } public boolean remove(boolean check) { if (check) { if (!Utils.check("Delete the Display ?")) return false; } // flush the offscreen images and close the frame destroy(); removeFromDatabase(); return true; } public Layer getLayer() { return layer; } public LayerSet getLayerSet() { return layer.getParent(); } public boolean isShowing(final Layer layer) { return this.layer == layer; } public DisplayNavigator getNavigator() { return navigator; } /** Repaint both the canvas and the navigator, updating the graphics, and the title and tabs. */ public void repaintAll() { if (repaint_disabled) return; navigator.repaint(true); canvas.repaint(true); Utils.updateComponent(tabs); updateTitle(); } /** Repaint the canvas updating graphics, the navigator without updating graphics, and the title. */ public void repaintAll2() { if (repaint_disabled) return; navigator.repaint(false); canvas.repaint(true); updateTitle(); } static public void repaintSnapshots(final LayerSet set) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.getLayer().getParent() == set) { d.navigator.repaint(true); Utils.updateComponent(d.tabs); } } } static public void repaintSnapshots(final Layer layer) { if (repaint_disabled) return; for (final Display d : al_displays) { if (d.getLayer() == layer) { d.navigator.repaint(true); Utils.updateComponent(d.tabs); } } } public void pack() { dispatcher.exec(new Runnable() { public void run() { try { Thread.currentThread().sleep(100); SwingUtilities.invokeAndWait(new Runnable() { public void run() { frame.pack(); }}); } catch (Exception e) { IJError.print(e); } }}); } static public void pack(final LayerSet ls) { for (final Display d : al_displays) { if (d.layer.getParent() == ls) d.pack(); } } private void adjustCanvas() { SwingUtilities.invokeLater(new Runnable() { public void run() { Rectangle r = split.getRightComponent().getBounds(); canvas.setDrawingSize(r.width, r.height, true); // fix not-on-top-left problem canvas.setLocation(0, 0); //frame.pack(); // don't! Would go into an infinite loop canvas.repaint(true); updateInDatabase("srcRect"); }}); } /** Grab the last selected display (or create an new one if none) and show in it the layer,centered on the Displayable object. */ static public void setFront(final Layer layer, final Displayable displ) { if (null == front) { Display display = new Display(layer.getProject(), layer); // gets set to front display.showCentered(displ); } else if (layer == front.layer) { front.showCentered(displ); } else { // find one: for (final Display d : al_displays) { if (d.layer == layer) { d.frame.toFront(); d.showCentered(displ); return; } } // else, open new one new Display(layer.getProject(), layer).showCentered(displ); } } /** Find the displays that show the given Layer, and add the given Displayable to the GUI and sets it active only in the front Display and only if 'activate' is true. */ static public void add(final Layer layer, final Displayable displ, final boolean activate) { for (final Display d : al_displays) { if (d.layer == layer) { if (front == d) { d.add(displ, activate, true); //front.frame.toFront(); } else { d.add(displ, false, true); } } } } static public void add(final Layer layer, final Displayable displ) { add(layer, displ, true); } /** Add the ZDisplayable to all Displays that show a Layer belonging to the given LayerSet. */ static public void add(final LayerSet set, final ZDisplayable zdispl) { for (final Display d : al_displays) { if (set.contains(d.layer)) { if (front == d) { zdispl.setLayer(d.layer); // the active one d.add(zdispl, true, true); // calling add(Displayable, boolean, boolean) //front.frame.toFront(); } else { d.add(zdispl, false, true); } } } } // TODO this very old method could take some improvement: // - there is no need to create a new DisplayablePanel if its panel is not shown // - other issues; the method looks overly "if a dog barks and a duck quacks during a lunar eclipse then .." /** Add it to the proper panel, at the top, and set it active. */ private final void add(final Displayable d, final boolean activate, final boolean repaint_snapshot) { DisplayablePanel dp = ht_panels.get(d); if (null != dp && activate) { // for ZDisplayable objects (TODO I think this is not used anymore) dp.setActive(true); //setActive(d); selection.clear(); selection.add(d); return; } // add to the proper list JPanel p = null; if (d instanceof Profile) { p = panel_profiles; } else if (d instanceof Patch) { p = panel_patches; } else if (d instanceof DLabel) { p = panel_labels; } else if (d instanceof ZDisplayable) { //both pipes and balls and AreaList p = panel_zdispl; } else { // LayerSet objects return; } dp = new DisplayablePanel(this, d); // TODO: instead of destroying/recreating, we could just recycle them by reassigning a different Displayable. See how it goes! It'd need a pool of objects addToPanel(p, 0, dp, activate); ht_panels.put(d, dp); if (activate) { dp.setActive(true); //setActive(d); selection.clear(); selection.add(d); } if (repaint_snapshot) navigator.repaint(true); } private void addToPanel(JPanel panel, int index, DisplayablePanel dp, boolean repaint) { // remove the label if (1 == panel.getComponentCount() && panel.getComponent(0) instanceof JLabel) { panel.removeAll(); } panel.add(dp, index); if (repaint) { Utils.updateComponent(tabs); } } /** Find the displays that show the given Layer, and remove the given Displayable from the GUI. */ static public void remove(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer) d.remove(displ); } } private void remove(final Displayable displ) { DisplayablePanel ob = ht_panels.remove(displ); if (null != ob) { final JScrollPane jsp = ht_tabs.get(displ.getClass()); if (null != jsp) { JPanel p = (JPanel)jsp.getViewport().getView(); p.remove((Component)ob); Utils.revalidateComponent(p); } } if (null == active || !selection.contains(displ)) { canvas.setUpdateGraphics(true); } canvas.invalidateVolatile(); // removing active, no need to update offscreen but yes the volatile repaint(displ, null, 5, true, false); // from Selection.deleteAll this method is called ... but it's ok: same thread, no locking problems. selection.remove(displ); } static public void remove(final ZDisplayable zdispl) { for (final Display d : al_displays) { if (zdispl.getLayerSet() == d.layer.getParent()) { d.remove((Displayable)zdispl); } } } static public void repaint(final Layer layer, final Displayable displ, final int extra) { repaint(layer, displ, displ.getBoundingBox(), extra); } static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra) { repaint(layer, displ, r, extra, true); } /** Find the displays that show the given Layer, and repaint the given Displayable. */ static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.repaint(displ, r, extra, repaint_navigator, false); } } } static public void repaint(final Displayable d) { if (d instanceof ZDisplayable) repaint(d.getLayerSet(), d, d.getBoundingBox(null), 5, true); repaint(d.getLayer(), d, d.getBoundingBox(null), 5, true); } /** Repaint as much as the bounding box around the given Displayable, or the r if not null. */ private void repaint(final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator, final boolean update_graphics) { if (repaint_disabled || null == displ) return; if (update_graphics || displ.getClass() == Patch.class || displ != active) { canvas.setUpdateGraphics(true); } if (null != r) canvas.repaint(r, extra); else canvas.repaint(displ, extra); if (repaint_navigator) { DisplayablePanel dp = ht_panels.get(displ); if (null != dp) dp.repaint(); // is null when creating it, or after deleting it navigator.repaint(true); // everything } } /** Repaint the snapshot for the given Displayable both at the DisplayNavigator and on its panel,and only if it has not been painted before. This method is intended for the loader to know when to paint a snap, to avoid overhead. */ static public void repaintSnapshot(final Displayable displ) { for (final Display d : al_displays) { if (d.layer.contains(displ)) { if (!d.navigator.isPainted(displ)) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); // is null when creating it, or after deleting it d.navigator.repaint(displ); } } } } /** Repaint the given Rectangle in all Displays showing the layer, updating the offscreen image if any. */ static public void repaint(final Layer layer, final Rectangle r, final int extra) { repaint(layer, extra, r, true, true); } static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator) { repaint(layer, extra, r, update_navigator, true); } static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator, final boolean update_graphics) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update_graphics); d.canvas.repaint(r, extra); if (update_navigator) { d.navigator.repaint(true); Utils.updateComponent(d.tabs.getSelectedComponent()); } } } } /** Repaint the given Rectangle in all Displays showing the layer, optionally updating the offscreen image (if any). */ static public void repaint(final Layer layer, final Rectangle r, final int extra, final boolean update_graphics) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.canvas.setUpdateGraphics(update_graphics); d.canvas.repaint(r, extra); d.navigator.repaint(update_graphics); if (update_graphics) Utils.updateComponent(d.tabs.getSelectedComponent()); } } } /** Repaint the DisplayablePanel (and DisplayNavigator) only for the given Displayable, in all Displays showing the given Layer. */ static public void repaint(final Layer layer, final Displayable displ) { if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); d.navigator.repaint(true); } } } static public void repaint(LayerSet set, Displayable displ, int extra) { repaint(set, displ, null, extra); } static public void repaint(LayerSet set, Displayable displ, Rectangle r, int extra) { repaint(set, displ, r, extra, true); } /** Repaint the Displayable in every Display that shows a Layer belonging to the given LayerSet. */ static public void repaint(final LayerSet set, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) { if (repaint_disabled) return; for (final Display d : al_displays) { if (set.contains(d.layer)) { if (repaint_navigator) { if (null != displ) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.repaint(); } d.navigator.repaint(true); } if (null == displ || displ != d.active) d.setUpdateGraphics(true); // safeguard // paint the given box or the actual Displayable's box if (null != r) d.canvas.repaint(r, extra); else d.canvas.repaint(displ, extra); } } } /** Repaint the entire LayerSet, in all Displays showing a Layer of it.*/ static public void repaint(final LayerSet set) { if (repaint_disabled) return; for (final Display d : al_displays) { if (set.contains(d.layer)) { d.navigator.repaint(true); d.canvas.repaint(true); } } } /** Repaint the given box in the LayerSet, in all Displays showing a Layer of it.*/ static public void repaint(final LayerSet set, final Rectangle box) { if (repaint_disabled) return; for (final Display d : al_displays) { if (set.contains(d.layer)) { d.navigator.repaint(box); d.canvas.repaint(box, 0, true); } } } /** Repaint the entire Layer, in all Displays showing it, including the tabs.*/ static public void repaint(final Layer layer) { // TODO this method overlaps with update(layer) if (repaint_disabled) return; for (final Display d : al_displays) { if (layer == d.layer) { d.navigator.repaint(true); d.canvas.repaint(true); } } } /** Call repaint on all open Displays. */ static public void repaint() { if (repaint_disabled) { Utils.logAll("Can't repaint -- repainting is disabled!"); return; } for (final Display d : al_displays) { d.navigator.repaint(true); d.canvas.repaint(true); } } static private boolean repaint_disabled = false; /** Set a flag to enable/disable repainting of all Display instances. */ static protected void setRepaint(boolean b) { repaint_disabled = !b; } public Rectangle getBounds() { return frame.getBounds(); } public Point getLocation() { return frame.getLocation(); } public JFrame getFrame() { return frame; } public void setLocation(Point p) { this.frame.setLocation(p); } public Displayable getActive() { return active; //TODO this should return selection.active !! } public void select(Displayable d) { select(d, false); } /** Select/deselect accordingly to the current state and the shift key. */ public void select(final Displayable d, final boolean shift_down) { if (null != active && active != d && active.getClass() != Patch.class) { // active is being deselected, so link underlying patches active.linkPatches(); } if (null == d) { //Utils.log2("Display.select: clearing selection"); canvas.setUpdateGraphics(true); selection.clear(); return; } if (!shift_down) { //Utils.log2("Display.select: single selection"); if (d != active) { selection.clear(); selection.add(d); } } else if (selection.contains(d)) { if (active == d) { selection.remove(d); //Utils.log2("Display.select: removing from a selection"); } else { //Utils.log2("Display.select: activing within a selection"); selection.setActive(d); } } else { //Utils.log2("Display.select: adding to an existing selection"); selection.add(d); } // update the image shown to ImageJ // NO longer necessary, always he same FakeImagePlus // setTempCurrentImage(); } protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, final Class c) { choose(screen_x_p, screen_y_p, x_p, y_p, false, c); } protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p) { choose(screen_x_p, screen_y_p, x_p, y_p, false, null); } /** Find a Displayable to add to the selection under the given point (which is in offscreen coords); will use a popup menu to give the user a range of Displayable objects to select from. */ protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, boolean shift_down, Class c) { //Utils.log("Display.choose: x,y " + x_p + "," + y_p); final ArrayList<Displayable> al = new ArrayList<Displayable>(layer.find(x_p, y_p, true)); al.addAll(layer.getParent().findZDisplayables(layer, x_p, y_p, true)); // only visible ones if (al.isEmpty()) { Displayable act = this.active; selection.clear(); canvas.setUpdateGraphics(true); //Utils.log("choose: set active to null"); // fixing lack of repainting for unknown reasons, of the active one TODO this is a temporary solution if (null != act) Display.repaint(layer, act, 5); } else if (1 == al.size()) { Displayable d = (Displayable)al.get(0); if (null != c && d.getClass() != c) { selection.clear(); return; } select(d, shift_down); //Utils.log("choose 1: set active to " + active); } else { if (al.contains(active) && !shift_down) { // do nothing } else { if (null != c) { // check if at least one of them is of class c // if only one is of class c, set as selected // else show menu for (Iterator it = al.iterator(); it.hasNext(); ) { Object ob = it.next(); if (ob.getClass() != c) it.remove(); } if (0 == al.size()) { // deselect selection.clear(); return; } if (1 == al.size()) { select((Displayable)al.get(0), shift_down); return; } // else, choose among the many } choose(screen_x_p, screen_y_p, al, shift_down, x_p, y_p); } //Utils.log("choose many: set active to " + active); } } private void choose(final int screen_x_p, final int screen_y_p, final Collection al, final boolean shift_down, final int x_p, final int y_p) { // show a popup on the canvas to choose new Thread() { public void run() { final Object lock = new Object(); final DisplayableChooser d_chooser = new DisplayableChooser(al, lock); final JPopupMenu pop = new JPopupMenu("Select:"); final Iterator itu = al.iterator(); while (itu.hasNext()) { Displayable d = (Displayable)itu.next(); JMenuItem menu_item = new JMenuItem(d.toString()); menu_item.addActionListener(d_chooser); pop.add(menu_item); } new Thread() { public void run() { pop.show(canvas, screen_x_p, screen_y_p); } }.start(); //now wait until selecting something synchronized(lock) { do { try { lock.wait(); } catch (InterruptedException ie) {} } while (d_chooser.isWaiting() && pop.isShowing()); } //grab the chosen Displayable object Displayable d = d_chooser.getChosen(); //Utils.log("Chosen: " + d.toString()); if (null == d) { Utils.log2("Display.choose: returning a null!"); } select(d, shift_down); pop.setVisible(false); // fix selection bug: never receives mouseReleased event when the popup shows selection.mouseReleased(null, x_p, y_p, x_p, y_p, x_p, y_p); } }.start(); } /** Used by the Selection exclusively. This method will change a lot in the near future, and may disappear in favor of getSelection().getActive(). All this method does is update GUI components related to the currently active and the newly active Displayable; called through SwingUtilities.invokeLater. */ protected void setActive(final Displayable displ) { final Displayable prev_active = this.active; this.active = displ; SwingUtilities.invokeLater(new Runnable() { public void run() { // renew current image if necessary if (null != displ && displ == prev_active) { // make sure the proper tab is selected. selectTab(displ); return; // the same } // deactivate previously active if (null != prev_active) { final DisplayablePanel ob = ht_panels.get(prev_active); if (null != ob) ob.setActive(false); // erase "decorations" of the previously active canvas.repaint(selection.getBox(), 4); } // activate the new active if (null != displ) { final DisplayablePanel ob = ht_panels.get(displ); if (null != ob) ob.setActive(true); updateInDatabase("active_displayable_id"); if (displ.getClass() != Patch.class) project.select(displ); // select the node in the corresponding tree, if any. // select the proper tab, and scroll to visible selectTab(displ); boolean update_graphics = null == prev_active || paintsBelow(prev_active, displ); // or if it's an image, but that's by default in the repaint method repaint(displ, null, 5, false, update_graphics); // to show the border, and to repaint out of the background image transp_slider.setValue((int)(displ.getAlpha() * 100)); } else { //ensure decorations are removed from the panels, for Displayables in a selection besides the active one Utils.updateComponent(tabs.getSelectedComponent()); } }}); } /** If the other paints under the base. */ public boolean paintsBelow(Displayable base, Displayable other) { boolean zd_base = base instanceof ZDisplayable; boolean zd_other = other instanceof ZDisplayable; if (zd_other) { if (base instanceof DLabel) return true; // zd paints under label if (!zd_base) return false; // any zd paints over a mere displ if not a label else { // both zd, compare indices ArrayList<ZDisplayable> al = other.getLayerSet().getZDisplayables(); return al.indexOf(base) > al.indexOf(other); } } else { if (!zd_base) { // both displ, compare indices ArrayList<Displayable> al = other.getLayer().getDisplayables(); return al.indexOf(base) > al.indexOf(other); } else { // base is zd, other is d if (other instanceof DLabel) return false; return true; } } } /** Select the proper tab, and also scroll it to show the given Displayable -unless it's a LayerSet, and unless the proper tab is already showing. */ private void selectTab(final Displayable displ) { Method method = null; try { if (!(displ instanceof LayerSet)) { method = Display.class.getDeclaredMethod("selectTab", new Class[]{displ.getClass()}); } } catch (Exception e) { IJError.print(e); } if (null != method) { final Method me = method; dispatcher.exec(new Runnable() { public void run() { try { me.setAccessible(true); me.invoke(Display.this, new Object[]{displ}); } catch (Exception e) { IJError.print(e); } }}); } } private void selectTab(Patch patch) { tabs.setSelectedComponent(scroll_patches); scrollToShow(scroll_patches, ht_panels.get(patch)); } private void selectTab(Profile profile) { tabs.setSelectedComponent(scroll_profiles); scrollToShow(scroll_profiles, ht_panels.get(profile)); } private void selectTab(DLabel label) { tabs.setSelectedComponent(scroll_labels); scrollToShow(scroll_labels, ht_panels.get(label)); } private void selectTab(ZDisplayable zd) { tabs.setSelectedComponent(scroll_zdispl); scrollToShow(scroll_zdispl, ht_panels.get(zd)); } private void selectTab(Pipe d) { selectTab((ZDisplayable)d); } private void selectTab(Polyline d) { selectTab((ZDisplayable)d); } private void selectTab(AreaList d) { selectTab((ZDisplayable)d); } private void selectTab(Ball d) { selectTab((ZDisplayable)d); } private void selectTab(Dissector d) { selectTab((ZDisplayable)d); } /** A method to update the given tab, creating a new DisplayablePanel for each Displayable present in the given ArrayList, and storing it in the ht_panels (which is cleared first). */ private void updateTab(final Container tab, final String label, final ArrayList al) { final boolean[] recreated = new boolean[]{false, true, true}; dispatcher.execSwing(new Runnable() { public void run() { try { if (0 == al.size()) { tab.removeAll(); tab.add(new JLabel("No " + label + ".")); } else { Component[] comp = tab.getComponents(); int next = 0; if (1 == comp.length && comp[0].getClass() == JLabel.class) { next = 1; tab.remove(0); } for (Iterator it = al.iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); DisplayablePanel dp = null; if (next < comp.length) { dp = (DisplayablePanel)comp[next++]; // recycling panels dp.set(d); } else { dp = new DisplayablePanel(Display.this, d); tab.add(dp); } ht_panels.put(d, dp); } if (next < comp.length) { // remove from the end, to avoid potential repaints of other panels for (int i=comp.length-1; i>=next; i--) { tab.remove(i); } } recreated[0] = true; } if (recreated[0]) { tab.invalidate(); tab.validate(); tab.repaint(); } if (null != Display.this.active) scrollToShow(Display.this.active); } catch (Throwable e) { IJError.print(e); } }}); } static public void setActive(final Object event, final Displayable displ) { if (!(event instanceof InputEvent)) return; // find which Display for (final Display d : al_displays) { if (d.isOrigin((InputEvent)event)) { d.setActive(displ); break; } } } /** Find out whether this Display is Transforming its active Displayable. */ public boolean isTransforming() { return canvas.isTransforming(); } /** Find whether any Display is transforming the given Displayable. */ static public boolean isTransforming(final Displayable displ) { for (final Display d : al_displays) { if (null != d.active && d.active == displ && d.canvas.isTransforming()) return true; } return false; } static public boolean isAligning(final LayerSet set) { for (final Display d : al_displays) { if (d.layer.getParent() == set && set.isAligning()) { return true; } } return false; } /** Set the front Display to transform the Displayable only if no other canvas is transforming it. */ static public void setTransforming(final Displayable displ) { if (null == front) return; if (front.active != displ) return; for (final Display d : al_displays) { if (d.active == displ) { if (d.canvas.isTransforming()) { Utils.showMessage("Already transforming " + displ.getTitle()); return; } } } front.canvas.setTransforming(true); } /** Check whether the source of the event is located in this instance.*/ private boolean isOrigin(InputEvent event) { Object source = event.getSource(); // find it ... check the canvas for now TODO if (canvas == source) { return true; } return false; } /** Get the layer of the front Display, or null if none.*/ static public Layer getFrontLayer() { if (null == front) return null; return front.layer; } /** Get the layer of an open Display of the given Project, or null if none.*/ static public Layer getFrontLayer(final Project project) { if (null == front) return null; if (front.project == project) return front.layer; // else, find an open Display for the given Project, if any for (final Display d : al_displays) { if (d.project == project) { d.frame.toFront(); return d.layer; } } return null; // none found } static public Display getFront(final Project project) { if (null == front) return null; if (front.project == project) return front; for (final Display d : al_displays) { if (d.project == project) { d.frame.toFront(); return d; } } return null; } public boolean isReadOnly() { // TEMPORARY: in the future one will be able show displays as read-only to other people, remotely return false; } static public void showPopup(Component c, int x, int y) { if (null != front) front.getPopupMenu().show(c, x, y); } /** Return a context-sensitive popup menu. */ public JPopupMenu getPopupMenu() { // called from canvas // get the job canceling dialog if (!canvas.isInputEnabled()) { return project.getLoader().getJobsPopup(this); } // create new this.popup = new JPopupMenu(); JMenuItem item = null; JMenu menu = null; if (ProjectToolbar.ALIGN == Toolbar.getToolId()) { boolean aligning = layer.getParent().isAligning(); item = new JMenuItem("Cancel alignment"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); if (!aligning) item.setEnabled(false); item = new JMenuItem("Align with landmarks"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true)); if (!aligning) item.setEnabled(false); item = new JMenuItem("Align and register"); item.addActionListener(this); popup.add(item); if (!aligning) item.setEnabled(false); item = new JMenuItem("Align using profiles"); item.addActionListener(this); popup.add(item); if (!aligning || selection.isEmpty() || !selection.contains(Profile.class)) item.setEnabled(false); item = new JMenuItem("Align stack slices"); item.addActionListener(this); popup.add(item); if (selection.isEmpty() || ! (getActive().getClass() == Patch.class && ((Patch)getActive()).isStack())) item.setEnabled(false); item = new JMenuItem("Align layers (layer-wise)"); item.addActionListener(this); popup.add(item); if (1 == layer.getParent().size()) item.setEnabled(false); item = new JMenuItem("Align layers (tile-wise global minimization)"); item.addActionListener(this); popup.add(item); if (1 == layer.getParent().size()) item.setEnabled(false); return popup; } JMenu adjust_menu = new JMenu("Adjust"); if (null != active) { if (!canvas.isTransforming()) { if (active instanceof Profile) { item = new JMenuItem("Duplicate, link and send to next layer"); item.addActionListener(this); popup.add(item); Layer nl = layer.getParent().next(layer); if (nl == layer) item.setEnabled(false); item = new JMenuItem("Duplicate, link and send to previous layer"); item.addActionListener(this); popup.add(item); nl = layer.getParent().previous(layer); if (nl == layer) item.setEnabled(false); menu = new JMenu("Duplicate, link and send to"); ArrayList al = layer.getParent().getLayers(); Iterator it = al.iterator(); int i = 1; while (it.hasNext()) { Layer la = (Layer)it.next(); item = new JMenuItem(i + ": z = " + la.getZ()); item.addActionListener(this); menu.add(item); // TODO should label which layers contain Profile instances linked to the one being duplicated if (la == this.layer) item.setEnabled(false); i++; } popup.add(menu); item = new JMenuItem("Duplicate, link and send to..."); item.addActionListener(this); popup.add(item); popup.addSeparator(); item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item); if (!active.isLinked()) item.setEnabled(false); // isLinked() checks if it's linked to a Patch in its own layer item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } else if (active instanceof Patch) { item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item); if (!active.isLinked(Patch.class)) item.setEnabled(false); if (((Patch)active).isStack()) { item = new JMenuItem("Unlink slices"); item.addActionListener(this); popup.add(item); } int n_sel_patches = selection.getSelected(Patch.class).size(); if (1 == n_sel_patches) { item = new JMenuItem("Snap"); item.addActionListener(this); popup.add(item); } else if (n_sel_patches > 1) { item = new JMenuItem("Montage"); item.addActionListener(this); popup.add(item); } item = new JMenuItem("Link images..."); item.addActionListener(this); popup.add(item); item = new JMenuItem("View volume"); item.addActionListener(this); popup.add(item); HashSet hs = active.getLinked(Patch.class); if (null == hs || 0 == hs.size()) item.setEnabled(false); item = new JMenuItem("View orthoslices"); item.addActionListener(this); popup.add(item); if (null == hs || 0 == hs.size()) item.setEnabled(false); // if no Patch instances among the directly linked, then it's not a stack popup.addSeparator(); } else { item = new JMenuItem("Unlink"); item.addActionListener(this); popup.add(item); item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } if (active instanceof AreaList) { item = new JMenuItem("Merge"); item.addActionListener(this); popup.add(item); ArrayList al = selection.getSelected(); int n = 0; for (Iterator it = al.iterator(); it.hasNext(); ) { if (it.next().getClass() == AreaList.class) n++; } if (n < 2) item.setEnabled(false); } else if (active instanceof Pipe) { item = new JMenuItem("Identify..."); item.addActionListener(this); popup.add(item); item = new JMenuItem("Identify with axes..."); item.addActionListener(this); popup.add(item); } } if (canvas.isTransforming()) { item = new JMenuItem("Apply transform"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true)); // dummy, for I don't add a MenuKeyListener, but "works" through the normal key listener. It's here to provide a visual cue } else { item = new JMenuItem("Transform"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0, true)); } item = new JMenuItem("Cancel transform"); item.addActionListener(this); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); if (!canvas.isTransforming()) item.setEnabled(false); if (canvas.isTransforming()) { item = new JMenuItem("Specify transform..."); item.addActionListener(this); popup.add(item); } if (!canvas.isTransforming()) { item = new JMenuItem("Color..."); item.addActionListener(this); popup.add(item); if (active instanceof LayerSet) item.setEnabled(false); if (active.isLocked()) { item = new JMenuItem("Unlock"); item.addActionListener(this); popup.add(item); } else { item = new JMenuItem("Lock"); item.addActionListener(this); popup.add(item); } menu = new JMenu("Move"); popup.addSeparator(); LayerSet ls = layer.getParent(); item = new JMenuItem("Move to top"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0, true)); // this is just to draw the key name by the menu; it does not incur on any event being generated (that I know if), and certainly not any event being listened to by TrakEM2. if (ls.isTop(active)) item.setEnabled(false); item = new JMenuItem("Move up"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0, true)); if (ls.isTop(active)) item.setEnabled(false); item = new JMenuItem("Move down"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0, true)); if (ls.isBottom(active)) item.setEnabled(false); item = new JMenuItem("Move to bottom"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0, true)); if (ls.isBottom(active)) item.setEnabled(false); popup.add(menu); popup.addSeparator(); item = new JMenuItem("Delete..."); item.addActionListener(this); popup.add(item); try { if (active instanceof Patch) { if (!active.isOnlyLinkedTo(Patch.class)) { item.setEnabled(false); } } else if (!(active instanceof DLabel)) { // can't delete elements from the trees (Profile, Pipe, LayerSet) item.setEnabled(false); } } catch (Exception e) { IJError.print(e); item.setEnabled(false); } if (active instanceof Patch) { item = new JMenuItem("Revert"); item.addActionListener(this); popup.add(item); popup.addSeparator(); } item = new JMenuItem("Properties..."); item.addActionListener(this); popup.add(item); item = new JMenuItem("Show centered"); item.addActionListener(this); popup.add(item); popup.addSeparator(); if (! (active instanceof ZDisplayable)) { ArrayList al_layers = layer.getParent().getLayers(); int i_layer = al_layers.indexOf(layer); int n_layers = al_layers.size(); item = new JMenuItem("Send to previous layer"); item.addActionListener(this); popup.add(item); if (1 == n_layers || 0 == i_layer || active.isLinked()) item.setEnabled(false); // check if the active is a profile and contains a link to another profile in the layer it is going to be sent to, or it is linked else if (active instanceof Profile && !active.canSendTo(layer.getParent().previous(layer))) item.setEnabled(false); item = new JMenuItem("Send to next layer"); item.addActionListener(this); popup.add(item); if (1 == n_layers || n_layers -1 == i_layer || active.isLinked()) item.setEnabled(false); else if (active instanceof Profile && !active.canSendTo(layer.getParent().next(layer))) item.setEnabled(false); menu = new JMenu("Send linked group to..."); if (active.hasLinkedGroupWithinLayer(this.layer)) { int i = 1; for (final Layer la : ls.getLayers()) { String layer_title = i + ": " + la.getTitle(); if (-1 == layer_title.indexOf(' ')) layer_title += " "; item = new JMenuItem(layer_title); item.addActionListener(this); menu.add(item); if (la == this.layer) item.setEnabled(false); i++; } popup.add(menu); } else { menu.setEnabled(false); //Utils.log("Active's linked group not within layer."); } popup.add(menu); popup.addSeparator(); } } } if (!canvas.isTransforming()) { item = new JMenuItem("Undo");item.addActionListener(this); popup.add(item); if (!layer.getParent().canUndo() || canvas.isTransforming()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Utils.getControlModifier(), true)); item = new JMenuItem("Redo");item.addActionListener(this); popup.add(item); if (!layer.getParent().canRedo() || canvas.isTransforming()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.ALT_MASK, true)); item = new JMenuItem("Enhance contrast layer-wise..."); item.addActionListener(this); adjust_menu.add(item); item = new JMenuItem("Enhance contrast (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); item = new JMenuItem("Set Min and Max layer-wise..."); item.addActionListener(this); adjust_menu.add(item); item = new JMenuItem("Set Min and Max (selected images)..."); item.addActionListener(this); adjust_menu.add(item); if (selection.isEmpty()) item.setEnabled(false); popup.add(adjust_menu); popup.addSeparator(); // Would get so much simpler with a clojure macro ... try { menu = new JMenu("Hide/Unhide"); item = new JMenuItem("Hide deselected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK, true)); boolean none = 0 == selection.getNSelected(); if (none) item.setEnabled(false); item = new JMenuItem("Hide deselected except images"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK | Event.ALT_MASK, true)); if (none) item.setEnabled(false); item = new JMenuItem("Hide selected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0, true)); if (none) item.setEnabled(false); none = ! layer.getParent().containsDisplayable(DLabel.class); item = new JMenuItem("Hide all labels"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all labels"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(AreaList.class); item = new JMenuItem("Hide all arealists"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all arealists"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.contains(Profile.class); item = new JMenuItem("Hide all profiles"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all profiles"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Pipe.class); item = new JMenuItem("Hide all pipes"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all pipes"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Polyline.class); item = new JMenuItem("Hide all polylines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all polylines"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().contains(Ball.class); item = new JMenuItem("Hide all balls"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all balls"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); none = ! layer.getParent().containsDisplayable(Patch.class); item = new JMenuItem("Hide all images"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Unhide all images"); item.addActionListener(this); menu.add(item); if (none) item.setEnabled(false); item = new JMenuItem("Hide all but images"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Unhide all"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.ALT_MASK, true)); popup.add(menu); } catch (Exception e) { IJError.print(e); } menu = new JMenu("Import"); item = new JMenuItem("Import image"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK & Event.SHIFT_MASK, true)); item = new JMenuItem("Import stack..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import grid..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import sequence as grid..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import from text file..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Import labels as arealists..."); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Export"); item = new JMenuItem("Make flat image..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Arealists as labels (tif)"); item.addActionListener(this); menu.add(item); if (0 == layer.getParent().getZDisplayables(AreaList.class).size()) item.setEnabled(false); item = new JMenuItem("Arealists as labels (amira)"); item.addActionListener(this); menu.add(item); if (0 == layer.getParent().getZDisplayables(AreaList.class).size()) item.setEnabled(false); popup.add(menu); menu = new JMenu("Display"); item = new JMenuItem("Resize canvas/LayerSet..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Autoresize canvas/LayerSet"); item.addActionListener(this); menu.add(item); // OBSOLETE // item = new JMenuItem("Rotate Layer/LayerSet..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Properties ..."); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Project"); this.project.getLoader().setupMenuItems(menu, this.getProject()); item = new JMenuItem("Project properties..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Create subproject"); item.addActionListener(this); menu.add(item); if (null == canvas.getFakeImagePlus().getRoi()) item.setEnabled(false); item = new JMenuItem("Release memory..."); item.addActionListener(this); menu.add(item); item = new JMenuItem("Flush image cache"); item.addActionListener(this); menu.add(item); popup.add(menu); menu = new JMenu("Selection"); item = new JMenuItem("Select all"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Utils.getControlModifier(), true)); if (0 == layer.getDisplayables().size() && 0 == layer.getParent().getZDisplayables().size()) item.setEnabled(false); item = new JMenuItem("Select none"); item.addActionListener(this); menu.add(item); if (0 == selection.getNSelected()) item.setEnabled(false); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true)); JMenu bytype = new JMenu("Select all by type"); item = new JMenuItem("AreaList"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Ball"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Dissector"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Image"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Text"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Pipe"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Polyline"); item.addActionListener(bytypelistener); bytype.add(item); item = new JMenuItem("Profile"); item.addActionListener(bytypelistener); bytype.add(item); menu.add(bytype); item = new JMenuItem("Restore selection"); item.addActionListener(this); menu.add(item); item = new JMenuItem("Select under ROI"); item.addActionListener(this); menu.add(item); if (canvas.getFakeImagePlus().getRoi() == null) item.setEnabled(false); popup.add(menu); item = new JMenuItem("Search..."); item.addActionListener(this); popup.add(item); } //canvas.add(popup); return popup; } private ByTypeListener bytypelistener = new ByTypeListener(this); static private class ByTypeListener implements ActionListener { final Display d; ByTypeListener(final Display d) { this.d = d; } public void actionPerformed(final ActionEvent ae) { final String command = ae.getActionCommand(); final java.awt.geom.Area aroi = Utils.getArea(d.canvas.getFakeImagePlus().getRoi()); d.dispatcher.exec(new Runnable() { public void run() { try { String type = command; if (type.equals("Image")) type = "Patch"; Class c = Class.forName("ini.trakem2.display." + type); java.util.List<Displayable> a = new ArrayList<Displayable>(); if (null != aroi) { a.addAll(d.layer.getDisplayables(c, aroi, true)); a.addAll(d.layer.getParent().getZDisplayables(c, d.layer, aroi, true)); } else { a.addAll(d.layer.getDisplayables(c)); a.addAll(d.layer.getParent().getZDisplayables(c)); // Remove non-visible ones for (final Iterator<Displayable> it = a.iterator(); it.hasNext(); ) { if (!it.next().isVisible()) it.remove(); } } if (0 == a.size()) return; boolean selected = false; if (0 == ae.getModifiers()) { Utils.log2("first"); d.selection.clear(); d.selection.selectAll(a); selected = true; } else if (0 == (ae.getModifiers() ^ Event.SHIFT_MASK)) { Utils.log2("with shift"); d.selection.selectAll(a); // just add them to the current selection selected = true; } if (selected) { // Activate last: d.selection.setActive(a.get(a.size() -1)); } } catch (ClassNotFoundException e) { Utils.log2(e.toString()); } }}); } } /** Check if a panel for the given Displayable is completely visible in the JScrollPane */ public boolean isWithinViewport(final Displayable d) { final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (ht_tabs.get(d.getClass()) == scroll) return isWithinViewport(scroll, ht_panels.get(d)); return false; } private boolean isWithinViewport(JScrollPane scroll, DisplayablePanel dp) { if(null == dp) return false; JViewport view = scroll.getViewport(); java.awt.Dimension dimensions = view.getExtentSize(); java.awt.Point p = view.getViewPosition(); int y = dp.getY(); if ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) { return true; } return false; } /** Check if a panel for the given Displayable is partially visible in the JScrollPane */ public boolean isPartiallyWithinViewport(final Displayable d) { final JScrollPane scroll = ht_tabs.get(d.getClass()); if (tabs.getSelectedComponent() == scroll) return isPartiallyWithinViewport(scroll, ht_panels.get(d)); return false; } /** Check if a panel for the given Displayable is at least partially visible in the JScrollPane */ private boolean isPartiallyWithinViewport(final JScrollPane scroll, final DisplayablePanel dp) { if(null == dp) { //Utils.log2("Display.isPartiallyWithinViewport: null DisplayablePanel ??"); return false; // to fast for you baby } JViewport view = scroll.getViewport(); java.awt.Dimension dimensions = view.getExtentSize(); java.awt.Point p = view.getViewPosition(); int y = dp.getY(); if ( ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) // completely visible || ((y + DisplayablePanel.HEIGHT - p.y) > dimensions.height && y < p.y + dimensions.height) // partially hovering at the bottom || ((y + DisplayablePanel.HEIGHT) > p.y && y < p.y) // partially hovering at the top ) { return true; } return false; } /** A function to make a Displayable panel be visible in the screen, by scrolling the viewport of the JScrollPane. */ private void scrollToShow(final Displayable d) { dispatcher.execSwing(new Runnable() { public void run() { final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent(); if (d instanceof ZDisplayable && scroll == scroll_zdispl) { scrollToShow(scroll_zdispl, ht_panels.get(d)); return; } final Class c = d.getClass(); if (Patch.class == c && scroll == scroll_patches) { scrollToShow(scroll_patches, ht_panels.get(d)); } else if (DLabel.class == c && scroll == scroll_labels) { scrollToShow(scroll_labels, ht_panels.get(d)); } else if (Profile.class == c && scroll == scroll_profiles) { scrollToShow(scroll_profiles, ht_panels.get(d)); } }}); } private void scrollToShow(final JScrollPane scroll, final DisplayablePanel dp) { if (null == dp) return; JViewport view = scroll.getViewport(); Point current = view.getViewPosition(); Dimension extent = view.getExtentSize(); int panel_y = dp.getY(); if ((panel_y + DisplayablePanel.HEIGHT - current.y) <= extent.height && panel_y >= current.y) { // it's completely visible already return; } else { // scroll just enough // if it's above, show at the top if (panel_y - current.y < 0) { view.setViewPosition(new Point(0, panel_y)); } // if it's below (even if partially), show at the bottom else if (panel_y + 50 > current.y + extent.height) { view.setViewPosition(new Point(0, panel_y - extent.height + 50)); //Utils.log("Display.scrollToShow: panel_y: " + panel_y + " current.y: " + current.y + " extent.height: " + extent.height); } } } /** Update the title of the given Displayable in its DisplayablePanel, if any. */ static public void updateTitle(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (layer == d.layer) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.updateTitle(); } } } /** Update the Display's title in all Displays showing the given Layer. */ static public void updateTitle(final Layer layer) { for (final Display d : al_displays) { if (d.layer == layer) { d.updateTitle(); } } } /** Update the Display's title in all Displays showing a Layer of the given LayerSet. */ static public void updateTitle(final LayerSet ls) { for (final Display d : al_displays) { if (d.layer.getParent() == ls) { d.updateTitle(); } } } /** Set a new title in the JFrame, showing info on the layer 'z' and the magnification. */ public void updateTitle() { // From ij.ImagePlus class, the solution: String scale = ""; final double magnification = canvas.getMagnification(); if (magnification!=1.0) { final double percent = magnification*100.0; scale = new StringBuffer(" (").append(Utils.d2s(percent, percent==(int)percent ? 0 : 1)).append("%)").toString(); } final Calibration cal = layer.getParent().getCalibration(); String title = new StringBuffer().append(layer.getParent().indexOf(layer) + 1).append('/').append(layer.getParent().size()).append(' ').append((null == layer.getTitle() ? "" : layer.getTitle())).append(scale).append(" -- ").append(getProject().toString()).append(' ').append(' ').append(Utils.cutNumber(layer.getParent().getLayerWidth() * cal.pixelWidth, 2, true)).append('x').append(Utils.cutNumber(layer.getParent().getLayerHeight() * cal.pixelHeight, 2, true)).append(' ').append(cal.getUnit()).toString(); frame.setTitle(title); // fix the title for the FakeImageWindow and thus the WindowManager listing in the menus canvas.getFakeImagePlus().setTitle(title); } /** If shift is down, scroll to the next non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers ahead; else just the next Layer. */ public void nextLayer(final int modifiers) { //setLayer(layer.getParent().next(layer)); //scroller.setValue(layer.getParent().getLayerIndex(layer.getId())); if (0 == (modifiers ^ Event.SHIFT_MASK)) { slt.set(layer.getParent().nextNonEmpty(layer)); } else if (scroll_step > 1) { int i = layer.getParent().indexOf(this.layer); Layer la = layer.getParent().getLayer(i + scroll_step); if (null != la) slt.set(la); } else { slt.set(layer.getParent().next(layer)); } updateInDatabase("layer_id"); } /** If shift is down, scroll to the previous non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers backward; else just the previous Layer. */ public void previousLayer(final int modifiers) { //setLayer(layer.getParent().previous(layer)); //scroller.setValue(layer.getParent().getLayerIndex(layer.getId())); if (0 == (modifiers ^ Event.SHIFT_MASK)) { slt.set(layer.getParent().previousNonEmpty(layer)); } else if (scroll_step > 1) { int i = layer.getParent().indexOf(this.layer); Layer la = layer.getParent().getLayer(i - scroll_step); if (null != la) slt.set(la); } else { slt.set(layer.getParent().previous(layer)); } updateInDatabase("layer_id"); } static public void updateLayerScroller(LayerSet set) { for (final Display d : al_displays) { if (d.layer.getParent() == set) { d.updateLayerScroller(d.layer); } } } private void updateLayerScroller(Layer layer) { int size = layer.getParent().size(); if (size <= 1) { scroller.setValues(0, 1, 0, 0); scroller.setEnabled(false); } else { scroller.setEnabled(true); scroller.setValues(layer.getParent().getLayerIndex(layer.getId()), 1, 0, size); } } private void updateSnapshots() { Enumeration<DisplayablePanel> e = ht_panels.elements(); while (e.hasMoreElements()) { e.nextElement().remake(); } Utils.updateComponent(tabs.getSelectedComponent()); } static public void updatePanel(Layer layer, final Displayable displ) { if (null == layer && null != front) layer = front.layer; // the front layer for (final Display d : al_displays) { if (d.layer == layer) { d.updatePanel(displ); } } } private void updatePanel(Displayable d) { JPanel c = null; if (d instanceof Profile) { c = panel_profiles; } else if (d instanceof Patch) { c = panel_patches; } else if (d instanceof DLabel) { c = panel_labels; } else if (d instanceof Pipe) { c = panel_zdispl; } if (null == c) return; DisplayablePanel dp = ht_panels.get(d); dp.remake(); Utils.updateComponent(c); } static public void updatePanelIndex(final Layer layer, final Displayable displ) { for (final Display d : al_displays) { if (d.layer == layer || displ instanceof ZDisplayable) { d.updatePanelIndex(displ); } } } private void updatePanelIndex(final Displayable d) { // find first of the kind, then remove and insert its panel int i = 0; JPanel c = null; if (d instanceof ZDisplayable) { i = layer.getParent().indexOf((ZDisplayable)d); c = panel_zdispl; } else { i = layer.relativeIndexOf(d); if (d instanceof Profile) { c = panel_profiles; } else if (d instanceof Patch) { c = panel_patches; } else if (d instanceof DLabel) { c = panel_labels; } } if (null == c) return; DisplayablePanel dp = ht_panels.get(d); if (null == dp) return; // may be half-baked, wait c.remove(dp); c.add(dp, i); // java and its fabulous consistency // not enough! Utils.updateComponent(c); // So, cocktail: c.invalidate(); c.validate(); Utils.updateComponent(c); } /** Repair possibly missing panels and other components by simply resetting the same Layer */ public void repairGUI() { Layer layer = this.layer; this.layer = null; setLayer(layer); } public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { // fix non-scrolling popup menu GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { // this is an item from the "Duplicate, link and send to" menu of layer z's Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { // WARNING the indexOf is very similar to the previous one // Send the linked group to the selected layer int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); HashSet hs = active.getLinkedGroup(new HashSet()); layer.getParent().move(hs, active.getLayer(), target); } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection();//selection.update(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { /* if (null != active) { Displayable d = active; selection.remove(d); d.remove(true); // will repaint } */ // remove all selected objects selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Undo")) { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Redo")) { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Transform")) { if (null == active) return; canvas.setTransforming(true); } else if (command.equals("Apply transform")) { if (null == active) return; canvas.setTransforming(false); } else if (command.equals("Cancel transform")) { if (null == active) return; canvas.cancelTransform(); } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); selection.removeAll(layer.getParent().hideExcept(type, false)); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { layer.getParent().setAllVisible(false); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); selection.removeAll(layer.getParent().setVisible(type, false, true)); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); layer.getParent().setVisible(type, true, true); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); // TODO should deselect them too? I don't think so. } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addLayerContentStep(layer); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importImages(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { // if there's a ROI, just use that as cropping rectangle Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { // otherwise, whatever is visible //srcRect = canvas.getSrcRect(); // The above is confusing. That is what ROIs are for. So paint all: srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { /* String[] layers = new String[layer.getParent().size()]; int i = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString(); i++; } int i_layer = layer.getParent().indexOf(layer); gd.addChoice("Start: ", layers, layers[i_layer]); gd.addChoice("End: ", layers, layers[i_layer]); */ Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); // in its own thread if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); } else if (command.equals("Unlock")) { selection.setLocked(false); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Cancel alignment")) { layer.getParent().cancelAlign(); } else if (command.equals("Align with landmarks")) { layer.getParent().applyAlign(false); } else if (command.equals("Align and register")) { layer.getParent().applyAlign(true); } else if (command.equals("Align using profiles")) { if (!selection.contains(Profile.class)) { Utils.showMessage("No profiles are selected."); return; } // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex()); Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (la_start == la_end) { Utils.showMessage("Need at least two layers."); return; } if (selection.isLocked()) { Utils.showMessage("There are locked objects."); return; } layer.getParent().startAlign(Display.this); layer.getParent().applyAlign(la_start, la_end, selection); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { // check linked group final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStep(linked); Bureaucrat burro = Registration.registerStackSlices((Patch)getActive()); // will repaint burro.addPostTask(new Runnable() { public void run() { // The current state when done ls.addTransformStep(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers (layer-wise)")) { final Layer la = layer; la.getParent().addTransformStep(la); Bureaucrat burro = AlignTask.alignLayersLinearlyTask( layer ); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(la); }}); } else if (command.equals("Align layers (tile-wise global minimization)")) { final Layer la = layer; // caching, since scroll wheel may change it la.getParent().addTransformStep(); Bureaucrat burro = Registration.registerLayers(la, Registration.GLOBAL_MINIMIZATION); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(); }}); } else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects. GenericDialog gd = new GenericDialog("Properties", Display.this.frame); //gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); String preprocessor = project.getLoader().getPreprocessor(); gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); // -------- gd.showDialog(); if (gd.wasCanceled()) return; // -------- int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); // layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); // boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { // nothing changed } else { if (using_mipmaps) { // and !generate_mipmaps lo.flushMipMaps(true); } else { // not using mipmaps before, and true == generate_mipmaps lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } // final String prepro = gd.getNextString(); if (!project.getLoader().setPreprocessor(prepro.trim())) { Utils.showMessage("Could NOT set the preprocessor to " + prepro); } // layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { ArrayList al_sel = selection.getSelected(); // put active at the beginning, to work as the base on which other's will get merged al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); AreaList ali = AreaList.merge(al_sel); if (null != ali) { // remove all but the first from the selection for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } else if (command.equals("Identify...")) { // for pipes only for now if (!(active instanceof Pipe)) return; ini.trakem2.vector.Compare.findSimilar((Pipe)active); } else if (command.equals("Identify with axes...")) { if (!(active instanceof Pipe)) return; if (Project.getProjects().size() < 2) { Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify"); return; } ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } // handle profile lists ... HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { if (!(active instanceof Patch)) return; StitchingTEM.snap(getActive(), Display.this); } else if (command.equals("Montage")) { if (!(active instanceof Patch)) { Utils.showMessage("Please select only images."); return; } final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); for (final Displayable d : affected) if (d.isLinked()) { Utils.showMessage( "You cannot montage linked objects." ); return; } // make an undo step! final LayerSet ls = layer.getParent(); ls.addTransformStep(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.addTransformStep(affected); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; boolean overlapping_only = 1 == gd.getNextChoiceIndex(); switch (gd.getNextChoiceIndex()) { case 0: Patch.crosslink(selection.getSelected(Patch.class), overlapping_only); break; case 1: Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only); break; case 2: for (final Layer la : layer.getParent().getLayers()) { Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only); } break; } } else if (command.equals("Enhance contrast (selected images)...")) { ArrayList al = selection.getSelected(Patch.class); getProject().getLoader().homogenizeContrast(al); } else if (command.equals("Enhance contrast layer-wise...")) { // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end Layer[] la = new Layer[list.size()]; list.toArray(la); project.getLoader().homogenizeContrast(la); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end al.addAll(la.getDisplayables(Patch.class)); } project.getLoader().setMinAndMax(al, min, max); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); } else if (command.equals("Enhance contrast (selected images)...")) { Utils.log("Not implemented yet"); } else if (command.equals("Enhance contrast layer-wise...")) { Utils.log("Not implemented yet"); } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; // the menu item is not active unless there is a ROI Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); final LayerSet subls = sub.getRootLayerSet(); final Display d = new Display(sub, subls.getLayer(0)); SwingUtilities.invokeLater(new Runnable() { public void run() { d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight())); }}); - } else if (command.startsWith("Export arealists as labels")) { + } else if (command.startsWith("Arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } // Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame? al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); - if (command.endsWith("(amira)")) { + if (-1 != command.indexOf("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); - } else if (command.endsWith("(tif)")) { + } else if (-1 != command.indexOf("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else { Utils.log2("Display: don't know what to do with command " + command); } }}); } /** Update in all displays the Transform for the given Displayable if it's selected. */ static public void updateTransform(final Displayable displ) { for (final Display d : al_displays) { if (d.selection.contains(displ)) d.selection.updateTransform(displ); } } /** Order the profiles of the parent profile_list by Z order, and fix the ProjectTree.*/ /* private void fixZOrdering(Profile profile) { ProjectThing thing = project.findProjectThing(profile); if (null == thing) { Utils.log2("Display.fixZOrdering: null thing?"); return; } ((ProjectThing)thing.getParent()).fixZOrdering(); project.getProjectTree().updateList(thing.getParent()); } */ /** The number of layers to scroll through with the wheel; 1 by default.*/ public int getScrollStep() { return this.scroll_step; } public void setScrollStep(int scroll_step) { if (scroll_step < 1) scroll_step = 1; this.scroll_step = scroll_step; updateInDatabase("scroll_step"); } protected Bureaucrat importImage() { Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN public void run() { startedWorking(); try { /// Rectangle srcRect = canvas.getSrcRect(); int x = srcRect.x + srcRect.width / 2; int y = srcRect.y + srcRect.height/ 2; Patch p = project.getLoader().importImage(project, x, y); if (null == p) { finishedWorking(); Utils.showMessage("Could not open the image."); return; } Display.this.getLayerSet().addLayerContentStep(layer); layer.add(p); // will add it to the proper Displays Display.this.getLayerSet().addLayerContentStep(layer); /// } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, getProject()); } protected Bureaucrat importNextImage() { Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN public void run() { startedWorking(); try { Rectangle srcRect = canvas.getSrcRect(); int x = srcRect.x + srcRect.width / 2;// - imp.getWidth() / 2; int y = srcRect.y + srcRect.height/ 2;// - imp.getHeight()/ 2; Patch p = project.getLoader().importNextImage(project, x, y); if (null == p) { Utils.showMessage("Could not open next image."); finishedWorking(); return; } Display.this.getLayerSet().addLayerContentStep(layer); layer.add(p); // will add it to the proper Displays Display.this.getLayerSet().addLayerContentStep(layer); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, getProject()); } /** Make the given channel have the given alpha (transparency). */ public void setChannel(int c, float alpha) { int a = (int)(255 * alpha); int l = (c_alphas&0xff000000)>>24; int r = (c_alphas&0xff0000)>>16; int g = (c_alphas&0xff00)>>8; int b = c_alphas&0xff; switch (c) { case Channel.MONO: // all to the given alpha c_alphas = (l<<24) + (r<<16) + (g<<8) + b; // parenthesis are NECESSARY break; case Channel.RED: // modify only the red c_alphas = (l<<24) + (a<<16) + (g<<8) + b; break; case Channel.GREEN: c_alphas = (l<<24) + (r<<16) + (a<<8) + b; break; case Channel.BLUE: c_alphas = (l<<24) + (r<<16) + (g<<8) + a; break; } //Utils.log2("c_alphas: " + c_alphas); //canvas.setUpdateGraphics(true); canvas.repaint(true); updateInDatabase("c_alphas"); } /** Set the channel as active and the others as inactive. */ public void setActiveChannel(Channel channel) { for (int i=0; i<4; i++) { if (channel != channels[i]) channels[i].setActive(false); else channel.setActive(true); } Utils.updateComponent(panel_channels); transp_slider.setValue((int)(channel.getAlpha() * 100)); } public int getDisplayChannelAlphas() { return c_alphas; } // rename this method and the getDisplayChannelAlphas ! They sound the same! public int getChannelAlphas() { return ((int)(channels[0].getAlpha() * 255)<<24) + ((int)(channels[1].getAlpha() * 255)<<16) + ((int)(channels[2].getAlpha() * 255)<<8) + (int)(channels[3].getAlpha() * 255); } public int getChannelAlphasState() { return ((channels[0].isSelected() ? 255 : 0)<<24) + ((channels[1].isSelected() ? 255 : 0)<<16) + ((channels[2].isSelected() ? 255 : 0)<<8) + (channels[3].isSelected() ? 255 : 0); } /** Show the layer in the front Display, or in a new Display if the front Display is showing a layer from a different LayerSet. */ static public void showFront(final Layer layer) { Display display = front; if (null == display || display.layer.getParent() != layer.getParent()) { display = new Display(layer.getProject(), layer, null); // gets set to front } else { display.setLayer(layer); } } /** Show the given Displayable centered and selected. If select is false, the selection is cleared. */ static public void showCentered(Layer layer, Displayable displ, boolean select, boolean shift_down) { // see if the given layer belongs to the layer set being displayed Display display = front; // to ensure thread consistency to some extent if (null == display || display.layer.getParent() != layer.getParent()) { display = new Display(layer.getProject(), layer, displ); // gets set to front } else if (display.layer != layer) { display.setLayer(layer); } if (select) { if (!shift_down) display.selection.clear(); display.selection.add(displ); } else { display.selection.clear(); } display.showCentered(displ); } private final void showCentered(final Displayable displ) { if (null == displ) return; SwingUtilities.invokeLater(new Runnable() { public void run() { displ.setVisible(true); Rectangle box = displ.getBoundingBox(); if (0 == box.width || 0 == box.height) { box.width = (int)layer.getLayerWidth(); box.height = (int)layer.getLayerHeight(); } canvas.showCentered(box); scrollToShow(displ); if (displ instanceof ZDisplayable) { // scroll to first layer that has a point ZDisplayable zd = (ZDisplayable)displ; setLayer(zd.getFirstLayer()); } }}); } /** Listen to interesting updates, such as the ColorPicker and updates to Patch objects. */ public void imageUpdated(ImagePlus updated) { // detect ColorPicker WARNING this will work even if the Display is not the window immediately active under the color picker. if (this == front && updated instanceof ij.plugin.ColorPicker) { if (null != active && project.isInputEnabled()) { selection.setColor(Toolbar.getForegroundColor()); Display.repaint(front.layer, selection.getBox(), 0); } return; } // $%#@!! LUT changes don't set the image as changed //if (updated instanceof PatchStack) { // updated.changes = 1 //} //Utils.log2("imageUpdated: " + updated + " " + updated.getClass()); /* // never gets called (?) // the above is overkill. Instead: if (updated instanceof PatchStack) { Patch p = ((PatchStack)updated).getCurrentPatch(); ImageProcessor ip = updated.getProcessor(); p.setMinAndMax(ip.getMin(), ip.getMax()); Utils.log2("setting min and max: " + ip.getMin() + ", " + ip.getMax()); project.getLoader().decacheAWT(p.getId()); // including level 0, which will be editable // on repaint, it will be recreated //((PatchStack)updated).decacheAll(); // so that it will repaint with a newly created image } */ // detect LUT changes: DONE at PatchStack, which is the active (virtual) image //Utils.log2("calling decache for " + updated); //getProject().getLoader().decache(updated); } public void imageClosed(ImagePlus imp) {} public void imageOpened(ImagePlus imp) {} /** Release memory captured by the offscreen images */ static public void flushAll() { for (final Display d : al_displays) { d.canvas.flush(); } //System.gc(); Thread.yield(); } /** Can be null. */ static public Display getFront() { return front; } static public void setCursorToAll(final Cursor c) { for (final Display d : al_displays) { d.frame.setCursor(c); } } protected void setCursor(Cursor c) { frame.setCursor(c); } /** Used by the Displayable to update the visibility checkbox in other Displays. */ static protected void updateVisibilityCheckbox(final Layer layer, final Displayable displ, final Display calling_display) { //LOCKS ALL //SwingUtilities.invokeLater(new Runnable() { public void run() { for (final Display d : al_displays) { if (d == calling_display) continue; if (d.layer.contains(displ) || (displ instanceof ZDisplayable && d.layer.getParent().contains((ZDisplayable)displ))) { DisplayablePanel dp = d.ht_panels.get(displ); if (null != dp) dp.updateVisibilityCheckbox(); } } //}}); } protected boolean isActiveWindow() { return frame.isActive(); } /** Toggle user input; pan and zoom are always enabled though.*/ static public void setReceivesInput(final Project project, final boolean b) { for (final Display d : al_displays) { if (d.project == project) d.canvas.setReceivesInput(b); } } /** Export the DTD that defines this object. */ static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) { if (hs.contains("t2_display")) return; // TODO to avoid collisions the type shoud be in a namespace such as tm2:display hs.add("t2_display"); sb_header.append(indent).append("<!ELEMENT t2_display EMPTY>\n") .append(indent).append("<!ATTLIST t2_display id NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display layer_id NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display x NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display y NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display magnification NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_x NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_y NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_width NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display srcrect_height NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display scroll_step NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display c_alphas NMTOKEN #REQUIRED>\n") .append(indent).append("<!ATTLIST t2_display c_alphas_state NMTOKEN #REQUIRED>\n") ; } /** Export all displays of the given project as XML entries. */ static public void exportXML(final Project project, final Writer writer, final String indent, final Object any) throws Exception { final StringBuffer sb_body = new StringBuffer(); final String in = indent + "\t"; for (final Display d : al_displays) { if (d.project != project) continue; final Rectangle r = d.frame.getBounds(); final Rectangle srcRect = d.canvas.getSrcRect(); final double magnification = d.canvas.getMagnification(); sb_body.append(indent).append("<t2_display id=\"").append(d.id).append("\"\n") .append(in).append("layer_id=\"").append(d.layer.getId()).append("\"\n") .append(in).append("c_alphas=\"").append(d.c_alphas).append("\"\n") .append(in).append("c_alphas_state=\"").append(d.getChannelAlphasState()).append("\"\n") .append(in).append("x=\"").append(r.x).append("\"\n") .append(in).append("y=\"").append(r.y).append("\"\n") .append(in).append("magnification=\"").append(magnification).append("\"\n") .append(in).append("srcrect_x=\"").append(srcRect.x).append("\"\n") .append(in).append("srcrect_y=\"").append(srcRect.y).append("\"\n") .append(in).append("srcrect_width=\"").append(srcRect.width).append("\"\n") .append(in).append("srcrect_height=\"").append(srcRect.height).append("\"\n") .append(in).append("scroll_step=\"").append(d.scroll_step).append("\"\n") ; sb_body.append(indent).append("/>\n"); } writer.write(sb_body.toString()); } static public void toolChanged(final String tool_name) { Utils.log2("tool name: " + tool_name); if (!tool_name.equals("ALIGN")) { for (final Display d : al_displays) { d.layer.getParent().cancelAlign(); } } } static public void toolChanged(final int tool) { //Utils.log2("int tool is " + tool); if (ProjectToolbar.PEN == tool) { // erase bounding boxes for (final Display d : al_displays) { if (null != d.active) d.repaint(d.layer, d.selection.getBox(), 2); } } if (null != front) { WindowManager.setTempCurrentImage(front.canvas.getFakeImagePlus()); } } public Selection getSelection() { return selection; } public boolean isSelected(Displayable d) { return selection.contains(d); } static public void updateSelection() { Display.updateSelection(null); } static public void updateSelection(final Display calling) { final HashSet hs = new HashSet(); for (final Display d : al_displays) { if (hs.contains(d.layer)) continue; hs.add(d.layer); if (null == d || null == d.selection) { Utils.log2("d is : "+ d + " d.selection is " + d.selection); } else { d.selection.update(); // recomputes box } if (d != calling) { // TODO this is so dirty! if (d.selection.getNLinked() > 1) d.canvas.setUpdateGraphics(true); // this is overkill anyway d.canvas.repaint(d.selection.getLinkedBox(), Selection.PADDING); d.navigator.repaint(true); // everything } } } static public void clearSelection(final Layer layer) { for (final Display d : al_displays) { if (d.layer == layer) d.selection.clear(); } } static public void clearSelection() { for (final Display d : al_displays) { d.selection.clear(); } } private void setTempCurrentImage() { WindowManager.setTempCurrentImage(canvas.getFakeImagePlus()); } /** Check if any display will paint the given Displayable at the given magnification. */ static public boolean willPaint(final Displayable displ, final double magnification) { Rectangle box = null; ; for (final Display d : al_displays) { /* // Can no longer do this check, because 'magnification' is now affected by the Displayable AffineTransform! And thus it would not paint after the prePaint. if (Math.abs(d.canvas.getMagnification() - magnification) > 0.00000001) { continue; } */ if (null == box) box = displ.getBoundingBox(null); if (d.canvas.getSrcRect().intersects(box)) { return true; } } return false; } public void hideDeselected(final boolean not_images) { // hide deselected final ArrayList all = layer.getParent().getZDisplayables(); // a copy all.addAll(layer.getDisplayables()); all.removeAll(selection.getSelected()); if (not_images) all.removeAll(layer.getDisplayables(Patch.class)); for (final Displayable d : (ArrayList<Displayable>)all) { if (d.isVisible()) d.setVisible(false); } Display.update(layer); } /** Cleanup internal lists that may contain the given Displayable. */ static public void flush(final Displayable displ) { for (final Display d : al_displays) { d.selection.removeFromPrev(displ); } } public void resizeCanvas() { GenericDialog gd = new GenericDialog("Resize LayerSet"); gd.addNumericField("new width: ", layer.getLayerWidth(), 3); gd.addNumericField("new height: ",layer.getLayerHeight(),3); gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[7]); gd.showDialog(); if (gd.wasCanceled()) return; double new_width = gd.getNextNumber(); double new_height =gd.getNextNumber(); layer.getParent().setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects } /* // To record layer changes -- but it's annoying, this is visualization not data. static class DoSetLayer implements DoStep { final Display display; final Layer layer; DoSetLayer(final Display display) { this.display = display; this.layer = display.layer; } public Displayable getD() { return null; } public boolean isEmpty() { return false; } public boolean apply(final int action) { display.setLayer(layer); } public boolean isIdenticalTo(final Object ob) { if (!ob instanceof DoSetLayer) return false; final DoSetLayer dsl = (DoSetLayer) ob; return dsl.display == this.display && dsl.layer == this.layer; } } */ protected void duplicateLinkAndSendTo(final Displayable active, final int position, final Layer other_layer) { if (null == active || !(active instanceof Profile)) return; if (active.getLayer() == other_layer) return; // can't do that! Profile profile = project.getProjectTree().duplicateChild((Profile)active, position, other_layer); if (null == profile) return; active.link(profile); slt.setAndWait(other_layer); other_layer.add(profile); selection.add(profile); } }
false
true
public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { // fix non-scrolling popup menu GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { // this is an item from the "Duplicate, link and send to" menu of layer z's Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { // WARNING the indexOf is very similar to the previous one // Send the linked group to the selected layer int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); HashSet hs = active.getLinkedGroup(new HashSet()); layer.getParent().move(hs, active.getLayer(), target); } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection();//selection.update(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { /* if (null != active) { Displayable d = active; selection.remove(d); d.remove(true); // will repaint } */ // remove all selected objects selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Undo")) { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Redo")) { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Transform")) { if (null == active) return; canvas.setTransforming(true); } else if (command.equals("Apply transform")) { if (null == active) return; canvas.setTransforming(false); } else if (command.equals("Cancel transform")) { if (null == active) return; canvas.cancelTransform(); } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); selection.removeAll(layer.getParent().hideExcept(type, false)); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { layer.getParent().setAllVisible(false); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); selection.removeAll(layer.getParent().setVisible(type, false, true)); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); layer.getParent().setVisible(type, true, true); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); // TODO should deselect them too? I don't think so. } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addLayerContentStep(layer); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importImages(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { // if there's a ROI, just use that as cropping rectangle Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { // otherwise, whatever is visible //srcRect = canvas.getSrcRect(); // The above is confusing. That is what ROIs are for. So paint all: srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { /* String[] layers = new String[layer.getParent().size()]; int i = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString(); i++; } int i_layer = layer.getParent().indexOf(layer); gd.addChoice("Start: ", layers, layers[i_layer]); gd.addChoice("End: ", layers, layers[i_layer]); */ Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); // in its own thread if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); } else if (command.equals("Unlock")) { selection.setLocked(false); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Cancel alignment")) { layer.getParent().cancelAlign(); } else if (command.equals("Align with landmarks")) { layer.getParent().applyAlign(false); } else if (command.equals("Align and register")) { layer.getParent().applyAlign(true); } else if (command.equals("Align using profiles")) { if (!selection.contains(Profile.class)) { Utils.showMessage("No profiles are selected."); return; } // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex()); Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (la_start == la_end) { Utils.showMessage("Need at least two layers."); return; } if (selection.isLocked()) { Utils.showMessage("There are locked objects."); return; } layer.getParent().startAlign(Display.this); layer.getParent().applyAlign(la_start, la_end, selection); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { // check linked group final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStep(linked); Bureaucrat burro = Registration.registerStackSlices((Patch)getActive()); // will repaint burro.addPostTask(new Runnable() { public void run() { // The current state when done ls.addTransformStep(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers (layer-wise)")) { final Layer la = layer; la.getParent().addTransformStep(la); Bureaucrat burro = AlignTask.alignLayersLinearlyTask( layer ); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(la); }}); } else if (command.equals("Align layers (tile-wise global minimization)")) { final Layer la = layer; // caching, since scroll wheel may change it la.getParent().addTransformStep(); Bureaucrat burro = Registration.registerLayers(la, Registration.GLOBAL_MINIMIZATION); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(); }}); } else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects. GenericDialog gd = new GenericDialog("Properties", Display.this.frame); //gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); String preprocessor = project.getLoader().getPreprocessor(); gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); // -------- gd.showDialog(); if (gd.wasCanceled()) return; // -------- int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); // layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); // boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { // nothing changed } else { if (using_mipmaps) { // and !generate_mipmaps lo.flushMipMaps(true); } else { // not using mipmaps before, and true == generate_mipmaps lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } // final String prepro = gd.getNextString(); if (!project.getLoader().setPreprocessor(prepro.trim())) { Utils.showMessage("Could NOT set the preprocessor to " + prepro); } // layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { ArrayList al_sel = selection.getSelected(); // put active at the beginning, to work as the base on which other's will get merged al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); AreaList ali = AreaList.merge(al_sel); if (null != ali) { // remove all but the first from the selection for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } else if (command.equals("Identify...")) { // for pipes only for now if (!(active instanceof Pipe)) return; ini.trakem2.vector.Compare.findSimilar((Pipe)active); } else if (command.equals("Identify with axes...")) { if (!(active instanceof Pipe)) return; if (Project.getProjects().size() < 2) { Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify"); return; } ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } // handle profile lists ... HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { if (!(active instanceof Patch)) return; StitchingTEM.snap(getActive(), Display.this); } else if (command.equals("Montage")) { if (!(active instanceof Patch)) { Utils.showMessage("Please select only images."); return; } final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); for (final Displayable d : affected) if (d.isLinked()) { Utils.showMessage( "You cannot montage linked objects." ); return; } // make an undo step! final LayerSet ls = layer.getParent(); ls.addTransformStep(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.addTransformStep(affected); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; boolean overlapping_only = 1 == gd.getNextChoiceIndex(); switch (gd.getNextChoiceIndex()) { case 0: Patch.crosslink(selection.getSelected(Patch.class), overlapping_only); break; case 1: Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only); break; case 2: for (final Layer la : layer.getParent().getLayers()) { Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only); } break; } } else if (command.equals("Enhance contrast (selected images)...")) { ArrayList al = selection.getSelected(Patch.class); getProject().getLoader().homogenizeContrast(al); } else if (command.equals("Enhance contrast layer-wise...")) { // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end Layer[] la = new Layer[list.size()]; list.toArray(la); project.getLoader().homogenizeContrast(la); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end al.addAll(la.getDisplayables(Patch.class)); } project.getLoader().setMinAndMax(al, min, max); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); } else if (command.equals("Enhance contrast (selected images)...")) { Utils.log("Not implemented yet"); } else if (command.equals("Enhance contrast layer-wise...")) { Utils.log("Not implemented yet"); } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; // the menu item is not active unless there is a ROI Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); final LayerSet subls = sub.getRootLayerSet(); final Display d = new Display(sub, subls.getLayer(0)); SwingUtilities.invokeLater(new Runnable() { public void run() { d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight())); }}); } else if (command.startsWith("Export arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } // Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame? al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); if (command.endsWith("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); } else if (command.endsWith("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else { Utils.log2("Display: don't know what to do with command " + command); } }});
public void actionPerformed(final ActionEvent ae) { dispatcher.exec(new Runnable() { public void run() { String command = ae.getActionCommand(); if (command.startsWith("Job")) { if (Utils.checkYN("Really cancel job?")) { project.getLoader().quitJob(command); repairGUI(); } return; } else if (command.equals("Move to top")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.TOP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move up")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.UP, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move down")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.DOWN, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Move to bottom")) { if (null == active) return; canvas.setUpdateGraphics(true); layer.getParent().move(LayerSet.BOTTOM, active); Display.repaint(layer.getParent(), active, 5); //Display.updatePanelIndex(layer, active); } else if (command.equals("Duplicate, link and send to next layer")) { duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer)); } else if (command.equals("Duplicate, link and send to previous layer")) { duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer)); } else if (command.equals("Duplicate, link and send to...")) { // fix non-scrolling popup menu GenericDialog gd = new GenericDialog("Send to"); gd.addMessage("Duplicate, link and send to..."); String[] sl = new String[layer.getParent().size()]; int next = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { sl[next++] = project.findLayerThing(it.next()).toString(); } gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]); gd.showDialog(); if (gd.wasCanceled()) return; Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (layer == la) { Utils.showMessage("Can't duplicate, link and send to the same layer."); return; } duplicateLinkAndSendTo(active, 0, la); } else if (-1 != command.indexOf("z = ")) { // this is an item from the "Duplicate, link and send to" menu of layer z's Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1))); Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__"); if (null == target_layer) return; duplicateLinkAndSendTo(active, 0, target_layer); } else if (-1 != command.indexOf("z=")) { // WARNING the indexOf is very similar to the previous one // Send the linked group to the selected layer int iz = command.indexOf("z=")+2; Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2)); int end = command.indexOf(' ', iz); if (-1 == end) end = command.length(); double lz = Double.parseDouble(command.substring(iz, end)); Layer target = layer.getParent().getLayer(lz); HashSet hs = active.getLinkedGroup(new HashSet()); layer.getParent().move(hs, active.getLayer(), target); } else if (command.equals("Unlink")) { if (null == active || active instanceof Patch) return; active.unlink(); updateSelection();//selection.update(); } else if (command.equals("Unlink from images")) { if (null == active) return; try { for (Displayable displ: selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } } else if (command.equals("Unlink slices")) { YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo."); if (!yn.yesPressed()) return; final ArrayList<Patch> pa = ((Patch)active).getStackPatches(); for (int i=pa.size()-1; i>0; i--) { pa.get(i).unlink(pa.get(i-1)); } } else if (command.equals("Send to next layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers selection.moveDown(); repaint(layer.getParent(), box); } else if (command.equals("Send to previous layer")) { Rectangle box = selection.getBox(); try { // unlink Patch instances for (final Displayable displ : selection.getSelected()) { displ.unlinkAll(Patch.class); } updateSelection();//selection.update(); } catch (Exception e) { IJError.print(e); } //layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers selection.moveUp(); repaint(layer.getParent(), box); } else if (command.equals("Show centered")) { if (active == null) return; showCentered(active); } else if (command.equals("Delete...")) { /* if (null != active) { Displayable d = active; selection.remove(d); d.remove(true); // will repaint } */ // remove all selected objects selection.deleteAll(); } else if (command.equals("Color...")) { IJ.doCommand("Color Picker..."); } else if (command.equals("Revert")) { if (null == active || active.getClass() != Patch.class) return; Patch p = (Patch)active; if (!p.revert()) { if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId()); else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId()); } } else if (command.equals("Undo")) { layer.getParent().undoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Redo")) { layer.getParent().redoOneStep(); Display.repaint(layer.getParent()); } else if (command.equals("Transform")) { if (null == active) return; canvas.setTransforming(true); } else if (command.equals("Apply transform")) { if (null == active) return; canvas.setTransforming(false); } else if (command.equals("Cancel transform")) { if (null == active) return; canvas.cancelTransform(); } else if (command.equals("Specify transform...")) { if (null == active) return; selection.specify(); } else if (command.equals("Hide all but images")) { ArrayList<Class> type = new ArrayList<Class>(); type.add(Patch.class); selection.removeAll(layer.getParent().hideExcept(type, false)); Display.update(layer.getParent(), false); } else if (command.equals("Unhide all")) { layer.getParent().setAllVisible(false); Display.update(layer.getParent(), false); } else if (command.startsWith("Hide all ")) { String type = command.substring(9, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); selection.removeAll(layer.getParent().setVisible(type, false, true)); } else if (command.startsWith("Unhide all ")) { String type = command.substring(11, command.length() -1); // skip the ending plural 's' type = type.substring(0, 1).toUpperCase() + type.substring(1); layer.getParent().setVisible(type, true, true); } else if (command.equals("Hide deselected")) { hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers())); } else if (command.equals("Hide deselected except images")) { hideDeselected(true); } else if (command.equals("Hide selected")) { selection.setVisible(false); // TODO should deselect them too? I don't think so. } else if (command.equals("Resize canvas/LayerSet...")) { resizeCanvas(); } else if (command.equals("Autoresize canvas/LayerSet")) { layer.getParent().setMinimumDimensions(); } else if (command.equals("Import image")) { importImage(); } else if (command.equals("Import next image")) { importNextImage(); } else if (command.equals("Import stack...")) { Display.this.getLayerSet().addLayerContentStep(layer); Rectangle sr = getCanvas().getSrcRect(); Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import sequence as grid...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import from text file...")) { Display.this.getLayerSet().addLayerContentStep(layer); Bureaucrat burro = project.getLoader().importImages(layer); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addLayerContentStep(layer); }}); } else if (command.equals("Import labels as arealists...")) { Display.this.getLayerSet().addChangeTreesStep(); Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false); burro.addPostTask(new Runnable() { public void run() { Display.this.getLayerSet().addChangeTreesStep(); }}); } else if (command.equals("Make flat image...")) { // if there's a ROI, just use that as cropping rectangle Rectangle srcRect = null; Roi roi = canvas.getFakeImagePlus().getRoi(); if (null != roi) { srcRect = roi.getBounds(); } else { // otherwise, whatever is visible //srcRect = canvas.getSrcRect(); // The above is confusing. That is what ROIs are for. So paint all: srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight())); } double scale = 1.0; final String[] types = new String[]{"8-bit grayscale", "RGB Color"}; int the_type = ImagePlus.GRAY8; final GenericDialog gd = new GenericDialog("Choose", frame); gd.addSlider("Scale: ", 1, 100, 100); gd.addChoice("Type: ", types, types[0]); if (layer.getParent().size() > 1) { /* String[] layers = new String[layer.getParent().size()]; int i = 0; for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) { layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString(); i++; } int i_layer = layer.getParent().indexOf(layer); gd.addChoice("Start: ", layers, layers[i_layer]); gd.addChoice("End: ", layers, layers[i_layer]); */ Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros gd.addCheckbox("Include non-empty layers only", true); } gd.addMessage("Background color:"); Utils.addRGBColorSliders(gd, Color.black); gd.addCheckbox("Best quality", false); gd.addMessage(""); gd.addCheckbox("Save to file", false); gd.addCheckbox("Save for web", false); gd.showDialog(); if (gd.wasCanceled()) return; scale = gd.getNextNumber() / 100; the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB); if (Double.isNaN(scale) || scale <= 0.0) { Utils.showMessage("Invalid scale."); return; } Layer[] layer_array = null; boolean non_empty_only = false; if (layer.getParent().size() > 1) { non_empty_only = gd.getNextBoolean(); int i_start = gd.getNextChoiceIndex(); int i_end = gd.getNextChoiceIndex(); ArrayList al = new ArrayList(); ArrayList al_zd = layer.getParent().getZDisplayables(); ZDisplayable[] zd = new ZDisplayable[al_zd.size()]; al_zd.toArray(zd); for (int i=i_start, j=0; i <= i_end; i++, j++) { Layer la = layer.getParent().getLayer(i); if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet } if (0 == al.size()) { Utils.showMessage("All layers are empty!"); return; } layer_array = new Layer[al.size()]; al.toArray(layer_array); } else { layer_array = new Layer[]{Display.this.layer}; } final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber()); final boolean quality = gd.getNextBoolean(); final boolean save_to_file = gd.getNextBoolean(); final boolean save_for_web = gd.getNextBoolean(); // in its own thread if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type); else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background); } else if (command.equals("Lock")) { selection.setLocked(true); } else if (command.equals("Unlock")) { selection.setLocked(false); } else if (command.equals("Properties...")) { active.adjustProperties(); updateSelection(); } else if (command.equals("Cancel alignment")) { layer.getParent().cancelAlign(); } else if (command.equals("Align with landmarks")) { layer.getParent().applyAlign(false); } else if (command.equals("Align and register")) { layer.getParent().applyAlign(true); } else if (command.equals("Align using profiles")) { if (!selection.contains(Profile.class)) { Utils.showMessage("No profiles are selected."); return; } // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex()); Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex()); if (la_start == la_end) { Utils.showMessage("Need at least two layers."); return; } if (selection.isLocked()) { Utils.showMessage("There are locked objects."); return; } layer.getParent().startAlign(Display.this); layer.getParent().applyAlign(la_start, la_end, selection); } else if (command.equals("Align stack slices")) { if (getActive() instanceof Patch) { final Patch slice = (Patch)getActive(); if (slice.isStack()) { // check linked group final HashSet hs = slice.getLinkedGroup(new HashSet()); for (Iterator it = hs.iterator(); it.hasNext(); ) { if (it.next().getClass() != Patch.class) { Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that return; } } final LayerSet ls = slice.getLayerSet(); final HashSet<Displayable> linked = slice.getLinkedGroup(null); ls.addTransformStep(linked); Bureaucrat burro = Registration.registerStackSlices((Patch)getActive()); // will repaint burro.addPostTask(new Runnable() { public void run() { // The current state when done ls.addTransformStep(linked); }}); } else { Utils.log("Align stack slices: selected image is not part of a stack."); } } } else if (command.equals("Align layers (layer-wise)")) { final Layer la = layer; la.getParent().addTransformStep(la); Bureaucrat burro = AlignTask.alignLayersLinearlyTask( layer ); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(la); }}); } else if (command.equals("Align layers (tile-wise global minimization)")) { final Layer la = layer; // caching, since scroll wheel may change it la.getParent().addTransformStep(); Bureaucrat burro = Registration.registerLayers(la, Registration.GLOBAL_MINIMIZATION); burro.addPostTask(new Runnable() { public void run() { la.getParent().addTransformStep(); }}); } else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects. GenericDialog gd = new GenericDialog("Properties", Display.this.frame); //gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0); gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step); gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]); gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality()); Loader lo = getProject().getLoader(); boolean using_mipmaps = lo.isMipMapsEnabled(); gd.addCheckbox("enable_mipmaps", using_mipmaps); String preprocessor = project.getLoader().getPreprocessor(); gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor); gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled()); double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight(); gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension()); // -------- gd.showDialog(); if (gd.wasCanceled()) return; // -------- int sc = (int) gd.getNextNumber(); if (sc < 1) sc = 1; Display.this.scroll_step = sc; updateInDatabase("scroll_step"); // layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex()); layer.getParent().setSnapshotsQuality(gd.getNextBoolean()); // boolean generate_mipmaps = gd.getNextBoolean(); if (using_mipmaps && generate_mipmaps) { // nothing changed } else { if (using_mipmaps) { // and !generate_mipmaps lo.flushMipMaps(true); } else { // not using mipmaps before, and true == generate_mipmaps lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class)); } } // final String prepro = gd.getNextString(); if (!project.getLoader().setPreprocessor(prepro.trim())) { Utils.showMessage("Could NOT set the preprocessor to " + prepro); } // layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean()); layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber()); } else if (command.equals("Search...")) { new Search(); } else if (command.equals("Select all")) { selection.selectAll(); repaint(Display.this.layer, selection.getBox(), 0); } else if (command.equals("Select none")) { Rectangle box = selection.getBox(); selection.clear(); repaint(Display.this.layer, box, 0); } else if (command.equals("Restore selection")) { selection.restore(); } else if (command.equals("Select under ROI")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; selection.selectAll(roi, true); } else if (command.equals("Merge")) { ArrayList al_sel = selection.getSelected(); // put active at the beginning, to work as the base on which other's will get merged al_sel.remove(Display.this.active); al_sel.add(0, Display.this.active); AreaList ali = AreaList.merge(al_sel); if (null != ali) { // remove all but the first from the selection for (int i=1; i<al_sel.size(); i++) { Object ob = al_sel.get(i); if (ob.getClass() == AreaList.class) { selection.remove((Displayable)ob); } } selection.updateTransform(ali); repaint(ali.getLayerSet(), ali, 0); } } else if (command.equals("Identify...")) { // for pipes only for now if (!(active instanceof Pipe)) return; ini.trakem2.vector.Compare.findSimilar((Pipe)active); } else if (command.equals("Identify with axes...")) { if (!(active instanceof Pipe)) return; if (Project.getProjects().size() < 2) { Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify"); return; } ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active); } else if (command.equals("View orthoslices")) { if (!(active instanceof Patch)) return; Display3D.showOrthoslices(((Patch)active)); } else if (command.equals("View volume")) { if (!(active instanceof Patch)) return; Display3D.showVolume(((Patch)active)); } else if (command.equals("Show in 3D")) { for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); Display3D.show(zd.getProject().findProjectThing(zd)); } // handle profile lists ... HashSet hs = new HashSet(); for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent(); if (!hs.contains(profile_list)) { Display3D.show(profile_list); hs.add(profile_list); } } } else if (command.equals("Snap")) { if (!(active instanceof Patch)) return; StitchingTEM.snap(getActive(), Display.this); } else if (command.equals("Montage")) { if (!(active instanceof Patch)) { Utils.showMessage("Please select only images."); return; } final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected()); for (final Displayable d : affected) if (d.isLinked()) { Utils.showMessage( "You cannot montage linked objects." ); return; } // make an undo step! final LayerSet ls = layer.getParent(); ls.addTransformStep(affected); Bureaucrat burro = AlignTask.alignSelectionTask( selection ); burro.addPostTask(new Runnable() { public void run() { ls.addTransformStep(affected); }}); } else if (command.equals("Link images...")) { GenericDialog gd = new GenericDialog("Options"); gd.addMessage("Linking images to images (within their own layer only):"); String[] options = {"all images to all images", "each image with any other overlapping image"}; gd.addChoice("Link: ", options, options[1]); String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"}; gd.addChoice("Apply to: ", options2, options2[0]); gd.showDialog(); if (gd.wasCanceled()) return; boolean overlapping_only = 1 == gd.getNextChoiceIndex(); switch (gd.getNextChoiceIndex()) { case 0: Patch.crosslink(selection.getSelected(Patch.class), overlapping_only); break; case 1: Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only); break; case 2: for (final Layer la : layer.getParent().getLayers()) { Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only); } break; } } else if (command.equals("Enhance contrast (selected images)...")) { ArrayList al = selection.getSelected(Patch.class); getProject().getLoader().homogenizeContrast(al); } else if (command.equals("Enhance contrast layer-wise...")) { // ask for range of layers final GenericDialog gd = new GenericDialog("Choose range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end Layer[] la = new Layer[list.size()]; list.toArray(la); project.getLoader().homogenizeContrast(la); } else if (command.equals("Set Min and Max layer-wise...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all images in the layer range"); Utils.addLayerRangeChoices(Display.this.layer, gd); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); ArrayList<Displayable> al = new ArrayList<Displayable>(); for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end al.addAll(la.getDisplayables(Patch.class)); } project.getLoader().setMinAndMax(al, min, max); } else if (command.equals("Set Min and Max (selected images)...")) { Displayable active = getActive(); double min = 0; double max = 0; if (null != active && active.getClass() == Patch.class) { min = ((Patch)active).getMin(); max = ((Patch)active).getMax(); } final GenericDialog gd = new GenericDialog("Min and Max"); gd.addMessage("Set min and max to all selected images"); gd.addNumericField("min: ", min, 2); gd.addNumericField("max: ", max, 2); gd.showDialog(); if (gd.wasCanceled()) return; // min = gd.getNextNumber(); max = gd.getNextNumber(); project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max); } else if (command.equals("Enhance contrast (selected images)...")) { Utils.log("Not implemented yet"); } else if (command.equals("Enhance contrast layer-wise...")) { Utils.log("Not implemented yet"); } else if (command.equals("Create subproject")) { Roi roi = canvas.getFakeImagePlus().getRoi(); if (null == roi) return; // the menu item is not active unless there is a ROI Layer first, last; if (1 == layer.getParent().size()) { first = last = layer; } else { GenericDialog gd = new GenericDialog("Choose layer range"); Utils.addLayerRangeChoices(layer, gd); gd.showDialog(); if (gd.wasCanceled()) return; first = layer.getParent().getLayer(gd.getNextChoiceIndex()); last = layer.getParent().getLayer(gd.getNextChoiceIndex()); Utils.log2("first, last: " + first + ", " + last); } Project sub = getProject().createSubproject(roi.getBounds(), first, last); final LayerSet subls = sub.getRootLayerSet(); final Display d = new Display(sub, subls.getLayer(0)); SwingUtilities.invokeLater(new Runnable() { public void run() { d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight())); }}); } else if (command.startsWith("Arealists as labels")) { GenericDialog gd = new GenericDialog("Export labels"); gd.addSlider("Scale: ", 1, 100, 100); final String[] options = {"All area list", "Selected area lists"}; gd.addChoice("Export: ", options, options[0]); Utils.addLayerRangeChoices(layer, gd); gd.addCheckbox("Visible only", true); gd.showDialog(); if (gd.wasCanceled()) return; final float scale = (float)(gd.getNextNumber() / 100); java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class); if (null == al) { Utils.log("No area lists found to export."); return; } // Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame? al = (java.util.List<Displayable>) al; int first = gd.getNextChoiceIndex(); int last = gd.getNextChoiceIndex(); boolean visible_only = gd.getNextBoolean(); if (-1 != command.indexOf("(amira)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true); } else if (-1 != command.indexOf("(tif)")) { AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false); } } else if (command.equals("Project properties...")) { project.adjustProperties(); } else if (command.equals("Release memory...")) { Bureaucrat.createAndStart(new Worker("Releasing memory") { public void run() { startedWorking(); try { GenericDialog gd = new GenericDialog("Release Memory"); int max = (int)(IJ.maxMemory() / 1000000); gd.addSlider("Megabytes: ", 0, max, max/2); gd.showDialog(); if (!gd.wasCanceled()) { int n_mb = (int)gd.getNextNumber(); project.getLoader().releaseToFit((long)n_mb*1000000); } } catch (Throwable e) { IJError.print(e); } finally { finishedWorking(); } } }, project); } else if (command.equals("Flush image cache")) { Loader.releaseAllCaches(); } else { Utils.log2("Display: don't know what to do with command " + command); } }});
diff --git a/src/test/DataTypeTests.java b/src/test/DataTypeTests.java index 1e12c33894..6a6bfe974b 100644 --- a/src/test/DataTypeTests.java +++ b/src/test/DataTypeTests.java @@ -1,979 +1,982 @@ package test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.meta_environment.rascal.interpreter.control_exceptions.Throw; import org.meta_environment.rascal.interpreter.staticErrors.StaticError; import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredFieldError; import org.meta_environment.rascal.interpreter.staticErrors.UninitializedVariableError; public class DataTypeTests extends TestFramework { @Test public void bool() { assertTrue(runTest("true == true;")); assertFalse(runTest("true == false;")); assertTrue(runTest("true != false;")); assertTrue(runTest("(!true) == false;")); assertTrue(runTest("(!false) == true;")); assertTrue(runTest("(true && true) == true;")); assertTrue(runTest("(true && false) == false;")); assertTrue(runTest("(false && true) == false;")); assertTrue(runTest("(false && false) == false;")); assertTrue(runTest("(true || true) == true;")); assertTrue(runTest("(true || false) == true;")); assertTrue(runTest("(false || true) == true;")); assertTrue(runTest("(false || false) == false;")); assertTrue(runTest("(true ==> true) == true;")); assertTrue(runTest("(true ==> false) == false;")); assertTrue(runTest("(false ==> true) == true;")); assertTrue(runTest("(false ==> false) == true;")); assertTrue(runTest("(true <==> true) == true;")); assertTrue(runTest("(true <==> false) == false;")); assertTrue(runTest("(false <==> true) == false;")); assertTrue(runTest("(false <==> false) == true;")); assertTrue(runTest("false <= false;")); assertTrue(runTest("false <= true;")); assertFalse(runTest("true <= false;")); assertTrue(runTest("true <= true;")); assertFalse(runTest("false < false;")); assertTrue(runTest("false < true;")); assertFalse(runTest("true < false;")); assertFalse(runTest("true < true;")); assertTrue(runTest("false >= false;")); assertTrue(runTest("true >= false;")); assertFalse(runTest("false >= true;")); assertTrue(runTest("true >= true;")); assertFalse(runTest("false > false;")); assertTrue(runTest("true > false;")); assertFalse(runTest("false > true;")); assertFalse(runTest("true > true;")); } @Test(expected=StaticError.class) public void andError() { runTest("3 && true;"); } @Test(expected=StaticError.class) public void impError() { runTest("3 ==> true;"); } @Test(expected=StaticError.class) public void condExpError() { runTest("1 ? 2 : 3;"); } @Test public void testInt() { assertTrue(runTest("1 == 1;")); assertTrue(runTest("1 != 2;")); assertTrue(runTest("-1 == -1;")); assertTrue(runTest("-1 != 1;")); assertTrue(runTest("1 + 1 == 2;")); assertTrue(runTest("-1 + 2 == 1;")); assertTrue(runTest("1 + (-2) == -1;")); assertTrue(runTest("2 - 1 == 1;")); assertTrue(runTest("2 - 3 == -1;")); assertTrue(runTest("2 - -1 == 3;")); assertTrue(runTest("-2 - 1 == -3;")); assertTrue(runTest("2 * 3 == 6;")); assertTrue(runTest("-2 * 3 == -6;")); assertTrue(runTest("2 * (-3) == -6;")); assertTrue(runTest("-2 * (-3) == 6;")); assertTrue(runTest("8 / 4 == 2;")); assertTrue(runTest("-8 / 4 == -2;")); assertTrue(runTest("8 / -4 == -2;")); assertTrue(runTest("-8 / -4 == 2;")); assertTrue(runTest("7 / 2 == 3;")); assertTrue(runTest("-7 / 2 == -3;")); assertTrue(runTest("7 / -2 == -3;")); assertTrue(runTest("-7 / -2 == 3;")); assertTrue(runTest("0 / 5 == 0;")); assertTrue(runTest("5 / 1 == 5;")); assertTrue(runTest("5 % 2 == 1;")); assertTrue(runTest("-5 % 2 == -1;")); assertTrue(runTest("5 % -2 == 1;")); assertTrue(runTest("-2 <= -1;")); assertTrue(runTest("-2 <= 1;")); assertTrue(runTest("1 <= 2;")); assertTrue(runTest("2 <= 2;")); assertFalse(runTest("2 <= 1;")); assertTrue(runTest("-2 < -1;")); assertTrue(runTest("-2 < 1;")); assertTrue(runTest("1 < 2;")); assertFalse(runTest("2 < 2;")); assertTrue(runTest("-1 >= -2;")); assertTrue(runTest("1 >= -1;")); assertTrue(runTest("2 >= 1;")); assertTrue(runTest("2 >= 2;")); assertFalse(runTest("1 >= 2;")); assertTrue(runTest("-1 > -2;")); assertTrue(runTest("1 > -1;")); assertTrue(runTest("2 > 1;")); assertFalse(runTest("2 > 2;")); assertFalse(runTest("1 > 2;")); assertTrue(runTest("(3 > 2 ? 3 : 2) == 3;")); } @Test(expected=StaticError.class) public void addError() { runTest("3 + true;"); } @Test(expected=StaticError.class) public void subError() { runTest("3 - true;"); } @Test(expected=StaticError.class) public void uMinusError() { runTest("- true;"); } @Test(expected=StaticError.class) public void timesError() { runTest("3 * true;"); } @Test(expected=StaticError.class) public void divError() { runTest("3 / true;"); } @Test(expected=StaticError.class) public void modError() { runTest("3 % true;"); } @Test public void valueEquals() { assertTrue(runTest("{value x = 1.0; value y = 2; x != y; }")); } @Test public void real() { assertTrue(runTest("1.0 == 1.0;")); assertTrue(runTest("1.0 != 2.0;")); assertTrue(runTest("-1.0 == -1.0;")); assertTrue(runTest("-1.0 != 1.0;")); assertTrue(runTest("1.0 == 1;")); + assertTrue(runTest("1.00 == 1.0;")); assertTrue(runTest("1 == 1.0;")); assertTrue(runTest("{value x = 1.0; value y = 1; x == y; }")); assertTrue(runTest("{value x = 1.0; value y = 2; x != y; }")); assertTrue(runTest("1.0 + 1.0 == 2.0;")); assertTrue(runTest("-1.0 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2.0) == -1.0;")); assertTrue(runTest("1.0 + 1 == 2.0;")); assertTrue(runTest("-1 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2) == -1.0;")); assertTrue(runTest("2.0 - 1.0 == 1.0;")); assertTrue(runTest("2.0 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1.0 == 3.0;")); assertTrue(runTest("-2.0 - 1.0 == -3.0;")); assertTrue(runTest("2.0 - 1 == 1.0;")); assertTrue(runTest("2 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1 == 3.0;")); assertTrue(runTest("-2 - 1.0 == -3.0;")); - assertTrue(runTest("2.0 * 3.0 == 6.0;")); - assertTrue(runTest("-2.0 * 3.0 == -6.0;")); - assertTrue(runTest("2.0 * (-3.0) == -6.0;")); - assertTrue(runTest("-2.0 * (-3.0) == 6.0;")); + assertTrue(runTest("2.0 * 3.0 == 6.00;")); + assertTrue(runTest("-2.0 * 3.0 == -6.00;")); + assertTrue(runTest("2.0 * (-3.0) == -6.00;")); + assertTrue(runTest("-2.0 * (-3.0) == 6.00;")); assertTrue(runTest("2.0 * 3 == 6.0;")); assertTrue(runTest("-2 * 3.0 == -6.0;")); assertTrue(runTest("2.0 * (-3) == -6.0;")); assertTrue(runTest("-2 * (-3.0) == 6.0;")); - assertTrue(runTest("8.0 / 4.0 == 2.0;")); - assertTrue(runTest("-8.0 / 4.0 == -2.0;")); - assertTrue(runTest("8.0 / -4.0 == -2.0;")); - assertTrue(runTest("-8.0 / -4.0 == 2.0;")); + assertTrue(runTest("8.0 / 4.0 == 2e0;")); + assertTrue(runTest("-8.0 / 4.0 == -2e0;")); + assertTrue(runTest("8.0 / -4.0 == -2e0;")); + assertTrue(runTest("-8.0 / -4.0 == 2e0;")); + // TODO, I don't get it, why does the previous have 1 digit precision and this + // one two digits assertTrue(runTest("7.0 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2.0 == -3.5;")); assertTrue(runTest("7.0 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2.0 == 3.5;")); assertTrue(runTest("0.0 / 5.0 == 0.0;")); assertTrue(runTest("5.0 / 1.0 == 5.0;")); assertTrue(runTest("7 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2 == -3.5;")); assertTrue(runTest("7 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2 == 3.5;")); assertTrue(runTest("-2.0 <= -1.0;")); assertTrue(runTest("-2.0 <= 1.0;")); assertTrue(runTest("1.0 <= 2.0;")); assertTrue(runTest("2.0 <= 2.0;")); assertFalse(runTest("2.0 <= 1.0;")); assertTrue(runTest("-2 <= -1.0;")); assertTrue(runTest("-2.0 <= 1;")); assertTrue(runTest("1 <= 2.0;")); assertTrue(runTest("2.0 <= 2;")); assertFalse(runTest("2 <= 1.0;")); assertTrue(runTest("-2.0 < -1.0;")); assertTrue(runTest("-2.0 < 1.0;")); assertTrue(runTest("1.0 < 2.0;")); assertFalse(runTest("2.0 < 2.0;")); assertTrue(runTest("-2 < -1.0;")); assertTrue(runTest("-2.0 < 1;")); assertTrue(runTest("1 < 2.0;")); assertFalse(runTest("2.0 < 2;")); assertTrue(runTest("-1.0 >= -2.0;")); assertTrue(runTest("1.0 >= -1.0;")); assertTrue(runTest("2.0 >= 1.0;")); assertTrue(runTest("2.0 >= 2.0;")); assertFalse(runTest("1.0 >= 2.0;")); assertTrue(runTest("-1 >= -2.0;")); assertTrue(runTest("1.0 >= -1;")); assertTrue(runTest("2 >= 1.0;")); assertTrue(runTest("2.0 >= 2;")); assertFalse(runTest("1 >= 2.0;")); assertTrue(runTest("-1.0 > -2.0;")); assertTrue(runTest("1.0 > -1.0;")); assertTrue(runTest("2.0 > 1.0;")); assertFalse(runTest("2.0 > 2.0;")); assertFalse(runTest("1.0 > 2.0;")); assertTrue(runTest("-1 > -2.0;")); assertTrue(runTest("1.0 > -1;")); assertTrue(runTest("2 > 1.0;")); assertFalse(runTest("2.0 > 2;")); assertFalse(runTest("1 > 2.0;")); assertTrue(runTest("3.5 > 2.5 ? 3.5 : 2.5 == 3.5;")); assertTrue(runTest("3.5 > 2 ? 3.5 : 2 == 3.5;")); assertTrue(runTest("3.5 > 4 ? 3.5 : 2 == 2;")); } @Test public void testString() { assertTrue(runTest("\"\" == \"\";")); assertTrue(runTest("\"abc\" != \"\";")); assertTrue(runTest("\"abc\" == \"abc\";")); assertTrue(runTest("\"abc\" != \"def\";")); assertTrue(runTest("\"abc\" + \"\" == \"abc\";")); assertTrue(runTest("\"abc\" + \"def\" == \"abcdef\";")); assertTrue(runTest("\"\" <= \"\";")); assertTrue(runTest("\"\" <= \"abc\";")); assertTrue(runTest("\"abc\" <= \"abc\";")); assertTrue(runTest("\"abc\" <= \"def\";")); assertFalse(runTest("\"\" < \"\";")); assertTrue(runTest("\"\" < \"abc\";")); assertFalse(runTest("\"abc\" < \"abc\";")); assertTrue(runTest("\"abc\" < \"def\";")); assertTrue(runTest("\"\" >= \"\";")); assertTrue(runTest("\"abc\" >= \"\";")); assertTrue(runTest("\"abc\" >= \"abc\";")); assertTrue(runTest("\"def\" >= \"abc\";")); assertFalse(runTest("\"\" > \"\";")); assertTrue(runTest("\"abc\" > \"\";")); assertFalse(runTest("\"abc\" > \"abc\";")); assertTrue(runTest("\"def\" > \"abc\";")); } @Test(expected=StaticError.class) public void orError() { runTest("3 || true;"); } @Test public void testLocation() { String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; String Loc2 = "loc(file:/home/paulk/pico2.trm?offset=0&length=1&begin=2,3&end=4,5)"; assertTrue(runTest("{" + Loc + "; true;}")); assertTrue(runTest(Loc + " == " + Loc + ";")); assertFalse(runTest(Loc + " == " + Loc2 + ";")); assertTrue(runTest(Loc + ".url == \"file:/home/paulk/pico.trm\";")); assertTrue(runTest(Loc + ".offset == 0;")); assertTrue(runTest(Loc + ".length == 1;")); assertTrue(runTest(Loc + ".beginLine == 2;")); assertTrue(runTest(Loc + ".beginColumn == 3;")); assertTrue(runTest(Loc + ".endLine == 4;")); assertTrue(runTest(Loc + ".endColumn == 5;")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.url == \"file:/home/paulk/pico.trm\";}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.offset == 0;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.length == 1;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.beginLine == 2;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.beginColumn == 3;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.endLine == 4;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.endColumn == 5;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.url = \"file:/home/paulk/pico2.trm\"; Loc.url == \"file:/home/paulk/pico2.trm\";}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.offset = 10; Loc.offset == 10;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.length = 11; Loc.length == 11;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.endLine = 14; Loc.endLine == 14;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.beginLine = 1; Loc.beginLine == 1;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.beginColumn = 13; Loc.beginColumn == 13;}")); assertTrue(runTest("{ loc Loc = " + Loc + "; Loc.endColumn = 15; Loc.endColumn == 15;}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[url= \"file:/home/paulk/pico2.trm\"]; Loc == loc(file:/home/paulk/pico2.trm?offset=0&length=1&begin=2,3&end=4,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[offset = 10]; Loc == loc(file:/home/paulk/pico.trm?offset=10&length=1&begin=2,3&end=4,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[length = 11]; Loc == loc(file:/home/paulk/pico.trm?offset=0&length=11&begin=2,3&end=4,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[beginLine = 1]; Loc == loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=1,3&end=4,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[beginColumn = 13]; Loc == loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,13&end=4,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[endLine = 14]; Loc == loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=14,5);}")); assertTrue(runTest("{loc Loc = " + Loc + "; Loc = Loc[endColumn = 15]; Loc == loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,15);}")); } @Test(expected=UninitializedVariableError.class) public void UndefinedLocationError1(){ runTest("{ loc Loc; Loc.url;}"); } @Test(expected=UninitializedVariableError.class) public void UndefinedLocationError2(){ runTest("{ loc Loc; Loc.url = \"abc\";}"); } @Test(expected=UninitializedVariableError.class) public void UndefinedLocationError3(){ runTest("{ loc Loc; Loc[url = \"abc\"];}"); } @Test(expected=StaticError.class) public void WrongLocFieldError1(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.bla;}"); } @Test(expected=StaticError.class) public void WrongLocFieldError2(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest(Loc + "[bla=3];"); } @Test(expected=StaticError.class) public void URLFieldError1(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.url=true;}"); } @Test(expected=StaticError.class) public void URLFieldError2(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.url=\"???\";}"); } @Test(expected=StaticError.class) public void LengthFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.length=true;}"); } @Test(expected=StaticError.class) public void OffsetFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.offset=true;}"); } @Test(expected=StaticError.class) public void BeginLineFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.beginLine=true;}"); } @Test(expected=StaticError.class) public void EndLineFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.endLine=true;}"); } @Test(expected=StaticError.class) public void BeginColumnFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.beginColumn=true;}"); } @Test(expected=StaticError.class) public void EndColumnFieldError(){ String Loc = "loc(file:/home/paulk/pico.trm?offset=0&length=1&begin=2,3&end=4,5)"; runTest("{loc Loc = " + Loc + "; Loc.endColumn=true;}"); } @Test public void testList() { assertTrue(runTest("[] == [];")); assertTrue(runTest("[] != [1];")); assertTrue(runTest("[1] == [1];")); assertTrue(runTest("[1] != [2];")); assertTrue(runTest("[1, 2] == [1, 2];")); assertTrue(runTest("[1, 2] != [2, 1];")); assertTrue(runTest("[] + [] == [];")); assertTrue(runTest("[1, 2, 3] + [] == [1, 2, 3];")); assertTrue(runTest("[] + [1, 2, 3] == [1, 2, 3];")); assertTrue(runTest("[1, 2] + [3, 4, 5] == [1, 2, 3, 4, 5];")); assertTrue(runTest("([1, 2] + [3, 4]) + [5] == [1, 2, 3, 4, 5];")); assertTrue(runTest("[1, 2] + ([3, 4] + [5]) == [1, 2, 3, 4, 5];")); assertTrue(runTest("[1, 2] + [3, 4] + [5] == [1, 2, 3, 4, 5];")); assertTrue(runTest("[1, 2] + 3 == [1, 2, 3];")); assertTrue(runTest("1 + [2, 3] == [1, 2, 3];")); assertTrue(runTest("[1,1,2,2,3,3,4,4,5] - [1,2,4] == [3,3,5];")); assertTrue(runTest("[1,2,3,4,5,4,3,2,1] - [1,2,4] == [3,5,3];")); assertTrue(runTest("[] <= [];")); assertTrue(runTest("[] <= [1];")); // These commented out tests assume that <= etc. are ("half") ordering operations // Currently they are strictly subset implementations. // assertTrue(runTest("[2, 1, 0] <= [2, 3];")); // assertTrue(runTest("[2, 1] <= [2, 3, 0];")); assertTrue(runTest("[2, 1] <= [2, 1];")); assertTrue(runTest("[2, 1] <= [2, 1, 0];")); assertTrue(runTest("[] < [1];")); // assertTrue(runTest("[2, 1, 0] < [2, 3];")); // assertTrue(runTest("[2, 1] < [2, 3, 0];")); assertTrue(runTest("[2, 1] < [2, 1, 0];")); assertTrue(runTest("[] >= [];")); // assertTrue(runTest("[1] >= [];")); // assertTrue(runTest("[2, 3] >= [2, 1, 0];")); // assertTrue(runTest("[2, 3, 0] >= [2, 1];")); assertTrue(runTest("[2, 1] >= [2, 1];")); assertTrue(runTest("[2, 1, 0] >= [2, 1];")); assertTrue(runTest("[1] > [];")); // assertTrue(runTest("[2, 3] > [2, 1, 0];")); // assertTrue(runTest("[2, 3, 0] > [2, 1];")); assertTrue(runTest("[2, 1, 0] > [2, 1];")); assertTrue(runTest("[] * [] == [];")); assertTrue(runTest("[1] * [9] == [<1,9>];")); assertTrue(runTest("[1, 2] * [9] == [<1,9>, <2,9>];")); assertTrue(runTest("[1, 2, 3] * [9] == [<1,9>, <2,9>, <3,9>];")); assertTrue(runTest("[1, 2, 3] * [9, 10] == [<1,9>, <1,10>, <2,9>, <2,10>, <3,9>, <3,10>];")); assertTrue(runTest("2 in [1, 2, 3];")); assertTrue(runTest("3 notin [2, 4, 6];")); assertTrue(runTest("2 > 3 ? [1,2] : [1,2,3] == [1,2,3];")); } @Test(expected=Throw.class) public void SubscriptError1() { runTest("[1,2][5];"); } @Test(expected=UninitializedVariableError.class) public void SubscriptError2() { runTest("L[5];"); } @Test public void testRange() { assertTrue(runTest("[1 .. 1] == [1];")); assertTrue(runTest("[1 .. 2] == [1, 2];")); assertTrue(runTest("[1 .. -1] == [1, 0, -1];")); assertTrue(runTest("[1, 2 .. 10] == [1,2,3,4,5,6,7,8,9,10];")); assertTrue(runTest("[1, 3 .. 10] == [1,3,5,7,9];")); assertTrue(runTest("[1, -2 .. 10] == [];")); assertTrue(runTest("[1, -3 .. -10] == [1,-3,-7];")); } @Test public void testSet() { assertTrue(runTest("{} == {};")); assertTrue(runTest("{} != {1};")); assertTrue(runTest("{1} == {1};")); assertTrue(runTest("{1} != {2};")); assertTrue(runTest("{1, 2} == {1, 2};")); assertTrue(runTest("{1, 2} == {2, 1};")); assertTrue(runTest("{1, 2, 3, 1, 2, 3} == {3, 2, 1};")); assertTrue(runTest("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};")); assertTrue(runTest("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};")); assertTrue(runTest("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == {10, 9, 3, 4, 5, 6, 7, 8, 2, 1};")); assertTrue(runTest("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == {10, 9, 7, 4, 5, 6, 3, 8, 2, 1};")); assertTrue(runTest("{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == {10, 9, 7, 6, 5, 4, 3, 8, 2, 1};")); assertTrue(runTest("{{1}, {2}} == {{2}, {1}};")); assertTrue(runTest("{{}} == {{}};")); assertTrue(runTest("{{}, {}} == {{}};")); assertTrue(runTest("{{}, {}, {}} == {{}};")); assertTrue(runTest("{{1, 2}, {3,4}} == {{2,1}, {4,3}};")); assertTrue(runTest("{} + {} == {};")); assertTrue(runTest("{1, 2, 3} + {} == {1, 2, 3};")); assertTrue(runTest("{} + {1, 2, 3} == {1, 2, 3};")); assertTrue(runTest("{1, 2} + {3, 4, 5} == {1, 2, 3, 4, 5};")); assertTrue(runTest("{1, 2, 3, 4} + {3, 4, 5} == {1, 2, 3, 4, 5};")); assertTrue(runTest("{{1, 2}, {3,4}} + {{5,6}} == {{1,2},{3,4},{5,6}};")); assertTrue(runTest("1 + {2,3} == {1,2,3};")); assertTrue(runTest("{1,2} + 3 == {1,2,3};")); assertTrue(runTest("{} - {} == {};")); assertTrue(runTest("{1, 2, 3} - {} == {1, 2, 3};")); assertTrue(runTest("{} - {1, 2, 3} == {};")); assertTrue(runTest("{1, 2, 3} - {3, 4, 5} == {1, 2};")); assertTrue(runTest("{1, 2, 3, 4} - {1, 2, 3, 4, 5} == {};")); assertTrue(runTest("{{1, 2}, {3,4}, {5,6}} - {{3,4}} == {{1,2}, {5,6}};")); assertTrue(runTest("{1,2,3} - 3 == {1,2};")); assertTrue(runTest("{} & {} == {};")); assertTrue(runTest("{1, 2, 3} & {} == {};")); assertTrue(runTest("{} & {1, 2, 3} == {};")); assertTrue(runTest("{1, 2, 3} & {3, 4, 5} == {3};")); assertTrue(runTest("{1, 2, 3, 4} & {3, 4, 5} == {3, 4};")); assertTrue(runTest("{{1,2},{3,4},{5,6}} & {{2,1}, {8,7}, {6,5}} == {{1,2},{5,6}};")); assertTrue(runTest("{} <= {};")); assertTrue(runTest("{} <= {1};")); assertTrue(runTest("{2, 1} <= {1, 2};")); assertTrue(runTest("{2, 1} <= {1, 2, 3};")); assertTrue(runTest("{2, 1} <= {2, 1, 0};")); assertTrue(runTest("{} < {1};")); assertTrue(runTest("{2, 1} < {2, 1, 3};")); assertTrue(runTest("{} >= {};")); assertTrue(runTest("{1} >= {};")); assertTrue(runTest("{2, 3} >= {2};")); assertTrue(runTest("{1} > {};")); assertTrue(runTest("{2, 1, 3} > {2, 3};")); assertTrue(runTest("{} * {} == {};")); assertTrue(runTest("{1} * {9} == {<1,9>};")); assertTrue(runTest("{1, 2} * {9} == {<1,9>, <2,9>};")); assertTrue(runTest("{1, 2, 3} * {9} == {<1,9>, <2,9>, <3,9>};")); assertTrue(runTest("{1, 2, 3} * {9, 10} == {<1,9>, <1,10>, <2,9>, <2,10>, <3,9>, <3,10>};")); assertTrue(runTest("2 in {1, 2, 3};")); assertTrue(runTest("{4,3} in {{1, 2}, {3,4}, {5,6}};")); assertTrue(runTest("5 notin {1, 2, 3};")); assertTrue(runTest("{7,8} notin {{1, 2}, {3,4}, {5,6}};")); assertTrue(runTest("3 > 2 ? {1,2} : {1,2,3} == {1,2};")); assertTrue(runTest("{<\"a\", [1,2]>, <\"b\", []>, <\"c\", [4,5,6]>} != {};")); } @Test(expected=UninitializedVariableError.class) public void UndefinedSetElementError(){ runTest("{X};"); } @Test(expected=StaticError.class) public void inError() { runTest("1 in 3;"); } @Ignore @Test(expected=StaticError.class) public void addSetError() { runTest("{1,2,3} + true;"); } @Test(expected=StaticError.class) public void productError() { runTest("{1,2,3} * true;"); } @Test public void testMap() { assertTrue(runTest("() == ();")); assertTrue(runTest("(1:10) != ();")); assertTrue(runTest("(1:10) == (1:10);")); assertTrue(runTest("(1:10) != (2:20);")); assertTrue(runTest("() + () == ();")); assertTrue(runTest("(1:10) + () == (1:10);")); assertTrue(runTest("(1:10) + (2:20) == (1:10, 2:20);")); assertTrue(runTest("(1:10, 2:20) + (2:25) == (1:10, 2:25);")); assertTrue(runTest("() - () == ();")); assertTrue(runTest("(1:10, 2:20) - () == (1:10,2:20);")); assertTrue(runTest("(1:10, 2:20) - (2:20) == (1:10);")); assertTrue(runTest("(1:10, 2:20) - (2:25) == (1:10);")); // This is current behaviour; is this ok? assertTrue(runTest("() & () == ();")); assertTrue(runTest("(1:10) & () == ();")); assertTrue(runTest("(1:10, 2:20, 3:30, 4:40) & (2:20, 4:40, 5:50) == (2:20, 4:40);")); assertTrue(runTest("(1:10, 2:20, 3:30, 4:40) & (5:50, 6:60) == ();")); assertTrue(runTest("() <= ();")); assertTrue(runTest("() <= (1:10);")); assertTrue(runTest("(1:10) <= (1:10);")); assertTrue(runTest("(1:10) <= (1:10, 2:20);")); assertFalse(runTest("() < ();")); assertTrue(runTest("() < (1:10);")); assertFalse(runTest("(1:10) < (1:10);")); assertTrue(runTest("(1:10) < (1:10, 2:20);")); assertTrue(runTest("() >= ();")); assertTrue(runTest("(1:10) >= ();")); assertTrue(runTest("(1:10) >= (1:10);")); assertTrue(runTest("(1:10, 2:20) >= (1:10);")); assertFalse(runTest("() > ();")); assertTrue(runTest("(1:10) > ();")); assertFalse(runTest("(1:10) > (1:10);")); assertTrue(runTest("(1:10, 2:20) > (1:10);")); assertTrue(runTest("20 in (1:10, 2:20);")); assertFalse(runTest("15 in (1:10, 2:20);")); assertTrue(runTest("15 notin (1:10, 2:20);")); assertFalse(runTest("20 notin (1:10, 2:20);")); assertTrue(runTest("{map[str,list[int]] m = (\"a\": [1,2], \"b\": [], \"c\": [4,5,6]); m[\"a\"] == [1,2];}")); } @Test(expected=UninitializedVariableError.class) public void UndefinedMapElementError1(){ runTest("(X:2);"); } @Test(expected=UninitializedVariableError.class) public void UndefinedMapElementError2(){ runTest("(1:Y);"); } @Test(expected=Throw.class) public void NoKeyError(){ runTest("(1:10, 2:20)[3];"); } @Test public void testTuple() { assertTrue(runTest("<1, 2.5, true> == <1, 2.5, true>;")); assertTrue(runTest("<1, 2.5, true> != <0, 2.5, true>;")); assertTrue(runTest("<{1,2}, 3> == <{2,1}, 3>;")); assertTrue(runTest("<1, {2,3}> == <1, {3,2}>;")); assertTrue(runTest("<{1,2}, {3,4}> == <{2,1},{4,3}>;")); assertTrue(runTest("<1> >= <1>;")); assertTrue(runTest("<2> >= <1>;")); assertTrue(runTest("<1,2> >= <1>;")); assertTrue(runTest("<1,2> >= <1,2>;")); assertTrue(runTest("<1,2> >= <1, 1>;")); assertTrue(runTest("<1,\"def\"> >= <1, \"abc\">;")); assertTrue(runTest("<1, [2,3,4]> >= <1, [2,3]>;")); assertTrue(runTest("<1, [2,3]> >= <1, [2,3]>;")); assertFalse(runTest("<1> > <1>;")); assertTrue(runTest("<2> > <1>;")); assertTrue(runTest("<1,2> > <1>;")); assertFalse(runTest("<1,2> > <1,2>;")); assertTrue(runTest("<1,2> > <1, 1>;")); assertTrue(runTest("<1,\"def\"> > <1, \"abc\">;")); assertTrue(runTest("<1, [2,3,4]> > <1, [2,3]>;")); assertFalse(runTest("<1, [2,3]> > <1, [2,3]>;")); assertTrue(runTest("<1> <= <1>;")); assertTrue(runTest("<1> <= <2>;")); assertTrue(runTest("<1> <= <1,2>;")); assertTrue(runTest("<1,2> <= <1,2>;")); assertTrue(runTest("<1,1> <= <1, 2>;")); assertTrue(runTest("<1,\"abc\"> <= <1, \"def\">;")); assertTrue(runTest("<1, [2,3]> <= <1, [2,3,4]>;")); assertTrue(runTest("<1, [2,3]> <= <1, [2,3]>;")); assertFalse(runTest("<1> < <1>;")); assertTrue(runTest("<1> < <2>;")); assertTrue(runTest("<1> < <1,2>;")); assertFalse(runTest("<1,2> < <1,2>;")); assertTrue(runTest("<1,1> < <1, 2>;")); assertTrue(runTest("<1,\"abc\"> < <1, \"def\">;")); assertTrue(runTest("<1, [2,3]> < <1, [2,3,4]>;")); assertFalse(runTest("<1, [2,3]> < <1, [2,3]>;")); assertTrue(runTest("<1, \"a\", true> + <1.5, \"def\"> == <1, \"a\", true> + <1.5, \"def\">;")); } @Test(expected=UninitializedVariableError.class) public void UndefinedTupleElementError1(){ runTest("<1,X,3>;"); } @Test public void namedTuple() { assertTrue(runTest("{tuple[int key, str val] T = <1, \"abc\">; T.key == 1;}")); assertTrue(runTest("{tuple[int key, str val] T = <1, \"abc\">; T.val == \"abc\";}")); } @Test(expected=UndeclaredFieldError.class) public void tupleError1(){ runTest("{tuple[int key, str val] T = <1, \"abc\">; T.zip == \"abc\";}"); } @Test(expected=UninitializedVariableError.class) public void tupleError2(){ runTest("{tuple[int key, str val] T; T.key;}"); } @Test public void testRelation() { assertTrue(runTest("{} == {};")); assertTrue(runTest("{<1,10>} == {<1,10>};")); assertTrue(runTest("{<1,2,3>} == {<1,2,3>};")); assertTrue(runTest("{<1,10>, <2,20>} == {<1,10>, <2,20>};")); assertTrue(runTest("{<1,10>, <2,20>, <3,30>} == {<1,10>, <2,20>, <3,30>};")); assertTrue(runTest("{<1,2,3>, <4,5,6>} == {<4,5,6>, <1,2,3>};")); assertTrue(runTest("{<1,2,3,4>, <4,5,6,7>} == {<4,5,6,7>, <1,2,3,4>};")); assertTrue(runTest("{} != {<1,2>, <3,4>};")); assertFalse(runTest("{<1,2>, <3,4>} == {};")); assertTrue(runTest("{<1, {1,2,3}>, <2, {2,3,4}>} == {<1, {1,2,3}>, <2, {2,3,4}>};")); assertTrue(runTest("{<1, {1,2,3}>, <2, {2,3,4}>} == {<2, {2,3,4}>, <1, {1,2,3}>};")); assertTrue(runTest("{<1, {1,2,3}>, <2, {2,3,4}>} == {<2, {4,3,2}>, <1, {2,1,3}>};")); assertTrue(runTest("{<1,10>} + {} == {<1,10>};")); assertTrue(runTest("{} + {<1,10>} == {<1,10>};")); assertTrue(runTest("{<1,10>} + {<2,20>} == {<1,10>, <2,20>};")); assertTrue(runTest("{<1,10>, <2,20>} + {<3,30>} == {<1,10>, <2,20>, <3,30>};")); assertTrue(runTest("{<1,10>, <2,20>} + {<2,20>, <3,30>} == {<1,10>, <2,20>, <3,30>};")); assertTrue(runTest("{<1,10>} - {} == {<1,10>};")); assertTrue(runTest("{} - {<1,10>} == {};")); assertTrue(runTest("{<1,10>, <2,20>} - {<2,20>, <3,30>} == {<1,10>};")); assertTrue(runTest("{<1,10>} & {} == {};")); assertTrue(runTest("{} & {<1,10>} == {};")); assertTrue(runTest("{<1,10>, <2,20>} & {<2,20>, <3,30>} == {<2,20>};")); assertTrue(runTest("{<1,2,3,4>, <2,3,4,5>} & {<2,3,4,5>,<3,4,5,6>} == {<2,3,4,5>};")); assertTrue(runTest("<2,20> in {<1,10>, <2,20>, <3,30>};")); assertTrue(runTest("<1,2,3> in {<1,2,3>, <4,5,6>};")); assertTrue(runTest("<4,40> notin {<1,10>, <2,20>, <3,30>};")); assertTrue(runTest("<1,2,4> notin {<1,2,3>, <4,5,6>};")); assertTrue(runTest("{} o {} == {};")); assertTrue(runTest("{<1,10>,<2,20>} o {} == {};")); assertTrue(runTest("{} o {<10,100>, <20,200>} == {};")); assertTrue(runTest("{<1,10>,<2,20>} o {<10,100>, <20,200>} == {<1,100>, <2,200>};")); assertTrue(runTest("{<1, \"a\">, <2, \"b\">} * {<false, 0>, <true, 1>} == {<1,\"a\",false,0>,<2,\"b\",false,0>,<1,\"a\",true,1>,<2,\"b\",true,1>};")); assertTrue(runTest("{} + == {};")); assertTrue(runTest("{} * == {};")); assertTrue(runTest("{<1,2>, <2,3>, <3,4>} + == {<1,2>, <2,3>, <3,4>, <1, 3>, <2, 4>, <1, 4>};")); assertTrue(runTest("{<1,2>, <2,3>, <3,4>} * == {<1,2>, <2,3>, <3,4>, <1, 3>, <2, 4>, <1, 4>, <1, 1>, <2, 2>, <3, 3>, <4, 4>};")); assertTrue(runTest("{<1,2>, <2,3>, <3,4>, <4,2>, <4,5>}+ == {<1,2>, <2,3>, <3,4>, <4,2>, <4,5>, <1, 3>, <2, 4>, <3, 2>, <3, 5>, <4, 3>, <1, 4>, <2, 2>, <2, 5>, <3, 3>, <4, 4>, <1, 5>};")); assertTrue(runTest("{<1,2>, <2,3>, <3,4>, <4,2>, <4,5>}* == {<1,2>, <2,3>, <3,4>, <4,2>, <4,5>, <1, 3>, <2, 4>, <3, 2>, <3, 5>, <4, 3>, <1, 4>, <2, 2>, <2, 5>, <3, 3>, <4, 4>, <1, 5>, <1, 1>, <5, 5>};")); } @Test(expected=UninitializedVariableError.class) public void UndeRelationElementError1(){ runTest("{<1,10>, <X,20>};"); } @Test(expected=UninitializedVariableError.class) public void UndefinedRelationElementError2(){ runTest("{<1,10>, <10, Y>};"); } @Test(expected=UninitializedVariableError.class) public void UndefinedRelationElementError3(){ runTest("{<1,10>, T, <3,30>};"); } @Test(expected=StaticError.class) public void compError() { runTest("1 o 3;"); } @Test(expected=StaticError.class) public void closError1() { runTest("1*;"); } @Test(expected=StaticError.class) public void closError2() { runTest("1+;"); } @Test public void namedRelation1() { assertTrue(runTest("{rel[int from, int to] R = {<1,10>, <2,20>}; R.from == {1,2};}")); assertTrue(runTest("{rel[int from, int to] R = {<1,10>, <2,20>}; R.to == {10,20};}")); } @Test(expected=UndeclaredFieldError.class) public void namedRelationError(){ runTest("{rel[int from, int to] R = {<1,10>, <2,20>}; R.zip == {10,20};}"); } @Test public void good() { prepare("data NODE = val(value V) | f | f(NODE a);"); assertTrue(runTestInSameEvaluator("f(val(1)) == f(val(1));")); } @Test public void node() { prepare("data NODE = i(int I) | s(str x) | st(set[NODE] s) | l(list[NODE]) | m(map[NODE,NODE] m) | f | f(NODE a) | f(NODE a, NODE b) | g | g(NODE a) | g(NODE a,NODE b);"); assertTrue(runTestInSameEvaluator("f() == f();")); assertTrue(runTestInSameEvaluator("f() != g();")); assertTrue(runTestInSameEvaluator("{NODE n = f(); NODE m = g(); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1)) == f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1)) != g(i(1));")); assertTrue(runTestInSameEvaluator("{NODE n = f(i(1)); NODE m = g(i(1)); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1),i(2)) == f(i(1),i(2));")); assertTrue(runTestInSameEvaluator("f(i(1),i(2)) != f(i(1),i(3));")); assertTrue(runTestInSameEvaluator("{ NODE n = f(i(1),i(2)); NODE m = f(i(1),i(3)); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1),g(i(2),i(3))) == f(i(1),g(i(2),i(3)));")); assertTrue(runTestInSameEvaluator("f(i(1),g(i(2),i(3))) != f(i(1),g(i(2),i(4)));")); assertTrue(runTestInSameEvaluator("{NODE n = f(i(1),g(i(2),i(3))); NODE m = f(i(1),g(i(2),i(4))); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1),g(i(2),st({i(3),i(4),i(5)}))) == f(i(1),g(i(2),st({i(3),i(4),i(5)})));")); assertTrue(runTestInSameEvaluator("{ NODE n = f(i(1),g(i(2),st({i(3),i(4),i(5)}))); NODE m = f(i(1),g(i(2),st({i(3),i(4),i(5),i(6)}))); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1),g(i(2),l([i(3),i(4),i(5)]))) == f(i(1),g(i(2),l([i(3),i(4),i(5)])));")); assertTrue(runTestInSameEvaluator("{ NODE n = f(i(1),g(i(2),l([i(3),i(4),i(5)]))); NODE m = f(i(1),g(i(2),l([i(3),i(4),i(5),i(6)]))); n != m;}")); assertTrue(runTestInSameEvaluator("f(i(1),g(i(2),m((i(3):i(3),i(4):i(4),i(5):i(5))))) == f(i(1),g(i(2),m((i(3):i(3),i(4):i(4),i(5):i(5)))));")); assertTrue(runTestInSameEvaluator("{NODE n = f(i(1),g(i(2),m((i(3):i(3),i(4):i(4),i(5):i(5))))); NODE m = f(i(1),g(i(2),m((i(3):i(3),i(4):i(4),i(5):i(0))))); n != m;}")); assertTrue(runTestInSameEvaluator("f() <= f();")); assertTrue(runTestInSameEvaluator("f() <= g();")); assertTrue(runTestInSameEvaluator("f() <= f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1)) <= f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1), i(2)) <= f(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), i(2)) <= g(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), s(\"abc\")) <= f(i(1), s(\"def\"));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) <= f(i(1), l([i(2),i(3),i(4)]));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) <= f(i(1), l([i(2),i(3)]));")); assertFalse(runTestInSameEvaluator("f() < f();")); assertTrue(runTestInSameEvaluator("f() < g();")); assertTrue(runTestInSameEvaluator("f() < f(i(1));")); assertFalse(runTestInSameEvaluator("f(i(1)) < f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1), i(2)) < f(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), i(2)) < g(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), s(\"abc\")) < f(i(1), s(\"def\"));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) < f(i(1), l([i(2),i(3),i(4)]));")); assertFalse(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) < f(i(1), l([i(2),i(3)]));")); assertTrue(runTestInSameEvaluator("f() >= f();")); assertTrue(runTestInSameEvaluator("g() >= f();")); assertTrue(runTestInSameEvaluator("f(i(1)) >= f();")); assertTrue(runTestInSameEvaluator("f(i(1)) >= f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1), i(3)) >= f(i(1), i(2));")); assertTrue(runTestInSameEvaluator("g(i(1), i(2)) >= f(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), s(\"def\")) >= f(i(1), s(\"abc\"));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2),i(3),i(4)])) >= f(i(1), l([i(2),i(3)]));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) >= f(i(1), l([i(2),i(3)]));")); assertFalse(runTestInSameEvaluator("f() > f();")); assertTrue(runTestInSameEvaluator("g() > f();")); assertTrue(runTestInSameEvaluator("f(i(1)) > f();")); assertFalse(runTestInSameEvaluator("f(i(1)) > f(i(1));")); assertTrue(runTestInSameEvaluator("f(i(1), i(3)) > f(i(1), i(2));")); assertTrue(runTestInSameEvaluator("g(i(1), i(2)) > f(i(1), i(3));")); assertTrue(runTestInSameEvaluator("f(i(1), s(\"def\")) > f(i(1), s(\"abc\"));")); assertTrue(runTestInSameEvaluator("f(i(1), l([i(2),i(3),i(4)])) > f(i(1), l([i(2),i(3)]));")); assertFalse(runTestInSameEvaluator("f(i(1), l([i(2), i(3)])) > f(i(1), l([i(2),i(3)]));")); } @Test(expected=UninitializedVariableError.class) public void UndefinedDataTypeAccess1(){ prepare("data D = d(int ival);"); runTestInSameEvaluator("{D someD; someD.ival;}"); } @Test(expected=UninitializedVariableError.class) public void UndefinedDataTypeAccess2(){ prepare("data D = d(int ival);"); runTestInSameEvaluator("{D someD; someD.ival = 3;}"); } @Test public void undefined() { assertTrue(runTest("{T = (1:10); (T[1] ? 13) == 10;}")); assertTrue(runTest("{T = (1:10); (T[2] ? 13) == 13;}")); assertTrue(runTest("{T = (1:10); T[1] ? == true;}")); assertTrue(runTest("{T = (1:10); T[2] ? == false;}")); } }
false
true
public void real() { assertTrue(runTest("1.0 == 1.0;")); assertTrue(runTest("1.0 != 2.0;")); assertTrue(runTest("-1.0 == -1.0;")); assertTrue(runTest("-1.0 != 1.0;")); assertTrue(runTest("1.0 == 1;")); assertTrue(runTest("1 == 1.0;")); assertTrue(runTest("{value x = 1.0; value y = 1; x == y; }")); assertTrue(runTest("{value x = 1.0; value y = 2; x != y; }")); assertTrue(runTest("1.0 + 1.0 == 2.0;")); assertTrue(runTest("-1.0 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2.0) == -1.0;")); assertTrue(runTest("1.0 + 1 == 2.0;")); assertTrue(runTest("-1 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2) == -1.0;")); assertTrue(runTest("2.0 - 1.0 == 1.0;")); assertTrue(runTest("2.0 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1.0 == 3.0;")); assertTrue(runTest("-2.0 - 1.0 == -3.0;")); assertTrue(runTest("2.0 - 1 == 1.0;")); assertTrue(runTest("2 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1 == 3.0;")); assertTrue(runTest("-2 - 1.0 == -3.0;")); assertTrue(runTest("2.0 * 3.0 == 6.0;")); assertTrue(runTest("-2.0 * 3.0 == -6.0;")); assertTrue(runTest("2.0 * (-3.0) == -6.0;")); assertTrue(runTest("-2.0 * (-3.0) == 6.0;")); assertTrue(runTest("2.0 * 3 == 6.0;")); assertTrue(runTest("-2 * 3.0 == -6.0;")); assertTrue(runTest("2.0 * (-3) == -6.0;")); assertTrue(runTest("-2 * (-3.0) == 6.0;")); assertTrue(runTest("8.0 / 4.0 == 2.0;")); assertTrue(runTest("-8.0 / 4.0 == -2.0;")); assertTrue(runTest("8.0 / -4.0 == -2.0;")); assertTrue(runTest("-8.0 / -4.0 == 2.0;")); assertTrue(runTest("7.0 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2.0 == -3.5;")); assertTrue(runTest("7.0 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2.0 == 3.5;")); assertTrue(runTest("0.0 / 5.0 == 0.0;")); assertTrue(runTest("5.0 / 1.0 == 5.0;")); assertTrue(runTest("7 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2 == -3.5;")); assertTrue(runTest("7 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2 == 3.5;")); assertTrue(runTest("-2.0 <= -1.0;")); assertTrue(runTest("-2.0 <= 1.0;")); assertTrue(runTest("1.0 <= 2.0;")); assertTrue(runTest("2.0 <= 2.0;")); assertFalse(runTest("2.0 <= 1.0;")); assertTrue(runTest("-2 <= -1.0;")); assertTrue(runTest("-2.0 <= 1;")); assertTrue(runTest("1 <= 2.0;")); assertTrue(runTest("2.0 <= 2;")); assertFalse(runTest("2 <= 1.0;")); assertTrue(runTest("-2.0 < -1.0;")); assertTrue(runTest("-2.0 < 1.0;")); assertTrue(runTest("1.0 < 2.0;")); assertFalse(runTest("2.0 < 2.0;")); assertTrue(runTest("-2 < -1.0;")); assertTrue(runTest("-2.0 < 1;")); assertTrue(runTest("1 < 2.0;")); assertFalse(runTest("2.0 < 2;")); assertTrue(runTest("-1.0 >= -2.0;")); assertTrue(runTest("1.0 >= -1.0;")); assertTrue(runTest("2.0 >= 1.0;")); assertTrue(runTest("2.0 >= 2.0;")); assertFalse(runTest("1.0 >= 2.0;")); assertTrue(runTest("-1 >= -2.0;")); assertTrue(runTest("1.0 >= -1;")); assertTrue(runTest("2 >= 1.0;")); assertTrue(runTest("2.0 >= 2;")); assertFalse(runTest("1 >= 2.0;")); assertTrue(runTest("-1.0 > -2.0;")); assertTrue(runTest("1.0 > -1.0;")); assertTrue(runTest("2.0 > 1.0;")); assertFalse(runTest("2.0 > 2.0;")); assertFalse(runTest("1.0 > 2.0;")); assertTrue(runTest("-1 > -2.0;")); assertTrue(runTest("1.0 > -1;")); assertTrue(runTest("2 > 1.0;")); assertFalse(runTest("2.0 > 2;")); assertFalse(runTest("1 > 2.0;")); assertTrue(runTest("3.5 > 2.5 ? 3.5 : 2.5 == 3.5;")); assertTrue(runTest("3.5 > 2 ? 3.5 : 2 == 3.5;")); assertTrue(runTest("3.5 > 4 ? 3.5 : 2 == 2;")); }
public void real() { assertTrue(runTest("1.0 == 1.0;")); assertTrue(runTest("1.0 != 2.0;")); assertTrue(runTest("-1.0 == -1.0;")); assertTrue(runTest("-1.0 != 1.0;")); assertTrue(runTest("1.0 == 1;")); assertTrue(runTest("1.00 == 1.0;")); assertTrue(runTest("1 == 1.0;")); assertTrue(runTest("{value x = 1.0; value y = 1; x == y; }")); assertTrue(runTest("{value x = 1.0; value y = 2; x != y; }")); assertTrue(runTest("1.0 + 1.0 == 2.0;")); assertTrue(runTest("-1.0 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2.0) == -1.0;")); assertTrue(runTest("1.0 + 1 == 2.0;")); assertTrue(runTest("-1 + 2.0 == 1.0;")); assertTrue(runTest("1.0 + (-2) == -1.0;")); assertTrue(runTest("2.0 - 1.0 == 1.0;")); assertTrue(runTest("2.0 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1.0 == 3.0;")); assertTrue(runTest("-2.0 - 1.0 == -3.0;")); assertTrue(runTest("2.0 - 1 == 1.0;")); assertTrue(runTest("2 - 3.0 == -1.0;")); assertTrue(runTest("2.0 - -1 == 3.0;")); assertTrue(runTest("-2 - 1.0 == -3.0;")); assertTrue(runTest("2.0 * 3.0 == 6.00;")); assertTrue(runTest("-2.0 * 3.0 == -6.00;")); assertTrue(runTest("2.0 * (-3.0) == -6.00;")); assertTrue(runTest("-2.0 * (-3.0) == 6.00;")); assertTrue(runTest("2.0 * 3 == 6.0;")); assertTrue(runTest("-2 * 3.0 == -6.0;")); assertTrue(runTest("2.0 * (-3) == -6.0;")); assertTrue(runTest("-2 * (-3.0) == 6.0;")); assertTrue(runTest("8.0 / 4.0 == 2e0;")); assertTrue(runTest("-8.0 / 4.0 == -2e0;")); assertTrue(runTest("8.0 / -4.0 == -2e0;")); assertTrue(runTest("-8.0 / -4.0 == 2e0;")); // TODO, I don't get it, why does the previous have 1 digit precision and this // one two digits assertTrue(runTest("7.0 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2.0 == -3.5;")); assertTrue(runTest("7.0 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2.0 == 3.5;")); assertTrue(runTest("0.0 / 5.0 == 0.0;")); assertTrue(runTest("5.0 / 1.0 == 5.0;")); assertTrue(runTest("7 / 2.0 == 3.5;")); assertTrue(runTest("-7.0 / 2 == -3.5;")); assertTrue(runTest("7 / -2.0 == -3.5;")); assertTrue(runTest("-7.0 / -2 == 3.5;")); assertTrue(runTest("-2.0 <= -1.0;")); assertTrue(runTest("-2.0 <= 1.0;")); assertTrue(runTest("1.0 <= 2.0;")); assertTrue(runTest("2.0 <= 2.0;")); assertFalse(runTest("2.0 <= 1.0;")); assertTrue(runTest("-2 <= -1.0;")); assertTrue(runTest("-2.0 <= 1;")); assertTrue(runTest("1 <= 2.0;")); assertTrue(runTest("2.0 <= 2;")); assertFalse(runTest("2 <= 1.0;")); assertTrue(runTest("-2.0 < -1.0;")); assertTrue(runTest("-2.0 < 1.0;")); assertTrue(runTest("1.0 < 2.0;")); assertFalse(runTest("2.0 < 2.0;")); assertTrue(runTest("-2 < -1.0;")); assertTrue(runTest("-2.0 < 1;")); assertTrue(runTest("1 < 2.0;")); assertFalse(runTest("2.0 < 2;")); assertTrue(runTest("-1.0 >= -2.0;")); assertTrue(runTest("1.0 >= -1.0;")); assertTrue(runTest("2.0 >= 1.0;")); assertTrue(runTest("2.0 >= 2.0;")); assertFalse(runTest("1.0 >= 2.0;")); assertTrue(runTest("-1 >= -2.0;")); assertTrue(runTest("1.0 >= -1;")); assertTrue(runTest("2 >= 1.0;")); assertTrue(runTest("2.0 >= 2;")); assertFalse(runTest("1 >= 2.0;")); assertTrue(runTest("-1.0 > -2.0;")); assertTrue(runTest("1.0 > -1.0;")); assertTrue(runTest("2.0 > 1.0;")); assertFalse(runTest("2.0 > 2.0;")); assertFalse(runTest("1.0 > 2.0;")); assertTrue(runTest("-1 > -2.0;")); assertTrue(runTest("1.0 > -1;")); assertTrue(runTest("2 > 1.0;")); assertFalse(runTest("2.0 > 2;")); assertFalse(runTest("1 > 2.0;")); assertTrue(runTest("3.5 > 2.5 ? 3.5 : 2.5 == 3.5;")); assertTrue(runTest("3.5 > 2 ? 3.5 : 2 == 3.5;")); assertTrue(runTest("3.5 > 4 ? 3.5 : 2 == 2;")); }
diff --git a/src/java/net/sf/picard/sam/SamToFastq.java b/src/java/net/sf/picard/sam/SamToFastq.java index a89b31b4..cc76174d 100755 --- a/src/java/net/sf/picard/sam/SamToFastq.java +++ b/src/java/net/sf/picard/sam/SamToFastq.java @@ -1,362 +1,366 @@ /* * The MIT License * * Copyright (c) 2009 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.sam; import net.sf.picard.PicardException; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.cmdline.Usage; import net.sf.picard.fastq.FastqRecord; import net.sf.picard.fastq.FastqWriter; import net.sf.picard.fastq.FastqWriterFactory; import net.sf.picard.io.IoUtil; import net.sf.picard.util.Log; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMReadGroupRecord; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMUtils; import net.sf.samtools.util.SequenceUtil; import net.sf.samtools.util.StringUtil; import java.io.File; import java.util.*; /** * $Id$ * <p/> * Extracts read sequences and qualities from the input SAM/BAM file and writes them into * the output file in Sanger fastq format. * See <a href="http://maq.sourceforge.net/fastq.shtml">MAQ FastQ specification</a> for details. * In the RC mode (default is True), if the read is aligned and the alignment is to the reverse strand on the genome, * the read's sequence from input sam file will be reverse-complemented prior to writing it to fastq in order restore correctly * the original read sequence as it was generated by the sequencer. */ public class SamToFastq extends CommandLineProgram { @Usage public String USAGE = "Extracts read sequences and qualities from the input SAM/BAM file and writes them into "+ "the output file in Sanger fastq format. In the RC mode (default is True), if the read is aligned and the alignment is to the reverse strand on the genome, "+ "the read's sequence from input SAM file will be reverse-complemented prior to writing it to fastq in order restore correctly "+ "the original read sequence as it was generated by the sequencer."; @Option(doc="Input SAM/BAM file to extract reads from", shortName=StandardOptionDefinitions.INPUT_SHORT_NAME) public File INPUT ; @Option(shortName="F", doc="Output fastq file (single-end fastq or, if paired, first end of the pair fastq).", mutex={"OUTPUT_PER_RG"}) public File FASTQ ; @Option(shortName="F2", doc="Output fastq file (if paired, second end of the pair fastq).", optional=true, mutex={"OUTPUT_PER_RG"}) public File SECOND_END_FASTQ ; @Option(shortName="OPRG", doc="Output a fastq file per read group (two fastq files per read group if the group is paired).", optional=true, mutex={"FASTQ", "SECOND_END_FASTQ"}) public boolean OUTPUT_PER_RG ; @Option(shortName="ODIR", doc="Directory in which to output the fastq file(s). Used only when OUTPUT_PER_RG is true.", optional=true) public File OUTPUT_DIR; @Option(shortName="RC", doc="Re-reverse bases and qualities of reads with negative strand flag set before writing them to fastq", optional=true) public boolean RE_REVERSE = true; @Option(shortName="NON_PF", doc="Include non-PF reads from the SAM file into the output FASTQ files.") public boolean INCLUDE_NON_PF_READS = false; @Option(shortName="CLIP_ATTR", doc="The attribute that stores the position at which " + "the SAM record should be clipped", optional=true) public String CLIPPING_ATTRIBUTE; @Option(shortName="CLIP_ACT", doc="The action that should be taken with clipped reads: " + "'X' means the reads and qualities should be trimmed at the clipped position; " + "'N' means the bases should be changed to Ns in the clipped region; and any " + "integer means that the base qualities should be set to that value in the " + "clipped region.", optional=true) public String CLIPPING_ACTION; @Option(shortName="R1_TRIM", doc="The number of bases to trim from the beginning of read 1.") public int READ1_TRIM = 0; @Option(shortName="R1_MAX_BASES", doc="The maximum number of bases to write from read 1 after trimming. " + "If there are fewer than this many bases left after trimming, all will be written. If this " + "value is null then all bases left after trimming will be written.", optional=true) public Integer READ1_MAX_BASES_TO_WRITE; @Option(shortName="R2_TRIM", doc="The number of bases to trim from the beginning of read 2.") public int READ2_TRIM = 0; @Option(shortName="R2_MAX_BASES", doc="The maximum number of bases to write from read 2 after trimming. " + "If there are fewer than this many bases left after trimming, all will be written. If this " + "value is null then all bases left after trimming will be written.", optional=true) public Integer READ2_MAX_BASES_TO_WRITE; @Option(doc="If true, include non-primary alignments in the output. Support of non-primary alignments in SamToFastq " + "is not comprehensive, so there may be exceptions if this is set to true and there are paired reads with non-primary alignments.") public boolean INCLUDE_NON_PRIMARY_ALIGNMENTS=false; private final Log log = Log.getInstance(SamToFastq.class); public static void main(final String[] argv) { System.exit(new SamToFastq().instanceMain(argv)); } protected int doWork() { IoUtil.assertFileIsReadable(INPUT); final SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); final Map<String,SAMRecord> firstSeenMates = new HashMap<String,SAMRecord>(); final FastqWriterFactory factory = new FastqWriterFactory(); final Map<SAMReadGroupRecord, List<FastqWriter>> writers = getWriters(reader.getFileHeader().getReadGroups(), factory); long count = 0; for (final SAMRecord currentRecord : reader) { if (currentRecord.getNotPrimaryAlignmentFlag() && !INCLUDE_NON_PRIMARY_ALIGNMENTS) continue; // Skip non-PF reads as necessary if (currentRecord.getReadFailsVendorQualityCheckFlag() && !INCLUDE_NON_PF_READS) continue; final List<FastqWriter> fq = writers.get(currentRecord.getReadGroup()); if (currentRecord.getReadPairedFlag()) { final String currentReadName = currentRecord.getReadName(); final SAMRecord firstRecord = firstSeenMates.remove(currentReadName); if (firstRecord == null) { firstSeenMates.put(currentReadName, currentRecord); } else { assertPairedMates(firstRecord, currentRecord); - if (OUTPUT_PER_RG && fq.size() == 1) { - fq.add(factory.newWriter(makeReadGroupFile(currentRecord.getReadGroup(), "_2"))); + if (fq.size() == 1) { + if (OUTPUT_PER_RG) { + fq.add(factory.newWriter(makeReadGroupFile(currentRecord.getReadGroup(), "_2"))); + } else { + throw new PicardException("Input contains paired reads but no SECOND_END_FASTQ specified."); + } } final SAMRecord read1 = currentRecord.getFirstOfPairFlag() ? currentRecord : firstRecord; final SAMRecord read2 = currentRecord.getFirstOfPairFlag() ? firstRecord : currentRecord; writeRecord(read1, 1, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); writeRecord(read2, 2, fq.get(1), READ2_TRIM, READ2_MAX_BASES_TO_WRITE); } } else { writeRecord(currentRecord, null, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); } if (++count % 10000000 == 0) { log.info("Processed " + count + " records."); } } reader.close(); // Close all the fastq writers being careful to close each one only once! final IdentityHashMap<FastqWriter,FastqWriter> seen = new IdentityHashMap<FastqWriter, FastqWriter>(); for (final List<FastqWriter> listOfWriters : writers.values()) { for (final FastqWriter w : listOfWriters) { if (!seen.containsKey(w)) { w.close(); seen.put(w,w); } } } if (firstSeenMates.size() > 0) { throw new PicardException("Found " + firstSeenMates.size() + " unpaired mates"); } return 0; } /** * Gets the pair of writers for a given read group or, if we are not sorting by read group, * just returns the single pair of writers. */ private Map<SAMReadGroupRecord, List<FastqWriter>> getWriters(final List<SAMReadGroupRecord> samReadGroupRecords, final FastqWriterFactory factory) { final Map<SAMReadGroupRecord, List<FastqWriter>> writerMap = new HashMap<SAMReadGroupRecord, List<FastqWriter>>(); if (!OUTPUT_PER_RG) { // If we're not outputting by read group, there's only // one writer for each end. final List<FastqWriter> fqw = new ArrayList<FastqWriter>(); IoUtil.assertFileIsWritable(FASTQ); IoUtil.openFileForWriting(FASTQ); fqw.add(factory.newWriter(FASTQ)); if (SECOND_END_FASTQ != null) { IoUtil.assertFileIsWritable(SECOND_END_FASTQ); IoUtil.openFileForWriting(SECOND_END_FASTQ); fqw.add(factory.newWriter(SECOND_END_FASTQ)); } // Store in map with null key, in case there are reads without read group. writerMap.put(null, fqw); // Also store for every read group in header. for (final SAMReadGroupRecord rg : samReadGroupRecords) { writerMap.put(rg, fqw); } } else { for (final SAMReadGroupRecord rg : samReadGroupRecords) { final List<FastqWriter> fqw = new ArrayList<FastqWriter>(); fqw.add(factory.newWriter(makeReadGroupFile(rg, "_1"))); writerMap.put(rg, fqw); } } return writerMap; } private File makeReadGroupFile(final SAMReadGroupRecord readGroup, final String preExtSuffix) { String fileName = readGroup.getPlatformUnit(); if (fileName == null) fileName = readGroup.getReadGroupId(); fileName = IoUtil.makeFileNameSafe(fileName); if(preExtSuffix != null) fileName += preExtSuffix; fileName += ".fastq"; final File result = (OUTPUT_DIR != null) ? new File(OUTPUT_DIR, fileName) : new File(fileName); IoUtil.assertFileIsWritable(result); return result; } void writeRecord(final SAMRecord read, final Integer mateNumber, final FastqWriter writer, final int basesToTrim, final Integer maxBasesToWrite) { final String seqHeader = mateNumber==null ? read.getReadName() : read.getReadName() + "/"+ mateNumber; String readString = read.getReadString(); String baseQualities = read.getBaseQualityString(); // If we're clipping, do the right thing to the bases or qualities if (CLIPPING_ATTRIBUTE != null) { final Integer clipPoint = (Integer)read.getAttribute(CLIPPING_ATTRIBUTE); if (clipPoint != null) { if (CLIPPING_ACTION.equalsIgnoreCase("X")) { readString = clip(readString, clipPoint, null, !read.getReadNegativeStrandFlag()); baseQualities = clip(baseQualities, clipPoint, null, !read.getReadNegativeStrandFlag()); } else if (CLIPPING_ACTION.equalsIgnoreCase("N")) { readString = clip(readString, clipPoint, 'N', !read.getReadNegativeStrandFlag()); } else { final char newQual = SAMUtils.phredToFastq( new byte[] { (byte)Integer.parseInt(CLIPPING_ACTION)}).charAt(0); baseQualities = clip(baseQualities, clipPoint, newQual, !read.getReadNegativeStrandFlag()); } } } if ( RE_REVERSE && read.getReadNegativeStrandFlag() ) { readString = SequenceUtil.reverseComplement(readString); baseQualities = StringUtil.reverseString(baseQualities); } if (basesToTrim > 0) { readString = readString.substring(basesToTrim); baseQualities = baseQualities.substring(basesToTrim); } if (maxBasesToWrite != null && maxBasesToWrite < readString.length()) { readString = readString.substring(0, maxBasesToWrite); baseQualities = baseQualities.substring(0, maxBasesToWrite); } writer.write(new FastqRecord(seqHeader, readString, "", baseQualities)); } /** * Utility method to handle the changes required to the base/quality strings by the clipping * parameters. * * @param src The string to clip * @param point The 1-based position of the first clipped base in the read * @param replacement If non-null, the character to replace in the clipped positions * in the string (a quality score or 'N'). If null, just trim src * @param posStrand Whether the read is on the positive strand * @return String The clipped read or qualities */ private String clip(final String src, final int point, final Character replacement, final boolean posStrand) { final int len = src.length(); String result = posStrand ? src.substring(0, point-1) : src.substring(len-point+1); if (replacement != null) { if (posStrand) { for (int i = point; i <= len; i++ ) { result += replacement; } } else { for (int i = 0; i <= len-point; i++) { result = replacement + result; } } } return result; } private void assertPairedMates(final SAMRecord record1, final SAMRecord record2) { if (! (record1.getFirstOfPairFlag() && record2.getSecondOfPairFlag() || record2.getFirstOfPairFlag() && record1.getSecondOfPairFlag() ) ) { throw new PicardException("Illegal mate state: " + record1.getReadName()); } } /** * Put any custom command-line validation in an override of this method. * clp is initialized at this point and can be used to print usage and access argv. * Any options set by command-line parser can be validated. * @return null if command line is valid. If command line is invalid, returns an array of error * messages to be written to the appropriate place. */ protected String[] customCommandLineValidation() { if ((CLIPPING_ATTRIBUTE != null && CLIPPING_ACTION == null) || (CLIPPING_ATTRIBUTE == null && CLIPPING_ACTION != null)) { return new String[] { "Both or neither of CLIPPING_ATTRIBUTE and CLIPPING_ACTION should be set." }; } if (CLIPPING_ACTION != null) { if (CLIPPING_ACTION.equals("N") || CLIPPING_ACTION.equals("X")) { // Do nothing, this is fine } else { try { Integer.parseInt(CLIPPING_ACTION); } catch (NumberFormatException nfe) { return new String[] {"CLIPPING ACTION must be one of: N, X, or an integer"}; } } } if ((OUTPUT_PER_RG && OUTPUT_DIR == null) || ((!OUTPUT_PER_RG) && OUTPUT_DIR != null)) { return new String[] { "If OUTPUT_PER_RG is true, then OUTPUT_DIR should be set. " + "If " }; } return null; } }
true
true
protected int doWork() { IoUtil.assertFileIsReadable(INPUT); final SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); final Map<String,SAMRecord> firstSeenMates = new HashMap<String,SAMRecord>(); final FastqWriterFactory factory = new FastqWriterFactory(); final Map<SAMReadGroupRecord, List<FastqWriter>> writers = getWriters(reader.getFileHeader().getReadGroups(), factory); long count = 0; for (final SAMRecord currentRecord : reader) { if (currentRecord.getNotPrimaryAlignmentFlag() && !INCLUDE_NON_PRIMARY_ALIGNMENTS) continue; // Skip non-PF reads as necessary if (currentRecord.getReadFailsVendorQualityCheckFlag() && !INCLUDE_NON_PF_READS) continue; final List<FastqWriter> fq = writers.get(currentRecord.getReadGroup()); if (currentRecord.getReadPairedFlag()) { final String currentReadName = currentRecord.getReadName(); final SAMRecord firstRecord = firstSeenMates.remove(currentReadName); if (firstRecord == null) { firstSeenMates.put(currentReadName, currentRecord); } else { assertPairedMates(firstRecord, currentRecord); if (OUTPUT_PER_RG && fq.size() == 1) { fq.add(factory.newWriter(makeReadGroupFile(currentRecord.getReadGroup(), "_2"))); } final SAMRecord read1 = currentRecord.getFirstOfPairFlag() ? currentRecord : firstRecord; final SAMRecord read2 = currentRecord.getFirstOfPairFlag() ? firstRecord : currentRecord; writeRecord(read1, 1, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); writeRecord(read2, 2, fq.get(1), READ2_TRIM, READ2_MAX_BASES_TO_WRITE); } } else { writeRecord(currentRecord, null, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); } if (++count % 10000000 == 0) { log.info("Processed " + count + " records."); } } reader.close(); // Close all the fastq writers being careful to close each one only once! final IdentityHashMap<FastqWriter,FastqWriter> seen = new IdentityHashMap<FastqWriter, FastqWriter>(); for (final List<FastqWriter> listOfWriters : writers.values()) { for (final FastqWriter w : listOfWriters) { if (!seen.containsKey(w)) { w.close(); seen.put(w,w); } } } if (firstSeenMates.size() > 0) { throw new PicardException("Found " + firstSeenMates.size() + " unpaired mates"); } return 0; }
protected int doWork() { IoUtil.assertFileIsReadable(INPUT); final SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); final Map<String,SAMRecord> firstSeenMates = new HashMap<String,SAMRecord>(); final FastqWriterFactory factory = new FastqWriterFactory(); final Map<SAMReadGroupRecord, List<FastqWriter>> writers = getWriters(reader.getFileHeader().getReadGroups(), factory); long count = 0; for (final SAMRecord currentRecord : reader) { if (currentRecord.getNotPrimaryAlignmentFlag() && !INCLUDE_NON_PRIMARY_ALIGNMENTS) continue; // Skip non-PF reads as necessary if (currentRecord.getReadFailsVendorQualityCheckFlag() && !INCLUDE_NON_PF_READS) continue; final List<FastqWriter> fq = writers.get(currentRecord.getReadGroup()); if (currentRecord.getReadPairedFlag()) { final String currentReadName = currentRecord.getReadName(); final SAMRecord firstRecord = firstSeenMates.remove(currentReadName); if (firstRecord == null) { firstSeenMates.put(currentReadName, currentRecord); } else { assertPairedMates(firstRecord, currentRecord); if (fq.size() == 1) { if (OUTPUT_PER_RG) { fq.add(factory.newWriter(makeReadGroupFile(currentRecord.getReadGroup(), "_2"))); } else { throw new PicardException("Input contains paired reads but no SECOND_END_FASTQ specified."); } } final SAMRecord read1 = currentRecord.getFirstOfPairFlag() ? currentRecord : firstRecord; final SAMRecord read2 = currentRecord.getFirstOfPairFlag() ? firstRecord : currentRecord; writeRecord(read1, 1, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); writeRecord(read2, 2, fq.get(1), READ2_TRIM, READ2_MAX_BASES_TO_WRITE); } } else { writeRecord(currentRecord, null, fq.get(0), READ1_TRIM, READ1_MAX_BASES_TO_WRITE); } if (++count % 10000000 == 0) { log.info("Processed " + count + " records."); } } reader.close(); // Close all the fastq writers being careful to close each one only once! final IdentityHashMap<FastqWriter,FastqWriter> seen = new IdentityHashMap<FastqWriter, FastqWriter>(); for (final List<FastqWriter> listOfWriters : writers.values()) { for (final FastqWriter w : listOfWriters) { if (!seen.containsKey(w)) { w.close(); seen.put(w,w); } } } if (firstSeenMates.size() > 0) { throw new PicardException("Found " + firstSeenMates.size() + " unpaired mates"); } return 0; }
diff --git a/rdfbean-maven-plugin/src/test/java/com/mysema/rdfbean/beangen/JavaBeanExporterTest.java b/rdfbean-maven-plugin/src/test/java/com/mysema/rdfbean/beangen/JavaBeanExporterTest.java index 1586ca42..fb34acc3 100644 --- a/rdfbean-maven-plugin/src/test/java/com/mysema/rdfbean/beangen/JavaBeanExporterTest.java +++ b/rdfbean-maven-plugin/src/test/java/com/mysema/rdfbean/beangen/JavaBeanExporterTest.java @@ -1,52 +1,55 @@ package com.mysema.rdfbean.beangen; import static org.junit.Assert.*; import java.util.List; import org.junit.Before; import org.junit.Test; import com.mysema.query.codegen.EntityType; import com.mysema.rdfbean.owl.Restriction; import com.mysema.rdfbean.rdfs.RDFSClass; public class JavaBeanExporterTest extends AbstractExportTest{ private JavaBeanExporter exporter; @Before public void setUp(){ exporter = new JavaBeanExporter(true); exporter.addPackage("http://www.mysema.com/semantics/blog/#", "com.mysema.blog"); exporter.addPackage("http://purl.org/dc/elements/1.1/", "com.mysema.dc"); exporter.addPackage("http://purl.org/dc/terms/", "com.mysema.dc"); exporter.addPackage("http://www.mysema.com/rdfbean/demo#", "com.mysema.demo"); exporter.addPackage("http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#", "com.mysema.wine"); } @SuppressWarnings("unchecked") @Test public void createBeanType(){ List<RDFSClass> rdfTypes = session.findInstances(RDFSClass.class); assertFalse(rdfTypes.isEmpty()); for (RDFSClass<?> rdfType : rdfTypes){ + if (rdfType.getId().isBNode()){ + continue; + } EntityType entityType = exporter.createBeanType(rdfType); // supertype count int supertypes = 0; for (RDFSClass<?> superClass : rdfType.getSuperClasses()){ if (superClass != null && !superClass.getClass().equals(Restriction.class)){ supertypes++; } } assertEquals(supertypes, entityType.getSuperTypes().size()); // property count assertTrue(entityType.getProperties().size() >= rdfType.getProperties().size()); } } }
true
true
public void createBeanType(){ List<RDFSClass> rdfTypes = session.findInstances(RDFSClass.class); assertFalse(rdfTypes.isEmpty()); for (RDFSClass<?> rdfType : rdfTypes){ EntityType entityType = exporter.createBeanType(rdfType); // supertype count int supertypes = 0; for (RDFSClass<?> superClass : rdfType.getSuperClasses()){ if (superClass != null && !superClass.getClass().equals(Restriction.class)){ supertypes++; } } assertEquals(supertypes, entityType.getSuperTypes().size()); // property count assertTrue(entityType.getProperties().size() >= rdfType.getProperties().size()); } }
public void createBeanType(){ List<RDFSClass> rdfTypes = session.findInstances(RDFSClass.class); assertFalse(rdfTypes.isEmpty()); for (RDFSClass<?> rdfType : rdfTypes){ if (rdfType.getId().isBNode()){ continue; } EntityType entityType = exporter.createBeanType(rdfType); // supertype count int supertypes = 0; for (RDFSClass<?> superClass : rdfType.getSuperClasses()){ if (superClass != null && !superClass.getClass().equals(Restriction.class)){ supertypes++; } } assertEquals(supertypes, entityType.getSuperTypes().size()); // property count assertTrue(entityType.getProperties().size() >= rdfType.getProperties().size()); } }
diff --git a/components/bio-formats/src/loci/formats/ImageReader.java b/components/bio-formats/src/loci/formats/ImageReader.java index c8cb8253b..d05228020 100644 --- a/components/bio-formats/src/loci/formats/ImageReader.java +++ b/components/bio-formats/src/loci/formats/ImageReader.java @@ -1,622 +1,622 @@ // // ImageReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; import loci.common.Location; import loci.common.LogTools; import loci.common.RandomAccessInputStream; import loci.formats.meta.MetadataStore; /** * ImageReader is the master file format reader for all supported formats. * It uses one instance of each reader subclass (specified in readers.txt, * or other class list source) to identify file formats and read data. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/ImageReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/ImageReader.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu */ public class ImageReader implements IFormatReader { // -- Static fields -- /** Default list of reader classes, for use with noargs constructor. */ private static ClassList defaultClasses; // -- Static helper methods -- private static ClassList getDefaultReaderClasses() { if (defaultClasses == null) { // load built-in reader classes from readers.txt file try { defaultClasses = new ClassList("readers.txt", IFormatReader.class); } catch (IOException exc) { defaultClasses = new ClassList(IFormatReader.class); LogTools.trace(exc); } } return defaultClasses; } // -- Fields -- /** List of supported file format readers. */ private IFormatReader[] readers; /** * Valid suffixes for this file format. * Populated the first time getSuffixes() is called. */ private String[] suffixes; /** Name of current file. */ private String currentId; /** Current form index. */ private int current; // -- Constructors -- /** * Constructs a new ImageReader with the default * list of reader classes from readers.txt. */ public ImageReader() { this(getDefaultReaderClasses()); } /** Constructs a new ImageReader from the given list of reader classes. */ public ImageReader(ClassList classList) { // add readers to the list Vector v = new Vector(); Class[] c = classList.getClasses(); for (int i=0; i<c.length; i++) { IFormatReader reader = null; try { reader = (IFormatReader) c[i].newInstance(); } catch (IllegalAccessException exc) { } catch (InstantiationException exc) { } if (reader == null) { LogTools.println("Error: " + c[i].getName() + " cannot be instantiated."); continue; } v.add(reader); } readers = new IFormatReader[v.size()]; v.copyInto(readers); } // -- ImageReader API methods -- /** Gets a string describing the file format for the given file. */ public String getFormat(String id) throws FormatException, IOException { return getReader(id).getFormat(); } /** Gets the reader used to open the given file. */ public IFormatReader getReader(String id) throws FormatException, IOException { // NB: Check that we can generate a valid handle for the ID; // e.g., for files, this will throw an exception if the file is missing. - Location.getHandle(id); + Location.getHandle(id).close(); if (!id.equals(currentId)) { // initialize file boolean success = false; for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(id)) { current = i; currentId = id; success = true; break; } } if (!success) { throw new UnknownFormatException("Unknown file format: " + id); } } return getReader(); } /** Gets the reader used to open the current file. */ public IFormatReader getReader() { FormatTools.assertId(currentId, true, 2); return readers[current]; } /** Gets the file format reader instance matching the given class. */ public IFormatReader getReader(Class c) { for (int i=0; i<readers.length; i++) { if (readers[i].getClass().equals(c)) return readers[i]; } return null; } /** Gets all constituent file format readers. */ public IFormatReader[] getReaders() { IFormatReader[] r = new IFormatReader[readers.length]; System.arraycopy(readers, 0, r, 0, readers.length); return r; } // -- IFormatReader API methods -- /* @see IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(name, open)) return true; } return false; } /* @see IFormatReader.isThisType(byte[]) */ public boolean isThisType(byte[] block) { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(block)) return true; } return false; } /* @see IFormatReader.isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(stream)) return true; } return false; } /* @see IFormatReader#getImageCount() */ public int getImageCount() { return getReader().getImageCount(); } /* @see IFormatReader#isRGB() */ public boolean isRGB() { return getReader().isRGB(); } /* @see IFormatReader#getSizeX() */ public int getSizeX() { return getReader().getSizeX(); } /* @see IFormatReader#getSizeY() */ public int getSizeY() { return getReader().getSizeY(); } /* @see IFormatReader#getSizeC() */ public int getSizeC() { return getReader().getSizeC(); } /* @see IFormatReader#getSizeZ() */ public int getSizeZ() { return getReader().getSizeZ(); } /* @see IFormatReader#getSizeT() */ public int getSizeT() { return getReader().getSizeT(); } /* @see IFormatReader#getPixelType() */ public int getPixelType() { return getReader().getPixelType(); } /* @see IFormatReader#getBitsPerPixel() */ public int getBitsPerPixel() { return getReader().getBitsPerPixel(); } /* @see IFormatReader#getEffectiveSizeC() */ public int getEffectiveSizeC() { return getReader().getEffectiveSizeC(); } /* @see IFormatReader#getRGBChannelCount() */ public int getRGBChannelCount() { return getReader().getRGBChannelCount(); } /* @see IFormatReader#isIndexed() */ public boolean isIndexed() { return getReader().isIndexed(); } /* @see IFormatReader#isFalseColor() */ public boolean isFalseColor() { return getReader().isFalseColor(); } /* @see IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { return getReader().get8BitLookupTable(); } /* @see IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { return getReader().get16BitLookupTable(); } /* @see IFormatReader#getChannelDimLengths() */ public int[] getChannelDimLengths() { return getReader().getChannelDimLengths(); } /* @see IFormatReader#getChannelDimTypes() */ public String[] getChannelDimTypes() { return getReader().getChannelDimTypes(); } /* @see IFormatReader#getThumbSizeX() */ public int getThumbSizeX() { return getReader().getThumbSizeX(); } /* @see IFormatReader#getThumbSizeY() */ public int getThumbSizeY() { return getReader().getThumbSizeY(); } /* @see IFormatReader#isLittleEndian() */ public boolean isLittleEndian() { return getReader().isLittleEndian(); } /* @see IFormatReader#getDimensionOrder() */ public String getDimensionOrder() { return getReader().getDimensionOrder(); } /* @see IFormatReader#isOrderCertain() */ public boolean isOrderCertain() { return getReader().isOrderCertain(); } /* @see IFormatReader#isThumbnailSeries() */ public boolean isThumbnailSeries() { return getReader().isThumbnailSeries(); } /* @see IFormatReader#isInterleaved() */ public boolean isInterleaved() { return getReader().isInterleaved(); } /* @see IFormatReader#isInterleaved(int) */ public boolean isInterleaved(int subC) { return getReader().isInterleaved(subC); } /* @see IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { return getReader().openBytes(no); } /* @see IFormatReader#openBytes(int, int, int, int, int) */ public byte[] openBytes(int no, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openBytes(no, x, y, w, h); } /* @see IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { return getReader().openBytes(no, buf); } /* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openBytes(no, buf, x, y, w, h); } /* @see IFormatReader#openPlane(int, int, int, int, int) */ public Object openPlane(int no, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openPlane(no, x, y, w, h); } /* @see IFormatReader#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { return getReader().openThumbBytes(no); } /* @see IFormatReader#getSeriesCount() */ public int getSeriesCount() { return getReader().getSeriesCount(); } /* @see IFormatReader#setSeries(int) */ public void setSeries(int no) { getReader().setSeries(no); } /* @see IFormatReader#getSeries() */ public int getSeries() { return getReader().getSeries(); } /* @see IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { return getReader().getUsedFiles(); } /* @see IFormatReader#getUsedFiles(boolean) */ public String[] getUsedFiles(boolean noPixels) { return getReader().getUsedFiles(noPixels); } /* @see IFormatReader#getSeriesUsedFiles() */ public String[] getSeriesUsedFiles() { return getReader().getSeriesUsedFiles(); } /* @see IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { return getReader().getSeriesUsedFiles(noPixels); } /* @see IFormatReader#getAdvancedUsedFiles(boolean) */ public FileInfo[] getAdvancedUsedFiles(boolean noPixels) { return getReader().getAdvancedUsedFiles(noPixels); } /* @see IFormatReader#getAdvancedSeriesUsedFiles(boolean) */ public FileInfo[] getAdvancedSeriesUsedFiles(boolean noPixels) { return getReader().getAdvancedSeriesUsedFiles(noPixels); } /* @see IFormatReader#getIndex(int, int, int) */ public int getIndex(int z, int c, int t) { return getReader().getIndex(z, c, t); } /* @see IFormatReader#getZCTCoords(int) */ public int[] getZCTCoords(int index) { return getReader().getZCTCoords(index); } /* @see IFormatReader#getMetadataValue(String) */ public Object getMetadataValue(String field) { return getReader().getMetadataValue(field); } /* @see IFormatReader#getGlobalMetadata() */ public Hashtable getGlobalMetadata() { return getReader().getGlobalMetadata(); } /* @see IFormatReader#getSeriesMetadata() */ public Hashtable getSeriesMetadata() { return getReader().getSeriesMetadata(); } /** @deprecated */ public Hashtable getMetadata() { return getReader().getMetadata(); } /* @see IFormatReader#getCoreMetadata() */ public CoreMetadata[] getCoreMetadata() { return getReader().getCoreMetadata(); } /* @see IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { for (int i=0; i<readers.length; i++) readers[i].close(fileOnly); if (!fileOnly) currentId = null; } /* @see IFormatReader#setGroupFiles(boolean) */ public void setGroupFiles(boolean group) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setGroupFiles(group); } /* @see IFormatReader#isGroupFiles() */ public boolean isGroupFiles() { return getReader().isGroupFiles(); } /* @see IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return getReader(id).fileGroupOption(id); } /* @see IFormatReader#isMetadataComplete() */ public boolean isMetadataComplete() { return getReader().isMetadataComplete(); } /* @see IFormatReader#setNormalized(boolean) */ public void setNormalized(boolean normalize) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setNormalized(normalize); } /* @see IFormatReader#isNormalized() */ public boolean isNormalized() { // NB: all readers should have the same normalization setting return readers[0].isNormalized(); } /* @see IFormatReader#setMetadataCollected(boolean) */ public void setMetadataCollected(boolean collect) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) { readers[i].setMetadataCollected(collect); } } /* @see IFormatReader#isMetadataCollected() */ public boolean isMetadataCollected() { return readers[0].isMetadataCollected(); } /* @see IFormatReader#setOriginalMetadataPopulated(boolean) */ public void setOriginalMetadataPopulated(boolean populate) { FormatTools.assertId(currentId, false, 1); for (int i=0; i<readers.length; i++) { readers[i].setOriginalMetadataPopulated(populate); } } /* @see IFormatReader#isOriginalMetadataPopulated() */ public boolean isOriginalMetadataPopulated() { return readers[0].isOriginalMetadataPopulated(); } /* @see IFormatReader#getCurrentFile() */ public String getCurrentFile() { return currentId; } /* @see IFormatReader#setMetadataFiltered(boolean) */ public void setMetadataFiltered(boolean filter) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setMetadataFiltered(filter); } /* @see IFormatReader#isMetadataFiltered() */ public boolean isMetadataFiltered() { // NB: all readers should have the same metadata filtering setting return readers[0].isMetadataFiltered(); } /* @see IFormatReader#setMetadataStore(MetadataStore) */ public void setMetadataStore(MetadataStore store) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setMetadataStore(store); } /* @see IFormatReader#getMetadataStore() */ public MetadataStore getMetadataStore() { return getReader().getMetadataStore(); } /* @see IFormatReader#getMetadataStoreRoot() */ public Object getMetadataStoreRoot() { return getReader().getMetadataStoreRoot(); } /* @see IFormatReader#getUnderlyingReaders() */ public IFormatReader[] getUnderlyingReaders() { return getReaders(); } /* @see IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return getReader(id).isSingleFile(id); } /* @see IFormatReader#getPossibleDomains(String) */ public String[] getPossibleDomains(String id) throws FormatException, IOException { return getReader(id).getPossibleDomains(id); } /* @see IFormatReader#getDomains() */ public String[] getDomains() { return getReader().getDomains(); } // -- IFormatHandler API methods -- /* @see IFormatHandler#isThisType(String) */ public boolean isThisType(String name) { // if necessary, open the file for further analysis // but check isThisType(name, false) first, for efficiency return isThisType(name, false) || isThisType(name, true); } /* @see IFormatHandler#getFormat() */ public String getFormat() { return getReader().getFormat(); } /* @see IFormatHandler#getSuffixes() */ public String[] getSuffixes() { if (suffixes == null) { HashSet suffixSet = new HashSet(); for (int i=0; i<readers.length; i++) { String[] suf = readers[i].getSuffixes(); for (int j=0; j<suf.length; j++) suffixSet.add(suf[j]); } suffixes = new String[suffixSet.size()]; suffixSet.toArray(suffixes); Arrays.sort(suffixes); } return suffixes; } /* @see IFormatHandler#getNativeDataType() */ public Class getNativeDataType() { return getReader().getNativeDataType(); } /* @see IFormatHandler#setId(String) */ public void setId(String id) throws FormatException, IOException { getReader(id).setId(id); } /* @see IFormatHandler#close() */ public void close() throws IOException { close(false); } // -- StatusReporter API methods -- /* @see IFormatHandler#addStatusListener(StatusListener) */ public void addStatusListener(StatusListener l) { for (int i=0; i<readers.length; i++) readers[i].addStatusListener(l); } /* @see IFormatHandler#removeStatusListener(StatusListener) */ public void removeStatusListener(StatusListener l) { for (int i=0; i<readers.length; i++) readers[i].removeStatusListener(l); } /* @see IFormatHandler#getStatusListeners() */ public StatusListener[] getStatusListeners() { // NB: all readers should have the same status listeners return readers[0].getStatusListeners(); } }
true
true
public IFormatReader getReader(String id) throws FormatException, IOException { // NB: Check that we can generate a valid handle for the ID; // e.g., for files, this will throw an exception if the file is missing. Location.getHandle(id); if (!id.equals(currentId)) { // initialize file boolean success = false; for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(id)) { current = i; currentId = id; success = true; break; } } if (!success) { throw new UnknownFormatException("Unknown file format: " + id); } } return getReader(); }
public IFormatReader getReader(String id) throws FormatException, IOException { // NB: Check that we can generate a valid handle for the ID; // e.g., for files, this will throw an exception if the file is missing. Location.getHandle(id).close(); if (!id.equals(currentId)) { // initialize file boolean success = false; for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(id)) { current = i; currentId = id; success = true; break; } } if (!success) { throw new UnknownFormatException("Unknown file format: " + id); } } return getReader(); }
diff --git a/USBCamera/src/com/ptplib/usbcamera/BaselineInitiator.java b/USBCamera/src/com/ptplib/usbcamera/BaselineInitiator.java index d4c6e07..e6e6035 100644 --- a/USBCamera/src/com/ptplib/usbcamera/BaselineInitiator.java +++ b/USBCamera/src/com/ptplib/usbcamera/BaselineInitiator.java @@ -1,1040 +1,1047 @@ // Copyright 2000 by David Brownell <[email protected]> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed epIn the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.ptplib.usbcamera; import java.nio.ByteBuffer; import com.ptplib.usbcamera.eos.EosEventConstants; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbRequest; import android.util.Log; import android.widget.ImageView; import android.widget.TextView; /** * This initiates interactions with USB devices, supporting only * mandatory PTP-over-USB operations; both * "push" and "pull" modes are supported. Note that there are some * operations that are mandatory for "push" responders and not "pull" * ones, and vice versa. A subclass adds additional standardized * operations, which some PTP devices won't support. All low * level interactions with the device are done by this class, * including especially error recovery. * * <p> The basic sequence of operations for any PTP or ISO 15470 * initiator (client) is: acquire the device; wrap it with this * driver class (or a subclass); issue operations; * close device. PTP has the notion * of a (single) session with the device, and until you have an open * session you may only invoke {@link #getDeviceInfo} and * {@link #openSession} operations. Moreover, devices may be used * both for reading images (as from a camera) and writing them * (as to a digital picture frame), depending on mode support. * * <p> Note that many of the IOExceptions thrown here are actually * going to be <code>usb.core.PTPException</code> values. That may * help your application level recovery processing. You should * assume that when any IOException is thrown, your current session * has been terminated. * * @see Initiator * * @version $Id: BaselineInitiator.java,v 1.17 2001/05/30 19:33:43 dbrownell Exp $ * @author David Brownell * * This class has been reworked by ste epIn order to make it compatible with * usbjava2. Also, this is more a derivative work than just an adaptation of the * original version. It has to serve the purposes of usbjava2 and cameracontrol. */ public class BaselineInitiator extends NameFactory implements Runnable { /////////////////////////////////////////////////////////////////// // USB Class-specific control requests; from Annex D.5.2 private static final byte CLASS_CANCEL_REQ = (byte) 0x64; private static final byte CLASS_GET_EVENT_DATA = (byte) 0x65; private static final byte CLASS_DEVICE_RESET = (byte) 0x66; private static final byte CLASS_GET_DEVICE_STATUS = (byte) 0x67; protected static final int DEFAULT_TIMEOUT = 1000; // ms final static boolean DEBUG = false; final static boolean TRACE = false; public static final String TAG = "BaselineInitiator"; protected UsbDevice device; protected UsbInterface intf; protected UsbEndpoint epIn; protected int inMaxPS; protected UsbEndpoint epOut; protected UsbEndpoint epEv; protected Session session; protected DeviceInfo info; public UsbDeviceConnection mConnection = null; // must be initialized first! // mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE); /** * Constructs a class driver object, if the device supports * operations according to Annex D of the PTP specification. * * @param device the first PTP interface will be used * @exception IllegalArgumentException if the device has no * Digital Still Imaging Class or PTP interfaces */ public BaselineInitiator(UsbDevice dev, UsbDeviceConnection connection) throws PTPException { if (connection == null) { throw new PTPException ("Connection = null");//IllegalArgumentException(); } this.mConnection = connection; // try { if (dev == null) { throw new PTPException ("dev = null");//IllegalArgumentException(); } session = new Session(); this.device = dev; intf = findUsbInterface (dev); // UsbInterface usbInterface = intf.getUsbInterface(); if (intf == null) { //if (usbInterface == null) { throw new PTPException("No PTP interfaces associated to the device"); } for (int i = 0; i < intf.getEndpointCount(); i++) { UsbEndpoint ep = intf.getEndpoint(i); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { epOut = ep; } else { epIn = ep; } } if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT){ epEv = ep; } } endpointSanityCheck(); inMaxPS = epOut.getMaxPacketSize(); //UsbDevice usbDevice = dev.getUsbDevice(); // UsbConfigDescriptor[] descriptors = usbDevice.getConfig(); // // if ((descriptors == null) || (descriptors.length < 1)) { // throw new PTPException("UsbDevice with no descriptors!"); // } // we want exclusive access to this interface. //TODO implement: UsbDeviceConnection.claimInterface (intf, true); // dev.open( // descriptors[0].getConfigurationValue(), // intf.getInterface(), // intf.getAlternateSetting() // ); // clear epOut any previous state reset(); if (getClearStatus() != Response.OK && getDeviceStatus(null) != Response.OK) { throw new PTPException("can't init"); } Log.d(TAG, "trying getDeviceInfoUncached"); // get info to sanity check later requests info = getDeviceInfoUncached(); // set up to use vendor extensions, if any if (info.vendorExtensionId != 0) { info.factory = updateFactory(info.vendorExtensionId); } session.setFactory((NameFactory) this); // } catch (USBBusyException e) { // throw new PTPBusyException(); // } catch (USBException e) { // throw new PTPException( // "Error initializing the communication with the camera (" + // e.getMessage() // + ")" , e); // } } // searches for an interface on the given USB device, returns only class 6 // From androiddevelopers ADB-Test private UsbInterface findUsbInterface(UsbDevice device) { //Log.d (TAG, "findAdbInterface " + device.getDeviceName()); int count = device.getInterfaceCount(); for (int i = 0; i < count; i++) { UsbInterface intf = device.getInterface(i); Log.d (TAG, "Interface " +i + " Class " +intf.getInterfaceClass() +" Prot " +intf.getInterfaceProtocol()); if (intf.getInterfaceClass() == 6 //255 && intf.getInterfaceSubclass() == 66 && intf.getInterfaceProtocol() == 1 ) { return intf; } } return null; } /** * @return the device */ public UsbDevice getDevice() { return device; } /** * Returns the last cached copy of the device info, or returns * a newly cached copy. * @see #getDeviceInfoUncached */ public DeviceInfo getDeviceInfo() throws PTPException { if (info == null) { return getDeviceInfoUncached(); } return info; } /** * Sends a USB level CLASS_DEVICE_RESET control message. * All PTP-over-USB devices support this operation. * This is documented to clear stalls and camera-specific suspends, * flush buffers, and close the current session. * * <p> <em>TO BE DETERMINED:</em> How does this differ from a bulk * protocol {@link Initiator#resetDevice ResetDevice} command? That * command is documented as very similar to this class operation. * Ideally, only this control request will ever be used, since it * works even when the bulk channels are halted. */ public void reset() throws PTPException { // try { /* * JAVA: public int controlMsg(int requestType, int request, int value, int index, byte[] data, int size, int timeout, boolean reopenOnTimeout) throws USBException Android: UsbDeviceConnection controlTransfer (int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) */ if (mConnection == null) throw new PTPException("No Connection"); mConnection.controlTransfer( (int) ( UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_CLASS /* | UsbConstants.RECIPIENT_INTERFACE */), CLASS_DEVICE_RESET, 0, 0, new byte[0], 0, DEFAULT_TIMEOUT //, //false ); session.close(); // } catch (USBException e) { // throw new PTPException( // "Error initializing the communication with the camera (" + // e.getMessage() // + ")" , e); // } } /** * Issues an OpenSession command to the device; may be used * with all responders. PTP-over-USB doesn't seem to support * multisession operations; you must close a session before * opening a new one. */ public void openSession() throws PTPException { Command command; Response response; synchronized (session) { command = new Command(Command.OpenSession, session, session.getNextSessionID()); response = transactUnsync(command, null); switch (response.getCode()) { case Response.OK: session.open(); Thread thread = new Thread (this); thread.start(); return; default: throw new PTPException(response.toString()); } } } /** * Issues a CloseSession command to the device; may be used * with all responders. */ public void closeSession() throws PTPException { Response response; synchronized (session) { // checks for session already open response = transact0(Command.CloseSession, null); switch (response.getCode()) { case Response.SessionNotOpen: if (DEBUG) { System.err.println("close unopen session?"); } // FALLTHROUGH case Response.OK: session.close(); return; default: throw new PTPException(response.toString()); } } } /** * Closes the session (if active) and releases the device. * * @throws PTPException */ public void close() throws PTPException { if (isSessionActive()) { try { closeSession(); } catch (PTPException ignore) { // // Is we cannot close the session, there is nothing we can do // } } try { if (mConnection != null && intf != null) mConnection.releaseInterface(intf); if (mConnection != null) mConnection.close(); device = null; info = null; } catch (Exception ignore) { throw new PTPException("Unable to close the USB device"); } } public Response showResponse (Response response) { Log.d(TAG, " Type: " + response.getBlockTypeName(response.getBlockType()) +" (Code: " +response.getBlockType() +")\n"); // getU16 (4) Log.d(TAG, " Name: " + response.getCodeName(response.getCode())+ ", code: 0x" +Integer.toHexString(response.getCode()) +"\n"); //getU16 (6) // log (" CodeString:" + response.getCodeString()+ "\n"); Log.d(TAG, " Length: " + response.getLength()+ " bytes\n"); //getS32 (0) Log.d(TAG, " String: " + response.toString()); return response; } public void showResponseCode (String comment, int code){ Log.d(TAG, comment +" Response: " +Response._getResponseString (code) +", code: 0x" +Integer.toHexString(code)); } /** * @return true if the current session is active, false otherwise */ public boolean isSessionActive() { synchronized (session) { return session.isActive(); } } /////////////////////////////////////////////////////////////////// // mandatory for all responders: generating events /** * Makes the invoking Thread read and report events reported * by the PTP responder, until the Initiator is closed. */ @Override public void run() { } // ------------------------------------------------------- Protected methods /////////////////////////////////////////////////////////////////// /** * Performs a PTP transaction, passing zero command parameters. * @param code the command code * @param data data to be sent or received; or null * @return response; check for code Response.OK before using * any positional response parameters */ protected Response transact0(int code, Data data) throws PTPException { synchronized (session) { Command command = new Command(code, session); return transactUnsync(command, data); } } /** * Performs a PTP transaction, passing one command parameter. * @param code the command code * @param data data to be sent or received; or null * @param p1 the first positional parameter * @return response; check for code Response.OK before using * any positional response parameters */ protected Response transact1(int code, Data data, int p1) throws PTPException { synchronized (session) { Command command = new Command(code, session, p1); return transactUnsync(command, data); } } /** * Performs a PTP transaction, passing two command parameters. * @param code the command code * @param data data to be sent or received; or null * @param p1 the first positional parameter * @param p2 the second positional parameter * @return response; check for code Response.OK before using * any positional response parameters */ protected Response transact2(int code, Data data, int p1, int p2) throws PTPException { synchronized (session) { Command command = new Command(code, session, p1, p2); return transactUnsync(command, data); } } /** * Performs a PTP transaction, passing three command parameters. * @param code the command code * @param data data to be sent or received; or null * @param p1 the first positional parameter * @param p2 the second positional parameter * @param p3 the third positional parameter * @return response; check for code Response.OK before using * any positional response parameters */ protected Response transact3(int code, Data data, int p1, int p2, int p3) throws PTPException { synchronized (session) { Command command = new Command(code, session, p1, p2, p3); return transactUnsync(command, data); } } // --------------------------------------------------------- Private methods // like getDeviceStatus(), // but clears stalled endpoints before returning // (except when exceptions are thrown) // returns -1 if device wouldn't return OK status int getClearStatus() throws PTPException { Buffer buf = new Buffer(null, 0); int retval = getDeviceStatus(buf); // any halted endpoints to clear? (always both) if (buf.length != 4) { while ((buf.offset + 4) <= buf.length) { int ep = buf.nextS32(); if (epIn.getAddress() == ep) { if (TRACE) { System.err.println("clearHalt epIn"); } clearHalt(epIn); } else if (epOut.getAddress() == ep) { if (TRACE) { System.err.println("clearHalt epOut"); } clearHalt(epOut); } else { if (DEBUG || TRACE) { System.err.println("?? halted EP: " + ep); } } } // device must say it's ready int status = Response.Undefined; for (int i = 0; i < 10; i++) { try { status = getDeviceStatus(null); } catch (PTPException x) { if (DEBUG) { x.printStackTrace(); } } if (status == Response.OK) { break; } if (TRACE) { System.err.println("sleep; status = " + getResponseString(status)); } try { Thread.sleep(1000); } catch (InterruptedException x) { } } if (status != Response.OK) { retval = -1; } } else { if (TRACE) { System.err.println("no endpoints halted"); } } return retval; } // returns Response.OK, Response.DeviceBusy, etc // per fig D.6, response may hold stalled endpoint numbers private int getDeviceStatus(Buffer buf) throws PTPException { // try { if (mConnection == null) throw new PTPException("No Connection"); byte[] data = new byte[33]; mConnection.controlTransfer( // device.controlMsg( (int) (UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_CLASS /* | UsbConstants.RECIPIENT_INTERFACE*/), CLASS_GET_DEVICE_STATUS, 0, 0, data, data.length, // force short reads DEFAULT_TIMEOUT //, //false ); if (buf == null) { buf = new Buffer(data); } else { buf.data = data; } buf.offset = 4; buf.length = buf.getU16(0); if (buf.length != buf.data.length) { //throw new PTPException("DeviceStatus error, Buffer length wrong!"); } return buf.getU16(2); // } catch (USBException e) { // throw new PTPException( // "Error initializing the communication with the camera (" + // e.getMessage() // + ")" , e); // } } // add event listener // rm event listener /////////////////////////////////////////////////////////////////// // mandatory for all responders /** * Issues a GetDeviceInfo command to the device; may be used * with all responders. This is the only generic PTP command * that may be issued both inside or outside of a session. */ private DeviceInfo getDeviceInfoUncached() throws PTPException { DeviceInfo data = new DeviceInfo(this); Response response; synchronized (session) { // Log.d(TAG, "getDeviceInfoUncached, sessionID " +session.getSessionId()); Command command; command = new Command(Command.GetDeviceInfo, session); // Log.d(TAG, "Command: " +(command.getCode()) +" session: " + session.getSessionId()); response = transactUnsync(command, data); // Log.d(TAG, "getDeviceInfoUncached finished, " +Response._getResponseString(response.getCode()) +" responsecode: " +response.getCode()); } switch (response.getCode()) { case Response.OK: info = data; return data; default: throw new PTPException(response.toString()); } } /////////////////////////////////////////////////////////////////// // INVARIANTS: // - caller is synchronized on session // - on return, device is always epIn idle/"command ready" state // - on return, session was only closed by CloseSession // - on PTPException, device (and session!) has been reset public Response transactUnsync(Command command, Data data) throws PTPException { if (!"command".equals(command.getBlockTypeName(command.getBlockType()))) { throw new IllegalArgumentException(command.toString()); } // Log.d(TAG, command.toString() + " Data: " +data.toString()); // sanity checking int opcode = command.getCode(); if (session.isActive()) { if (Command.OpenSession == opcode) { throw new IllegalStateException("session already open"); } } else { if (Command.GetDeviceInfo != opcode && Command.OpenSession != opcode) { throw new IllegalStateException("no session"); } } // this would be UnsupportedOperationException ... // except that it's not available on jdk 1.1 if (info != null && !info.supportsOperation(opcode)) { throw new UnsupportedOperationException(command.getCodeName(opcode)); } // ok, then we'll really talk to the device Response response; boolean abort = true; // try { // OutputStream stream = device.getOutputStream(epOut); // issue command // rejected commands will stall both EPs if (TRACE) { System.err.println(command.toString()); } int lenC = mConnection.bulkTransfer(epOut, command.data , command.length , DEFAULT_TIMEOUT); // Log.d(TAG, "Command bytes sent " +lenC); // stream.write(command.data, 0, command.length); // may need to terminate request with zero length packet if ((command.length % epOut.getMaxPacketSize()) == 0) { lenC = mConnection.bulkTransfer(epOut, command.data, 0, DEFAULT_TIMEOUT); // Log.d(TAG, "0 sent bytes:" +lenC); //stream.write(command.data, 0, 0); } // data exchanged? // errors or cancel (another thread) will stall both EPs if (data != null) { // write data? if (!data.isIn()) { // Log.d(TAG, "Start Write Data"); data.offset = 0; data.putHeader(data.getLength(), 2 /*Data*/, opcode, command.getXID()); if (TRACE) { System.err.println(data.toString()); } // Special handling for the read-from-N-mbytes-file case //TODO yet to be implemented // if (data instanceof FileSendData) { // FileSendData fd = (FileSendData) data; // int len = fd.data.length - fd.offset; // int temp; // // // fill up the rest of the first buffer // len = fd.read(fd.data, fd.offset, len); // if (len < 0) { // throw new PTPException("eh? " + len); // } // len += fd.offset; // // for (;;) { // // write data or terminating packet // mConnection.bulkTransfer(epOut, data , command.length , DEFAULT_TIMEOUT); // //stream.write(fd.data, 0, len); // if (len != fd.data.length) { // break; // } // // len = fd.read(fd.data, 0, fd.data.length); // if (len < 0) { // throw new PTPException("short: " + len); // } // } // // } else { // write data and maybe terminating packet byte[] bytes = data.getData();//new byte [data.length]; // Log.d(TAG, "send Data"); int len = mConnection.bulkTransfer(epOut, bytes , bytes.length, DEFAULT_TIMEOUT); // Log.d(TAG, "bytes sent " +len); if (len < 0) { throw new PTPException("short: " + len); } //stream.write(data.data, 0, data.length); if ((data.length % epOut.getMaxPacketSize()) == 0) { // Log.d(TAG, "send 0 Data"); mConnection.bulkTransfer(epOut, bytes , 0, DEFAULT_TIMEOUT); //stream.write(data.data, 0, 0); // } } // read data? } else { // Log.d(TAG, "Start Read Data"); byte buf1[] = new byte[inMaxPS]; int len = 0; //len = device.getInputStream(epIn).read(buf1); // Log.d(TAG, "Receive data, max " +inMaxPS); len = mConnection.bulkTransfer(epIn, buf1, inMaxPS , DEFAULT_TIMEOUT); // Log.d(TAG, "received data bytes: " +len); // Get the first bulk packet(s), check header for length data.data = buf1; data.length = len; if (TRACE) { System.err.println(data.toString()); } if (!"data".equals(data.getBlockTypeName(data.getBlockType())) || data.getCode() != command.getCode() || data.getXID() != command.getXID()) { throw new PTPException("protocol err 1, " + data); } // get the rest of it int expected = data.getLength(); // Special handling for the write-to-N-mbytes-file case //TODO yet to be implemented // if (data instanceof OutputStreamData) { // OutputStreamData fd = (OutputStreamData) data; // fd.write(buf1, Data.HDR_LEN, len - Data.HDR_LEN); // if (len == inMaxPS && expected != inMaxPS) { // InputStream is = device.getInputStream(epIn); // // // at max usb data rate, 128K ~= 0.11 seconds // // typically it's more time than that // buf1 = new byte[128 * 1024]; // do { // len = is.read(buf1); // fd.write(buf1, 0, len); // } while (len == buf1.length); // } // } else - if (len == inMaxPS && expected != inMaxPS) { - buf1 = new byte[expected]; - System.arraycopy(data.data, 0, buf1, 0, len); - data.data = buf1; -// Log.d(TAG, "read additional bytes " +(expected - len)); - data.length += mConnection.bulkTransfer(epIn, buf1, expected - len, DEFAULT_TIMEOUT);//device.getInputStream(epIn).read(buf1, len, expected - len); -// Log.d(TAG, "Read oK"); + if (len == inMaxPS && expected != inMaxPS) { + buf1 = new byte[expected]; + byte [] buf2 = new byte[expected]; + // System.arraycopy(data.data, 0, buf1, 0, len); + // data.data = buf1; + // Log.d(TAG, "read additional bytes " +(expected - len)); + System.arraycopy(data.data, 0, buf2, 0, inMaxPS); + data.length += mConnection.bulkTransfer(epIn, buf1, + expected - len, DEFAULT_TIMEOUT);// device.getInputStream(epIn).read(buf1, + // len, expected + // - len); + // Log.d(TAG, "Read oK"); + System.arraycopy(buf1, 0, buf2, inMaxPS, data.length-inMaxPS); + data.data = buf2; } // if ((expected % inMaxPS) == 0) // ... next packet will be zero length // and do whatever parsing needs to be done data.parse(); } } // (short) read the response // this won't stall anything byte buf[] = new byte[inMaxPS]; // Log.d(TAG, "read response"); int len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);//device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); // ZLP terminated previous data? if (len == 0) { len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);// device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); } response = new Response(buf, len, this); if (TRACE) { System.err.println(response.toString()); } abort = false; return response; //TODO implement stall detection // } catch (USBException e) { // if (DEBUG) { // e.printStackTrace(); // } // // // PTP devices will stall bulk EPs on error ... recover. // if (e.isStalled()) { // int status = -1; // // try { // // NOTE: this is the request's response code! It can't // // be gotten otherwise; despite current specs, this is a // // "control-and-bulk" protocol, NOT "bulk-only"; or more // // structurally, the protocol handles certain operations // // concurrently. // status = getClearStatus(); // } catch (PTPException x) { // if (DEBUG) { // x.printStackTrace(); // } // } // // // something's very broken // if (status == Response.OK || status == -1) { // throw new PTPException(e.getMessage(), e); // } // // // treat status code as the device's response // response = new Response(new byte[Response.HDR_LEN], this); // response.putHeader(Response.HDR_LEN, 3 /*response*/, // status, command.getXID()); // if (TRACE) { // System.err.println("STALLED: " + response.toString()); // } // // abort = false; // return response; // } // throw new PTPException(e.getMessage(), e); // // } catch (IOException e) { // throw new PTPException(e.getMessage(), e); // // } finally { // if (abort) { // // not an error we know how to recover; // // bye bye session! // reset(); // } // } } private void endpointSanityCheck() throws PTPException { if (epIn == null) { throw new PTPException("No input end-point found!"); } if (epOut == null) { throw new PTPException("No output end-point found!"); } if (epEv == null) { throw new PTPException("No input interrupt end-point found!"); } if (DEBUG){ Log.d(TAG, "Get: "+device.getInterfaceCount()+" Other: "+device.getDeviceName()); Log.d(TAG, "\nClass: "+intf.getInterfaceClass()+","+intf.getInterfaceSubclass()+","+intf.getInterfaceProtocol() + "\nIendpoints: "+epIn.getMaxPacketSize()+ " Type "+ epIn.getType() + " Dir "+epIn.getDirection()); //512 2 USB_ENDPOINT_XFER_BULK USB_DIR_IN Log.d(TAG, "\nOendpoints: "+epOut.getMaxPacketSize()+ " Type "+ epOut.getType() + " Dir "+epOut.getDirection()); //512 2 USB_ENDPOINT_XFER_BULK USB_DIR_OUT Log.d(TAG, "\nEendpoints: "+epEv.getMaxPacketSize()+ " Type "+ epEv.getType() + " Dir "+epEv.getDirection()); //8,3 USB_ENDPOINT_XFER_INT USB_DIR_IN } } private void clearHalt(UsbEndpoint e) { // // TODO: implement clearHalt of an endpoint // } //Ash code public void writeExtraData(Command command, Data data, int timeout) { int lenC = mConnection.bulkTransfer(epOut, command.data , command.length , timeout); if ((command.length % epOut.getMaxPacketSize()) == 0) { lenC = mConnection.bulkTransfer(epOut, command.data, 0, timeout); } //////////////////////////////////// int opcode = command.getCode(); data.offset = 0; data.putHeader(data.getLength(), 2 , opcode, command.getXID()); byte[] bytes = data.getData(); mConnection.bulkTransfer(epOut, data.getData() , data.length , timeout); if ((data.length % epOut.getMaxPacketSize()) == 0) { mConnection.bulkTransfer(epOut, bytes , 0, timeout); } } /************************************************************************************* * * * Methods to be overridden in camera-specific instances of baselineInititator * * * *************************************************************************************/ // this is an abstract method to be declared in public Response initiateCapture(int storageId, int formatCode) throws PTPException { return null; } public Response startBulb () throws PTPException{ return null; } public Response stopBulb () throws PTPException{ return null; } public Response setShutterSpeed (int speed) throws PTPException{ return null; } public Response setExposure(int exposure) throws PTPException{ return null; } public Response setISO(int value) throws PTPException{ return null; } public Response setAperture(int value) throws PTPException{ return null; } public Response setImageQuality(int value) throws PTPException{ return null; } // Floating point adapters public Response setShutterSpeed (double timeSeconds) throws PTPException{ return null; } public Response setAperture(double apertureValue) throws PTPException{ return null; } // Sets ISO to 50, 100, 200... or nearest value public Response setISO(double isoValue) throws PTPException{ return null; } public Response setExposure(double exposureValue) throws PTPException{ Log.d(TAG, "Not overriden!!!"); return null; } /** Selects image Quality from "S" to "RAW" in 4 steps * */ public Response setImageQuality (String quality) throws PTPException{ return null; } ////////////////////////Ash public Response setDevicePropValueEx (int x, int y) throws PTPException{ return null; } public Response MoveFocus (int x) throws PTPException{ return null; } public Response setPictureStyle (int x) throws PTPException{ return null; } public Response setWhiteBalance (int x) throws PTPException{ return null; } public Response setMetering (int x) throws PTPException{ return null; } public Response setDriveMode (int x) throws PTPException{ return null; } public DevicePropDesc getPropValue (int value) throws PTPException{ return null; } public void setupLiveview () throws PTPException{ } public void getLiveView(ImageView x){ } public byte[] read(int timeout) { Log.d(TAG,"Reading data"); byte data[] = new byte[inMaxPS]; //int lengthOfBytes = mConnection.bulkTransfer(epIn, data , inMaxPS , timeout); int retries=10; int tmp=-1; for(int i=0;i<retries;retries--){ tmp= mConnection.bulkTransfer(epIn, data , inMaxPS , timeout); if(tmp<0) Log.e(TAG,"Reading failed, retry"); else break; } return data; } public void write(byte[] data, int length, int timeout) { Log.d(TAG,"Sending command"); mConnection.bulkTransfer(epOut, data , length , timeout); } ///////////////////////// public void setFocusPos(int x, int y) { } public void setZoom(int zoomLevel) { } public void doAutoFocus() { } }
true
true
public Response transactUnsync(Command command, Data data) throws PTPException { if (!"command".equals(command.getBlockTypeName(command.getBlockType()))) { throw new IllegalArgumentException(command.toString()); } // Log.d(TAG, command.toString() + " Data: " +data.toString()); // sanity checking int opcode = command.getCode(); if (session.isActive()) { if (Command.OpenSession == opcode) { throw new IllegalStateException("session already open"); } } else { if (Command.GetDeviceInfo != opcode && Command.OpenSession != opcode) { throw new IllegalStateException("no session"); } } // this would be UnsupportedOperationException ... // except that it's not available on jdk 1.1 if (info != null && !info.supportsOperation(opcode)) { throw new UnsupportedOperationException(command.getCodeName(opcode)); } // ok, then we'll really talk to the device Response response; boolean abort = true; // try { // OutputStream stream = device.getOutputStream(epOut); // issue command // rejected commands will stall both EPs if (TRACE) { System.err.println(command.toString()); } int lenC = mConnection.bulkTransfer(epOut, command.data , command.length , DEFAULT_TIMEOUT); // Log.d(TAG, "Command bytes sent " +lenC); // stream.write(command.data, 0, command.length); // may need to terminate request with zero length packet if ((command.length % epOut.getMaxPacketSize()) == 0) { lenC = mConnection.bulkTransfer(epOut, command.data, 0, DEFAULT_TIMEOUT); // Log.d(TAG, "0 sent bytes:" +lenC); //stream.write(command.data, 0, 0); } // data exchanged? // errors or cancel (another thread) will stall both EPs if (data != null) { // write data? if (!data.isIn()) { // Log.d(TAG, "Start Write Data"); data.offset = 0; data.putHeader(data.getLength(), 2 /*Data*/, opcode, command.getXID()); if (TRACE) { System.err.println(data.toString()); } // Special handling for the read-from-N-mbytes-file case //TODO yet to be implemented // if (data instanceof FileSendData) { // FileSendData fd = (FileSendData) data; // int len = fd.data.length - fd.offset; // int temp; // // // fill up the rest of the first buffer // len = fd.read(fd.data, fd.offset, len); // if (len < 0) { // throw new PTPException("eh? " + len); // } // len += fd.offset; // // for (;;) { // // write data or terminating packet // mConnection.bulkTransfer(epOut, data , command.length , DEFAULT_TIMEOUT); // //stream.write(fd.data, 0, len); // if (len != fd.data.length) { // break; // } // // len = fd.read(fd.data, 0, fd.data.length); // if (len < 0) { // throw new PTPException("short: " + len); // } // } // // } else { // write data and maybe terminating packet byte[] bytes = data.getData();//new byte [data.length]; // Log.d(TAG, "send Data"); int len = mConnection.bulkTransfer(epOut, bytes , bytes.length, DEFAULT_TIMEOUT); // Log.d(TAG, "bytes sent " +len); if (len < 0) { throw new PTPException("short: " + len); } //stream.write(data.data, 0, data.length); if ((data.length % epOut.getMaxPacketSize()) == 0) { // Log.d(TAG, "send 0 Data"); mConnection.bulkTransfer(epOut, bytes , 0, DEFAULT_TIMEOUT); //stream.write(data.data, 0, 0); // } } // read data? } else { // Log.d(TAG, "Start Read Data"); byte buf1[] = new byte[inMaxPS]; int len = 0; //len = device.getInputStream(epIn).read(buf1); // Log.d(TAG, "Receive data, max " +inMaxPS); len = mConnection.bulkTransfer(epIn, buf1, inMaxPS , DEFAULT_TIMEOUT); // Log.d(TAG, "received data bytes: " +len); // Get the first bulk packet(s), check header for length data.data = buf1; data.length = len; if (TRACE) { System.err.println(data.toString()); } if (!"data".equals(data.getBlockTypeName(data.getBlockType())) || data.getCode() != command.getCode() || data.getXID() != command.getXID()) { throw new PTPException("protocol err 1, " + data); } // get the rest of it int expected = data.getLength(); // Special handling for the write-to-N-mbytes-file case //TODO yet to be implemented // if (data instanceof OutputStreamData) { // OutputStreamData fd = (OutputStreamData) data; // fd.write(buf1, Data.HDR_LEN, len - Data.HDR_LEN); // if (len == inMaxPS && expected != inMaxPS) { // InputStream is = device.getInputStream(epIn); // // // at max usb data rate, 128K ~= 0.11 seconds // // typically it's more time than that // buf1 = new byte[128 * 1024]; // do { // len = is.read(buf1); // fd.write(buf1, 0, len); // } while (len == buf1.length); // } // } else if (len == inMaxPS && expected != inMaxPS) { buf1 = new byte[expected]; System.arraycopy(data.data, 0, buf1, 0, len); data.data = buf1; // Log.d(TAG, "read additional bytes " +(expected - len)); data.length += mConnection.bulkTransfer(epIn, buf1, expected - len, DEFAULT_TIMEOUT);//device.getInputStream(epIn).read(buf1, len, expected - len); // Log.d(TAG, "Read oK"); } // if ((expected % inMaxPS) == 0) // ... next packet will be zero length // and do whatever parsing needs to be done data.parse(); } } // (short) read the response // this won't stall anything byte buf[] = new byte[inMaxPS]; // Log.d(TAG, "read response"); int len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);//device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); // ZLP terminated previous data? if (len == 0) { len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);// device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); } response = new Response(buf, len, this); if (TRACE) { System.err.println(response.toString()); } abort = false; return response; //TODO implement stall detection // } catch (USBException e) { // if (DEBUG) { // e.printStackTrace(); // } // // // PTP devices will stall bulk EPs on error ... recover. // if (e.isStalled()) { // int status = -1; // // try { // // NOTE: this is the request's response code! It can't // // be gotten otherwise; despite current specs, this is a // // "control-and-bulk" protocol, NOT "bulk-only"; or more // // structurally, the protocol handles certain operations // // concurrently. // status = getClearStatus(); // } catch (PTPException x) { // if (DEBUG) { // x.printStackTrace(); // } // } // // // something's very broken // if (status == Response.OK || status == -1) { // throw new PTPException(e.getMessage(), e); // } // // // treat status code as the device's response // response = new Response(new byte[Response.HDR_LEN], this); // response.putHeader(Response.HDR_LEN, 3 /*response*/, // status, command.getXID()); // if (TRACE) { // System.err.println("STALLED: " + response.toString()); // } // // abort = false; // return response; // } // throw new PTPException(e.getMessage(), e); // // } catch (IOException e) { // throw new PTPException(e.getMessage(), e); // // } finally { // if (abort) { // // not an error we know how to recover; // // bye bye session! // reset(); // } // } }
public Response transactUnsync(Command command, Data data) throws PTPException { if (!"command".equals(command.getBlockTypeName(command.getBlockType()))) { throw new IllegalArgumentException(command.toString()); } // Log.d(TAG, command.toString() + " Data: " +data.toString()); // sanity checking int opcode = command.getCode(); if (session.isActive()) { if (Command.OpenSession == opcode) { throw new IllegalStateException("session already open"); } } else { if (Command.GetDeviceInfo != opcode && Command.OpenSession != opcode) { throw new IllegalStateException("no session"); } } // this would be UnsupportedOperationException ... // except that it's not available on jdk 1.1 if (info != null && !info.supportsOperation(opcode)) { throw new UnsupportedOperationException(command.getCodeName(opcode)); } // ok, then we'll really talk to the device Response response; boolean abort = true; // try { // OutputStream stream = device.getOutputStream(epOut); // issue command // rejected commands will stall both EPs if (TRACE) { System.err.println(command.toString()); } int lenC = mConnection.bulkTransfer(epOut, command.data , command.length , DEFAULT_TIMEOUT); // Log.d(TAG, "Command bytes sent " +lenC); // stream.write(command.data, 0, command.length); // may need to terminate request with zero length packet if ((command.length % epOut.getMaxPacketSize()) == 0) { lenC = mConnection.bulkTransfer(epOut, command.data, 0, DEFAULT_TIMEOUT); // Log.d(TAG, "0 sent bytes:" +lenC); //stream.write(command.data, 0, 0); } // data exchanged? // errors or cancel (another thread) will stall both EPs if (data != null) { // write data? if (!data.isIn()) { // Log.d(TAG, "Start Write Data"); data.offset = 0; data.putHeader(data.getLength(), 2 /*Data*/, opcode, command.getXID()); if (TRACE) { System.err.println(data.toString()); } // Special handling for the read-from-N-mbytes-file case //TODO yet to be implemented // if (data instanceof FileSendData) { // FileSendData fd = (FileSendData) data; // int len = fd.data.length - fd.offset; // int temp; // // // fill up the rest of the first buffer // len = fd.read(fd.data, fd.offset, len); // if (len < 0) { // throw new PTPException("eh? " + len); // } // len += fd.offset; // // for (;;) { // // write data or terminating packet // mConnection.bulkTransfer(epOut, data , command.length , DEFAULT_TIMEOUT); // //stream.write(fd.data, 0, len); // if (len != fd.data.length) { // break; // } // // len = fd.read(fd.data, 0, fd.data.length); // if (len < 0) { // throw new PTPException("short: " + len); // } // } // // } else { // write data and maybe terminating packet byte[] bytes = data.getData();//new byte [data.length]; // Log.d(TAG, "send Data"); int len = mConnection.bulkTransfer(epOut, bytes , bytes.length, DEFAULT_TIMEOUT); // Log.d(TAG, "bytes sent " +len); if (len < 0) { throw new PTPException("short: " + len); } //stream.write(data.data, 0, data.length); if ((data.length % epOut.getMaxPacketSize()) == 0) { // Log.d(TAG, "send 0 Data"); mConnection.bulkTransfer(epOut, bytes , 0, DEFAULT_TIMEOUT); //stream.write(data.data, 0, 0); // } } // read data? } else { // Log.d(TAG, "Start Read Data"); byte buf1[] = new byte[inMaxPS]; int len = 0; //len = device.getInputStream(epIn).read(buf1); // Log.d(TAG, "Receive data, max " +inMaxPS); len = mConnection.bulkTransfer(epIn, buf1, inMaxPS , DEFAULT_TIMEOUT); // Log.d(TAG, "received data bytes: " +len); // Get the first bulk packet(s), check header for length data.data = buf1; data.length = len; if (TRACE) { System.err.println(data.toString()); } if (!"data".equals(data.getBlockTypeName(data.getBlockType())) || data.getCode() != command.getCode() || data.getXID() != command.getXID()) { throw new PTPException("protocol err 1, " + data); } // get the rest of it int expected = data.getLength(); // Special handling for the write-to-N-mbytes-file case //TODO yet to be implemented // if (data instanceof OutputStreamData) { // OutputStreamData fd = (OutputStreamData) data; // fd.write(buf1, Data.HDR_LEN, len - Data.HDR_LEN); // if (len == inMaxPS && expected != inMaxPS) { // InputStream is = device.getInputStream(epIn); // // // at max usb data rate, 128K ~= 0.11 seconds // // typically it's more time than that // buf1 = new byte[128 * 1024]; // do { // len = is.read(buf1); // fd.write(buf1, 0, len); // } while (len == buf1.length); // } // } else if (len == inMaxPS && expected != inMaxPS) { buf1 = new byte[expected]; byte [] buf2 = new byte[expected]; // System.arraycopy(data.data, 0, buf1, 0, len); // data.data = buf1; // Log.d(TAG, "read additional bytes " +(expected - len)); System.arraycopy(data.data, 0, buf2, 0, inMaxPS); data.length += mConnection.bulkTransfer(epIn, buf1, expected - len, DEFAULT_TIMEOUT);// device.getInputStream(epIn).read(buf1, // len, expected // - len); // Log.d(TAG, "Read oK"); System.arraycopy(buf1, 0, buf2, inMaxPS, data.length-inMaxPS); data.data = buf2; } // if ((expected % inMaxPS) == 0) // ... next packet will be zero length // and do whatever parsing needs to be done data.parse(); } } // (short) read the response // this won't stall anything byte buf[] = new byte[inMaxPS]; // Log.d(TAG, "read response"); int len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);//device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); // ZLP terminated previous data? if (len == 0) { len = mConnection.bulkTransfer(epIn, buf ,inMaxPS , DEFAULT_TIMEOUT);// device.getInputStream(epIn).read(buf); // Log.d(TAG, "received data bytes: " +len); } response = new Response(buf, len, this); if (TRACE) { System.err.println(response.toString()); } abort = false; return response; //TODO implement stall detection // } catch (USBException e) { // if (DEBUG) { // e.printStackTrace(); // } // // // PTP devices will stall bulk EPs on error ... recover. // if (e.isStalled()) { // int status = -1; // // try { // // NOTE: this is the request's response code! It can't // // be gotten otherwise; despite current specs, this is a // // "control-and-bulk" protocol, NOT "bulk-only"; or more // // structurally, the protocol handles certain operations // // concurrently. // status = getClearStatus(); // } catch (PTPException x) { // if (DEBUG) { // x.printStackTrace(); // } // } // // // something's very broken // if (status == Response.OK || status == -1) { // throw new PTPException(e.getMessage(), e); // } // // // treat status code as the device's response // response = new Response(new byte[Response.HDR_LEN], this); // response.putHeader(Response.HDR_LEN, 3 /*response*/, // status, command.getXID()); // if (TRACE) { // System.err.println("STALLED: " + response.toString()); // } // // abort = false; // return response; // } // throw new PTPException(e.getMessage(), e); // // } catch (IOException e) { // throw new PTPException(e.getMessage(), e); // // } finally { // if (abort) { // // not an error we know how to recover; // // bye bye session! // reset(); // } // } }
diff --git a/collect-server/src/it/java/org/openforis/collect/manager/CodeListImportProcessIntegrationTest.java b/collect-server/src/it/java/org/openforis/collect/manager/CodeListImportProcessIntegrationTest.java index 286e03f2e..451b4a078 100644 --- a/collect-server/src/it/java/org/openforis/collect/manager/CodeListImportProcessIntegrationTest.java +++ b/collect-server/src/it/java/org/openforis/collect/manager/CodeListImportProcessIntegrationTest.java @@ -1,201 +1,201 @@ package org.openforis.collect.manager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.openforis.collect.CollectIntegrationTest; import org.openforis.collect.manager.codelistimport.CodeListImportProcess; import org.openforis.collect.manager.codelistimport.CodeListImportStatus; import org.openforis.collect.manager.referencedataimport.ParsingError; import org.openforis.collect.model.CollectSurvey; import org.openforis.collect.persistence.SurveyImportException; import org.openforis.idm.metamodel.CodeList; import org.openforis.idm.metamodel.CodeList.CodeScope; import org.openforis.idm.metamodel.CodeListItem; import org.openforis.idm.metamodel.xml.IdmlParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author S. Ricci */ @RunWith( SpringJUnit4ClassRunner.class ) @ContextConfiguration( locations = {"classpath:test-context.xml"} ) @TransactionConfiguration(defaultRollback=true) @Transactional public class CodeListImportProcessIntegrationTest extends CollectIntegrationTest { private static final String VALID_TEST_CSV = "code-list-test.csv"; private static final String VALID_MULTILANG_TEST_CSV = "code-list-multi-lang-test.csv"; private static final String INVALID_TEST_CSV = "code-list-invalid-test.csv"; private static final String INVALID_SCHEME_SCOPE_TEST_CSV = "code-list-invalid-scheme-scope-test.csv"; private static final String LANG = "en"; private static final String TEST_CODE_LIST_NAME = "test"; @Autowired private SurveyManager surveyManager; @Autowired private CodeListManager codeListManager; private CollectSurvey survey; @Before public void init() throws IdmlParseException, IOException, SurveyImportException { survey = loadSurvey(); surveyManager.saveSurveyWork(survey); } public CodeListImportProcess importCSVFile(String fileName, CodeList codeList, CodeScope codeScope) throws Exception { File file = getTestFile(fileName); CodeListImportProcess process = new CodeListImportProcess(codeListManager, codeList, codeScope, LANG, file, true); process.call(); return process; } @Test public void testImport() throws Exception { CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(VALID_TEST_CSV, codeList, CodeScope.LOCAL); CodeListImportStatus status = process.getStatus(); assertTrue(status.isComplete()); assertTrue(status.getSkippedRows().isEmpty()); assertEquals(6, status.getProcessed()); - List<CodeListItem> items = codeList.getItems(); + List<CodeListItem> items = codeListManager.loadRootItems(codeList); assertEquals(3, items.size()); { - CodeListItem item = codeList.getItem("001"); + CodeListItem item = codeListManager.loadRootItem(codeList, "001", null); assertNotNull(item); assertEquals("Dodoma", item.getLabel(LANG)); - List<CodeListItem> childItems = item.getChildItems(); + List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Kondoa", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Mpwapwa", childItem.getLabel(LANG)); } { - CodeListItem item = codeList.getItem("002"); + CodeListItem item = codeListManager.loadRootItem(codeList, "002", null); assertNotNull(item); assertEquals("Arusha", item.getLabel(LANG)); - List<CodeListItem> childItems = item.getChildItems(); + List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Monduli", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Arumeru", childItem.getLabel(LANG)); } { - CodeListItem item = codeList.getItem("003"); + CodeListItem item = codeListManager.loadRootItem(codeList, "003", null); assertNotNull(item); } } @Test public void testMultiLangImport() throws Exception { survey.addLanguage("es"); CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(VALID_MULTILANG_TEST_CSV, codeList, CodeScope.LOCAL); CodeListImportStatus status = process.getStatus(); assertTrue(status.isComplete()); assertTrue(status.getSkippedRows().isEmpty()); assertEquals(5, status.getProcessed()); List<CodeListItem> items = codeListManager.loadRootItems(codeList); assertEquals(2, items.size()); { CodeListItem item = codeListManager.loadRootItem(codeList, "001", null); assertNotNull(item); assertEquals("Dodoma", item.getLabel(LANG)); assertEquals("Dodoma ES", item.getLabel("es")); List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Kondoa", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Mpwapwa", childItem.getLabel(LANG)); assertEquals("Mpwapwa ES", childItem.getLabel("es")); } { CodeListItem item = codeListManager.loadRootItem(codeList, "002", null); assertNotNull(item); assertEquals("Arusha", item.getLabel(LANG)); List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Monduli", childItem.getLabel(LANG)); assertNull(childItem.getLabel("es")); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Arumeru", childItem.getLabel(LANG)); } } @Test public void testDuplicateValues() throws Exception { CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(INVALID_TEST_CSV, codeList, CodeScope.LOCAL); CodeListImportStatus status = process.getStatus(); assertTrue(status.isError()); List<ParsingError> errors = status.getErrors(); assertTrue(containsError(errors, 4, "region_label_en")); //different label assertTrue(containsError(errors, 4, "district_code")); assertTrue(containsError(errors, 7, "district_code")); } @Test public void testDuplicateValuesSchemeScope() throws Exception { CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(INVALID_SCHEME_SCOPE_TEST_CSV, codeList, CodeScope.SCHEME); CodeListImportStatus status = process.getStatus(); assertTrue(status.isError()); List<ParsingError> errors = status.getErrors(); assertTrue(containsError(errors, 4, "region_label_en")); //different label assertTrue(containsError(errors, 5, "district_code")); assertTrue(containsError(errors, 6, "district_code")); } protected boolean containsError(List<ParsingError> errors, long row, String column) { for (ParsingError error : errors) { if ( error.getRow() == row && Arrays.asList(error.getColumns()).contains(column) ) { return true; } } return false; } protected File getTestFile(String fileName) throws URISyntaxException { URL fileUrl = ClassLoader.getSystemResource(fileName); File file = new File(fileUrl.toURI()); return file; } }
false
true
public void testImport() throws Exception { CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(VALID_TEST_CSV, codeList, CodeScope.LOCAL); CodeListImportStatus status = process.getStatus(); assertTrue(status.isComplete()); assertTrue(status.getSkippedRows().isEmpty()); assertEquals(6, status.getProcessed()); List<CodeListItem> items = codeList.getItems(); assertEquals(3, items.size()); { CodeListItem item = codeList.getItem("001"); assertNotNull(item); assertEquals("Dodoma", item.getLabel(LANG)); List<CodeListItem> childItems = item.getChildItems(); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Kondoa", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Mpwapwa", childItem.getLabel(LANG)); } { CodeListItem item = codeList.getItem("002"); assertNotNull(item); assertEquals("Arusha", item.getLabel(LANG)); List<CodeListItem> childItems = item.getChildItems(); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Monduli", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Arumeru", childItem.getLabel(LANG)); } { CodeListItem item = codeList.getItem("003"); assertNotNull(item); } }
public void testImport() throws Exception { CodeList codeList = survey.createCodeList(); codeList.setName(TEST_CODE_LIST_NAME); survey.addCodeList(codeList); CodeListImportProcess process = importCSVFile(VALID_TEST_CSV, codeList, CodeScope.LOCAL); CodeListImportStatus status = process.getStatus(); assertTrue(status.isComplete()); assertTrue(status.getSkippedRows().isEmpty()); assertEquals(6, status.getProcessed()); List<CodeListItem> items = codeListManager.loadRootItems(codeList); assertEquals(3, items.size()); { CodeListItem item = codeListManager.loadRootItem(codeList, "001", null); assertNotNull(item); assertEquals("Dodoma", item.getLabel(LANG)); List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Kondoa", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Mpwapwa", childItem.getLabel(LANG)); } { CodeListItem item = codeListManager.loadRootItem(codeList, "002", null); assertNotNull(item); assertEquals("Arusha", item.getLabel(LANG)); List<CodeListItem> childItems = codeListManager.loadChildItems(item); assertEquals(2, childItems.size()); CodeListItem childItem = childItems.get(0); assertEquals("001", childItem.getCode()); assertEquals("Monduli", childItem.getLabel(LANG)); childItem = childItems.get(1); assertEquals("002", childItem.getCode()); assertEquals("Arumeru", childItem.getLabel(LANG)); } { CodeListItem item = codeListManager.loadRootItem(codeList, "003", null); assertNotNull(item); } }
diff --git a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/vespucci_model/diagram/edit/parts/outline/OutlineDummyEditPart.java b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/vespucci_model/diagram/edit/parts/outline/OutlineDummyEditPart.java index 5ee11dbe..c8b4fc0f 100644 --- a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/vespucci_model/diagram/edit/parts/outline/OutlineDummyEditPart.java +++ b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/vespucci_model/diagram/edit/parts/outline/OutlineDummyEditPart.java @@ -1,110 +1,112 @@ /* * License (BSD Style License): * Copyright (c) 2010 * Author Artem Vovk * Software Engineering * Department of Computer Science * Technische Universit�t Darmstadt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the Software Engineering Group or Technische * Universit�t Darmstadt nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.tud.cs.st.vespucci.vespucci_model.diagram.edit.parts.outline; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.gmf.runtime.diagram.ui.editparts.TreeEditPart; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.gmf.runtime.notation.impl.ConnectorImpl; import org.eclipse.gmf.runtime.notation.impl.NodeImpl; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import de.tud.cs.st.vespucci.vespucci_model.diagram.part.VespucciDiagramEditorPlugin; /** * OutlineEditPart for dummy object * * @author a_vovk * */ public class OutlineDummyEditPart extends TreeEditPart { private static final String ENSEMBLE_IMAGE = "icons/outline/Dummy.gif"; public OutlineDummyEditPart(Object model) { super(model); } @Override protected Image getImage() { ImageDescriptor imageDescriptor = VespucciDiagramEditorPlugin .getBundledImageDescriptor(ENSEMBLE_IMAGE); return imageDescriptor.createImage(); } @SuppressWarnings("unchecked") @Override protected List<?> getModelChildren() { Object model = getModel(); if (model instanceof NodeImpl) { NodeImpl node = (NodeImpl) getModel(); - return filterConnectionsFromConnectorImpl(node.getSourceEdges()); + EList<View> out = filterConnectionsFromConnectorImpl(node.getSourceEdges()); + out.addAll(node.getTargetEdges()); + return out; } return Collections.EMPTY_LIST; } /** * Filter connections for EdgeImpl: delete ConnectorImpl * * @param connections * connections to filter * @return filtered connections */ private EList<View> filterConnectionsFromConnectorImpl( EList<View> connections) { EList<View> out = new BasicEList<View>(); for (View i : connections) { if (!(i instanceof ConnectorImpl)) { out.add(i); } } return out; } @Override protected void handleNotificationEvent(Notification event) { refresh(); } }
true
true
protected List<?> getModelChildren() { Object model = getModel(); if (model instanceof NodeImpl) { NodeImpl node = (NodeImpl) getModel(); return filterConnectionsFromConnectorImpl(node.getSourceEdges()); } return Collections.EMPTY_LIST; }
protected List<?> getModelChildren() { Object model = getModel(); if (model instanceof NodeImpl) { NodeImpl node = (NodeImpl) getModel(); EList<View> out = filterConnectionsFromConnectorImpl(node.getSourceEdges()); out.addAll(node.getTargetEdges()); return out; } return Collections.EMPTY_LIST; }
diff --git a/raven-integration-tests/src/test/java/net/kencochrane/raven/integration/ClientTest.java b/raven-integration-tests/src/test/java/net/kencochrane/raven/integration/ClientTest.java index 121b4194..3fac067b 100644 --- a/raven-integration-tests/src/test/java/net/kencochrane/raven/integration/ClientTest.java +++ b/raven-integration-tests/src/test/java/net/kencochrane/raven/integration/ClientTest.java @@ -1,141 +1,139 @@ package net.kencochrane.raven.integration; import net.kencochrane.raven.Client; import net.kencochrane.raven.SentryApi; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.*; import static org.junit.Assert.*; /** * Integration tests for {@link net.kencochrane.raven.Client}. */ public class ClientTest { private SentryApi api; @Test public void captureMessage_http() throws IOException, InterruptedException { Client client = new Client(IntegrationContext.httpDsn); String message = ClientTest.class.getName() + ".captureMessage_http says hi!"; captureMessage(client, message, false); } @Test public void captureMessage_withTags() throws IOException, InterruptedException { Client client = new Client(IntegrationContext.httpDsn); String message = ClientTest.class.getName() + ".captureMessage_withTags says hi!"; Map<String, Object> tags = new HashMap<String, Object>(); tags.put("release", "1.2.0"); tags.put("uptime", 60000L); tags.put("client", "Raven-Java"); captureMessage(client, message, false, tags); } @Test public void captureMessage_udp() throws IOException, InterruptedException { Client client = new Client(IntegrationContext.udpDsn); String message = ClientTest.class.getName() + ".captureMessage_udp says hi!"; captureMessage(client, message, true); } @Test public void captureMessage_complex_http() throws IOException { Client client = new Client(IntegrationContext.httpDsn); final String message = ClientTest.class.getName() + ".captureMessage_complex_http says hi!"; final String logger = "some.custom.logger.Name"; final String culprit = "Damn you!"; client.captureMessage(message, null, logger, null, culprit); List<SentryApi.Event> events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event event = events.get(0); assertTrue(event.count > 0); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(culprit, event.title); assertEquals(logger, event.logger); } @Test public void captureMessage_complex_udp() throws IOException, InterruptedException { Client client = new Client(IntegrationContext.udpDsn); final String message = ClientTest.class.getName() + ".captureMessage_complex_udp says hi!"; final String logger = "some.custom.logger.Name"; final String culprit = "Damn you!"; client.captureMessage(message, null, logger, null, culprit); Thread.sleep(1000); List<SentryApi.Event> events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event event = events.get(0); assertTrue(event.count > 0); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(culprit, event.title); assertEquals(logger, event.logger); } protected void captureMessage(Client client, String message, boolean wait) throws IOException, InterruptedException { captureMessage(client, message, wait, null); } protected void captureMessage(Client client, String message, boolean wait, Map<String, ?> tags) throws IOException, InterruptedException { client.captureMessage(message, tags); if (wait) { // Wait a bit in case of UDP transport Thread.sleep(1000); } List<SentryApi.Event> events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event event = events.get(0); assertTrue(event.count > 0); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); // Log the same message; the count should be incremented client.captureMessage(message, tags); if (wait) { Thread.sleep(1000); } events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event newEvent = events.get(0); assertEquals(event.count + 1, newEvent.count); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); JSONArray jsonArray = api.getRawJson(IntegrationContext.projectSlug, newEvent.group); assertNotNull(jsonArray); assertTrue(jsonArray.size() > 0); JSONObject json = (JSONObject) jsonArray.get(0); JSONObject messageJson = (JSONObject) json.get("sentry.interfaces.Message"); assertNotNull(messageJson); assertEquals(message, messageJson.get("message")); assertTrue(messageJson.get("params") instanceof JSONArray); if (tags != null && !tags.isEmpty()) { List<String> tagNames = api.getAvailableTags(IntegrationContext.projectSlug); - Set<String> nonMatches = new HashSet<String>(tags.keySet()); - nonMatches.removeAll(tagNames); - assertTrue(nonMatches.isEmpty()); + assertTrue(new HashSet<String>(tagNames).containsAll(tags.keySet())); } } @Before public void setUp() throws IOException { IntegrationContext.init(); api = IntegrationContext.api; api.clear(IntegrationContext.httpDsn.projectId); } }
true
true
protected void captureMessage(Client client, String message, boolean wait, Map<String, ?> tags) throws IOException, InterruptedException { client.captureMessage(message, tags); if (wait) { // Wait a bit in case of UDP transport Thread.sleep(1000); } List<SentryApi.Event> events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event event = events.get(0); assertTrue(event.count > 0); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); // Log the same message; the count should be incremented client.captureMessage(message, tags); if (wait) { Thread.sleep(1000); } events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event newEvent = events.get(0); assertEquals(event.count + 1, newEvent.count); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); JSONArray jsonArray = api.getRawJson(IntegrationContext.projectSlug, newEvent.group); assertNotNull(jsonArray); assertTrue(jsonArray.size() > 0); JSONObject json = (JSONObject) jsonArray.get(0); JSONObject messageJson = (JSONObject) json.get("sentry.interfaces.Message"); assertNotNull(messageJson); assertEquals(message, messageJson.get("message")); assertTrue(messageJson.get("params") instanceof JSONArray); if (tags != null && !tags.isEmpty()) { List<String> tagNames = api.getAvailableTags(IntegrationContext.projectSlug); Set<String> nonMatches = new HashSet<String>(tags.keySet()); nonMatches.removeAll(tagNames); assertTrue(nonMatches.isEmpty()); } }
protected void captureMessage(Client client, String message, boolean wait, Map<String, ?> tags) throws IOException, InterruptedException { client.captureMessage(message, tags); if (wait) { // Wait a bit in case of UDP transport Thread.sleep(1000); } List<SentryApi.Event> events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event event = events.get(0); assertTrue(event.count > 0); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); // Log the same message; the count should be incremented client.captureMessage(message, tags); if (wait) { Thread.sleep(1000); } events = api.getEvents(IntegrationContext.projectSlug); assertEquals(1, events.size()); SentryApi.Event newEvent = events.get(0); assertEquals(event.count + 1, newEvent.count); assertEquals(Client.Default.LOG_LEVEL, event.level); assertEquals(message, event.message); assertEquals(message, event.title); assertEquals(Client.Default.LOGGER, event.logger); JSONArray jsonArray = api.getRawJson(IntegrationContext.projectSlug, newEvent.group); assertNotNull(jsonArray); assertTrue(jsonArray.size() > 0); JSONObject json = (JSONObject) jsonArray.get(0); JSONObject messageJson = (JSONObject) json.get("sentry.interfaces.Message"); assertNotNull(messageJson); assertEquals(message, messageJson.get("message")); assertTrue(messageJson.get("params") instanceof JSONArray); if (tags != null && !tags.isEmpty()) { List<String> tagNames = api.getAvailableTags(IntegrationContext.projectSlug); assertTrue(new HashSet<String>(tagNames).containsAll(tags.keySet())); } }
diff --git a/core/src/org/objenesis/InstantiatorFactory.java b/core/src/org/objenesis/InstantiatorFactory.java index 0754c63..74a98c7 100644 --- a/core/src/org/objenesis/InstantiatorFactory.java +++ b/core/src/org/objenesis/InstantiatorFactory.java @@ -1,24 +1,24 @@ package org.objenesis; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class InstantiatorFactory { public static ObjectInstantiator getInstantiator(Class instantiatorClass, Class type) { Constructor constructor; try { constructor = instantiatorClass.getDeclaredConstructor(new Class[] {Class.class}); return (ObjectInstantiator)constructor.newInstance(new Object[]{type}); } catch (SecurityException e) { - throw new UnsupportedOperationException("Security Manager does not allow creation through reflection"); + throw new UnsupportedOperationException("Security Manager exception: "+e.getMessage()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Bad instantiator class. No constructor found with 'java.lang.Class' argument"); } catch (InstantiationException e) { - throw new RuntimeException("Problems creating instantiator", e); + throw new RuntimeException("InstantiationException creating instantiator of class "+type.getName()+": "+e.getMessage()); } catch (IllegalAccessException e) { - throw new RuntimeException("Problems creating instantiator", e); + throw new RuntimeException("IlleglAccessException creating instantiator of class "+type.getName()+": "+e.getMessage()); } catch (InvocationTargetException e) { - throw new RuntimeException("Problems creating instantiator", e); + throw new RuntimeException("InvocationTargetException creating instantiator of class "+type.getName()+": "+e.getMessage()); } - } + } }
false
true
public static ObjectInstantiator getInstantiator(Class instantiatorClass, Class type) { Constructor constructor; try { constructor = instantiatorClass.getDeclaredConstructor(new Class[] {Class.class}); return (ObjectInstantiator)constructor.newInstance(new Object[]{type}); } catch (SecurityException e) { throw new UnsupportedOperationException("Security Manager does not allow creation through reflection"); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Bad instantiator class. No constructor found with 'java.lang.Class' argument"); } catch (InstantiationException e) { throw new RuntimeException("Problems creating instantiator", e); } catch (IllegalAccessException e) { throw new RuntimeException("Problems creating instantiator", e); } catch (InvocationTargetException e) { throw new RuntimeException("Problems creating instantiator", e); } }
public static ObjectInstantiator getInstantiator(Class instantiatorClass, Class type) { Constructor constructor; try { constructor = instantiatorClass.getDeclaredConstructor(new Class[] {Class.class}); return (ObjectInstantiator)constructor.newInstance(new Object[]{type}); } catch (SecurityException e) { throw new UnsupportedOperationException("Security Manager exception: "+e.getMessage()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Bad instantiator class. No constructor found with 'java.lang.Class' argument"); } catch (InstantiationException e) { throw new RuntimeException("InstantiationException creating instantiator of class "+type.getName()+": "+e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("IlleglAccessException creating instantiator of class "+type.getName()+": "+e.getMessage()); } catch (InvocationTargetException e) { throw new RuntimeException("InvocationTargetException creating instantiator of class "+type.getName()+": "+e.getMessage()); } }
diff --git a/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java b/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java index 77d7ce8c..dbd2b6a9 100644 --- a/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java +++ b/src/main/java/org/primefaces/extensions/component/tooltip/TooltipRenderer.java @@ -1,135 +1,139 @@ /* * Copyright 2011 PrimeFaces Extensions. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ */ package org.primefaces.extensions.component.tooltip; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.extensions.util.ComponentUtils; import org.primefaces.extensions.util.FastStringWriter; import org.primefaces.renderkit.CoreRenderer; /** * Renderer for the {@link Tooltip} component. * * @author Oleg Varaksin / last modified by $Author$ * @version $Revision$ * @since 0.2 */ public class TooltipRenderer extends CoreRenderer { @Override public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); Tooltip tooltip = (Tooltip) component; String clientId = tooltip.getClientId(context); boolean global = tooltip.isGlobal(); boolean shared = tooltip.isShared(); boolean autoShow = tooltip.isAutoShow(); boolean mouseTracking = tooltip.isMouseTracking(); String target = null; if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) { target = ComponentUtils.findTarget(context, tooltip); } startScript(writer, clientId); writer.write("$(function() {"); writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{"); writer.write("id:'" + clientId + "'"); writer.write(",global:" + global); writer.write(",shared:" + shared); writer.write(",autoShow:" + autoShow); if (target == null) { writer.write(",forTarget:null"); } else { writer.write(",forTarget:'" + target + "'"); } if (!global) { writer.write(",content:\""); if (tooltip.getChildCount() > 0) { FastStringWriter fsw = new FastStringWriter(); ResponseWriter clonedWriter = writer.cloneWithWriter(fsw); context.setResponseWriter(clonedWriter); renderChildren(context, tooltip); context.setResponseWriter(writer); writer.write(escapeText(fsw.toString())); } else { String valueToRender = ComponentUtils.getValueToRender(context, tooltip); if (valueToRender != null) { writer.write(escapeText(valueToRender)); } } writer.write("\""); } // events if (mouseTracking) { writer.write(",hide:{fixed:true}"); } else if (shared && !global) { - writer.write(",show:{target:$('" + target + "')}"); - writer.write(",hide:{target:$('" + target + "')}"); + writer.write(",show:{target:$('" + target + "')" + ",delay:" + tooltip.getShowDelay() + + ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + + ");}}"); + writer.write(",hide:{target:$('" + target + "')" + ",delay:" + tooltip.getHideDelay() + + ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + + ");}}"); } else if (autoShow) { writer.write(",show:{when:false,ready:true}"); writer.write(",hide:false"); } else { writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay() + ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + ");}}"); writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay() + ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + ");}}"); } // position writer.write(",position: {"); writer.write("at:'" + tooltip.getAtPosition() + "'"); writer.write(",my:'" + tooltip.getMyPosition() + "'"); writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}"); if (mouseTracking) { writer.write(",target:'mouse'"); writer.write(",viewport:$(window)"); } else if (shared && !global) { writer.write(",target:'event'"); writer.write(",effect:false"); } writer.write("}},true);});"); endScript(writer); } @Override public void encodeChildren(final FacesContext context, final UIComponent component) throws IOException { //do nothing } @Override public boolean getRendersChildren() { return true; } }
true
true
public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); Tooltip tooltip = (Tooltip) component; String clientId = tooltip.getClientId(context); boolean global = tooltip.isGlobal(); boolean shared = tooltip.isShared(); boolean autoShow = tooltip.isAutoShow(); boolean mouseTracking = tooltip.isMouseTracking(); String target = null; if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) { target = ComponentUtils.findTarget(context, tooltip); } startScript(writer, clientId); writer.write("$(function() {"); writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{"); writer.write("id:'" + clientId + "'"); writer.write(",global:" + global); writer.write(",shared:" + shared); writer.write(",autoShow:" + autoShow); if (target == null) { writer.write(",forTarget:null"); } else { writer.write(",forTarget:'" + target + "'"); } if (!global) { writer.write(",content:\""); if (tooltip.getChildCount() > 0) { FastStringWriter fsw = new FastStringWriter(); ResponseWriter clonedWriter = writer.cloneWithWriter(fsw); context.setResponseWriter(clonedWriter); renderChildren(context, tooltip); context.setResponseWriter(writer); writer.write(escapeText(fsw.toString())); } else { String valueToRender = ComponentUtils.getValueToRender(context, tooltip); if (valueToRender != null) { writer.write(escapeText(valueToRender)); } } writer.write("\""); } // events if (mouseTracking) { writer.write(",hide:{fixed:true}"); } else if (shared && !global) { writer.write(",show:{target:$('" + target + "')}"); writer.write(",hide:{target:$('" + target + "')}"); } else if (autoShow) { writer.write(",show:{when:false,ready:true}"); writer.write(",hide:false"); } else { writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay() + ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + ");}}"); writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay() + ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + ");}}"); } // position writer.write(",position: {"); writer.write("at:'" + tooltip.getAtPosition() + "'"); writer.write(",my:'" + tooltip.getMyPosition() + "'"); writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}"); if (mouseTracking) { writer.write(",target:'mouse'"); writer.write(",viewport:$(window)"); } else if (shared && !global) { writer.write(",target:'event'"); writer.write(",effect:false"); } writer.write("}},true);});"); endScript(writer); }
public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); Tooltip tooltip = (Tooltip) component; String clientId = tooltip.getClientId(context); boolean global = tooltip.isGlobal(); boolean shared = tooltip.isShared(); boolean autoShow = tooltip.isAutoShow(); boolean mouseTracking = tooltip.isMouseTracking(); String target = null; if (!global || (tooltip.getFor() != null || tooltip.getForSelector() != null)) { target = ComponentUtils.findTarget(context, tooltip); } startScript(writer, clientId); writer.write("$(function() {"); writer.write("PrimeFacesExt.cw('Tooltip', '" + tooltip.resolveWidgetVar() + "',{"); writer.write("id:'" + clientId + "'"); writer.write(",global:" + global); writer.write(",shared:" + shared); writer.write(",autoShow:" + autoShow); if (target == null) { writer.write(",forTarget:null"); } else { writer.write(",forTarget:'" + target + "'"); } if (!global) { writer.write(",content:\""); if (tooltip.getChildCount() > 0) { FastStringWriter fsw = new FastStringWriter(); ResponseWriter clonedWriter = writer.cloneWithWriter(fsw); context.setResponseWriter(clonedWriter); renderChildren(context, tooltip); context.setResponseWriter(writer); writer.write(escapeText(fsw.toString())); } else { String valueToRender = ComponentUtils.getValueToRender(context, tooltip); if (valueToRender != null) { writer.write(escapeText(valueToRender)); } } writer.write("\""); } // events if (mouseTracking) { writer.write(",hide:{fixed:true}"); } else if (shared && !global) { writer.write(",show:{target:$('" + target + "')" + ",delay:" + tooltip.getShowDelay() + ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + ");}}"); writer.write(",hide:{target:$('" + target + "')" + ",delay:" + tooltip.getHideDelay() + ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + ");}}"); } else if (autoShow) { writer.write(",show:{when:false,ready:true}"); writer.write(",hide:false"); } else { writer.write(",show:{event:'" + tooltip.getShowEvent() + "',delay:" + tooltip.getShowDelay() + ",effect:function(){$(this)." + tooltip.getShowEffect() + "(" + tooltip.getShowEffectLength() + ");}}"); writer.write(",hide:{event:'" + tooltip.getHideEvent() + "',delay:" + tooltip.getHideDelay() + ",effect:function(){$(this)." + tooltip.getHideEffect() + "(" + tooltip.getHideEffectLength() + ");}}"); } // position writer.write(",position: {"); writer.write("at:'" + tooltip.getAtPosition() + "'"); writer.write(",my:'" + tooltip.getMyPosition() + "'"); writer.write(",adjust:{x:" + tooltip.getAdjustX() + ",y:" + tooltip.getAdjustY() + "}"); if (mouseTracking) { writer.write(",target:'mouse'"); writer.write(",viewport:$(window)"); } else if (shared && !global) { writer.write(",target:'event'"); writer.write(",effect:false"); } writer.write("}},true);});"); endScript(writer); }
diff --git a/src/lang/psi/dataFlow/reachingDefs/ReachingDefinitionsDfaInstance.java b/src/lang/psi/dataFlow/reachingDefs/ReachingDefinitionsDfaInstance.java index 104e46c7..e181b014 100644 --- a/src/lang/psi/dataFlow/reachingDefs/ReachingDefinitionsDfaInstance.java +++ b/src/lang/psi/dataFlow/reachingDefs/ReachingDefinitionsDfaInstance.java @@ -1,74 +1,75 @@ /* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sylvanaar.idea.Lua.lang.psi.dataFlow.reachingDefs; import com.sylvanaar.idea.Lua.lang.psi.controlFlow.Instruction; import com.sylvanaar.idea.Lua.lang.psi.controlFlow.ReadWriteVariableInstruction; import com.sylvanaar.idea.Lua.lang.psi.dataFlow.DfaInstance; import gnu.trove.TIntHashSet; import gnu.trove.TIntObjectHashMap; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NotNull; /** * @author ven */ public class ReachingDefinitionsDfaInstance implements DfaInstance<TIntObjectHashMap<TIntHashSet>> { private final TObjectIntHashMap<String> myVarToIndexMap = new TObjectIntHashMap<String>(); public int getVarIndex(String varName) { return myVarToIndexMap.get(varName); } public ReachingDefinitionsDfaInstance(Instruction[] flow) { int num = 0; for (Instruction instruction : flow) { if (instruction instanceof ReadWriteVariableInstruction) { final String name = ((ReadWriteVariableInstruction) instruction).getVariableName(); if (!myVarToIndexMap.containsKey(name)) { myVarToIndexMap.put(name, num++); } } } } public void fun(TIntObjectHashMap<TIntHashSet> m, Instruction instruction) { if (instruction instanceof ReadWriteVariableInstruction) { final ReadWriteVariableInstruction varInsn = (ReadWriteVariableInstruction) instruction; final String name = varInsn.getVariableName(); + if (name == null) return; assert myVarToIndexMap.containsKey(name); final int num = myVarToIndexMap.get(name); if (varInsn.isWrite()) { TIntHashSet defs = m.get(num); if (defs == null) { defs = new TIntHashSet(); m.put(num, defs); } else defs.clear(); defs.add(varInsn.num()); } } } @NotNull public TIntObjectHashMap<TIntHashSet> initial() { return new TIntObjectHashMap<TIntHashSet>(); } public boolean isForward() { return true; } }
true
true
public void fun(TIntObjectHashMap<TIntHashSet> m, Instruction instruction) { if (instruction instanceof ReadWriteVariableInstruction) { final ReadWriteVariableInstruction varInsn = (ReadWriteVariableInstruction) instruction; final String name = varInsn.getVariableName(); assert myVarToIndexMap.containsKey(name); final int num = myVarToIndexMap.get(name); if (varInsn.isWrite()) { TIntHashSet defs = m.get(num); if (defs == null) { defs = new TIntHashSet(); m.put(num, defs); } else defs.clear(); defs.add(varInsn.num()); } } }
public void fun(TIntObjectHashMap<TIntHashSet> m, Instruction instruction) { if (instruction instanceof ReadWriteVariableInstruction) { final ReadWriteVariableInstruction varInsn = (ReadWriteVariableInstruction) instruction; final String name = varInsn.getVariableName(); if (name == null) return; assert myVarToIndexMap.containsKey(name); final int num = myVarToIndexMap.get(name); if (varInsn.isWrite()) { TIntHashSet defs = m.get(num); if (defs == null) { defs = new TIntHashSet(); m.put(num, defs); } else defs.clear(); defs.add(varInsn.num()); } } }
diff --git a/src/functions/Left.java b/src/functions/Left.java index 5b12a85..d6226e2 100644 --- a/src/functions/Left.java +++ b/src/functions/Left.java @@ -1,18 +1,18 @@ package functions; import backEnd.Turtle; public class Left extends TurtleFunction { public Left (Turtle turtle) { super(turtle); } @Override public void execute (String[] args) { - int myAngle = Integer.parseInt(args[1]); - getTurtle().rotate(myAngle); + int angle = Integer.parseInt(args[1]); + getTurtle().rotate(angle); } }
true
true
public void execute (String[] args) { int myAngle = Integer.parseInt(args[1]); getTurtle().rotate(myAngle); }
public void execute (String[] args) { int angle = Integer.parseInt(args[1]); getTurtle().rotate(angle); }
diff --git a/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java b/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java index feb7665..fb29c26 100644 --- a/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java +++ b/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java @@ -1,366 +1,368 @@ /* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can be found * in the LICENSE file in the root of the source tree. An additional * intellectual property rights grant can be found in the file PATENTS. All * contributing project authors may be found in the AUTHORS file in the root of * the source tree. */ /* * VoiceEngine Android test application. It starts either auto test or acts like * a GUI test. */ package com.tuenti.voice.core; import android.content.Context; import android.util.Log; import com.tuenti.voice.core.manager.BuddyManager; import com.tuenti.voice.core.manager.CallManager; import com.tuenti.voice.core.manager.ConnectionManager; import com.tuenti.voice.core.manager.StatManager; public class VoiceClient { // ------------------------------ FIELDS ------------------------------ //Event constants /* Event Types */ public static final int CALL_STATE_EVENT = 0; public static final int XMPP_STATE_EVENT = 1; public static final int XMPP_ERROR_EVENT = 2; public static final int BUDDY_LIST_EVENT = 3; public static final int XMPP_SOCKET_CLOSE_EVENT = 4; public static final int CALL_ERROR_EVENT = 5; public static final int AUDIO_PLAYOUT_EVENT = 6; public static final int STATS_UPDATE_EVENT = 7; public static final int CALL_TRACKER_ID_EVENT = 8; //End Event constants private final static String TAG = "j-VoiceClient"; private static final Object mLock = new Object(); private boolean initialized; private boolean voiceClientLoaded; private BuddyManager mBuddyManager; private CallManager mCallManager; private ConnectionManager mConnectionManager; private StatManager mStatManager; // --------------------------- CONSTRUCTORS --------------------------- public VoiceClient() { synchronized ( mLock ) { Log.i( TAG, "loading native library voiceclient" ); try { System.loadLibrary( "voiceclient" ); voiceClientLoaded = true; } catch (UnsatisfiedLinkError e) { // We need to do this, because Android will generate OOM error // loading an so file on older phones when they don't have // enough available memory at load time. voiceClientLoaded = false; } } } // -------------------------- OTHER METHODS -------------------------- public boolean loaded() { return voiceClientLoaded; } public void acceptCall( long call_id ) { Log.i( TAG, "native accept call " + call_id ); if (loaded()) { nativeAcceptCall( call_id ); } } public void call( String remoteUsername ) { if (loaded()) { nativeCall( remoteUsername ); } } public void callWithTrackerId( String remoteUsername, String callTrackerId ) { if (loaded()) { nativeCallWithTrackerId( remoteUsername, callTrackerId ); } } public void declineCall( long call_id, boolean busy ) { if (loaded()) { nativeDeclineCall( call_id, busy ); } } public void endCall( long call_id ) { if (loaded()) { nativeEndCall( call_id ); } } public void holdCall( long call_id, boolean hold ) { if (loaded()) { nativeHoldCall( call_id, hold ); } } public void init( Context context ) { if ( loaded() && !initialized ) { nativeInit( context ); initialized = true; } } public void login( String username, String password, String stunServer, String turnServer, String turnUsername, String turnPassword, String xmppServer, int xmppPort, boolean useSsl, int portAllocatorFilter ) { if (loaded()) { nativeLogin( username, password, stunServer, turnServer, turnUsername, turnPassword, xmppServer, xmppPort, useSsl, portAllocatorFilter ); } } public void replaceTurn( String turnServer ) { if (loaded()) { nativeReplaceTurn( turnServer ); } } public void logout() { if (loaded()) { nativeLogout(); } } public void muteCall( long call_id, boolean mute ) { if (loaded()) { nativeMuteCall( call_id, mute ); } } public void release() { if ( loaded() && initialized ) { initialized = false; nativeRelease(); } } public void setBuddyManager( BuddyManager buddyManager ) { mBuddyManager = buddyManager; } public void setCallManager( CallManager callManager ) { mCallManager = callManager; } public void setConnectionManager( ConnectionManager connectionManager ) { mConnectionManager = connectionManager; } public void setStatManager( StatManager statManager ) { mStatManager = statManager; } /** * @see BuddyManager#handleBuddyListChanged(int, String) */ protected void handleBuddyListChanged( int state, String remoteJid ) { if ( mBuddyManager != null ) { synchronized ( mLock ) { mBuddyManager.handleBuddyListChanged( state, remoteJid ); } } } /** * @see CallManager#handleCallError(int, long) */ protected void handleCallError( int error, long callId ) { if ( mCallManager != null ) { synchronized ( mLock ) { mCallManager.handleCallError( error, callId ); } } } /** * @see CallManager#handleCallStateChanged(int, String, long) */ protected void handleCallStateChanged( int state, String remoteJid, long callId ) { if ( mCallManager != null ) { synchronized ( mLock ) { mCallManager.handleCallStateChanged( state, remoteJid, callId ); } } } /** * @see ConnectionManager#handleXmppError(int) */ protected void handleXmppError( int error ) { if ( mConnectionManager != null ) { synchronized ( mLock ) { mConnectionManager.handleXmppError( error ); } } } /** * @see ConnectionManager#handleXmppSocketClose(int) */ protected void handleXmppSocketClose( int state ) { if ( mConnectionManager != null ) { synchronized ( mLock ) { mConnectionManager.handleXmppSocketClose( state ); } } } /** * @see ConnectionManager#handleXmppStateChanged(int) */ protected void handleXmppStateChanged( int state ) { if ( mConnectionManager != null ) { synchronized ( mLock ) { mConnectionManager.handleXmppStateChanged( state ); } } } /** * @see StatManager#handleStatsUpdate(String) */ protected void handleStatsUpdate( String stats ) { if ( mStatManager != null ) { synchronized ( mLock ) { mStatManager.handleStatsUpdate( stats ); } } } /** * @see CallManager#handleCallTrackerId(int, String) */ protected void handleCallTrackerId( long callId, String callTrackerId ) { if ( mCallManager != null ) { synchronized ( mLock ) { mCallManager.handleCallTrackerId( callId, callTrackerId ); } } } @SuppressWarnings("UnusedDeclaration") //TODO: change the signature to be: //dispatchNativeEvent( int what, int code, String data ) private void dispatchNativeEvent( int what, int code, String data, long callId ) { switch ( what ) { case CALL_STATE_EVENT: // data contains remoteJid handleCallStateChanged( code, data, callId ); break; case CALL_ERROR_EVENT: handleCallError( code, callId ); break; case BUDDY_LIST_EVENT: // data contains remoteJid handleBuddyListChanged( code, data ); break; case XMPP_STATE_EVENT: handleXmppStateChanged( code ); break; case XMPP_ERROR_EVENT: handleXmppError( code ); break; case XMPP_SOCKET_CLOSE_EVENT: handleXmppSocketClose( code ); + break; case STATS_UPDATE_EVENT: // data constains stats handleStatsUpdate( data ); + break; case CALL_TRACKER_ID_EVENT: // data contains call_tracking_id handleCallTrackerId( callId, data ); break; } } private native void nativeAcceptCall( long call_id ); private native void nativeCall( String remoteJid ); private native void nativeCallWithTrackerId( String remoteJid, String callTrackerId ); private native void nativeDeclineCall( long call_id, boolean busy ); private native void nativeEndCall( long call_id ); private native void nativeHoldCall( long call_id, boolean hold ); private native void nativeInit( Context context ); private native void nativeLogin( String user_name, String password, String stunServer, String turnServer, String turnUsername, String turnPassword, String xmppServer, int xmppPort, boolean UseSSL, int portAllocatorFilter ); private native void nativeReplaceTurn(String turn); private native void nativeLogout(); private native void nativeMuteCall( long call_id, boolean mute ); private native void nativeRelease(); }
false
true
private void dispatchNativeEvent( int what, int code, String data, long callId ) { switch ( what ) { case CALL_STATE_EVENT: // data contains remoteJid handleCallStateChanged( code, data, callId ); break; case CALL_ERROR_EVENT: handleCallError( code, callId ); break; case BUDDY_LIST_EVENT: // data contains remoteJid handleBuddyListChanged( code, data ); break; case XMPP_STATE_EVENT: handleXmppStateChanged( code ); break; case XMPP_ERROR_EVENT: handleXmppError( code ); break; case XMPP_SOCKET_CLOSE_EVENT: handleXmppSocketClose( code ); case STATS_UPDATE_EVENT: // data constains stats handleStatsUpdate( data ); case CALL_TRACKER_ID_EVENT: // data contains call_tracking_id handleCallTrackerId( callId, data ); break; } }
private void dispatchNativeEvent( int what, int code, String data, long callId ) { switch ( what ) { case CALL_STATE_EVENT: // data contains remoteJid handleCallStateChanged( code, data, callId ); break; case CALL_ERROR_EVENT: handleCallError( code, callId ); break; case BUDDY_LIST_EVENT: // data contains remoteJid handleBuddyListChanged( code, data ); break; case XMPP_STATE_EVENT: handleXmppStateChanged( code ); break; case XMPP_ERROR_EVENT: handleXmppError( code ); break; case XMPP_SOCKET_CLOSE_EVENT: handleXmppSocketClose( code ); break; case STATS_UPDATE_EVENT: // data constains stats handleStatsUpdate( data ); break; case CALL_TRACKER_ID_EVENT: // data contains call_tracking_id handleCallTrackerId( callId, data ); break; } }
diff --git a/src/api/org/openmrs/util/OpenmrsConstants.java b/src/api/org/openmrs/util/OpenmrsConstants.java index e627d1d2..e93c0b37 100644 --- a/src/api/org/openmrs/util/OpenmrsConstants.java +++ b/src/api/org/openmrs/util/OpenmrsConstants.java @@ -1,1153 +1,1151 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Vector; import org.openmrs.GlobalProperty; import org.openmrs.Privilege; import org.openmrs.api.ConceptService; import org.openmrs.module.ModuleConstants; import org.openmrs.module.ModuleFactory; import org.openmrs.patient.impl.LuhnIdentifierValidator; import org.openmrs.scheduler.SchedulerConstants; /** * Constants used in OpenMRS. Contents built from build properties (version, version_short, and * expected_database). Some are set at runtime (database, database version). This file should * contain all privilege names and global property names. Those strings added to the static CORE_* * methods will be written to the database at startup if they don't exist yet. */ public final class OpenmrsConstants { //private static Log log = LogFactory.getLog(OpenmrsConstants.class); /** * This is the hard coded primary key of the order type for DRUG. This has to be done because * some logic in the API acts on this order type */ public static final int ORDERTYPE_DRUG = 2; /** * This is the hard coded primary key of the concept class for DRUG. This has to be done because * some logic in the API acts on this concept class */ public static final int CONCEPT_CLASS_DRUG = 3; /** * hack alert: During an ant build, the openmrs api jar manifest file is loaded with these * values. When constructing the OpenmrsConstants class file, the api jar is read and the values * are copied in as constants */ private static final Package THIS_PACKAGE = OpenmrsConstants.class.getPackage(); public static final String OPENMRS_VERSION = THIS_PACKAGE.getSpecificationVendor(); public static final String OPENMRS_VERSION_SHORT = THIS_PACKAGE.getSpecificationVersion(); /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ public static final String DATABASE_VERSION_EXPECTED = THIS_PACKAGE.getImplementationVersion(); public static String DATABASE_NAME = "openmrs"; public static String DATABASE_BUSINESS_NAME = "openmrs"; /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ public static String DATABASE_VERSION = null; /** * Set true from runtime configuration to obscure patients for system demonstrations */ public static boolean OBSCURE_PATIENTS = false; public static String OBSCURE_PATIENTS_GIVEN_NAME = "Demo"; public static String OBSCURE_PATIENTS_MIDDLE_NAME = null; public static String OBSCURE_PATIENTS_FAMILY_NAME = "Person"; public static final String REGEX_LARGE = "[!\"#\\$%&'\\(\\)\\*,+-\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final String REGEX_SMALL = "[!\"#\\$%&'\\(\\)\\*,\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final Integer CIVIL_STATUS_CONCEPT_ID = 1054; /** * The directory that will store filesystem data about openmrs like module omods, generated data * exports, etc. This shouldn't be accessed directory, the * OpenmrsUtil.getApplicationDataDirectory() should be used. This should be null here. This * constant will hold the value of the user's runtime property for the * application_data_directory and is set programmatically at startup. This value is set in the * openmrs startup method If this is null, the getApplicationDataDirectory() uses some OS * heuristics to determine where to put an app data dir. * * @see #APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY * @see OpenmrsUtil.getApplicationDataDirectory() * @see OpenmrsUtil.startup(java.util.Properties); */ public static String APPLICATION_DATA_DIRECTORY = null; /** * The name of the runtime property that a user can set that will specify where openmrs's * application directory is * * @see #APPLICATION_DATA_DIRECTORY */ public static String APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY = "application_data_directory"; /** * The name of the runtime property that a user can set that will specify whether the database * is automatically updated on startup */ public static String AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY = "auto_update_database"; /** * These words are ignored in concept and patient searches * * @return */ public static final Collection<String> STOP_WORDS() { List<String> stopWords = new Vector<String>(); stopWords.add("A"); stopWords.add("AND"); stopWords.add("AT"); stopWords.add("BUT"); stopWords.add("BY"); stopWords.add("FOR"); stopWords.add("HAS"); stopWords.add("OF"); stopWords.add("THE"); stopWords.add("TO"); return stopWords; } /** * A gender character to gender name map TODO issues with localization. How should this be * handled? * * @return */ public static final Map<String, String> GENDER() { Map<String, String> genders = new LinkedHashMap<String, String>(); genders.put("M", "Male"); genders.put("F", "Female"); return genders; } // Baked in Privileges: public static final String PRIV_VIEW_CONCEPTS = "View Concepts"; public static final String PRIV_MANAGE_CONCEPTS = "Manage Concepts"; public static final String PRIV_PURGE_CONCEPTS = "Purge Concepts"; public static final String PRIV_VIEW_CONCEPT_PROPOSALS = "View Concept Proposals"; public static final String PRIV_ADD_CONCEPT_PROPOSALS = "Add Concept Proposals"; public static final String PRIV_EDIT_CONCEPT_PROPOSALS = "Edit Concept Proposals"; public static final String PRIV_DELETE_CONCEPT_PROPOSALS = "Delete Concept Proposals"; public static final String PRIV_PURGE_CONCEPT_PROPOSALS = "Purge Concept Proposals"; public static final String PRIV_VIEW_USERS = "View Users"; public static final String PRIV_ADD_USERS = "Add Users"; public static final String PRIV_EDIT_USERS = "Edit Users"; public static final String PRIV_DELETE_USERS = "Delete Users"; public static final String PRIV_PURGE_USERS = "Purge Users"; public static final String PRIV_EDIT_USER_PASSWORDS = "Edit User Passwords"; public static final String PRIV_VIEW_ENCOUNTERS = "View Encounters"; public static final String PRIV_ADD_ENCOUNTERS = "Add Encounters"; public static final String PRIV_EDIT_ENCOUNTERS = "Edit Encounters"; public static final String PRIV_DELETE_ENCOUNTERS = "Delete Encounters"; public static final String PRIV_PURGE_ENCOUNTERS = "Purge Encounters"; public static final String PRIV_VIEW_ENCOUNTER_TYPES = "View Encounter Types"; public static final String PRIV_MANAGE_ENCOUNTER_TYPES = "Manage Encounter Types"; public static final String PRIV_PURGE_ENCOUNTER_TYPES = "Purge Encounter Types"; public static final String PRIV_VIEW_LOCATIONS = "View Locations"; public static final String PRIV_MANAGE_LOCATIONS = "Manage Locations"; public static final String PRIV_PURGE_LOCATIONS = "Purge Locations"; public static final String PRIV_MANAGE_LOCATION_TAGS = "Manage Location Tags"; public static final String PRIV_PURGE_LOCATION_TAGS = "Purge Location Tags"; public static final String PRIV_VIEW_OBS = "View Observations"; public static final String PRIV_ADD_OBS = "Add Observations"; public static final String PRIV_EDIT_OBS = "Edit Observations"; public static final String PRIV_DELETE_OBS = "Delete Observations"; public static final String PRIV_PURGE_OBS = "Purge Observations"; @Deprecated public static final String PRIV_VIEW_MIME_TYPES = "View Mime Types"; @Deprecated public static final String PRIV_PURGE_MIME_TYPES = "Purge Mime Types"; public static final String PRIV_VIEW_PATIENTS = "View Patients"; public static final String PRIV_ADD_PATIENTS = "Add Patients"; public static final String PRIV_EDIT_PATIENTS = "Edit Patients"; public static final String PRIV_DELETE_PATIENTS = "Delete Patients"; public static final String PRIV_PURGE_PATIENTS = "Purge Patients"; public static final String PRIV_VIEW_PATIENT_IDENTIFIERS = "View Patient Identifiers"; public static final String PRIV_ADD_PATIENT_IDENTIFIERS = "Add Patient Identifiers"; public static final String PRIV_EDIT_PATIENT_IDENTIFIERS = "Edit Patient Identifiers"; public static final String PRIV_DELETE_PATIENT_IDENTIFIERS = "Delete Patient Identifiers"; public static final String PRIV_PURGE_PATIENT_IDENTIFIERS = "Purge Patient Identifiers"; public static final String PRIV_VIEW_PATIENT_COHORTS = "View Patient Cohorts"; public static final String PRIV_ADD_COHORTS = "Add Cohorts"; public static final String PRIV_EDIT_COHORTS = "Edit Cohorts"; public static final String PRIV_DELETE_COHORTS = "Delete Cohorts"; public static final String PRIV_PURGE_COHORTS = "Purge Cohorts"; public static final String PRIV_VIEW_ORDERS = "View Orders"; public static final String PRIV_ADD_ORDERS = "Add Orders"; public static final String PRIV_EDIT_ORDERS = "Edit Orders"; public static final String PRIV_DELETE_ORDERS = "Delete Orders"; public static final String PRIV_PURGE_ORDERS = "Purge Orders"; public static final String PRIV_VIEW_FORMS = "View Forms"; public static final String PRIV_MANAGE_FORMS = "Manage Forms"; public static final String PRIV_PURGE_FORMS = "Purge Forms"; public static final String PRIV_VIEW_REPORTS = "View Reports"; public static final String PRIV_ADD_REPORTS = "Add Reports"; public static final String PRIV_EDIT_REPORTS = "Edit Reports"; public static final String PRIV_DELETE_REPORTS = "Delete Reports"; public static final String PRIV_RUN_REPORTS = "Run Reports"; public static final String PRIV_VIEW_REPORT_OBJECTS = "View Report Objects"; public static final String PRIV_ADD_REPORT_OBJECTS = "Add Report Objects"; public static final String PRIV_EDIT_REPORT_OBJECTS = "Edit Report Objects"; public static final String PRIV_DELETE_REPORT_OBJECTS = "Delete Report Objects"; public static final String PRIV_MANAGE_IDENTIFIER_TYPES = "Manage Identifier Types"; public static final String PRIV_VIEW_IDENTIFIER_TYPES = "View Identifier Types"; public static final String PRIV_PURGE_IDENTIFIER_TYPES = "Purge Identifier Types"; @Deprecated public static final String PRIV_MANAGE_MIME_TYPES = "Manage Mime Types"; public static final String PRIV_VIEW_CONCEPT_CLASSES = "View Concept Classes"; public static final String PRIV_MANAGE_CONCEPT_CLASSES = "Manage Concept Classes"; public static final String PRIV_PURGE_CONCEPT_CLASSES = "Purge Concept Classes"; public static final String PRIV_VIEW_CONCEPT_DATATYPES = "View Concept Datatypes"; public static final String PRIV_MANAGE_CONCEPT_DATATYPES = "Manage Concept Datatypes"; public static final String PRIV_PURGE_CONCEPT_DATATYPES = "Purge Concept Datatypes"; public static final String PRIV_VIEW_PRIVILEGES = "View Privileges"; public static final String PRIV_MANAGE_PRIVILEGES = "Manage Privileges"; public static final String PRIV_PURGE_PRIVILEGES = "Purge Privileges"; public static final String PRIV_VIEW_ROLES = "View Roles"; public static final String PRIV_MANAGE_ROLES = "Manage Roles"; public static final String PRIV_PURGE_ROLES = "Purge Roles"; public static final String PRIV_VIEW_FIELD_TYPES = "View Field Types"; public static final String PRIV_MANAGE_FIELD_TYPES = "Manage Field Types"; public static final String PRIV_PURGE_FIELD_TYPES = "Purge Field Types"; public static final String PRIV_VIEW_ORDER_TYPES = "View Order Types"; public static final String PRIV_MANAGE_ORDER_TYPES = "Manage Order Types"; public static final String PRIV_PURGE_ORDER_TYPES = "Purge Order Types"; public static final String PRIV_VIEW_RELATIONSHIP_TYPES = "View Relationship Types"; public static final String PRIV_MANAGE_RELATIONSHIP_TYPES = "Manage Relationship Types"; public static final String PRIV_PURGE_RELATIONSHIP_TYPES = "Purge Relationship Types"; public static final String PRIV_MANAGE_ALERTS = "Manage Alerts"; public static final String PRIV_MANAGE_CONCEPT_SOURCES = "Manage Concept Sources"; public static final String PRIV_VIEW_CONCEPT_SOURCES = "View Concept Sources"; public static final String PRIV_PURGE_CONCEPT_SOURCES = "Purge Concept Sources"; public static final String PRIV_VIEW_NAVIGATION_MENU = "View Navigation Menu"; public static final String PRIV_VIEW_ADMIN_FUNCTIONS = "View Administration Functions"; public static final String PRIV_VIEW_UNPUBLISHED_FORMS = "View Unpublished Forms"; public static final String PRIV_VIEW_PROGRAMS = "View Programs"; public static final String PRIV_MANAGE_PROGRAMS = "Manage Programs"; public static final String PRIV_VIEW_PATIENT_PROGRAMS = "View Patient Programs"; public static final String PRIV_ADD_PATIENT_PROGRAMS = "Add Patient Programs"; public static final String PRIV_EDIT_PATIENT_PROGRAMS = "Edit Patient Programs"; public static final String PRIV_DELETE_PATIENT_PROGRAMS = "Delete Patient Programs"; public static final String PRIV_PURGE_PATIENT_PROGRAMS = "Add Patient Programs"; public static final String PRIV_DASHBOARD_OVERVIEW = "Patient Dashboard - View Overview Section"; public static final String PRIV_DASHBOARD_REGIMEN = "Patient Dashboard - View Regimen Section"; public static final String PRIV_DASHBOARD_ENCOUNTERS = "Patient Dashboard - View Encounters Section"; public static final String PRIV_DASHBOARD_DEMOGRAPHICS = "Patient Dashboard - View Demographics Section"; public static final String PRIV_DASHBOARD_GRAPHS = "Patient Dashboard - View Graphs Section"; public static final String PRIV_DASHBOARD_FORMS = "Patient Dashboard - View Forms Section"; public static final String PRIV_DASHBOARD_SUMMARY = "Patient Dashboard - View Patient Summary"; public static final String PRIV_VIEW_GLOBAL_PROPERTIES = "View Global Properties"; public static final String PRIV_MANAGE_GLOBAL_PROPERTIES = "Manage Global Properties"; public static final String PRIV_PURGE_GLOBAL_PROPERTIES = "Purge Global Properties"; public static final String PRIV_MANAGE_MODULES = "Manage Modules"; public static final String PRIV_MANAGE_SCHEDULER = "Manage Scheduler"; public static final String PRIV_VIEW_PERSON_ATTRIBUTE_TYPES = "View Person Attribute Types"; public static final String PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES = "Manage Person Attribute Types"; public static final String PRIV_PURGE_PERSON_ATTRIBUTE_TYPES = "Purge Person Attribute Types"; public static final String PRIV_VIEW_PERSONS = "View People"; public static final String PRIV_ADD_PERSONS = "Add People"; public static final String PRIV_EDIT_PERSONS = "Edit People"; public static final String PRIV_DELETE_PERSONS = "Delete People"; public static final String PRIV_PURGE_PERSONS = "Purge People"; /** * @deprecated replacing with ADD/EDIT/DELETE privileges */ public static final String PRIV_MANAGE_RELATIONSHIPS = "Manage Relationships"; public static final String PRIV_VIEW_RELATIONSHIPS = "View Relationships"; public static final String PRIV_ADD_RELATIONSHIPS = "Add Relationships"; public static final String PRIV_EDIT_RELATIONSHIPS = "Edit Relationships"; public static final String PRIV_DELETE_RELATIONSHIPS = "Delete Relationships"; public static final String PRIV_PURGE_RELATIONSHIPS = "Purge Relationships"; public static final String PRIV_VIEW_DATAENTRY_STATS = "View Data Entry Statistics"; public static final String PRIV_VIEW_DATABASE_CHANGES = "View Database Changes"; /** * Cached list of core privileges */ private static Map<String, String> CORE_PRIVILEGES = null; /** * These are the privileges that are required by OpenMRS. Upon startup, if any of these * privileges do not exist in the database, they are inserted. These privileges are not allowed * to be deleted. They are marked as 'locked' in the administration screens. * * @return privileges core to the system */ public static final Map<String, String> CORE_PRIVILEGES() { // if we don't have a cache, create one if (CORE_PRIVILEGES == null) { CORE_PRIVILEGES = new HashMap<String, String>(); CORE_PRIVILEGES.put(PRIV_VIEW_PROGRAMS, "Able to view patient programs"); CORE_PRIVILEGES.put(PRIV_MANAGE_PROGRAMS, "Able to add/view/delete patient programs"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_PROGRAMS, "Able to see which programs that patients are in"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_PROGRAMS, "Able to add patients to programs"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_PROGRAMS, "Able to edit patients in programs"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_PROGRAMS, "Able to delete patients from programs"); CORE_PRIVILEGES.put(PRIV_VIEW_UNPUBLISHED_FORMS, "Able to view and fill out unpublished forms"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPTS, "Able to view concept entries"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPTS, "Able to add/edit/delete concept entries"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_PROPOSALS, "Able to view concept proposals to the system"); CORE_PRIVILEGES.put(PRIV_ADD_CONCEPT_PROPOSALS, "Able to add concept proposals to the system"); CORE_PRIVILEGES.put(PRIV_EDIT_CONCEPT_PROPOSALS, "Able to edit concept proposals in the system"); CORE_PRIVILEGES.put(PRIV_DELETE_CONCEPT_PROPOSALS, "Able to delete concept proposals from the system"); CORE_PRIVILEGES.put(PRIV_VIEW_USERS, "Able to view users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_ADD_USERS, "Able to add users to OpenMRS"); CORE_PRIVILEGES.put(PRIV_EDIT_USERS, "Able to edit users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_DELETE_USERS, "Able to delete users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_EDIT_USER_PASSWORDS, "Able to change the passwords of users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTERS, "Able to view patient encounters"); CORE_PRIVILEGES.put(PRIV_ADD_ENCOUNTERS, "Able to add patient encounters"); CORE_PRIVILEGES.put(PRIV_EDIT_ENCOUNTERS, "Able to edit patient encounters"); CORE_PRIVILEGES.put(PRIV_DELETE_ENCOUNTERS, "Able to delete patient encounters"); CORE_PRIVILEGES.put(PRIV_VIEW_OBS, "Able to view patient observations"); CORE_PRIVILEGES.put(PRIV_ADD_OBS, "Able to add patient observations"); CORE_PRIVILEGES.put(PRIV_EDIT_OBS, "Able to edit patient observations"); CORE_PRIVILEGES.put(PRIV_DELETE_OBS, "Able to delete patient observations"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENTS, "Able to view patients"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENTS, "Able to add patients"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENTS, "Able to edit patients"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENTS, "Able to delete patients"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_IDENTIFIERS, "Able to view patient identifiers"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_IDENTIFIERS, "Able to add patient identifiers"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_IDENTIFIERS, "Able to edit patient identifiers"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_IDENTIFIERS, "Able to delete patient identifiers"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_COHORTS, "Able to view patient cohorts"); CORE_PRIVILEGES.put(PRIV_ADD_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_EDIT_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_DELETE_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_VIEW_ORDERS, "Able to view orders"); CORE_PRIVILEGES.put(PRIV_ADD_ORDERS, "Able to add orders"); CORE_PRIVILEGES.put(PRIV_EDIT_ORDERS, "Able to edit orders"); CORE_PRIVILEGES.put(PRIV_DELETE_ORDERS, "Able to delete orders"); CORE_PRIVILEGES.put(PRIV_VIEW_FORMS, "Able to view forms"); CORE_PRIVILEGES.put(PRIV_MANAGE_FORMS, "Able to add/edit/delete forms"); CORE_PRIVILEGES.put(PRIV_VIEW_REPORTS, "Able to view reports"); CORE_PRIVILEGES.put(PRIV_ADD_REPORTS, "Able to add reports"); CORE_PRIVILEGES.put(PRIV_EDIT_REPORTS, "Able to edit reports"); CORE_PRIVILEGES.put(PRIV_DELETE_REPORTS, "Able to delete reports"); CORE_PRIVILEGES.put(PRIV_RUN_REPORTS, "Able to run reports"); CORE_PRIVILEGES.put(PRIV_VIEW_REPORT_OBJECTS, "Able to view report objects"); CORE_PRIVILEGES.put(PRIV_ADD_REPORT_OBJECTS, "Able to add report objects"); CORE_PRIVILEGES.put(PRIV_EDIT_REPORT_OBJECTS, "Able to edit report objects"); CORE_PRIVILEGES.put(PRIV_DELETE_REPORT_OBJECTS, "Able to delete report objects"); CORE_PRIVILEGES.put(PRIV_VIEW_IDENTIFIER_TYPES, "Able to view patient identifier types"); CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIPS, "Able to add/edit/delete relationships"); CORE_PRIVILEGES.put(PRIV_MANAGE_IDENTIFIER_TYPES, "Able to add/edit/delete patient identifier types"); CORE_PRIVILEGES.put(PRIV_VIEW_LOCATIONS, "Able to view locations"); CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATIONS, "Able to add/edit/delete locations"); CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATION_TAGS, "Able to add/edit/delete location tags"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_CLASSES, "Able to view concept classes"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_CLASSES, "Able to add/edit/retire concept classes"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_DATATYPES, "Able to view concept datatypes"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_DATATYPES, "Able to add/edit/retire concept datatypes"); CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTER_TYPES, "Able to view encounter types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ENCOUNTER_TYPES, "Able to add/edit/delete encounter types"); CORE_PRIVILEGES.put(PRIV_VIEW_PRIVILEGES, "Able to view user privileges"); CORE_PRIVILEGES.put(PRIV_MANAGE_PRIVILEGES, "Able to add/edit/delete privileges"); CORE_PRIVILEGES.put(PRIV_VIEW_FIELD_TYPES, "Able to view field types"); CORE_PRIVILEGES.put(PRIV_MANAGE_FIELD_TYPES, "Able to add/edit/retire field types"); CORE_PRIVILEGES.put(PRIV_PURGE_FIELD_TYPES, "Able to purge field types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ORDER_TYPES, "Able to add/edit/retire order types"); CORE_PRIVILEGES.put(PRIV_VIEW_ORDER_TYPES, "Able to view order types"); CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIP_TYPES, "Able to view relationship types"); CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIP_TYPES, "Able to add/edit/retire relationship types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ALERTS, "Able to add/edit/delete user alerts"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_SOURCES, "Able to add/edit/delete concept sources"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_SOURCES, "Able to view concept sources"); CORE_PRIVILEGES.put(PRIV_VIEW_ROLES, "Able to view user roles"); CORE_PRIVILEGES.put(PRIV_MANAGE_ROLES, "Able to add/edit/delete user roles"); CORE_PRIVILEGES.put(PRIV_VIEW_NAVIGATION_MENU, "Able to view the navigation menu (Home, View Patients, Dictionary, Administration, My Profile)"); CORE_PRIVILEGES.put(PRIV_VIEW_ADMIN_FUNCTIONS, "Able to view the 'Administration' link in the navigation bar"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_OVERVIEW, "Able to view the 'Overview' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_REGIMEN, "Able to view the 'Regimen' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_ENCOUNTERS, "Able to view the 'Encounters' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_DEMOGRAPHICS, "Able to view the 'Demographics' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_GRAPHS, "Able to view the 'Graphs' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_FORMS, "Able to view the 'Forms' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_SUMMARY, "Able to view the 'Summary' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_VIEW_GLOBAL_PROPERTIES, "Able to view global properties on the administration screen"); CORE_PRIVILEGES.put(PRIV_MANAGE_GLOBAL_PROPERTIES, "Able to add/edit global properties"); CORE_PRIVILEGES.put(PRIV_MANAGE_MODULES, "Able to add/remove modules to the system"); CORE_PRIVILEGES.put(PRIV_MANAGE_SCHEDULER, "Able to add/edit/remove scheduled tasks"); CORE_PRIVILEGES.put(PRIV_VIEW_PERSON_ATTRIBUTE_TYPES, "Able to view person attribute types"); CORE_PRIVILEGES.put(PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES, "Able to add/edit/delete person attribute types"); CORE_PRIVILEGES.put(PRIV_VIEW_PERSONS, "Able to view person objects"); CORE_PRIVILEGES.put(PRIV_ADD_PERSONS, "Able to add person objects"); CORE_PRIVILEGES.put(PRIV_EDIT_PERSONS, "Able to edit person objects"); CORE_PRIVILEGES.put(PRIV_DELETE_PERSONS, "Able to delete objects"); CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIPS, "Able to view relationships"); CORE_PRIVILEGES.put(PRIV_ADD_RELATIONSHIPS, "Able to add relationships"); CORE_PRIVILEGES.put(PRIV_EDIT_RELATIONSHIPS, "Able to edit relationships"); CORE_PRIVILEGES.put(PRIV_DELETE_RELATIONSHIPS, "Able to delete relationships"); CORE_PRIVILEGES.put(PRIV_VIEW_DATAENTRY_STATS, "Able to view data entry statistics from the admin screen"); CORE_PRIVILEGES.put(PRIV_VIEW_DATABASE_CHANGES, "Able to view database changes from the admin screen"); } // always add the module core privileges back on for (Privilege privilege : ModuleFactory.getPrivileges()) { CORE_PRIVILEGES.put(privilege.getPrivilege(), privilege.getDescription()); } return CORE_PRIVILEGES; } // Baked in Roles: public static final String SUPERUSER_ROLE = "System Developer"; public static final String ANONYMOUS_ROLE = "Anonymous"; public static final String AUTHENTICATED_ROLE = "Authenticated"; public static final String PROVIDER_ROLE = "Provider"; /** * All roles returned by this method are inserted into the database if they do not exist * already. These roles are also forbidden to be deleted from the administration screens. * * @return roles that are core to the system */ public static final Map<String, String> CORE_ROLES() { Map<String, String> roles = new HashMap<String, String>(); roles .put(SUPERUSER_ROLE, "Assigned to developers of OpenMRS. Gives additional access to change fundamental structure of the database model."); roles.put(ANONYMOUS_ROLE, "Privileges for non-authenticated users."); roles.put(AUTHENTICATED_ROLE, "Privileges gained once authentication has been established."); roles.put(PROVIDER_ROLE, "All users with the 'Provider' role will appear as options in the default Infopath "); return roles; } /** * These roles are given to a user automatically and cannot be assigned * * @return */ public static final Collection<String> AUTO_ROLES() { List<String> roles = new Vector<String>(); roles.add(ANONYMOUS_ROLE); roles.add(AUTHENTICATED_ROLE); return roles; } public static final String GLOBAL_PROPERTY_CONCEPTS_LOCKED = "concepts.locked"; public static final String GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES = "patient.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES = "patient.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES = "patient.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES = "user.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES = "user.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES = "user.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX = "patient.identifierRegex"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX = "patient.identifierPrefix"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX = "patient.identifierSuffix"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS = "patient.searchMaxResults"; public static final String GLOBAL_PROPERTY_GZIP_ENABLED = "gzip.enabled"; public static final String GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS = "concept.medicalRecordObservations"; public static final String GLOBAL_PROPERTY_REPORT_XML_MACROS = "report.xmlMacros"; public static final String GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS = "dashboard.regimen.standardRegimens"; public static final String GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR = "patient.defaultPatientIdentifierValidator"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES = "patient_identifier.importantTypes"; public static final String GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER = "encounterForm.obsSortOrder"; public static final String GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST = "locale.allowed.list"; public static final String GLOBAL_PROPERTY_IMPLEMENTATION_ID = "implementation_id"; public static final String GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS = "newPatientForm.relationships"; public static final String GLOBAL_PROPERTY_COMPLEX_OBS_DIR = "obs.complex_obs_dir"; public static final String GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS = "minSearchCharacters"; /** * These properties (and default values) are set if not found in the database when OpenMRS is * started if they do not exist yet * * @return */ public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow", "Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); - props - .add(new GlobalProperty("concept.cd4_count", "5497", - "Concept id of the concept defining the CD4 count concept")); + props.add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", - "Concept id of the concept defining the PATIEND DIED concept")); + "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; } // ConceptProposal proposed concept identifier keyword public static final String PROPOSED_CONCEPT_IDENTIFIER = "PROPOSED"; // ConceptProposal states public static final String CONCEPT_PROPOSAL_UNMAPPED = "UNMAPPED"; public static final String CONCEPT_PROPOSAL_CONCEPT = "CONCEPT"; public static final String CONCEPT_PROPOSAL_SYNONYM = "SYNONYM"; public static final String CONCEPT_PROPOSAL_REJECT = "REJECT"; public static final Collection<String> CONCEPT_PROPOSAL_STATES() { Collection<String> states = new Vector<String>(); states.add(CONCEPT_PROPOSAL_UNMAPPED); states.add(CONCEPT_PROPOSAL_CONCEPT); states.add(CONCEPT_PROPOSAL_SYNONYM); states.add(CONCEPT_PROPOSAL_REJECT); return states; } public static Locale SPANISH_LANGUAGE = new Locale("es"); public static Locale PORTUGUESE_LANGUAGE = new Locale("pt"); public static Locale ITALIAN_LANGUAGE = new Locale("it"); /** * @return Collection of locales available to openmrs * @deprecated */ public static final Collection<Locale> OPENMRS_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.US); languages.add(Locale.UK); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } public static final Locale GLOBAL_DEFAULT_LOCALE = Locale.US; /** * @return Collection of locales that the concept dictionary should be aware of * @see ConceptService#getLocalesOfConceptNames() * @deprecated */ public static final Collection<Locale> OPENMRS_CONCEPT_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.ENGLISH); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } private static Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS = null; /** * This method is necessary until SimpleDateFormat(SHORT, java.util.locale) returns a pattern * with a four digit year <locale.toString().toLowerCase(), pattern> * * @return Mapping of Locales to locale specific date pattern */ public static final Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS() { if (OPENMRS_LOCALE_DATE_PATTERNS == null) { Map<String, String> patterns = new HashMap<String, String>(); patterns.put(Locale.US.toString().toLowerCase(), "MM/dd/yyyy"); patterns.put(Locale.UK.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.FRENCH.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.GERMAN.toString().toLowerCase(), "MM.dd.yyyy"); patterns.put(SPANISH_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(PORTUGUESE_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(ITALIAN_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); OPENMRS_LOCALE_DATE_PATTERNS = patterns; } return OPENMRS_LOCALE_DATE_PATTERNS; } /* * User property names */ public static final String USER_PROPERTY_CHANGE_PASSWORD = "forcePassword"; public static final String USER_PROPERTY_DEFAULT_LOCALE = "defaultLocale"; public static final String USER_PROPERTY_DEFAULT_LOCATION = "defaultLocation"; public static final String USER_PROPERTY_SHOW_RETIRED = "showRetired"; public static final String USER_PROPERTY_SHOW_VERBOSE = "showVerbose"; public static final String USER_PROPERTY_NOTIFICATION = "notification"; public static final String USER_PROPERTY_NOTIFICATION_ADDRESS = "notificationAddress"; public static final String USER_PROPERTY_NOTIFICATION_FORMAT = "notificationFormat"; // text/plain, text/html /** * Name of the user_property that stores the number of unsuccessful login attempts this user has * made */ public static final String USER_PROPERTY_LOGIN_ATTEMPTS = "loginAttempts"; /** * Name of the user_property that stores the time the user was locked out due to too many login * attempts */ public static final String USER_PROPERTY_LOCKOUT_TIMESTAMP = "lockoutTimestamp"; /** * A user property name. The value should be a comma-separated ordered list of fully qualified * locales within which the user is a proficient speaker. The list should be ordered from the * most to the least proficiency. Example: * <code>proficientLocales = en_US, en_GB, en, fr_RW</code> */ public static final String USER_PROPERTY_PROFICIENT_LOCALES = "proficientLocales"; /** * Report object properties */ public static final String REPORT_OBJECT_TYPE_PATIENTFILTER = "Patient Filter"; public static final String REPORT_OBJECT_TYPE_PATIENTSEARCH = "Patient Search"; public static final String REPORT_OBJECT_TYPE_PATIENTDATAPRODUCER = "Patient Data Producer"; // Used for differences between windows/linux upload capabilities) // Used for determining where to find runtime properties public static final String OPERATING_SYSTEM_KEY = "os.name"; public static final String OPERATING_SYSTEM = System.getProperty(OPERATING_SYSTEM_KEY); public static final String OPERATING_SYSTEM_WINDOWS_XP = "Windows XP"; public static final String OPERATING_SYSTEM_WINDOWS_VISTA = "Windows Vista"; public static final String OPERATING_SYSTEM_LINUX = "Linux"; public static final String OPERATING_SYSTEM_SUNOS = "SunOS"; public static final String OPERATING_SYSTEM_FREEBSD = "FreeBSD"; public static final String OPERATING_SYSTEM_OSX = "Mac OS X"; /** * URL to the concept source id verification server */ public static final String IMPLEMENTATION_ID_REMOTE_CONNECTION_URL = "http://resources.openmrs.org/tools/implementationid"; /** * Shortcut booleans used to make some OS specific checks more generic; note the *nix flavored * check is missing some less obvious choices */ public static final boolean UNIX_BASED_OPERATING_SYSTEM = (OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_LINUX) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_SUNOS) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_FREEBSD) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_OSX) > -1); public static final boolean WINDOWS_BASED_OPERATING_SYSTEM = OPERATING_SYSTEM.indexOf("Windows") > -1; public static final boolean WINDOWS_VISTA_OPERATING_SYSTEM = OPERATING_SYSTEM.equals(OPERATING_SYSTEM_WINDOWS_VISTA); /** * Marker put into the serialization session map to tell @Replace methods whether or not to do * just the very basic serialization */ public static final String SHORT_SERIALIZATION = "isShortSerialization"; // Global property key for global logger level public static final String GLOBAL_PROPERTY_LOG_LEVEL = "log.level.openmrs"; // Global logger category public static final String LOG_CLASS_DEFAULT = "org.openmrs"; // Log levels public static final String LOG_LEVEL_TRACE = "trace"; public static final String LOG_LEVEL_DEBUG = "debug"; public static final String LOG_LEVEL_INFO = "info"; public static final String LOG_LEVEL_WARN = "warn"; public static final String LOG_LEVEL_ERROR = "error"; public static final String LOG_LEVEL_FATAL = "fatal"; /** * These enumerations should be used in ObsService and PersonService getters to help determine * which type of object to restrict on * * @see org.openmrs.api.ObsService * @see org.openmrs.api.PersonService */ public static enum PERSON_TYPE { PERSON, PATIENT, USER } //Patient Identifier Validators public static final String LUHN_IDENTIFIER_VALIDATOR = LuhnIdentifierValidator.class.getName(); // ComplexObsHandler views public static final String RAW_VIEW = "RAW_VIEW"; public static final String TEXT_VIEW = "TEXT_VIEW"; }
false
true
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow", "Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIEND DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow", "Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props.add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
diff --git a/src/info/plagiatsjaeger/SourceLoader.java b/src/info/plagiatsjaeger/SourceLoader.java index 1bf33aa..b66ad0b 100644 --- a/src/info/plagiatsjaeger/SourceLoader.java +++ b/src/info/plagiatsjaeger/SourceLoader.java @@ -1,195 +1,195 @@ package info.plagiatsjaeger; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.mozilla.universalchardet.UniversalDetector; /** * Klasse zum Laden von Daten. * * @author Andreas */ public class SourceLoader { public static final Logger _logger = Logger.getLogger(SourceLoader.class.getName()); private static final String DEFAULT_CONTENTTYPE = ConfigReader.getPropertyString("DEFAULTCONTENTTYPE"); private static String _detectedCharset = DEFAULT_CONTENTTYPE; /** * Laedt den Text einer Webseite. * * @param strURL * @return */ public String loadURL(String strURL) { return loadURL(strURL, true); } /** * Laed den Text einer Webseite. * * @param strUrl * @return */ public String loadURL(String strUrl, boolean cleanUrl) { String result = ""; try { if (cleanUrl) { strUrl = cleanUrl(strUrl); } URL url = new URL(strUrl); BufferedInputStream inputStream = new BufferedInputStream(url.openStream()); byte[] array = IOUtils.toByteArray(inputStream); _detectedCharset = guessEncoding(array); result = Jsoup.parse(url.openStream(), _detectedCharset, strUrl).text(); } catch (MalformedURLException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); return "FAIL MalformedURLException"; } catch (UnsupportedEncodingException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); return "FAIL UnsupportedEncodingException"; } catch (IOException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); return "FAIL IOException"; } return result; } /** * Laed eine Datei. * * @param filePath * @return */ public static String loadFile(String filePath) { String result = ""; FileInputStream inputStream = null; DataInputStream dataInputStream = null; StringBuilder stringBuilder = new StringBuilder(); String charset = ""; try { inputStream = new FileInputStream(filePath); String line = ""; byte[] array = IOUtils.toByteArray(inputStream); charset = guessEncoding(array); - if (charset.equalsIgnoreCase("WINDOWS-1255")) + if (charset.equalsIgnoreCase("WINDOWS-1252")) { charset = "CP1252"; } inputStream = new FileInputStream(filePath); dataInputStream = new DataInputStream(inputStream); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, charset)); while ((line = bufferedReader.readLine()) != null) { if (stringBuilder.length() > 0) { stringBuilder.append("\n"); } stringBuilder.append(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } finally { if (dataInputStream != null) { try { dataInputStream.close(); } catch (IOException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); } result = stringBuilder.toString(); } } return result; } /** * Bereinigt eine Url, sodass sie immer vollstaendig ist * * @param dirtyUrl * @return result */ public static String cleanUrl(String dirtyUrl) { String result = ""; //dirtyUrl = dirtyUrl.replaceAll("www.", ""); dirtyUrl = dirtyUrl.replaceAll("http://", ""); dirtyUrl = dirtyUrl.replaceAll("https://", ""); result = "http://" + dirtyUrl; // result = "http://www." + dirtyUrl; _logger.info("Dirty-URL: " + dirtyUrl); _logger.info("Clean-URL: " + result); return result; } /** * Versucht Charset herauszufinden * * @param bytes * @return Charset als String */ public static String guessEncoding(byte[] bytes) { UniversalDetector detector = new UniversalDetector(null); detector.handleData(bytes, 0, bytes.length); detector.dataEnd(); String encoding = detector.getDetectedCharset(); detector.reset(); if (encoding == null) { encoding = DEFAULT_CONTENTTYPE; } return encoding; } }
true
true
public static String loadFile(String filePath) { String result = ""; FileInputStream inputStream = null; DataInputStream dataInputStream = null; StringBuilder stringBuilder = new StringBuilder(); String charset = ""; try { inputStream = new FileInputStream(filePath); String line = ""; byte[] array = IOUtils.toByteArray(inputStream); charset = guessEncoding(array); if (charset.equalsIgnoreCase("WINDOWS-1255")) { charset = "CP1252"; } inputStream = new FileInputStream(filePath); dataInputStream = new DataInputStream(inputStream); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, charset)); while ((line = bufferedReader.readLine()) != null) { if (stringBuilder.length() > 0) { stringBuilder.append("\n"); } stringBuilder.append(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } finally { if (dataInputStream != null) { try { dataInputStream.close(); } catch (IOException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); } result = stringBuilder.toString(); } } return result; }
public static String loadFile(String filePath) { String result = ""; FileInputStream inputStream = null; DataInputStream dataInputStream = null; StringBuilder stringBuilder = new StringBuilder(); String charset = ""; try { inputStream = new FileInputStream(filePath); String line = ""; byte[] array = IOUtils.toByteArray(inputStream); charset = guessEncoding(array); if (charset.equalsIgnoreCase("WINDOWS-1252")) { charset = "CP1252"; } inputStream = new FileInputStream(filePath); dataInputStream = new DataInputStream(inputStream); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, charset)); while ((line = bufferedReader.readLine()) != null) { if (stringBuilder.length() > 0) { stringBuilder.append("\n"); } stringBuilder.append(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block _logger.fatal(e.getMessage(), e); e.printStackTrace(); } finally { if (dataInputStream != null) { try { dataInputStream.close(); } catch (IOException e) { _logger.fatal(e.getMessage(), e); e.printStackTrace(); } result = stringBuilder.toString(); } } return result; }
diff --git a/jsrc/assets/Ticket.java b/jsrc/assets/Ticket.java index 528551d..8912840 100644 --- a/jsrc/assets/Ticket.java +++ b/jsrc/assets/Ticket.java @@ -1,42 +1,42 @@ package assets; /** * Represents a ticket line from an available tickets file, containing * a quantity of tickets from being sold from some seller, to some event. */ public class Ticket { private String eventName; private int quantity; private int price; private String username; public static final int eventName_size = 19; public static final int quantity_size = 3; public static final int price_size = 6; public static final int username_size = 15; /** * Constructs a new Ticket object, from the given line of text * from the available tickets file. */ public Ticket(String ATFLine) { this.eventName = ATFLine.substring(0, eventName_size-1); - this.username = ATFLine.substring(eventName+1, eventName+1+username_size-1); - this.quantity = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1, eventName_size + 1 + username_size + 1 + quantity_size -1 )); - this.price = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1 + quantity_size + 1, eventName_size + 1 + username_size + 1 + quantity_size + 1 + price_size -1 )); + this.username = ATFLine.substring( eventName_size + 1, eventName_size + 1 + username_size - 1); + this.quantity = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1, eventName_size + 1 + username_size + 1 + quantity_size - 1 )); + this.price = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1 + quantity_size + 1, eventName_size + 1 + username_size + 1 + quantity_size + 1 + price_size - 1 )); } /** * Returns the string representation of this ticket, in a format * suitable to be written to an available tickets file. */ public String toString() { return ""; } }
true
true
public Ticket(String ATFLine) { this.eventName = ATFLine.substring(0, eventName_size-1); this.username = ATFLine.substring(eventName+1, eventName+1+username_size-1); this.quantity = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1, eventName_size + 1 + username_size + 1 + quantity_size -1 )); this.price = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1 + quantity_size + 1, eventName_size + 1 + username_size + 1 + quantity_size + 1 + price_size -1 )); }
public Ticket(String ATFLine) { this.eventName = ATFLine.substring(0, eventName_size-1); this.username = ATFLine.substring( eventName_size + 1, eventName_size + 1 + username_size - 1); this.quantity = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1, eventName_size + 1 + username_size + 1 + quantity_size - 1 )); this.price = Integer.parseInt( ATFLine.substring(eventName_size + 1 + username_size + 1 + quantity_size + 1, eventName_size + 1 + username_size + 1 + quantity_size + 1 + price_size - 1 )); }
diff --git a/src/de/rallye/api/Game.java b/src/de/rallye/api/Game.java index d18abb6..ed447ee 100644 --- a/src/de/rallye/api/Game.java +++ b/src/de/rallye/api/Game.java @@ -1,67 +1,68 @@ package de.rallye.api; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.sun.jersey.spi.container.ResourceFilters; import de.rallye.RallyeResources; import de.rallye.RallyeServer; import de.rallye.auth.KnownUserAuth; import de.rallye.auth.RallyePrincipal; import de.rallye.exceptions.DataException; import de.rallye.exceptions.WebAppExcept; import de.rallye.model.structures.GameState; @Path("rallye/game") public class Game { private Logger logger = LogManager.getLogger(Game.class); private RallyeResources R = RallyeServer.getResources(); @GET @ResourceFilters(KnownUserAuth.class) @Path("state") @Produces(MediaType.APPLICATION_JSON) public GameState getChats(@Context SecurityContext sec) { return R.getGameState(); } @POST @ResourceFilters(KnownUserAuth.class) @Path("nextPosition") @Consumes(MediaType.APPLICATION_JSON) public Response setUpcomingPosition(@Context SecurityContext sec, int nodeID) { logger.entry(); int groupId = ((RallyePrincipal)sec.getUserPrincipal()).getGroupID(); logger.debug(groupId +" goes to "+nodeID); try { R.getGameState().setUpcomingPosition(groupId,nodeID); } catch (DataException e) { logger.error("getChatrooms failed", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } catch (WebAppExcept e) { - throw logger.throwing(e); + logger.warn(e); + throw e; } return logger.exit(Response.ok().build()); } }
true
true
public Response setUpcomingPosition(@Context SecurityContext sec, int nodeID) { logger.entry(); int groupId = ((RallyePrincipal)sec.getUserPrincipal()).getGroupID(); logger.debug(groupId +" goes to "+nodeID); try { R.getGameState().setUpcomingPosition(groupId,nodeID); } catch (DataException e) { logger.error("getChatrooms failed", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } catch (WebAppExcept e) { throw logger.throwing(e); } return logger.exit(Response.ok().build()); }
public Response setUpcomingPosition(@Context SecurityContext sec, int nodeID) { logger.entry(); int groupId = ((RallyePrincipal)sec.getUserPrincipal()).getGroupID(); logger.debug(groupId +" goes to "+nodeID); try { R.getGameState().setUpcomingPosition(groupId,nodeID); } catch (DataException e) { logger.error("getChatrooms failed", e); throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } catch (WebAppExcept e) { logger.warn(e); throw e; } return logger.exit(Response.ok().build()); }
diff --git a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java index c3cfeee..644e394 100644 --- a/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java +++ b/src/test/java/edu/chl/dat076/foodfeed/model/dao/RecipeDaoTest.java @@ -1,102 +1,102 @@ package edu.chl.dat076.foodfeed.model.dao; import edu.chl.dat076.foodfeed.exception.ResourceNotFoundException; import edu.chl.dat076.foodfeed.model.entity.Grocery; import edu.chl.dat076.foodfeed.model.entity.Ingredient; import edu.chl.dat076.foodfeed.model.entity.Recipe; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:spring/root-context.xml", "classpath*:spring/security-context.xml"}) @Transactional public class RecipeDaoTest { @Autowired RecipeDao recipeDao; public Recipe recipe; /* * Creates a Recipe Object to be used in tests */ private Recipe createTestRecipeObject(){ - List<Ingredient> ingredients = new ArrayList(); + List<Ingredient> ingredients = new ArrayList<>(); ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken")); ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter")); Recipe recipe = new Recipe(); recipe.setDescription("Best soup in the world"); recipe.setName("Soup"); recipe.setIngredients(ingredients); recipe.setInstructions("Add all ingredients"); return recipe; } @Before public void createRecipe(){ recipe = createTestRecipeObject(); recipeDao.create(recipe); } @Test public void testCreate(){ Assert.assertNotNull("recipe could not be created", recipe.getId()); } @Test(expected = ResourceNotFoundException.class) public void testDelete(){ recipeDao.delete(recipe); Assert.assertNull("recipe removed", recipeDao.find(recipe.getId())); } @Test(expected = ResourceNotFoundException.class) public void testDeleteID(){ recipeDao.delete(recipe.getId()); Assert.assertNull("recipe not removed", recipeDao.find(recipe.getId())); } @Test public void testFind(){ Recipe result = recipeDao.find(recipe.getId()); Assert.assertNotNull("recipe not found", result); } @Test public void testFindAll() { List<Recipe> recipes = recipeDao.findAll(); assertFalse("Check that true is true", recipes.isEmpty()); } @Test public void testUpdate(){ Recipe old = new Recipe(); old.setName(recipe.getName()); recipe.setName("New name"); recipeDao.update(recipe); Assert.assertNotSame("Recipe not updated", recipe.getName(), old.getName()); } @Test public void testGetByIngredient(){ List<Recipe> result = recipeDao.getByIngredient(recipe.getIngredients().get(0)); Assert.assertFalse("found no recipe", result.isEmpty()); } @Test public void testGetByName(){ List<Recipe> result = recipeDao.getByName(recipe.getName()); Assert.assertFalse("found no recipe", result.isEmpty()); } }
true
true
private Recipe createTestRecipeObject(){ List<Ingredient> ingredients = new ArrayList(); ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken")); ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter")); Recipe recipe = new Recipe(); recipe.setDescription("Best soup in the world"); recipe.setName("Soup"); recipe.setIngredients(ingredients); recipe.setInstructions("Add all ingredients"); return recipe; }
private Recipe createTestRecipeObject(){ List<Ingredient> ingredients = new ArrayList<>(); ingredients.add(new Ingredient(new Grocery("Red pepper", "Swedish red pepper"), 2.0, "stycken")); ingredients.add(new Ingredient(new Grocery("Water", "Tap water"), 20.0, "liter")); Recipe recipe = new Recipe(); recipe.setDescription("Best soup in the world"); recipe.setName("Soup"); recipe.setIngredients(ingredients); recipe.setInstructions("Add all ingredients"); return recipe; }
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/ProcessStatsActivity.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/ProcessStatsActivity.java index 4d2770e8..27e26a19 100644 --- a/BetterBatteryStats/src/com/asksven/betterbatterystats/ProcessStatsActivity.java +++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/ProcessStatsActivity.java @@ -1,136 +1,137 @@ /* * Copyright (C) 2011 asksven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asksven.betterbatterystats; /** * @author sven * */ import java.util.Collections; import java.util.List; import java.util.Vector; import com.asksven.android.common.privateapiproxies.BatteryStatsProxy; import com.asksven.android.common.privateapiproxies.BatteryStatsTypes; import com.asksven.android.common.privateapiproxies.Wakelock; import com.asksven.android.common.privateapiproxies.Process; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView; import android.view.View; public class ProcessStatsActivity extends ListActivity implements AdapterView.OnItemSelectedListener { /** * The logging TAG */ private static final String TAG = "ProcessStatsActivity"; /** * The ArrayAdpater for rendering the ListView */ private ArrayAdapter<String> m_listViewAdapter; /** * The Type of Stat to be displayed (default is "Since charged") */ private int m_iStatType = 0; /** * @see android.app.Activity#onCreate(Bundle@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes") ) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.process_stats); Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType); ArrayAdapter spinnerAdapter = ArrayAdapter.createFromResource( this, R.array.stat_types, android.R.layout.simple_spinner_item); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStatType.setAdapter(spinnerAdapter); spinnerStatType.setOnItemSelectedListener(this); m_listViewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getStatList()); setListAdapter(m_listViewAdapter); } /** * Take the change of selection from the spinner into account and refresh the ListView */ public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { m_iStatType = position; m_listViewAdapter.notifyDataSetChanged(); m_listViewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getStatList()); setListAdapter(m_listViewAdapter); } public void onNothingSelected(AdapterView<?> parent) { // default m_iStatType = 0; m_listViewAdapter.notifyDataSetChanged(); } /** * Get the Wakelock Stats to be displayed * @return a List of Wakelocks sorted by duration (descending) */ List<String> getStatList() { List<String> myStats = new Vector<String>(); BatteryStatsProxy mStats = new BatteryStatsProxy(this); try { List<Process> myProcesses = mStats.getProcessStats(this, m_iStatType); // sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo Collections.sort(myProcesses); for (int i = 0; i < myProcesses.size(); i++) { Process ps = myProcesses.get(i); -// if ((ps.getSystem()/1000) > 0) + // show only non-zero values + if ( ((ps.getSystemTime()+ps.getUserTime()) /1000) > 0) { - myStats.add(ps.getName() + " Sys:" + ps.getSystemTime()/1000 + "s, Us: " + ps.getUserTime()/1000); + myStats.add(ps.getName() + " Sys:" + ps.getSystemTime()/1000 + "s, Us: " + ps.getUserTime()/1000 + "s"); } } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); Toast.makeText(this, "Wakelock Stats: an error occured while retrieving the statistics", Toast.LENGTH_SHORT).show(); } return myStats; } }
false
true
List<String> getStatList() { List<String> myStats = new Vector<String>(); BatteryStatsProxy mStats = new BatteryStatsProxy(this); try { List<Process> myProcesses = mStats.getProcessStats(this, m_iStatType); // sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo Collections.sort(myProcesses); for (int i = 0; i < myProcesses.size(); i++) { Process ps = myProcesses.get(i); // if ((ps.getSystem()/1000) > 0) { myStats.add(ps.getName() + " Sys:" + ps.getSystemTime()/1000 + "s, Us: " + ps.getUserTime()/1000); } } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); Toast.makeText(this, "Wakelock Stats: an error occured while retrieving the statistics", Toast.LENGTH_SHORT).show(); } return myStats; }
List<String> getStatList() { List<String> myStats = new Vector<String>(); BatteryStatsProxy mStats = new BatteryStatsProxy(this); try { List<Process> myProcesses = mStats.getProcessStats(this, m_iStatType); // sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo Collections.sort(myProcesses); for (int i = 0; i < myProcesses.size(); i++) { Process ps = myProcesses.get(i); // show only non-zero values if ( ((ps.getSystemTime()+ps.getUserTime()) /1000) > 0) { myStats.add(ps.getName() + " Sys:" + ps.getSystemTime()/1000 + "s, Us: " + ps.getUserTime()/1000 + "s"); } } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); Toast.makeText(this, "Wakelock Stats: an error occured while retrieving the statistics", Toast.LENGTH_SHORT).show(); } return myStats; }
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/response/QueryResponseTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/response/QueryResponseTest.java index 0de8662d2..b8230eff3 100644 --- a/solr/solrj/src/test/org/apache/solr/client/solrj/response/QueryResponseTest.java +++ b/solr/solrj/src/test/org/apache/solr/client/solrj/response/QueryResponseTest.java @@ -1,116 +1,116 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.client.solrj.response; import junit.framework.Assert; import org.apache.lucene.util.LuceneTestCase; import org.apache.solr.client.solrj.impl.XMLResponseParser; import org.apache.solr.common.util.DateUtil; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.SolrResourceLoader; import org.junit.Test; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; /** * Simple test for Date facet support in QueryResponse * * @since solr 1.3 */ public class QueryResponseTest extends LuceneTestCase { @Test public void testDateFacets() throws Exception { XMLResponseParser parser = new XMLResponseParser(); InputStream is = new SolrResourceLoader(null, null).openResource("solrj/sampleDateFacetResponse.xml"); assertNotNull(is); Reader in = new InputStreamReader(is, "UTF-8"); NamedList<Object> response = parser.processResponse(in); in.close(); QueryResponse qr = new QueryResponse(response, null); Assert.assertNotNull(qr); Assert.assertNotNull(qr.getFacetDates()); for (FacetField f : qr.getFacetDates()) { Assert.assertNotNull(f); // TODO - test values? // System.out.println(f.toString()); // System.out.println("GAP: " + f.getGap()); // System.out.println("END: " + f.getEnd()); } } @Test public void testRangeFacets() throws Exception { XMLResponseParser parser = new XMLResponseParser(); - InputStream is = new SolrResourceLoader(null, null).openResource("sampleDateFacetResponse.xml"); + InputStream is = new SolrResourceLoader(null, null).openResource("solrj/sampleDateFacetResponse.xml"); assertNotNull(is); Reader in = new InputStreamReader(is, "UTF-8"); NamedList<Object> response = parser.processResponse(in); in.close(); QueryResponse qr = new QueryResponse(response, null); Assert.assertNotNull(qr); int counter = 0; RangeFacet.Numeric price = null; RangeFacet.Date manufacturedateDt = null; for (RangeFacet r : qr.getFacetRanges()){ assertNotNull(r); if ("price".equals(r.getName())) { price = (RangeFacet.Numeric) r; } else if ("manufacturedate_dt".equals(r.getName())) { manufacturedateDt = (RangeFacet.Date) r; } counter++; } assertEquals(2, counter); assertNotNull(price); assertNotNull(manufacturedateDt); assertEquals(0.0F, price.getStart()); assertEquals(5.0F, price.getEnd()); assertEquals(1.0F, price.getGap()); assertEquals("0.0", price.getCounts().get(0).getValue()); assertEquals(3, price.getCounts().get(0).getCount()); assertEquals("1.0", price.getCounts().get(1).getValue()); assertEquals(0, price.getCounts().get(1).getCount()); assertEquals("2.0", price.getCounts().get(2).getValue()); assertEquals(0, price.getCounts().get(2).getCount()); assertEquals("3.0", price.getCounts().get(3).getValue()); assertEquals(0, price.getCounts().get(3).getCount()); assertEquals("4.0", price.getCounts().get(4).getValue()); assertEquals(0, price.getCounts().get(4).getCount()); assertEquals(DateUtil.parseDate("2005-02-13T15:26:37Z"), manufacturedateDt.getStart()); assertEquals(DateUtil.parseDate("2008-02-13T15:26:37Z"), manufacturedateDt.getEnd()); assertEquals("+1YEAR", manufacturedateDt.getGap()); assertEquals("2005-02-13T15:26:37Z", manufacturedateDt.getCounts().get(0).getValue()); assertEquals(4, manufacturedateDt.getCounts().get(0).getCount()); assertEquals("2006-02-13T15:26:37Z", manufacturedateDt.getCounts().get(1).getValue()); assertEquals(7, manufacturedateDt.getCounts().get(1).getCount()); assertEquals("2007-02-13T15:26:37Z", manufacturedateDt.getCounts().get(2).getValue()); assertEquals(0, manufacturedateDt.getCounts().get(2).getCount()); } }
true
true
public void testRangeFacets() throws Exception { XMLResponseParser parser = new XMLResponseParser(); InputStream is = new SolrResourceLoader(null, null).openResource("sampleDateFacetResponse.xml"); assertNotNull(is); Reader in = new InputStreamReader(is, "UTF-8"); NamedList<Object> response = parser.processResponse(in); in.close(); QueryResponse qr = new QueryResponse(response, null); Assert.assertNotNull(qr); int counter = 0; RangeFacet.Numeric price = null; RangeFacet.Date manufacturedateDt = null; for (RangeFacet r : qr.getFacetRanges()){ assertNotNull(r); if ("price".equals(r.getName())) { price = (RangeFacet.Numeric) r; } else if ("manufacturedate_dt".equals(r.getName())) { manufacturedateDt = (RangeFacet.Date) r; } counter++; } assertEquals(2, counter); assertNotNull(price); assertNotNull(manufacturedateDt); assertEquals(0.0F, price.getStart()); assertEquals(5.0F, price.getEnd()); assertEquals(1.0F, price.getGap()); assertEquals("0.0", price.getCounts().get(0).getValue()); assertEquals(3, price.getCounts().get(0).getCount()); assertEquals("1.0", price.getCounts().get(1).getValue()); assertEquals(0, price.getCounts().get(1).getCount()); assertEquals("2.0", price.getCounts().get(2).getValue()); assertEquals(0, price.getCounts().get(2).getCount()); assertEquals("3.0", price.getCounts().get(3).getValue()); assertEquals(0, price.getCounts().get(3).getCount()); assertEquals("4.0", price.getCounts().get(4).getValue()); assertEquals(0, price.getCounts().get(4).getCount()); assertEquals(DateUtil.parseDate("2005-02-13T15:26:37Z"), manufacturedateDt.getStart()); assertEquals(DateUtil.parseDate("2008-02-13T15:26:37Z"), manufacturedateDt.getEnd()); assertEquals("+1YEAR", manufacturedateDt.getGap()); assertEquals("2005-02-13T15:26:37Z", manufacturedateDt.getCounts().get(0).getValue()); assertEquals(4, manufacturedateDt.getCounts().get(0).getCount()); assertEquals("2006-02-13T15:26:37Z", manufacturedateDt.getCounts().get(1).getValue()); assertEquals(7, manufacturedateDt.getCounts().get(1).getCount()); assertEquals("2007-02-13T15:26:37Z", manufacturedateDt.getCounts().get(2).getValue()); assertEquals(0, manufacturedateDt.getCounts().get(2).getCount()); }
public void testRangeFacets() throws Exception { XMLResponseParser parser = new XMLResponseParser(); InputStream is = new SolrResourceLoader(null, null).openResource("solrj/sampleDateFacetResponse.xml"); assertNotNull(is); Reader in = new InputStreamReader(is, "UTF-8"); NamedList<Object> response = parser.processResponse(in); in.close(); QueryResponse qr = new QueryResponse(response, null); Assert.assertNotNull(qr); int counter = 0; RangeFacet.Numeric price = null; RangeFacet.Date manufacturedateDt = null; for (RangeFacet r : qr.getFacetRanges()){ assertNotNull(r); if ("price".equals(r.getName())) { price = (RangeFacet.Numeric) r; } else if ("manufacturedate_dt".equals(r.getName())) { manufacturedateDt = (RangeFacet.Date) r; } counter++; } assertEquals(2, counter); assertNotNull(price); assertNotNull(manufacturedateDt); assertEquals(0.0F, price.getStart()); assertEquals(5.0F, price.getEnd()); assertEquals(1.0F, price.getGap()); assertEquals("0.0", price.getCounts().get(0).getValue()); assertEquals(3, price.getCounts().get(0).getCount()); assertEquals("1.0", price.getCounts().get(1).getValue()); assertEquals(0, price.getCounts().get(1).getCount()); assertEquals("2.0", price.getCounts().get(2).getValue()); assertEquals(0, price.getCounts().get(2).getCount()); assertEquals("3.0", price.getCounts().get(3).getValue()); assertEquals(0, price.getCounts().get(3).getCount()); assertEquals("4.0", price.getCounts().get(4).getValue()); assertEquals(0, price.getCounts().get(4).getCount()); assertEquals(DateUtil.parseDate("2005-02-13T15:26:37Z"), manufacturedateDt.getStart()); assertEquals(DateUtil.parseDate("2008-02-13T15:26:37Z"), manufacturedateDt.getEnd()); assertEquals("+1YEAR", manufacturedateDt.getGap()); assertEquals("2005-02-13T15:26:37Z", manufacturedateDt.getCounts().get(0).getValue()); assertEquals(4, manufacturedateDt.getCounts().get(0).getCount()); assertEquals("2006-02-13T15:26:37Z", manufacturedateDt.getCounts().get(1).getValue()); assertEquals(7, manufacturedateDt.getCounts().get(1).getCount()); assertEquals("2007-02-13T15:26:37Z", manufacturedateDt.getCounts().get(2).getValue()); assertEquals(0, manufacturedateDt.getCounts().get(2).getCount()); }
diff --git a/src/main/java/com/nzonly/tb/web/ScheduleController.java b/src/main/java/com/nzonly/tb/web/ScheduleController.java index 5165169..fa6612c 100644 --- a/src/main/java/com/nzonly/tb/web/ScheduleController.java +++ b/src/main/java/com/nzonly/tb/web/ScheduleController.java @@ -1,29 +1,29 @@ package com.nzonly.tb.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.nzonly.tb.quartz.ScheduleService; /** * @author yinheli * @link [email protected] * @date 2012-7-22 上午10:43:27 * @version V1.0 */ @Controller @RequestMapping("/schedule") public class ScheduleController extends BaseController { @Autowired private ScheduleService scheduleService; @RequestMapping(value = {"index", ""}) public String index(Model model) { model.addAttribute("list", new Object()); - return "index"; + return "schedule/index"; } }
true
true
public String index(Model model) { model.addAttribute("list", new Object()); return "index"; }
public String index(Model model) { model.addAttribute("list", new Object()); return "schedule/index"; }
diff --git a/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java b/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java index 1d12aaf2..5dae3b0e 100644 --- a/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java +++ b/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java @@ -1,280 +1,280 @@ package org.oryxeditor.server; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Node; import de.hpi.xforms.XForm; import de.hpi.xforms.generation.WSDL2XFormsTransformation; import de.hpi.xforms.rdf.XFormsERDFExporter; import de.hpi.xforms.serialization.XFormsXHTMLImporter; /** * * @author [email protected] * @author [email protected] */ public class WSDL2XFormsServlet extends HttpServlet { private static final long serialVersionUID = 6084194342174761234L; private static String wsdlUrl = ""; // port type -> ( operation name -> form url ) private static Map<String, Map<String, String>> forms; // GET is totally wrong in this case!!! ONLY for testing! protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException { doPost(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { wsdlUrl = req.getParameter("wsdlUrl"); forms = new HashMap<String, Map<String, String>>(); HashMap<String, Document> distinctXFormsDocs = getXFormDocuments( getWSDL(), generateWsdlId(wsdlUrl)); saveXFormsInOryxRepository(distinctXFormsDocs, Repository .getBaseUrl(req)); writeResponse(req, res); } private Document getWSDL() { try { URL url = new URL(wsdlUrl); DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(url.openStream()); } catch (Exception e) { e.printStackTrace(); } return null; } private HashMap<String, Document> getXFormDocuments(Document wsdl, String wsdlId) { // transform to XForms documents List<Document> xformsDocs = WSDL2XFormsTransformation.transform( getServletContext(), wsdl.getDocumentElement(), wsdlId); // filter duplicates HashMap<String, Document> distinctXFormsDocs = new HashMap<String, Document>(); for (Document xformsDoc : xformsDocs) { String name = getSuitableFormName(xformsDoc); if (!distinctXFormsDocs.containsKey(name)) distinctXFormsDocs.put(name, xformsDoc); } return distinctXFormsDocs; } private void saveXFormsInOryxRepository( HashMap<String, Document> distinctXFormsDocs, String baseUrl) { for (String xformsDocName : distinctXFormsDocs.keySet()) { Document xformsDoc = distinctXFormsDocs.get(xformsDocName); XFormsXHTMLImporter importer = new XFormsXHTMLImporter(xformsDoc); XForm form = importer.getXForm(); // convert XForm to erdf XFormsERDFExporter exporter = new XFormsERDFExporter(form, getServletContext().getRealPath( "/stencilsets/xforms/xforms.json")); StringWriter erdfWriter = new StringWriter(); exporter.exportERDF(erdfWriter); // save XForm to repository Repository repo = new Repository(baseUrl); String modelUrl = baseUrl + repo.saveNewModelErdf(erdfWriter.toString(), xformsDocName, xformsDocName, "http://b3mn.org/stencilset/xforms#", "/stencilsets/xforms/xforms.json", getServletContext()); addResponseParams(xformsDoc.getDocumentElement(), modelUrl .substring(modelUrl.lastIndexOf("http://"))); } } private static String generateWsdlId(String url) { UUID uuid = UUID.nameUUIDFromBytes(url.getBytes()); return uuid.toString(); } private static String getSuitableFormName(Document formNode) { Node instanceNode = getChild(getChild(getChild(formNode .getDocumentElement(), "xhtml:head"), "xforms:model"), "xforms:instance"); if (instanceNode != null) { String[] splitted = getAttributeValue(instanceNode, "id").split( "\\."); return splitted[1] + ":" + splitted[2]; } return null; } private static void addResponseParams(Node formNode, String formUrl) { Node instanceNode = getChild(getChild(getChild(formNode, "xhtml:head"), "xforms:model"), "xforms:instance"); if (instanceNode != null) { String[] splitted = getAttributeValue(instanceNode, "id").split( "\\."); Map<String, String> operations = new HashMap<String, String>(); if (!forms.containsKey(splitted[1])) forms.put(splitted[1], operations); else operations = forms.get(splitted[1]); operations.put(splitted[2], formUrl); } } private static Node getChild(Node n, String name) { if (n == null) return null; for (Node node = n.getFirstChild(); node != null; node = node .getNextSibling()) if (node.getNodeName().equals(name)) return node; return null; } private static String getAttributeValue(Node node, String attribute) { Node item = node.getAttributes().getNamedItem(attribute); if (item != null) return item.getNodeValue(); else return null; } private static void writeResponse(HttpServletRequest req, HttpServletResponse res) { String representation = req.getParameter("representation"); try { Writer resWriter = res.getWriter(); - if (representation.equals("xhtml")) { + if (representation != null && representation.equals("xhtml")) { // TODO: examination of the HTTP Accept header (see // http://www.w3.org/TR/xhtml-media-types/#media-types) res.setContentType("application/xhtml+xml"); resWriter .write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<body style=\"font-size: 75%; font-family: sans-serif;\">" + "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>" + "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>" + "<p>To execute the forms below, you will need an XForms-capable browser, e.g., " + "<a href=\"http://www.x-smiles.org/\">X-Smiles</a>, " + "<br />" + "or a suitable browser plugin, e.g., " + "<a href=\"https://addons.mozilla.org/en-US/firefox/addon/824\">the XForms extension for Firefox 2.x and 3.x</a> " + "or <a href=\"http://www.formsplayer.com/\">formsPlayer for Internet Explorer</a>." + "<br />" + "See also <a href=\"http://www.xml.com/pub/a/2003/09/10/xforms.html\">Ten Favorite XForms Engines</a> " + "and <a href=\"http://en.wikipedia.org/wiki/Xforms#Software_support\">XForms Software Support</a>." + "</p>"); String contextPath = req.getContextPath(); for (String portType : forms.keySet()) { resWriter.write("<h2>PortType: " + portType + "</h2>"); for (String operationName : forms.get(portType).keySet()) { resWriter.write("<h3>Operation: " + operationName + "</h3>"); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | "); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | "); resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>"); } } resWriter.write("</body></html>"); - } else if (representation.equals("json")) { + } else if (representation != null && representation.equals("json")) { res.setContentType("application/json"); JSONObject response = new JSONObject(); try { response.put("wsdlUrl", wsdlUrl); JSONArray portTypes = new JSONArray(); for (String portTypeName : forms.keySet()) { JSONObject portType = new JSONObject(); JSONArray operations = new JSONArray(); for (String operationName : forms.get(portTypeName).keySet()) { JSONObject operation = new JSONObject(); operation.put("name", operationName); operation.put("url", forms.get(portTypeName).get(operationName)); operations.put(operation); } portType.put("operations", operations); portType.put("name", portTypeName); portTypes.put(portType); } response.put("portTypes", portTypes); } catch (JSONException e) { e.printStackTrace(); } resWriter.write(response.toString()); } else { res.setContentType("text/plain"); resWriter.write("svc0=" + wsdlUrl); int ptId = 0; for (String portType : forms.keySet()) { resWriter.write("&svc0_pt" + ptId + "=" + portType); int opId = 0; for (String operationName : forms.get(portType).keySet()) { resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName); resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName)); opId++; } ptId++; } } } catch (IOException e) { e.printStackTrace(); } } }
false
true
private static void writeResponse(HttpServletRequest req, HttpServletResponse res) { String representation = req.getParameter("representation"); try { Writer resWriter = res.getWriter(); if (representation.equals("xhtml")) { // TODO: examination of the HTTP Accept header (see // http://www.w3.org/TR/xhtml-media-types/#media-types) res.setContentType("application/xhtml+xml"); resWriter .write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<body style=\"font-size: 75%; font-family: sans-serif;\">" + "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>" + "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>" + "<p>To execute the forms below, you will need an XForms-capable browser, e.g., " + "<a href=\"http://www.x-smiles.org/\">X-Smiles</a>, " + "<br />" + "or a suitable browser plugin, e.g., " + "<a href=\"https://addons.mozilla.org/en-US/firefox/addon/824\">the XForms extension for Firefox 2.x and 3.x</a> " + "or <a href=\"http://www.formsplayer.com/\">formsPlayer for Internet Explorer</a>." + "<br />" + "See also <a href=\"http://www.xml.com/pub/a/2003/09/10/xforms.html\">Ten Favorite XForms Engines</a> " + "and <a href=\"http://en.wikipedia.org/wiki/Xforms#Software_support\">XForms Software Support</a>." + "</p>"); String contextPath = req.getContextPath(); for (String portType : forms.keySet()) { resWriter.write("<h2>PortType: " + portType + "</h2>"); for (String operationName : forms.get(portType).keySet()) { resWriter.write("<h3>Operation: " + operationName + "</h3>"); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | "); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | "); resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>"); } } resWriter.write("</body></html>"); } else if (representation.equals("json")) { res.setContentType("application/json"); JSONObject response = new JSONObject(); try { response.put("wsdlUrl", wsdlUrl); JSONArray portTypes = new JSONArray(); for (String portTypeName : forms.keySet()) { JSONObject portType = new JSONObject(); JSONArray operations = new JSONArray(); for (String operationName : forms.get(portTypeName).keySet()) { JSONObject operation = new JSONObject(); operation.put("name", operationName); operation.put("url", forms.get(portTypeName).get(operationName)); operations.put(operation); } portType.put("operations", operations); portType.put("name", portTypeName); portTypes.put(portType); } response.put("portTypes", portTypes); } catch (JSONException e) { e.printStackTrace(); } resWriter.write(response.toString()); } else { res.setContentType("text/plain"); resWriter.write("svc0=" + wsdlUrl); int ptId = 0; for (String portType : forms.keySet()) { resWriter.write("&svc0_pt" + ptId + "=" + portType); int opId = 0; for (String operationName : forms.get(portType).keySet()) { resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName); resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName)); opId++; } ptId++; } } } catch (IOException e) { e.printStackTrace(); } }
private static void writeResponse(HttpServletRequest req, HttpServletResponse res) { String representation = req.getParameter("representation"); try { Writer resWriter = res.getWriter(); if (representation != null && representation.equals("xhtml")) { // TODO: examination of the HTTP Accept header (see // http://www.w3.org/TR/xhtml-media-types/#media-types) res.setContentType("application/xhtml+xml"); resWriter .write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<body style=\"font-size: 75%; font-family: sans-serif;\">" + "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>" + "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>" + "<p>To execute the forms below, you will need an XForms-capable browser, e.g., " + "<a href=\"http://www.x-smiles.org/\">X-Smiles</a>, " + "<br />" + "or a suitable browser plugin, e.g., " + "<a href=\"https://addons.mozilla.org/en-US/firefox/addon/824\">the XForms extension for Firefox 2.x and 3.x</a> " + "or <a href=\"http://www.formsplayer.com/\">formsPlayer for Internet Explorer</a>." + "<br />" + "See also <a href=\"http://www.xml.com/pub/a/2003/09/10/xforms.html\">Ten Favorite XForms Engines</a> " + "and <a href=\"http://en.wikipedia.org/wiki/Xforms#Software_support\">XForms Software Support</a>." + "</p>"); String contextPath = req.getContextPath(); for (String portType : forms.keySet()) { resWriter.write("<h2>PortType: " + portType + "</h2>"); for (String operationName : forms.get(portType).keySet()) { resWriter.write("<h3>Operation: " + operationName + "</h3>"); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | "); resWriter .write("<a href=\"" + forms .get(portType) .get(operationName) .replace( "/backend", contextPath + "/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | "); resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>"); } } resWriter.write("</body></html>"); } else if (representation != null && representation.equals("json")) { res.setContentType("application/json"); JSONObject response = new JSONObject(); try { response.put("wsdlUrl", wsdlUrl); JSONArray portTypes = new JSONArray(); for (String portTypeName : forms.keySet()) { JSONObject portType = new JSONObject(); JSONArray operations = new JSONArray(); for (String operationName : forms.get(portTypeName).keySet()) { JSONObject operation = new JSONObject(); operation.put("name", operationName); operation.put("url", forms.get(portTypeName).get(operationName)); operations.put(operation); } portType.put("operations", operations); portType.put("name", portTypeName); portTypes.put(portType); } response.put("portTypes", portTypes); } catch (JSONException e) { e.printStackTrace(); } resWriter.write(response.toString()); } else { res.setContentType("text/plain"); resWriter.write("svc0=" + wsdlUrl); int ptId = 0; for (String portType : forms.keySet()) { resWriter.write("&svc0_pt" + ptId + "=" + portType); int opId = 0; for (String operationName : forms.get(portType).keySet()) { resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName); resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName)); opId++; } ptId++; } } } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java index 72deab0b..4c51e532 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java @@ -1,4416 +1,4431 @@ package com.redhat.ceylon.compiler.js; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisWarning; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassAlias; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.ImportableScope; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.InterfaceAlias; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.Specification; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.*; import com.redhat.ceylon.compiler.typechecker.tree.Tree.*; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Stack<Continuation> continues = new Stack<Continuation>(); private final EnclosingFunctionVisitor encloser = new EnclosingFunctionVisitor(); private final JsIdentifierNames names; private final Set<Declaration> directAccess = new HashSet<Declaration>(); private final RetainedVars retainedVars = new RetainedVars(); final ConditionGenerator conds; private final InvocationGenerator invoker; private final List<CommonToken> tokens; private int dynblock; private final class SuperVisitor extends Visitor { private final List<Declaration> decs; private SuperVisitor(List<Declaration> decs) { this.decs = decs; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { Term primary = eliminateParensAndWidening(qe.getPrimary()); if (primary instanceof Super) { decs.add(qe.getDeclaration()); } super.visit(qe); } @Override public void visit(QualifiedType that) { if (that.getOuterType() instanceof SuperType) { decs.add(that.getDeclarationModel()); } super.visit(that); } public void visit(Tree.ClassOrInterface qe) { //don't recurse if (qe instanceof ClassDefinition) { ExtendedType extType = ((ClassDefinition) qe).getExtendedType(); if (extType != null) { super.visit(extType); } } } } private final class OuterVisitor extends Visitor { boolean found = false; private Declaration dec; private OuterVisitor(Declaration dec) { this.dec = dec; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { if (qe.getPrimary() instanceof Outer || qe.getPrimary() instanceof This) { if ( qe.getDeclaration().equals(dec) ) { found = true; } } super.visit(qe); } } private List<? extends Statement> currentStatements = null; private final TypeUtils types; private Writer out; private final Writer originalOut; final Options opts; private CompilationUnit root; private static String clAlias=""; private static final String function="function "; private boolean needIndent = true; private int indentLevel = 0; Package getCurrentPackage() { return root.getUnit().getPackage(); } private static void setCLAlias(String alias) { clAlias = alias + "."; } /** Returns the module name for the language module. */ static String getClAlias() { return clAlias; } @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } private final JsOutput jsout; public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names, List<CommonToken> tokens, TypeUtils typeUtils) throws IOException { this.jsout = out; this.opts = options; this.out = out.getWriter(); originalOut = out.getWriter(); this.names = names; conds = new ConditionGenerator(this, names, directAccess); this.tokens = tokens; types = typeUtils; invoker = new InvocationGenerator(this, names, retainedVars); } TypeUtils getTypeUtils() { return types; } InvocationGenerator getInvoker() { return invoker; } /** Returns the helper component to handle naming. */ JsIdentifierNames getNames() { return names; } private static interface GenerateCallback { public void generateValue(); } /** Print generated code to the Writer specified at creation time. * Automatically prints indentation first if necessary. * @param code The main code * @param codez Optional additional strings to print after the main code. */ void out(String code, String... codez) { try { if (opts.isIndent() && needIndent) { for (int i=0;i<indentLevel;i++) { out.write(" "); } } needIndent = false; out.write(code); for (String s : codez) { out.write(s); } if (opts.isVerbose() && out == originalOut) { //Print code to console (when printing to REAL output) System.out.print(code); for (String s : codez) { System.out.print(s); } } } catch (IOException ioe) { throw new RuntimeException("Generating JS code", ioe); } } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. */ void endLine() { endLine(false); } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. * @param semicolon if <code>true</code> then a semicolon is printed at the end * of the previous line*/ void endLine(boolean semicolon) { if (semicolon) { out(";"); } out("\n"); needIndent = true; } /** Calls {@link #endLine()} if the current position is not already the beginning * of a line. */ void beginNewLine() { if (!needIndent) { endLine(); } } /** Increases indentation level, prints opening brace and newline. Indentation will * automatically be printed by {@link #out(String, String...)} when the next line is started. */ void beginBlock() { indentLevel++; out("{"); endLine(); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. */ void endBlockNewLine() { endBlock(false, true); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. * @param semicolon if <code>true</code> then prints a semicolon after the brace*/ void endBlockNewLine(boolean semicolon) { endBlock(semicolon, true); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). */ void endBlock() { endBlock(false, false); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). * @param semicolon if <code>true</code> then prints a semicolon after the brace * @param newline if <code>true</code> then additionally calls {@link #endLine()} */ void endBlock(boolean semicolon, boolean newline) { indentLevel--; beginNewLine(); out(semicolon ? "};" : "}"); if (newline) { endLine(); } } /** Prints source code location in the form "at [filename] ([location])" */ void location(Node node) { out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")"); } private String generateToString(final GenerateCallback callback) { final Writer oldWriter = out; out = new StringWriter(); callback.generateValue(); final String str = out.toString(); out = oldWriter; return str; } @Override public void visit(CompilationUnit that) { root = that; Module clm = that.getUnit().getPackage().getModule() .getLanguageModule(); if (!JsCompiler.compilingLanguageModule) { setCLAlias(names.moduleAlias(clm)); require(clm); } if (that.getModuleDescriptor() != null) { out("exports.$mod$ans$="); TypeUtils.outputAnnotationsFunction(that.getModuleDescriptor().getAnnotationList(), this); endLine(true); } if (that.getPackageDescriptor() != null) { final String pknm = that.getUnit().getPackage().getNameAsString().replaceAll("\\.", "\\$"); out("exports.$pkg$ans$", pknm, "="); TypeUtils.outputAnnotationsFunction(that.getPackageDescriptor().getAnnotationList(), this); endLine(true); } for (CompilerAnnotation ca: that.getCompilerAnnotations()) { ca.visit(this); } if (that.getImportList() != null) { that.getImportList().visit(this); } visitStatements(that.getDeclarations()); } public void visit(Import that) { ImportableScope scope = that.getImportMemberOrTypeList().getImportList().getImportedScope(); if (scope instanceof Package) { require(((Package) scope).getModule()); } } private void require(Module mod) { final String path = scriptPath(mod); final String modAlias = names.moduleAlias(mod); if (jsout.requires.put(path, modAlias) == null) { out("var ", modAlias, "=require('", path, "');"); endLine(); if (modAlias != null && !modAlias.isEmpty()) { out(clAlias, "$addmod$(", modAlias,",'", mod.getNameAsString(), "/", mod.getVersion(), "');"); endLine(); } } } private String scriptPath(Module mod) { StringBuilder path = new StringBuilder(mod.getNameAsString().replace('.', '/')).append('/'); if (!mod.isDefault()) { path.append(mod.getVersion()).append('/'); } path.append(mod.getNameAsString()); if (!mod.isDefault()) { path.append('-').append(mod.getVersion()); } return path.toString(); } @Override public void visit(Parameter that) { out(names.name(that.getParameterModel())); } @Override public void visit(ParameterList that) { out("("); boolean first=true; boolean ptypes = false; //Check if this is the first parameter list if (that.getScope() instanceof Method && that.getModel().isFirst()) { ptypes = ((Method)that.getScope()).getTypeParameters() != null && !((Method)that.getScope()).getTypeParameters().isEmpty(); } for (Parameter param: that.getParameters()) { if (!first) out(","); out(names.name(param.getParameterModel())); first = false; } if (ptypes) { if (!first) out(","); out("$$$mptypes"); } out(")"); } private void visitStatements(List<? extends Statement> statements) { List<String> oldRetainedVars = retainedVars.reset(null); final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; for (int i=0; i<statements.size(); i++) { Statement s = statements.get(i); s.visit(this); beginNewLine(); retainedVars.emitRetainedVars(this); } retainedVars.reset(oldRetainedVars); currentStatements = prevStatements; } @Override public void visit(Body that) { visitStatements(that.getStatements()); } @Override public void visit(Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); } else { beginBlock(); initSelf(that); visitStatements(stmnts); endBlock(); } } private void initSelf(Block block) { initSelf(block.getScope()); } private void initSelf(Scope scope) { if ((prototypeOwner != null) && ((scope instanceof MethodOrValue) || (scope instanceof TypeDeclaration) || (scope instanceof Specification))) { out("var "); self(prototypeOwner); out("=this;"); endLine(); } } private void comment(Tree.Declaration that) { if (!opts.isComment()) return; endLine(); out("//", that.getNodeType(), " ", that.getDeclarationModel().getName()); location(that); endLine(); } private void var(Declaration d) { out("var ", names.name(d), "="); } private boolean share(Declaration d) { return share(d, true); } private boolean share(Declaration d, boolean excludeProtoMembers) { boolean shared = false; if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember()) && isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.name(d), "=", names.name(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(ClassDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) { //But warnings are ok for (Message err : that.getErrors()) { if (!(err instanceof AnalysisWarning)) { return; } } } Class d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; comment(that); Tree.ClassSpecifier ext = that.getClassSpecifier(); out(function, names.name(d), "("); //Generate each parameter because we need to append one at the end for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } TypeArgumentList targs = ext.getType().getTypeArgumentList(); if (targs != null && !targs.getTypes().isEmpty()) { out("$$targs$$,"); } self(d); out(")"); TypeDeclaration aliased = ext.getType().getDeclarationModel(); out("{return "); qualify(ext.getType(), aliased); out(names.name(aliased), "("); if (ext.getInvocationExpression().getPositionalArgumentList() != null) { ext.getInvocationExpression().getPositionalArgumentList().visit(this); if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) { out(","); } } else { out("/*PENDIENTE NAMED ARG CLASS DECL */"); } if (targs != null && !targs.getTypes().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( aliased.getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(that, invargs, this); } else { out("/*TARGS != TPARAMS!!!! WTF?????*/"); } out(","); } self(d); out(");}"); endLine(); out(names.name(d), ".$$="); qualify(ext, aliased); out(names.name(aliased), ".$$;"); endLine(); share(d); } private void addClassDeclarationToPrototype(TypeDeclaration outer, ClassDeclaration that) { comment(that); TypeDeclaration dec = that.getClassSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } @Override public void visit(InterfaceDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Interface d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; //It's pointless declaring interface aliases outside of classes/interfaces Scope scope = that.getScope(); if (scope instanceof InterfaceAlias) { scope = scope.getContainer(); if (!(scope instanceof ClassOrInterface)) return; } comment(that); var(d); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel() .getDeclaration(); qualify(that,dec); out(names.name(dec), ";"); endLine(); share(d); } private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, InterfaceDeclaration that) { comment(that); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } private void addInterfaceToPrototype(ClassOrInterface type, InterfaceDefinition interfaceDef) { interfaceDefinition(interfaceDef); Interface d = interfaceDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(InterfaceDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { interfaceDefinition(that); } } private void interfaceDefinition(InterfaceDefinition that) { Interface d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); final List<TypeParameterDeclaration> tparms = that.getTypeParameterList() == null ? null : that.getTypeParameterList().getTypeParameterDeclarations(); if (tparms != null && !tparms.isEmpty()) { out("$$targs$$,"); } self(d); out(")"); beginBlock(); //declareSelf(d); referenceOuter(d); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getInterfaceBody()); } callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); if (tparms != null && !tparms.isEmpty()) { out(clAlias, "set_type_args("); self(d); out(",$$targs$$)"); endLine(true); } that.getInterfaceBody().visit(this); //returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void addClassToPrototype(ClassOrInterface type, ClassDefinition classDef) { classDefinition(classDef); Class d = classDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(ClassDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { classDefinition(that); } } private void classDefinition(ClassDefinition that) { Class d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } final boolean withTargs = that.getTypeParameterList() != null && !that.getTypeParameterList().getTypeParameterDeclarations().isEmpty(); if (withTargs) { out("$$targs$$,"); } self(d); out(")"); beginBlock(); //This takes care of top-level attributes defined before the class definition out("$init$", names.name(d), "();"); endLine(); declareSelf(d); if (withTargs) { out(clAlias, "set_type_args("); self(d); out(",$$targs$$);"); endLine(); } else { //Check if any of the satisfied types have type arguments if (that.getSatisfiedTypes() != null) { for(Tree.StaticType sat : that.getSatisfiedTypes().getTypes()) { boolean first = true; Map<TypeParameter,ProducedType> targs = sat.getTypeModel().getTypeArguments(); if (targs != null && !targs.isEmpty()) { if (first) { self(d); out(".$$targs$$="); TypeUtils.printTypeArguments(that, targs, this); endLine(true); } else { out("/*TODO: more type arguments*/"); endLine(); } } } } } referenceOuter(d); initParameters(that.getParameterList(), d, null); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(that.getExtendedType(), d, that, superDecs); callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); if (!opts.isOptimize()) { //Fix #231 for lexical scope for (Parameter p : that.getParameterList().getParameters()) { if (!p.getParameterModel().isHidden()){ generateAttributeForParameter(d, p.getParameterModel()); } } } if (d.isNative()) { out("if (typeof($init$native$", names.name(d), "$before)==='function')$init$native$", names.name(d), "$before("); self(d); if (withTargs)out(",$$targs$$"); out(");"); endLine(); } that.getClassBody().visit(this); if (d.isNative()) { out("if (typeof($init$native$", names.name(d), "$after)==='function')$init$native$", names.name(d), "$after("); self(d); if (withTargs)out(",$$targs$$"); out(");"); endLine(); System.out.printf("%s is annotated native.", d.getQualifiedNameString()); System.out.printf("You can implement two functions named $init$native$%s$before and $init$native$%<s$after", names.name(d)); System.out.print("that will be called (if they exist) before and after the class body. "); System.out.print("These functions will receive the instance being initialized"); if (withTargs) { System.out.print(" and the type arguments with which it is being initialized"); } System.out.println("."); } returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void referenceOuter(TypeDeclaration d) { if (d.isClassOrInterfaceMember()) { self(d); out("."); out("$$outer"); //outerSelf(d); out("=this;"); endLine(); } } private void copySuperMembers(TypeDeclaration typeDecl, final List<Declaration> decs, ClassOrInterface d) { if (!opts.isOptimize()) { for (Declaration dec: decs) { if (!typeDecl.isMember(dec)) { continue; } String suffix = names.scopeSuffix(dec.getContainer()); if (dec instanceof Value && ((Value)dec).isTransient()) { superGetterRef(dec,d,suffix); if (((Value) dec).isVariable()) { superSetterRef(dec,d,suffix); } } else { superRef(dec,d,suffix); } } } } private void callSuperclass(ExtendedType extendedType, Class d, Node that, final List<Declaration> superDecs) { if (extendedType!=null) { PositionalArgumentList argList = extendedType.getInvocationExpression() .getPositionalArgumentList(); TypeDeclaration typeDecl = extendedType.getType().getDeclarationModel(); out(memberAccessBase(extendedType.getType(), typeDecl, false, qualifiedPath(that, typeDecl)), (opts.isOptimize() && (getSuperMemberScope(extendedType.getType()) != null)) ? ".call(this," : "("); invoker.generatePositionalArguments(argList, argList.getPositionalArguments(), false, false); if (argList.getPositionalArguments().size() > 0) { out(","); } //There may be defaulted args we must pass as undefined if (d.getExtendedTypeDeclaration().getParameterList().getParameters().size() > argList.getPositionalArguments().size()) { List<com.redhat.ceylon.compiler.typechecker.model.Parameter> superParams = d.getExtendedTypeDeclaration().getParameterList().getParameters(); for (int i = argList.getPositionalArguments().size(); i < superParams.size(); i++) { com.redhat.ceylon.compiler.typechecker.model.Parameter p = superParams.get(i); if (p.isSequenced()) { out(clAlias, "getEmpty(),"); } else { out("undefined,"); } } } //If the supertype has type arguments, add them to the call if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { extendedType.getType().getTypeArgumentList().getTypeModels(); TypeUtils.printTypeArguments(that, TypeUtils.matchTypeParametersWithArguments(typeDecl.getTypeParameters(), extendedType.getType().getTypeArgumentList().getTypeModels()), this); out(","); } self(d); out(");"); endLine(); copySuperMembers(typeDecl, superDecs, d); } } private void callInterfaces(SatisfiedTypes satisfiedTypes, ClassOrInterface d, Tree.StatementOrArgument that, final List<Declaration> superDecs) { if (satisfiedTypes!=null) { for (StaticType st: satisfiedTypes.getTypes()) { TypeDeclaration typeDecl = st.getTypeModel().getDeclaration(); if (typeDecl.isAlias()) { typeDecl = typeDecl.getExtendedTypeDeclaration(); } qualify(that, typeDecl); out(names.name((ClassOrInterface)typeDecl), "("); if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { self(d); out(".$$targs$$===undefined?$$targs$$:"); } TypeUtils.printTypeArguments(that, st.getTypeModel().getTypeArguments(), this); out(","); } self(d); out(");"); endLine(); //Set the reified types from interfaces Map<TypeParameter, ProducedType> reifs = st.getTypeModel().getTypeArguments(); if (reifs != null && !reifs.isEmpty()) { for (Map.Entry<TypeParameter, ProducedType> e : reifs.entrySet()) { if (e.getValue().getDeclaration() instanceof ClassOrInterface) { out(clAlias, "add_type_arg("); self(d); out(",'", e.getKey().getName(), "',"); TypeUtils.typeNameOrList(that, e.getValue(), this, true); out(");"); endLine(); } } } copySuperMembers(typeDecl, superDecs, d); } } } /** Generates a function to initialize the specified type. */ private void typeInitialization(final Tree.Declaration type) { ExtendedType extendedType = null; SatisfiedTypes satisfiedTypes = null; boolean isInterface = false; ClassOrInterface decl = null; if (type instanceof ClassDefinition) { ClassDefinition classDef = (ClassDefinition) type; extendedType = classDef.getExtendedType(); satisfiedTypes = classDef.getSatisfiedTypes(); decl = classDef.getDeclarationModel(); } else if (type instanceof InterfaceDefinition) { satisfiedTypes = ((InterfaceDefinition) type).getSatisfiedTypes(); isInterface = true; decl = ((InterfaceDefinition) type).getDeclarationModel(); } else if (type instanceof ObjectDefinition) { ObjectDefinition objectDef = (ObjectDefinition) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getDeclarationModel().getTypeDeclaration(); } final PrototypeInitCallback callback = new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { if (type instanceof ClassDefinition) { com.redhat.ceylon.compiler.typechecker.model.Class c = ((ClassDefinition)type).getDeclarationModel(); addToPrototype(c, ((ClassDefinition)type).getClassBody().getStatements()); } else if (type instanceof InterfaceDefinition) { addToPrototype(((InterfaceDefinition)type).getDeclarationModel(), ((InterfaceDefinition)type).getInterfaceBody().getStatements()); } } }; typeInitialization(extendedType, satisfiedTypes, isInterface, decl, callback); } /** This is now the main method to generate the type initialization code. * @param extendedType The type that is being extended. * @param satisfiedTypes The types satisfied by the type being initialized. * @param isInterface Tells whether the type being initialized is an interface * @param d The declaration for the type being initialized * @param callback A callback to add something more to the type initializer in prototype style. */ private void typeInitialization(ExtendedType extendedType, SatisfiedTypes satisfiedTypes, boolean isInterface, final ClassOrInterface d, PrototypeInitCallback callback) { //Let's always use initTypeProto to avoid #113 String initFuncName = "initTypeProto"; out("function $init$", names.name(d), "()"); beginBlock(); out("if (", names.name(d), ".$$===undefined)"); beginBlock(); String qns = d.getQualifiedNameString(); if (JsCompiler.compilingLanguageModule && qns.indexOf("::") < 0) { //Language module files get compiled in default module //so they need to have this added to their qualified name qns = "ceylon.language::" + qns; } out(clAlias, initFuncName, "(", names.name(d), ",'", qns, "'"); if (extendedType != null) { String fname = typeFunctionName(extendedType.getType(), false); out(",", fname); } else if (!isInterface) { out(",", clAlias, "Basic"); } if (satisfiedTypes != null) { for (StaticType satType : satisfiedTypes.getTypes()) { TypeDeclaration tdec = satType.getTypeModel().getDeclaration(); if (tdec.isAlias()) { tdec = tdec.getExtendedTypeDeclaration(); } String fname = typeFunctionName(satType, true); //Actually it could be "if not in same module" if (!JsCompiler.compilingLanguageModule && declaredInCL(tdec)) { out(",", fname); } else { int idx = fname.lastIndexOf('.'); if (idx > 0) { fname = fname.substring(0, idx+1) + "$init$" + fname.substring(idx+1); } else { fname = "$init$" + fname; } out(",", fname, "()"); } } } out(");"); //Add ref to outer type if (d.isMember()) { StringBuilder containers = new StringBuilder(); Scope _d2 = d; while (_d2 instanceof ClassOrInterface) { if (containers.length() > 0) { containers.insert(0, '.'); } containers.insert(0, names.name((Declaration)_d2)); _d2 = _d2.getScope(); } endLine(); out(containers.toString(), "=", names.name(d), ";"); } //The class definition needs to be inside the init function if we want forwards decls to work in prototype style if (opts.isOptimize()) { endLine(); callback.addToPrototypeCallback(); } endBlockNewLine(); out("return ", names.name(d), ";"); endBlockNewLine(); //If it's nested, share the init function if (outerSelf(d)) { out(".$init$", names.name(d), "=$init$", names.name(d), ";"); endLine(); } out("$init$", names.name(d), "();"); endLine(); } private String typeFunctionName(StaticType type, boolean removeAlias) { TypeDeclaration d = type.getTypeModel().getDeclaration(); if (removeAlias && d.isAlias()) { d = d.getExtendedTypeDeclaration(); } boolean inProto = opts.isOptimize() && (type.getScope().getContainer() instanceof TypeDeclaration); return memberAccessBase(type, d, false, qualifiedPath(type, d, inProto)); } private void addToPrototype(ClassOrInterface d, List<Statement> statements) { boolean enter = opts.isOptimize(); ArrayList<com.redhat.ceylon.compiler.typechecker.model.Parameter> plist = null; if (enter) { enter = !statements.isEmpty(); if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { com.redhat.ceylon.compiler.typechecker.model.ParameterList _pl = ((com.redhat.ceylon.compiler.typechecker.model.Class)d).getParameterList(); if (_pl != null) { plist = new ArrayList<>(); plist.addAll(_pl.getParameters()); enter |= !plist.isEmpty(); } } } if (enter) { final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; out("(function(", names.self(d), ")"); beginBlock(); for (Statement s: statements) { addToPrototype(d, s, plist); } //Generated attributes with corresponding parameters will remove them from the list if (plist != null) { for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : plist) { generateAttributeForParameter((com.redhat.ceylon.compiler.typechecker.model.Class)d, p); } } endBlock(); out(")(", names.name(d), ".$$.prototype);"); endLine(); currentStatements = prevStatements; } } private void generateAttributeForParameter(com.redhat.ceylon.compiler.typechecker.model.Class d, com.redhat.ceylon.compiler.typechecker.model.Parameter p) { final String privname = names.name(p) + "_"; out(clAlias, "defineAttr(", names.self(d), ",'", names.name(p.getModel()), "',function(){"); if (p.getModel().isLate()) { generateUnitializedAttributeReadCheck("this."+privname, names.name(p)); } out("return this.", privname, ";}"); if (p.getModel().isVariable() || p.getModel().isLate()) { final String param = names.createTempVariable(d.getName()); out(",function(", param, "){"); if (p.getModel().isLate() && !p.getModel().isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(p)); } out("return this.", privname, "=", param, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(p.getModel(), this); out(");"); endLine(); } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, Statement s, List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) { ClassOrInterface oldPrototypeOwner = prototypeOwner; prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } else if (s instanceof MethodDeclaration) { methodDeclaration(d, (MethodDeclaration) s); } else if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } else if (s instanceof AttributeDeclaration) { addGetterAndSetterToPrototype(d, (AttributeDeclaration) s); } else if (s instanceof ClassDefinition) { addClassToPrototype(d, (ClassDefinition) s); } else if (s instanceof InterfaceDefinition) { addInterfaceToPrototype(d, (InterfaceDefinition) s); } else if (s instanceof ObjectDefinition) { addObjectToPrototype(d, (ObjectDefinition) s); } else if (s instanceof ClassDeclaration) { addClassDeclarationToPrototype(d, (ClassDeclaration) s); } else if (s instanceof InterfaceDeclaration) { addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s); } else if (s instanceof SpecifierStatement) { addSpecifierToPrototype(d, (SpecifierStatement) s); } //This fixes #231 for prototype style if (params != null && s instanceof Tree.Declaration) { Declaration m = ((Tree.Declaration)s).getDeclarationModel(); for (Iterator<com.redhat.ceylon.compiler.typechecker.model.Parameter> iter = params.iterator(); iter.hasNext();) { com.redhat.ceylon.compiler.typechecker.model.Parameter _p = iter.next(); if (m.getName() != null && m.getName().equals(_p.getName())) { iter.remove(); break; } } } prototypeOwner = oldPrototypeOwner; } private void declareSelf(ClassOrInterface d) { out("if ("); self(d); out("===undefined)"); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); /*out("var "); self(d); out("="); self(); out(";"); endLine();*/ } private void instantiateSelf(ClassOrInterface d) { out("var "); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); } private void returnSelf(ClassOrInterface d) { out("return "); self(d); out(";"); } private void addObjectToPrototype(ClassOrInterface type, ObjectDefinition objDef) { objectDefinition(objDef); Value d = objDef.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); out(names.self(type), ".", names.name(c), "=", names.name(c), ";"); endLine(); } @Override public void visit(ObjectDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Value d = that.getDeclarationModel(); if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) { objectDefinition(that); } else { Class c = (Class) d.getTypeDeclaration(); comment(that); outerSelf(d); out(".", names.privateName(d), "="); outerSelf(d); out(".", names.name(c), "();"); endLine(); } } private void objectDefinition(ObjectDefinition that) { comment(that); Value d = that.getDeclarationModel(); boolean addToPrototype = opts.isOptimize() && d.isClassOrInterfaceMember(); Class c = (Class) d.getTypeDeclaration(); out(function, names.name(c)); Map<TypeParameter, ProducedType> targs=new HashMap<TypeParameter, ProducedType>(); if (that.getSatisfiedTypes() != null) { for (StaticType st : that.getSatisfiedTypes().getTypes()) { Map<TypeParameter, ProducedType> stargs = st.getTypeModel().getTypeArguments(); if (stargs != null && !stargs.isEmpty()) { targs.putAll(stargs); } } } out(targs.isEmpty()?"()":"($$targs$$)"); beginBlock(); instantiateSelf(c); referenceOuter(c); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } if (!targs.isEmpty()) { self(c); out(".$$targs$$=$$targs$$;"); endLine(); } callSuperclass(that.getExtendedType(), c, that, superDecs); callInterfaces(that.getSatisfiedTypes(), c, that, superDecs); that.getClassBody().visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); typeInitialization(that); addToPrototype(c, that.getClassBody().getStatements()); if (!addToPrototype) { out("var ", names.name(d), "=", names.name(c), "("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, this); } out(");"); endLine(); } if (!defineAsProperty(d)) { out("var ", names.getter(d), "=function()"); beginBlock(); out("return "); if (addToPrototype) { out("this."); } out(names.name(d), ";"); endBlockNewLine(); if (addToPrototype || d.isShared()) { outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); outerSelf(d); out(".", names.getter(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } } else { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); if (addToPrototype) { out("this.", names.privateName(d)); } else { out(names.name(d)); } out(";},undefined,"); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } } private void superRef(Declaration d, ClassOrInterface sub, String parentSuffix) { //if (d.isActual()) { self(sub); out(".", names.name(d), parentSuffix, "="); self(sub); out(".", names.name(d), ";"); endLine(); //} } private void superGetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (defineAsProperty(d)) { out(clAlias, "copySuperAttr(", names.self(sub), ",'", names.name(d), "','", parentSuffix, "');"); } else { self(sub); out(".", names.getter(d), parentSuffix, "="); self(sub); out(".", names.getter(d), ";"); } endLine(); } private void superSetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (!defineAsProperty(d)) { self(sub); out(".", names.setter(d), parentSuffix, "="); self(sub); out(".", names.setter(d), ";"); endLine(); } } @Override public void visit(MethodDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; methodDeclaration(null, that); } private void methodDeclaration(TypeDeclaration outer, MethodDeclaration that) { Method m = that.getDeclarationModel(); if (that.getSpecifierExpression() != null) { // method(params) => expr if (outer == null) { // Not in a prototype definition. Null to do here if it's a // member in prototype style. if (opts.isOptimize() && m.isMember()) { return; } comment(that); initDefaultedParameters(that.getParameterLists().get(0), m); out("var "); } else { // prototype definition comment(that); initDefaultedParameters(that.getParameterLists().get(0), m); out(names.self(outer), "."); } out(names.name(m), "="); singleExprFunction(that.getParameterLists(), that.getSpecifierExpression().getExpression(), that.getScope()); endLine(true); if (outer != null) { out(names.self(outer), "."); } out(names.name(m), ".$$metamodel$$="); TypeUtils.encodeForRuntime(m, that.getAnnotationList(), this); endLine(true); share(m); } else if (outer == null) { // don't do the following in a prototype definition //Check for refinement of simple param declaration if (m == that.getScope()) { if (m.getContainer() instanceof Class && m.isClassOrInterfaceMember()) { //Declare the method just by pointing to the param function final String name = names.name(((Class)m.getContainer()).getParameter(m.getName())); if (name != null) { self((Class)m.getContainer()); out(".", names.name(m), "=", name, ";"); endLine(); } } else if (m.getContainer() instanceof Method) { //Declare the function just by forcing the name we used in the param list final String name = names.name(((Method)m.getContainer()).getParameter(m.getName())); if (names != null) { names.forceName(m, name); } } //Only the first paramlist can have defaults initDefaultedParameters(that.getParameterLists().get(0), m); } } } @Override public void visit(MethodDefinition that) { Method d = that.getDeclarationModel(); //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!((opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) || isNative(d))) { comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); methodDefinition(that); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } } private void methodDefinition(MethodDefinition that) { Method d = that.getDeclarationModel(); if (that.getParameterLists().size() == 1) { out(function, names.name(d)); ParameterList paramList = that.getParameterLists().get(0); paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, null, d); visitStatements(that.getBlock().getStatements()); endBlock(); } else { int count=0; for (ParameterList paramList : that.getParameterLists()) { if (count==0) { out(function, names.name(d)); } else { out("return function"); } paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, d.getTypeDeclaration(), d); count++; } visitStatements(that.getBlock().getStatements()); for (int i=0; i < count; i++) { endBlock(); } } if (!share(d)) { out(";"); } } /** Get the specifier expression for a Parameter, if one is available. */ private SpecifierOrInitializerExpression getDefaultExpression(Parameter param) { final SpecifierOrInitializerExpression expr; if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) { MethodDeclaration md = null; if (param instanceof ParameterDeclaration) { TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration(); if (td instanceof AttributeDeclaration) { expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression(); } else if (td instanceof MethodDeclaration) { md = (MethodDeclaration)td; expr = md.getSpecifierExpression(); } else { param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName()); expr = null; } } else { expr = ((InitializerParameter) param).getSpecifierExpression(); } } else { param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param); expr = null; } return expr; } /** Create special functions with the expressions for defaulted parameters in a parameter list. */ private void initDefaultedParameters(ParameterList params, Method container) { if (!container.isMember())return; for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); if (pd.isDefaulted()) { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { continue; } qualify(params, container); out(names.name(container), "$defs$", pd.getName(), "=function"); params.visit(this); out("{"); initSelf(container); out("return "); if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), null); } else { expr.visit(this); } out(";}"); endLine(true); } } } /** Initialize the sequenced, defaulted and captured parameters in a type declaration. */ private void initParameters(ParameterList params, TypeDeclaration typeDecl, Method m) { for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); final String paramName = names.name(pd); if (pd.isDefaulted() || pd.isSequenced()) { out("if(", paramName, "===undefined){", paramName, "="); if (pd.isDefaulted()) { if (m !=null && m.isMember()) { qualify(params, m); out(names.name(m), "$defs$", pd.getName(), "("); boolean firstParam=true; for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) { if (firstParam){firstParam=false;}else out(","); out(names.name(p)); } out(")"); } else { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { param.addUnexpectedError("Default expression missing for " + pd.getName()); out("null"); } else if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), m.getContainer()); } else { expr.visit(this); } } } else { out(clAlias, "getEmpty()"); } out(";}"); endLine(); } if ((typeDecl != null) && !pd.isHidden() && pd.getModel().isCaptured()) { self(typeDecl); out(".", paramName, "_=", paramName, ";"); endLine(); } } } private void addMethodToPrototype(TypeDeclaration outer, MethodDefinition that) { Method d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); out(names.self(outer), ".", names.name(d), "="); methodDefinition(that); //Add reference to metamodel out(names.self(outer), ".", names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } @Override public void visit(AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return; comment(that); if (defineAsProperty(d)) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); } else { out("var ", names.getter(d), "=function()"); super.visit(that); if (!shareGetter(d)) { out(";"); } } } private void addGetterToPrototype(TypeDeclaration outer, AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); } private AttributeSetterDefinition associatedSetterDefinition( Value valueDecl) { final Setter setter = valueDecl.getSetter(); if ((setter != null) && (currentStatements != null)) { for (Statement stmt : currentStatements) { if (stmt instanceof AttributeSetterDefinition) { final AttributeSetterDefinition setterDef = (AttributeSetterDefinition) stmt; if (setterDef.getDeclarationModel() == setter) { return setterDef; } } } } return null; } /** Exports a getter function; useful in non-prototype style. */ private boolean shareGetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return; comment(that); out("var ", names.setter(d.getGetter()), "=function(", names.name(d.getParameter()), ")"); if (that.getSpecifierExpression() == null) { that.getBlock().visit(this); } else { out("{return "); that.getSpecifierExpression().visit(this); out(";}"); } if (!shareSetter(d)) { out(";"); } } private boolean isCaptured(Declaration d) { if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures if (d.isShared() || d.isCaptured() ) { return true; } else { OuterVisitor ov = new OuterVisitor(d); ov.visit(root); return ov.found; } } else { return false; } } private boolean shareSetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.setter(d), "=", names.setter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeDeclaration that) { Value d = that.getDeclarationModel(); //Check if the attribute corresponds to a class parameter //This is because of the new initializer syntax String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } if (!d.isFormal()) { comment(that); final boolean isLate = d.isLate(); SpecifierOrInitializerExpression specInitExpr = that.getSpecifierOrInitializerExpression(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { if ((specInitExpr != null && !(specInitExpr instanceof LazySpecifierExpression)) || isLate) { outerSelf(d); out(".", names.privateName(d), "="); if (isLate) { out("undefined"); } else { super.visit(that); } endLine(true); } else if (classParam != null) { outerSelf(d); out(".", names.privateName(d), "=", classParam); endLine(true); } } else if (specInitExpr instanceof LazySpecifierExpression) { final boolean property = defineAsProperty(d); if (property) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); } else { out("var ", names.getter(d), "=function(){return "); } int boxType = boxStart(specInitExpr.getExpression().getTerm()); specInitExpr.getExpression().visit(this); if (boxType == 4) out("/*TODO: callable targs 1*/"); boxUnboxEnd(boxType); out(";}"); if (property) { boolean hasSetter = false; if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { hasSetter = true; out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } if (!hasSetter) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } else { endLine(true); shareGetter(d); } } else { final boolean addGetter = (specInitExpr != null) || (classParam != null) || !d.isMember() || d.isVariable() || isLate; if (addGetter) { generateAttributeGetter(that, d, specInitExpr, classParam); } final boolean addSetter = (d.isVariable() || isLate) && !defineAsProperty(d); if (addSetter) { final String varName = names.name(d); String paramVarName = names.createTempVariable(d.getName()); out("var ", names.setter(d), "=function(", paramVarName, "){"); if (isLate) { generateImmutableAttributeReassignmentCheck(varName, names.name(d)); } out("return ", varName, "=", paramVarName, ";};"); endLine(); shareSetter(d); } if (d.isToplevel()) { out("$prop$", names.name(d), "={$$metamodel$$:"); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(",get:"); if (addGetter && isCaptured(d) && !defineAsProperty(d)) { out(names.getter(d)); } else { out("function(){return ", names.name(d), "}"); } if (addSetter) { out(",set:", names.setter(d)); } out("}"); endLine(true); out("exports.$prop$", names.name(d), "=$prop$", names.name(d)); endLine(true); } } } } private void generateAttributeGetter(AnyAttribute attributeNode, MethodOrValue decl, SpecifierOrInitializerExpression expr, String param) { final String varName = names.name(decl); out("var ", varName); if (expr != null) { out("="); int boxType = boxStart(expr.getExpression().getTerm()); if (dynblock > 0 && TypeUtils.isUnknown(expr.getExpression().getTypeModel()) && !TypeUtils.isUnknown(decl.getType())) { TypeUtils.generateDynamicCheck(expr.getExpression(), decl.getType(), this); } else { expr.visit(this); } if (boxType == 4) { //Pass Callable argument types out(","); if (decl instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)decl).getParameterLists().get(0), GenerateJsVisitor.this); } else { //Type of value must be Callable //And the Args Type Parameters is a Tuple types.encodeTupleAsParameterListForRuntime(decl.getType(), this); } out(","); TypeUtils.printTypeArguments(expr, expr.getExpression().getTypeModel().getTypeArguments(), this); } boxUnboxEnd(boxType); } else if (param != null) { out("=", param); } endLine(true); if (decl instanceof Method) { if (decl.isClassOrInterfaceMember() && isCaptured(decl)) { beginNewLine(); outerSelf(decl); out(".", names.name(decl), "=", names.name(decl), ";"); endLine(); } } else { if (isCaptured(decl)) { final boolean isLate = decl.isLate(); if (defineAsProperty(decl)) { out(clAlias, "defineAttr("); outerSelf(decl); out(",'", varName, "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck(varName, names.name(decl)); } out("return ", varName, ";}"); if (decl.isVariable() || isLate) { final String par = names.createTempVariable(decl.getName()); out(",function(", par, "){"); if (isLate && !decl.isVariable()) { generateImmutableAttributeReassignmentCheck(varName, names.name(decl)); } out("return ", varName, "=", par, ";}"); } else { out(",undefined"); } out(","); //TODO if attributeNode is null then annotations should come from decl if (attributeNode == null) { TypeUtils.encodeForRuntime(decl, this); } else { TypeUtils.encodeForRuntime(decl, attributeNode.getAnnotationList(), this); } out(");"); endLine(); } else { out("var ", names.getter(decl),"=function(){return ", varName, ";};"); endLine(); shareGetter(decl); } } else { directAccess.add(decl); } } } void generateUnitializedAttributeReadCheck(String privname, String pubname) { //TODO we can later optimize this, to replace this getter with the plain one //once the value has been defined out("if (", privname, "===undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to read unitialized attribute «", pubname, "»'));"); } void generateImmutableAttributeReassignmentCheck(String privname, String pubname) { out("if(", privname, "!==undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to reassign immutable attribute «", pubname, "»'));"); } private void addGetterAndSetterToPrototype(TypeDeclaration outer, AttributeDeclaration that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||d.isToplevel()) return; if (!d.isFormal()) { comment(that); String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } final boolean isLate = d.isLate(); if ((that.getSpecifierOrInitializerExpression() != null) || d.isVariable() || classParam != null || isLate) { if (that.getSpecifierOrInitializerExpression() instanceof LazySpecifierExpression) { // attribute is defined by a lazy expression ("=>" syntax) out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); beginBlock(); initSelf(that.getScope()); out("return "); Expression expr = that.getSpecifierOrInitializerExpression().getExpression(); int boxType = boxStart(expr.getTerm()); expr.visit(this); endLine(true); if (boxType == 4) out("/*TODO: callable targs 3*/"); boxUnboxEnd(boxType); endBlock(); boolean hasSetter = false; if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { hasSetter = true; out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{"); initSelf(that.getScope()); out("return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } if (!hasSetter) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(")"); endLine(true); } else { final String privname = names.privateName(d); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck("this."+privname, names.name(d)); } out("return this.", privname, ";}"); if (d.isVariable() || isLate) { final String param = names.createTempVariable(d.getName()); out(",function(", param, "){"); if (isLate && !d.isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(d)); } out("return this.", privname, "=", param, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(");"); endLine(); } } } } @Override public void visit(CharLiteral that) { out(clAlias, "Character("); out(String.valueOf(that.getText().codePointAt(1))); out(")"); } /** Escapes a StringLiteral (needs to be quoted). */ String escapeStringLiteral(String s) { StringBuilder text = new StringBuilder(s); //Escape special chars for (int i=0; i < text.length();i++) { switch(text.charAt(i)) { case 8:text.replace(i, i+1, "\\b"); i++; break; case 9:text.replace(i, i+1, "\\t"); i++; break; case 10:text.replace(i, i+1, "\\n"); i++; break; case 12:text.replace(i, i+1, "\\f"); i++; break; case 13:text.replace(i, i+1, "\\r"); i++; break; case 34:text.replace(i, i+1, "\\\""); i++; break; case 39:text.replace(i, i+1, "\\'"); i++; break; case 92:text.replace(i, i+1, "\\\\"); i++; break; case 0x2028:text.replace(i, i+1, "\\u2028"); i++; break; case 0x2029:text.replace(i, i+1, "\\u2029"); i++; break; } } return text.toString(); } @Override public void visit(StringLiteral that) { final int slen = that.getText().codePointCount(0, that.getText().length()); if (JsCompiler.compilingLanguageModule) { out("String$(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } else { out(clAlias, "String(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } } @Override public void visit(StringTemplate that) { List<StringLiteral> literals = that.getStringLiterals(); List<Expression> exprs = that.getExpressions(); out(clAlias, "StringBuilder().appendAll(["); boolean first = true; for (int i = 0; i < literals.size(); i++) { StringLiteral literal = literals.get(i); if (!literal.getText().isEmpty()) { if (!first) { out(","); } first = false; literal.visit(this); } if (i < exprs.size()) { if (!first) { out(","); } first = false; exprs.get(i).visit(this); out(".string"); } } out("]).string"); } @Override public void visit(FloatLiteral that) { out(clAlias, "Float(", that.getText(), ")"); } @Override public void visit(NaturalLiteral that) { char prefix = that.getText().charAt(0); if (prefix == '$' || prefix == '#') { int radix= prefix == '$' ? 2 : 16; try { out("(", new java.math.BigInteger(that.getText().substring(1), radix).toString(), ")"); } catch (NumberFormatException ex) { that.addError("Invalid numeric literal " + that.getText()); } } else { out("(", that.getText(), ")"); } } @Override public void visit(This that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Super that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Outer that) { boolean outer = false; if (opts.isOptimize()) { Scope scope = that.getScope(); while ((scope != null) && !(scope instanceof TypeDeclaration)) { scope = scope.getContainer(); } if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) { self((TypeDeclaration) scope); out("."); outer = true; } } if (outer) { out("$$outer"); } else { self(that.getTypeModel().getDeclaration()); } } @Override public void visit(BaseMemberExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) { //Don't even bother processing a node with errors return; } Declaration decl = that.getDeclaration(); if (decl != null) { String name = decl.getName(); String pkgName = decl.getUnit().getPackage().getQualifiedNameString(); // map Ceylon true/false/null directly to JS true/false/null if ("ceylon.language".equals(pkgName)) { if ("true".equals(name) || "false".equals(name) || "null".equals(name)) { out(name); return; } } } String exp = memberAccess(that, null); if (decl == null && isInDynamicBlock()) { out("(typeof ", exp, "==='undefined'||", exp, "===null?"); generateThrow("Undefined or null reference: " + exp, that); out(":", exp, ")"); } else { out(exp); } } private boolean accessDirectly(Declaration d) { return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter(); } private boolean accessThroughGetter(Declaration d) { return (d instanceof MethodOrValue) && !(d instanceof Method) && !defineAsProperty(d); } private boolean defineAsProperty(Declaration d) { // for now, only define member attributes as properties, not toplevel attributes return d.isMember() && (d instanceof MethodOrValue) && !(d instanceof Method); } /** Returns true if the top-level declaration for the term is annotated "nativejs" */ private static boolean isNative(Term t) { if (t instanceof MemberOrTypeExpression) { return isNative(((MemberOrTypeExpression)t).getDeclaration()); } return false; } /** Returns true if the declaration is annotated "nativejs" */ private static boolean isNative(Declaration d) { return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d); } private static Declaration getToplevel(Declaration d) { while (d != null && !d.isToplevel()) { Scope s = d.getContainer(); // Skip any non-declaration elements while (s != null && !(s instanceof Declaration)) { s = s.getContainer(); } d = (Declaration) s; } return d; } private static boolean hasAnnotationByName(Declaration d, String name){ if (d != null) { for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){ if(annotation.getName().equals(name)) return true; } } return false; } private void generateSafeOp(QualifiedMemberOrTypeExpression that) { boolean isMethod = that.getDeclaration() instanceof Method; String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); super.visit(that); out(","); if (isMethod) { out(clAlias, "JsCallable(", lhsVar, ","); } out(lhsVar, "!==null?", memberAccess(that, lhsVar), ":null)"); if (isMethod) { out(")"); } } @Override public void visit(final QualifiedMemberExpression that) { //Big TODO: make sure the member is actually // refined by the current class! if (that.getMemberOperator() instanceof SafeMemberOp) { generateSafeOp(that); } else if (that.getMemberOperator() instanceof SpreadOp) { generateSpread(that); } else if (that.getDeclaration() instanceof Method && that.getSignature() == null) { //TODO right now this causes that all method invocations are done this way //we need to filter somehow to only use this pattern when the result is supposed to be a callable //looks like checking for signature is a good way (not THE way though; named arg calls don't have signature) generateCallable(that, null); } else if (that.getStaticMethodReference()) { out("function($O$) {return "); if (that.getDeclaration() instanceof Method) { out(clAlias, "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ");}"); } else { out("$O$.", names.name(that.getDeclaration()), ";}"); } } else { final String lhs = generateToString(new GenerateCallback() { @Override public void generateValue() { GenerateJsVisitor.super.visit(that); } }); out(memberAccess(that, lhs)); } } /** SpreadOp cannot be a simple function call because we need to reference the object methods directly, so it's a function */ private void generateSpread(QualifiedMemberOrTypeExpression that) { //Determine if it's a method or attribute boolean isMethod = that.getDeclaration() instanceof Method; //Define a function out("(function()"); beginBlock(); if (opts.isComment()) { out("//SpreadOp at ", that.getLocation()); endLine(); } //Declare an array to store the values/references String tmplist = names.createTempVariable("lst"); out("var ", tmplist, "=[];"); endLine(); //Get an iterator String iter = names.createTempVariable("it"); out("var ", iter, "="); super.visit(that); out(".iterator();"); endLine(); //Iterate String elem = names.createTempVariable("elem"); out("var ", elem, ";"); endLine(); out("while ((", elem, "=", iter, ".next())!==", clAlias, "getFinished())"); beginBlock(); //Add value or reference to the array out(tmplist, ".push("); if (isMethod) { out("{o:", elem, ", f:", memberAccess(that, elem), "}"); } else { out(memberAccess(that, elem)); } out(");"); endBlockNewLine(); //Gather arguments to pass to the callable //Return the array of values or a Callable with the arguments out("return ", clAlias); if (isMethod) { out("JsCallableList(", tmplist, ");"); } else { out("ArraySequence(", tmplist, ");"); } endBlock(); out("())"); } private void generateCallable(QualifiedMemberOrTypeExpression that, String name) { String primaryVar = createRetainedTempVar("opt"); out("(", primaryVar, "="); that.getPrimary().visit(this); out(",", clAlias, "JsCallable(", primaryVar, ",", primaryVar, "!==null?", (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name), ":null))"); } /** * Checks if the given node is a MemberOrTypeExpression or QualifiedType which * represents an access to a supertype member and returns the scope of that * member or null. */ Scope getSuperMemberScope(Node node) { Scope scope = null; if (node instanceof QualifiedMemberOrTypeExpression) { // Check for "super.member" QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node; final Term primary = eliminateParensAndWidening(qmte.getPrimary()); if (primary instanceof Super) { scope = qmte.getDeclaration().getContainer(); } } else if (node instanceof QualifiedType) { // Check for super.Membertype QualifiedType qtype = (QualifiedType) node; if (qtype.getOuterType() instanceof SuperType) { scope = qtype.getDeclarationModel().getContainer(); } } return scope; } private String memberAccessBase(Node node, Declaration decl, boolean setter, String lhs) { final StringBuilder sb = new StringBuilder(); if (lhs != null) { if (lhs.length() > 0) { sb.append(lhs).append("."); } } else if (node instanceof BaseMemberOrTypeExpression) { BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node; Declaration bmd = bmte.getDeclaration(); if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) { return names.name(bmd); } String path = qualifiedPath(node, bmd); if (path.length() > 0) { sb.append(path); sb.append("."); } } Scope scope = getSuperMemberScope(node); if (opts.isOptimize() && (scope != null)) { sb.append("getT$all()['"); sb.append(scope.getQualifiedNameString()); sb.append("']"); if (defineAsProperty(decl)) { return clAlias + (setter ? "attrSetter(" : "attrGetter(") + sb.toString() + ",'" + names.name(decl) + "')"; } sb.append(".$$.prototype."); } final String member = (accessThroughGetter(decl) && !accessDirectly(decl)) ? (setter ? names.setter(decl) : names.getter(decl)) : names.name(decl); sb.append(member); if (!opts.isOptimize() && (scope != null)) { sb.append(names.scopeSuffix(scope)); } //When compiling the language module we need to modify certain base type names String rval = sb.toString(); if (TypeUtils.isReservedTypename(rval)) { rval = sb.append("$").toString(); } return rval; } /** * Returns a string representing a read access to a member, as represented by * the given expression. If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private String memberAccess(StaticMemberOrTypeExpression expr, String lhs) { Declaration decl = expr.getDeclaration(); String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { return ((lhs != null) && (lhs.length() > 0)) ? (lhs + "." + plainName) : plainName; } boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without getter return memberAccessBase(expr, decl, false, lhs); } // access through getter return memberAccessBase(expr, decl, false, lhs) + (protoCall ? ".call(this)" : "()"); } /** * Generates a write access to a member, as represented by the given expression. * The given callback is responsible for generating the assigned value. * If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private void generateMemberAccess(StaticMemberOrTypeExpression expr, GenerateCallback callback, String lhs) { Declaration decl = expr.getDeclaration(); boolean paren = false; String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { if ((lhs != null) && (lhs.length() > 0)) { out(lhs, "."); } out(plainName, "="); } else { boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without setter out(memberAccessBase(expr, decl, true, lhs), "="); } else { // access through setter out(memberAccessBase(expr, decl, true, lhs), protoCall ? ".call(this," : "("); paren = true; } } callback.generateValue(); if (paren) { out(")"); } } private void generateMemberAccess(final StaticMemberOrTypeExpression expr, final String strValue, final String lhs) { generateMemberAccess(expr, new GenerateCallback() { @Override public void generateValue() { out(strValue); } }, lhs); } @Override public void visit(BaseTypeExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Declaration d = that.getDeclaration(); if (d == null && isInDynamicBlock()) { //It's a native js type but will be wrapped in dyntype() call String id = that.getIdentifier().getText(); out("(typeof ", id, "==='undefined'?"); generateThrow("Undefined type " + id, that); out(":", id, ")"); } else { qualify(that, d); out(names.name(d)); } } @Override public void visit(QualifiedTypeExpression that) { if (that.getMemberOperator() instanceof SafeMemberOp) { generateCallable(that, names.name(that.getDeclaration())); } else { super.visit(that); out(".", names.name(that.getDeclaration())); } } public void visit(Dynamic that) { //this is value{xxx} invoker.nativeObject(that.getNamedArgumentList()); } @Override public void visit(InvocationExpression that) { invoker.generateInvocation(that); } @Override public void visit(PositionalArgumentList that) { invoker.generatePositionalArguments(that, that.getPositionalArguments(), false, false); } /** Box a term, visit it, unbox it. */ private void box(Term term) { final int t = boxStart(term); term.visit(this); if (t == 4) out("/*TODO: callable targs 4*/"); boxUnboxEnd(t); } // Make sure fromTerm is compatible with toTerm by boxing it when necessary private int boxStart(Term fromTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = false; ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, Term toTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toTerm); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toDecl); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } int boxUnboxStart(boolean fromNative, ProducedType fromType, boolean toNative) { // Box the value final String fromTypeName = TypeUtils.isUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName(); if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) { if (fromNative) { // conversion from native value to Ceylon value if (fromTypeName.equals("ceylon.language::String")) { if (JsCompiler.compilingLanguageModule) { out("String$("); } else { out(clAlias, "String("); } } else if (fromTypeName.equals("ceylon.language::Integer")) { out("("); } else if (fromTypeName.equals("ceylon.language::Float")) { out(clAlias, "Float("); } else if (fromTypeName.equals("ceylon.language::Boolean")) { out("("); } else if (fromTypeName.equals("ceylon.language::Character")) { out(clAlias, "Character("); } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 0; } return 1; } else if ("ceylon.language::String".equals(fromTypeName) || "ceylon.language::Float".equals(fromTypeName)) { // conversion from Ceylon String or Float to native value return 2; } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 3; } } return 0; } void boxUnboxEnd(int boxType) { switch (boxType) { case 1: out(")"); break; case 2: out(".valueOf()"); break; case 4: out(")"); break; default: //nothing } } @Override public void visit(ObjectArgument that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; final Class c = (Class)that.getDeclarationModel().getTypeDeclaration(); out("(function()"); beginBlock(); out("//ObjectArgument ", that.getIdentifier().getText()); location(that); endLine(); out(function, names.name(c), "()"); beginBlock(); instantiateSelf(c); referenceOuter(c); ExtendedType xt = that.getExtendedType(); final ClassBody body = that.getClassBody(); SatisfiedTypes sts = that.getSatisfiedTypes(); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(xt, c, that, superDecs); callInterfaces(sts, c, that, superDecs); body.visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); //Add reference to metamodel out(names.name(c), ".$$metamodel$$="); TypeUtils.encodeForRuntime(c, null, this); endLine(true); typeInitialization(xt, sts, false, c, new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { addToPrototype(c, body.getStatements()); } }); out("return ", names.name(c), "(new ", names.name(c), ".$$);"); endBlock(); out("())"); } @Override public void visit(AttributeArgument that) { out("(function()"); beginBlock(); out("//AttributeArgument ", that.getParameter().getName()); location(that); endLine(); Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("return "); specExpr.getExpression().visit(this); out(";"); } else if (block != null) { visitStatements(block.getStatements()); } endBlock(); out("())"); } @Override public void visit(SequencedArgument that) { List<PositionalArgument> positionalArguments = that.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; if (!spread) { out("["); } boolean first=true; for (PositionalArgument arg: positionalArguments) { if (!first) out(","); if (arg instanceof Tree.ListedArgument) { ((Tree.ListedArgument) arg).getExpression().visit(this); } else if(arg instanceof Tree.SpreadArgument) ((Tree.SpreadArgument) arg).getExpression().visit(this); else // comprehension arg.visit(this); first = false; } if (!spread) { out("]"); } } @Override public void visit(SequenceEnumeration that) { SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); int lim = positionalArguments.size()-1; boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int count=0; ProducedType chainedType = null; if (lim>0 || !spread) { out("["); } for (PositionalArgument expr : positionalArguments) { if (count==lim && spread) { if (lim > 0) { ProducedType seqType = TypeUtils.findSupertype(types.iterable, that.getTypeModel()); closeSequenceWithReifiedType(that, seqType.getTypeArguments()); out(".chain("); chainedType = TypeUtils.findSupertype(types.iterable, expr.getTypeModel()); } count--; } else { if (count > 0) { out(","); } } if (dynblock > 0 && expr instanceof ListedArgument && TypeUtils.isUnknown(expr.getTypeModel())) { TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), types.anything.getType(), this); } else { expr.visit(this); } count++; } if (chainedType == null) { if (!spread) { closeSequenceWithReifiedType(that, that.getTypeModel().getTypeArguments()); } } else { out(","); TypeUtils.printTypeArguments(that, chainedType.getTypeArguments(), this); out(")"); } } } @Override public void visit(Comprehension that) { new ComprehensionGenerator(this, names, directAccess).generateComprehension(that); } @Override public void visit(final SpecifierStatement that) { // A lazy specifier expression in a class/interface should go into the // prototype in prototype style, so don't generate them here. if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression) && (that.getScope().getContainer() instanceof TypeDeclaration))) { specifierStatement(null, that); } } private void specifierStatement(final TypeDeclaration outer, final SpecifierStatement specStmt) { if (dynblock > 0 && TypeUtils.isUnknown(specStmt.getBaseMemberExpression().getTypeModel())) { specStmt.getBaseMemberExpression().visit(this); out("="); int box = boxUnboxStart(specStmt.getSpecifierExpression().getExpression(), specStmt.getBaseMemberExpression()); specStmt.getSpecifierExpression().getExpression().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); out(";"); return; } if (specStmt.getBaseMemberExpression() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) specStmt.getBaseMemberExpression(); Declaration bmeDecl = bme.getDeclaration(); if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) { // attr => expr; final boolean property = defineAsProperty(bmeDecl); if (property) { out(clAlias, "defineAttr(", qualifiedPath(specStmt, bmeDecl), ",'", names.name(bmeDecl), "',function()"); } else { if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out ("var "); } out(names.getter(bmeDecl), "=function()"); } beginBlock(); if (outer != null) { initSelf(specStmt.getScope()); } out ("return "); specStmt.getSpecifierExpression().visit(this); out(";"); endBlock(); if (property) { out(",undefined,"); TypeUtils.encodeForRuntime(bmeDecl, this); out(")"); } endLine(true); directAccess.remove(bmeDecl); } else if (outer != null) { // "attr = expr;" in a prototype definition if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) { out("delete ", names.self(outer), ".", names.name(bmeDecl)); endLine(true); } } else if (bmeDecl instanceof MethodOrValue) { // "attr = expr;" in an initializer or method final MethodOrValue moval = (MethodOrValue)bmeDecl; if (moval.isVariable()) { // simple assignment to a variable attribute generateMemberAccess(bme, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(specStmt.getSpecifierExpression().getExpression().getTerm(), moval); if (dynblock > 0 && !TypeUtils.isUnknown(moval.getType()) && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), moval.getType(), GenerateJsVisitor.this); } else { specStmt.getSpecifierExpression().getExpression().visit(GenerateJsVisitor.this); } if (boxType == 4) { out(","); if (moval instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this); out(","); } else { //TODO extract parameters from Value out("[/*VALUE Callable params", moval.getClass().getName(), "*/],"); } TypeUtils.printTypeArguments(specStmt.getSpecifierExpression().getExpression(), specStmt.getSpecifierExpression().getExpression().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); } boxUnboxEnd(boxType); } }, null); out(";"); } else if (moval.isMember()) { if (moval instanceof Method) { //same as fat arrow qualify(specStmt, bmeDecl); out(names.name(moval), "=function ", names.name(moval), "("); //Build the parameter list, we'll use it several times final StringBuilder paramNames = new StringBuilder(); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : ((Method) moval).getParameterLists().get(0).getParameters()) { if (paramNames.length() > 0) paramNames.append(","); paramNames.append(names.name(p)); } out(paramNames.toString()); out("){"); initSelf(moval.getContainer()); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : ((Method) moval).getParameterLists().get(0).getParameters()) { if (p.isDefaulted()) { out("if (", names.name(p), "===undefined)", names.name(p),"="); qualify(specStmt, moval); out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")"); endLine(true); } } out("return "); specStmt.getSpecifierExpression().visit(this); out("(", paramNames.toString(), ");}"); endLine(true); } else { // Specifier for a member attribute. This actually defines the // member (e.g. in shortcut refinement syntax the attribute // declaration itself can be omitted), so generate the attribute. generateAttributeGetter(null, moval, specStmt.getSpecifierExpression(), null); } } else { // Specifier for some other attribute, or for a method. if (opts.isOptimize() || (bmeDecl.isMember() && (bmeDecl instanceof Method))) { qualify(specStmt, bmeDecl); } out(names.name(bmeDecl), "="); if (dynblock > 0 && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), bme.getTypeModel(), this); } else { specStmt.getSpecifierExpression().visit(this); } out(";"); } } } else if ((specStmt.getBaseMemberExpression() instanceof ParameterizedExpression) && (specStmt.getSpecifierExpression() != null)) { final ParameterizedExpression paramExpr = (ParameterizedExpression) specStmt.getBaseMemberExpression(); if (paramExpr.getPrimary() instanceof BaseMemberExpression) { // func(params) => expr; BaseMemberExpression bme = (BaseMemberExpression) paramExpr.getPrimary(); Declaration bmeDecl = bme.getDeclaration(); if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out("var "); } out(names.name(bmeDecl), "="); singleExprFunction(paramExpr.getParameterLists(), specStmt.getSpecifierExpression().getExpression(), bmeDecl instanceof Scope ? (Scope)bmeDecl : null); out(";"); } } } private void addSpecifierToPrototype(final TypeDeclaration outer, final SpecifierStatement specStmt) { specifierStatement(outer, specStmt); } @Override public void visit(final AssignOp that) { String returnValue = null; StaticMemberOrTypeExpression lhsExpr = null; if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { that.getLeftTerm().visit(this); out("="); int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); return; } out("("); if (that.getLeftTerm() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm(); lhsExpr = bme; Declaration bmeDecl = bme.getDeclaration(); boolean simpleSetter = hasSimpleGetterSetter(bmeDecl); if (!simpleSetter) { returnValue = memberAccess(bme, null); } } else if (that.getLeftTerm() instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm(); lhsExpr = qme; boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration()); String lhsVar = null; if (!simpleSetter) { lhsVar = createRetainedTempVar(); out(lhsVar, "="); super.visit(qme); out(",", lhsVar, "."); returnValue = memberAccess(qme, lhsVar); } else { super.visit(qme); out("."); } } generateMemberAccess(lhsExpr, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(GenerateJsVisitor.this); if (boxType == 4) out("/*TODO: callable targs 7*/"); boxUnboxEnd(boxType); } }, null); if (returnValue != null) { out(",", returnValue); } out(")"); } /** Outputs the module name for the specified declaration. Returns true if something was output. */ boolean qualify(Node that, Declaration d) { String path = qualifiedPath(that, d); if (path.length() > 0) { out(path, "."); } return path.length() > 0; } private String qualifiedPath(Node that, Declaration d) { return qualifiedPath(that, d, false); } private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); if (dynblock > 0 && TypeUtils.isUnknown(that.getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(that.getExpression(), that.getExpression().getTypeModel(), this); endLine(true); return; } super.visit(that); } @Override public void visit(AnnotationList that) {} void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { final String lhs = names.createTempVariable(); out("function(){var ", lhs, "="); termgen.left(); out(";return "); termgen.right(); out(".scale(", lhs, ");}()"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); if (type!=null) { TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); } out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } if (resources != null) { for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){", clAlias, "addSuppressedException(", resourceVar, "$swallow,", catchVarName, ");}"); } } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null) { out("finally"); encloseBlockInFunction(that.getFinallyClause().getBlock()); } } @Override public void visit(Throw that) { out("throw ", clAlias, "wrapexc("); if (that.getExpression() == null) { out(clAlias, "Exception()"); } else { that.getExpression().visit(this); } - out(",'", that.getLocation(), "','", that.getUnit().getFilename(), "');"); + that.getUnit().getFullPath(); + out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); - } else if (item instanceof MatchCase){ + } else if (item instanceof MatchCase) { boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); - out(expvar, "==="); //TODO equality? - /*out(".equals(");*/ - exp.visit(this); - //out(")==="); clAlias(); out("getTrue()"); + if (exp.getTerm() instanceof Tree.Literal) { + if (switchTerm.getTypeModel().isUnknown()) { + out(expvar, "=="); + exp.visit(this); + } else { + if (switchTerm.getUnit().isOptionalType(switchTerm.getTypeModel())) { + out(expvar,"!==null&&"); + } + out(expvar, ".equals("); + exp.visit(this); + out(")"); + } + } else { + out(expvar, "==="); + exp.visit(this); + } first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() == null) { if (dynblock > 0 && expr.getTypeModel().getDeclaration() instanceof UnknownType) { out("else throw ", clAlias, "Exception('Ceylon switch over unknown type does not cover all cases')"); } } else { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), scope instanceof TypeDeclaration ? (TypeDeclaration)scope : null, null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null, scope instanceof Method ? (Method)scope : null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); Scope parent = scope == null ? null : scope.getContainer(); initParameters(paramList, parent instanceof TypeDeclaration ? (TypeDeclaration)parent : null, scope instanceof Method ? (Method)scope:null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape out(") {throw ", clAlias, "wrapexc(", clAlias, "AssertionException(\"", escapeStringLiteral(sb.toString()), "\"),'",that.getLocation(), "','", that.getUnit().getFilename(), "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } /** Tells whether the typeModel of a TypeLiteral or MemberLiteral node is open or closed. * Some things are open and closed; we should prefer the open version since we can get the applied one * from it, but this might cause problems when the closed version is expected... */ private boolean isTypeLiteralModelOpen(ProducedType t) { final String qn = t.getProducedTypeQualifiedName(); return qn.contains("ceylon.language.model.declaration::"); } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$model({Type:"); final ProducedType ltype = that.getType().getTypeModel(); if (isTypeLiteralModelOpen(that.getTypeModel()) && !ltype.containsTypeParameters()) { TypeDeclaration d = ltype.getDeclaration(); qualify(that,d); out(names.name(d)); } else { TypeUtils.typeNameOrList(that, ltype, this, true); } out("})"); } @Override public void visit(MemberLiteral that) { com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget(); if (ref == null) { that.addUnexpectedError("Member literal with no valid target"); } else { final Declaration d = ref.getDeclaration(); final ProducedType ltype = that.getType() == null ? null : that.getType().getTypeModel(); final boolean open = isTypeLiteralModelOpen(that.getTypeModel()) && (ltype == null || !ltype.containsTypeParameters()); out(clAlias, "typeLiteral$model({Type:"); if (!open)out("{t:"); if (ltype == null) { qualify(that, d); } else { qualify(that, ltype.getDeclaration()); out(names.name(ltype.getDeclaration())); out(".$$.prototype."); } if (d instanceof Value) { out("$prop$"); } out(names.name(d)); if (!open) { if (ltype != null && ltype.getTypeArguments() != null && !ltype.getTypeArguments().isEmpty()) { out(",a:"); TypeUtils.printTypeArguments(that, ltype.getTypeArguments(), this); } out("}"); } out("})"); } } + /** Call internal function "throwexc" with the specified message and source location. */ void generateThrow(String msg, Node node) { out(clAlias, "throwexc(", clAlias, "Exception(", clAlias, "String"); if (JsCompiler.isCompilingLanguageModule()) { out("$"); } - out("(\"", escapeStringLiteral(msg), "\")),'", node.getLocation(), "','", node.getUnit().getFilename(), "')"); + out("(\"", escapeStringLiteral(msg), "\")),'", node.getLocation(), "','", + node.getUnit().getFilename(), "')"); } }
false
true
private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); if (dynblock > 0 && TypeUtils.isUnknown(that.getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(that.getExpression(), that.getExpression().getTypeModel(), this); endLine(true); return; } super.visit(that); } @Override public void visit(AnnotationList that) {} void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { final String lhs = names.createTempVariable(); out("function(){var ", lhs, "="); termgen.left(); out(";return "); termgen.right(); out(".scale(", lhs, ");}()"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); if (type!=null) { TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); } out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } if (resources != null) { for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){", clAlias, "addSuppressedException(", resourceVar, "$swallow,", catchVarName, ");}"); } } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null) { out("finally"); encloseBlockInFunction(that.getFinallyClause().getBlock()); } } @Override public void visit(Throw that) { out("throw ", clAlias, "wrapexc("); if (that.getExpression() == null) { out(clAlias, "Exception()"); } else { that.getExpression().visit(this); } out(",'", that.getLocation(), "','", that.getUnit().getFilename(), "');"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase){ boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); out(expvar, "==="); //TODO equality? /*out(".equals(");*/ exp.visit(this); //out(")==="); clAlias(); out("getTrue()"); first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() == null) { if (dynblock > 0 && expr.getTypeModel().getDeclaration() instanceof UnknownType) { out("else throw ", clAlias, "Exception('Ceylon switch over unknown type does not cover all cases')"); } } else { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), scope instanceof TypeDeclaration ? (TypeDeclaration)scope : null, null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null, scope instanceof Method ? (Method)scope : null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); Scope parent = scope == null ? null : scope.getContainer(); initParameters(paramList, parent instanceof TypeDeclaration ? (TypeDeclaration)parent : null, scope instanceof Method ? (Method)scope:null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape out(") {throw ", clAlias, "wrapexc(", clAlias, "AssertionException(\"", escapeStringLiteral(sb.toString()), "\"),'",that.getLocation(), "','", that.getUnit().getFilename(), "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } /** Tells whether the typeModel of a TypeLiteral or MemberLiteral node is open or closed. * Some things are open and closed; we should prefer the open version since we can get the applied one * from it, but this might cause problems when the closed version is expected... */ private boolean isTypeLiteralModelOpen(ProducedType t) { final String qn = t.getProducedTypeQualifiedName(); return qn.contains("ceylon.language.model.declaration::"); } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$model({Type:"); final ProducedType ltype = that.getType().getTypeModel(); if (isTypeLiteralModelOpen(that.getTypeModel()) && !ltype.containsTypeParameters()) { TypeDeclaration d = ltype.getDeclaration(); qualify(that,d); out(names.name(d)); } else { TypeUtils.typeNameOrList(that, ltype, this, true); } out("})"); } @Override public void visit(MemberLiteral that) { com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget(); if (ref == null) { that.addUnexpectedError("Member literal with no valid target"); } else { final Declaration d = ref.getDeclaration(); final ProducedType ltype = that.getType() == null ? null : that.getType().getTypeModel(); final boolean open = isTypeLiteralModelOpen(that.getTypeModel()) && (ltype == null || !ltype.containsTypeParameters()); out(clAlias, "typeLiteral$model({Type:"); if (!open)out("{t:"); if (ltype == null) { qualify(that, d); } else { qualify(that, ltype.getDeclaration()); out(names.name(ltype.getDeclaration())); out(".$$.prototype."); } if (d instanceof Value) { out("$prop$"); } out(names.name(d)); if (!open) { if (ltype != null && ltype.getTypeArguments() != null && !ltype.getTypeArguments().isEmpty()) { out(",a:"); TypeUtils.printTypeArguments(that, ltype.getTypeArguments(), this); } out("}"); } out("})"); } } void generateThrow(String msg, Node node) { out(clAlias, "throwexc(", clAlias, "Exception(", clAlias, "String"); if (JsCompiler.isCompilingLanguageModule()) { out("$"); } out("(\"", escapeStringLiteral(msg), "\")),'", node.getLocation(), "','", node.getUnit().getFilename(), "')"); } }
private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); if (dynblock > 0 && TypeUtils.isUnknown(that.getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(that.getExpression(), that.getExpression().getTypeModel(), this); endLine(true); return; } super.visit(that); } @Override public void visit(AnnotationList that) {} void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { final String lhs = names.createTempVariable(); out("function(){var ", lhs, "="); termgen.left(); out(";return "); termgen.right(); out(".scale(", lhs, ");}()"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); if (type!=null) { TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); } out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } if (resources != null) { for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){", clAlias, "addSuppressedException(", resourceVar, "$swallow,", catchVarName, ");}"); } } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null) { out("finally"); encloseBlockInFunction(that.getFinallyClause().getBlock()); } } @Override public void visit(Throw that) { out("throw ", clAlias, "wrapexc("); if (that.getExpression() == null) { out(clAlias, "Exception()"); } else { that.getExpression().visit(this); } that.getUnit().getFullPath(); out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase) { boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); if (exp.getTerm() instanceof Tree.Literal) { if (switchTerm.getTypeModel().isUnknown()) { out(expvar, "=="); exp.visit(this); } else { if (switchTerm.getUnit().isOptionalType(switchTerm.getTypeModel())) { out(expvar,"!==null&&"); } out(expvar, ".equals("); exp.visit(this); out(")"); } } else { out(expvar, "==="); exp.visit(this); } first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() == null) { if (dynblock > 0 && expr.getTypeModel().getDeclaration() instanceof UnknownType) { out("else throw ", clAlias, "Exception('Ceylon switch over unknown type does not cover all cases')"); } } else { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), scope instanceof TypeDeclaration ? (TypeDeclaration)scope : null, null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null, scope instanceof Method ? (Method)scope : null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); Scope parent = scope == null ? null : scope.getContainer(); initParameters(paramList, parent instanceof TypeDeclaration ? (TypeDeclaration)parent : null, scope instanceof Method ? (Method)scope:null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape out(") {throw ", clAlias, "wrapexc(", clAlias, "AssertionException(\"", escapeStringLiteral(sb.toString()), "\"),'",that.getLocation(), "','", that.getUnit().getFilename(), "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } /** Tells whether the typeModel of a TypeLiteral or MemberLiteral node is open or closed. * Some things are open and closed; we should prefer the open version since we can get the applied one * from it, but this might cause problems when the closed version is expected... */ private boolean isTypeLiteralModelOpen(ProducedType t) { final String qn = t.getProducedTypeQualifiedName(); return qn.contains("ceylon.language.model.declaration::"); } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$model({Type:"); final ProducedType ltype = that.getType().getTypeModel(); if (isTypeLiteralModelOpen(that.getTypeModel()) && !ltype.containsTypeParameters()) { TypeDeclaration d = ltype.getDeclaration(); qualify(that,d); out(names.name(d)); } else { TypeUtils.typeNameOrList(that, ltype, this, true); } out("})"); } @Override public void visit(MemberLiteral that) { com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget(); if (ref == null) { that.addUnexpectedError("Member literal with no valid target"); } else { final Declaration d = ref.getDeclaration(); final ProducedType ltype = that.getType() == null ? null : that.getType().getTypeModel(); final boolean open = isTypeLiteralModelOpen(that.getTypeModel()) && (ltype == null || !ltype.containsTypeParameters()); out(clAlias, "typeLiteral$model({Type:"); if (!open)out("{t:"); if (ltype == null) { qualify(that, d); } else { qualify(that, ltype.getDeclaration()); out(names.name(ltype.getDeclaration())); out(".$$.prototype."); } if (d instanceof Value) { out("$prop$"); } out(names.name(d)); if (!open) { if (ltype != null && ltype.getTypeArguments() != null && !ltype.getTypeArguments().isEmpty()) { out(",a:"); TypeUtils.printTypeArguments(that, ltype.getTypeArguments(), this); } out("}"); } out("})"); } } /** Call internal function "throwexc" with the specified message and source location. */ void generateThrow(String msg, Node node) { out(clAlias, "throwexc(", clAlias, "Exception(", clAlias, "String"); if (JsCompiler.isCompilingLanguageModule()) { out("$"); } out("(\"", escapeStringLiteral(msg), "\")),'", node.getLocation(), "','", node.getUnit().getFilename(), "')"); } }
diff --git a/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java b/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java index bebe00dae..f583e331e 100644 --- a/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java +++ b/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java @@ -1,81 +1,81 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ /* * Created on May 6, 2005 */ package org.eclipse.mylyn.internal.ide.ui; import java.lang.reflect.Method; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.viewers.Viewer; import org.eclipse.mylyn.ide.ui.AbstractMarkerInterestFilter; import org.eclipse.ui.views.markers.MarkerItem; /** * @author Mik Kersten */ public class MarkerInterestFilter extends AbstractMarkerInterestFilter { @Override public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { // HACK: using reflection to gain accessibily Class<?> clazz; try { clazz = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); Method method = clazz.getDeclaredMethod("getChildren", new Class[] {}); method.setAccessible(true); Object result = method.invoke(element, new Object[] {}); - System.err.println(">>>>>> " + result.getClass()); +// System.err.println(">>>>>> " + result.getClass()); } catch (Exception e) { e.printStackTrace(); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; // return true; // NOTE: code commented out below did a look-down the children, which may be too expensive // if (element instanceof MarkerNode) { // MarkerNode markerNode = (MarkerNode) element; // MarkerNode[] children = markerNode.getChildren(); // for (int i = 0; i < children.length; i++) { // MarkerNode node = children[i]; // if (node instanceof ConcreteMarker) { // return isInteresting((ConcreteMarker) node, viewer, parent); // } else { // return true; // } // } // } // } else { // ConcreteMarker marker = (ConcreteMarker) element; // return isInteresting((ConcreteMarker) element, viewer, parent); // } } @Override protected boolean isImplicitlyInteresting(IMarker marker) { try { Object severity = marker.getAttribute(IMarker.SEVERITY); return severity != null && severity.equals(IMarker.SEVERITY_ERROR); } catch (CoreException e) { // ignore } return false; } }
true
true
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { // HACK: using reflection to gain accessibily Class<?> clazz; try { clazz = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); Method method = clazz.getDeclaredMethod("getChildren", new Class[] {}); method.setAccessible(true); Object result = method.invoke(element, new Object[] {}); System.err.println(">>>>>> " + result.getClass()); } catch (Exception e) { e.printStackTrace(); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; // return true; // NOTE: code commented out below did a look-down the children, which may be too expensive // if (element instanceof MarkerNode) { // MarkerNode markerNode = (MarkerNode) element; // MarkerNode[] children = markerNode.getChildren(); // for (int i = 0; i < children.length; i++) { // MarkerNode node = children[i]; // if (node instanceof ConcreteMarker) { // return isInteresting((ConcreteMarker) node, viewer, parent); // } else { // return true; // } // } // } // } else { // ConcreteMarker marker = (ConcreteMarker) element; // return isInteresting((ConcreteMarker) element, viewer, parent); // } }
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { // HACK: using reflection to gain accessibily Class<?> clazz; try { clazz = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); Method method = clazz.getDeclaredMethod("getChildren", new Class[] {}); method.setAccessible(true); Object result = method.invoke(element, new Object[] {}); // System.err.println(">>>>>> " + result.getClass()); } catch (Exception e) { e.printStackTrace(); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; // return true; // NOTE: code commented out below did a look-down the children, which may be too expensive // if (element instanceof MarkerNode) { // MarkerNode markerNode = (MarkerNode) element; // MarkerNode[] children = markerNode.getChildren(); // for (int i = 0; i < children.length; i++) { // MarkerNode node = children[i]; // if (node instanceof ConcreteMarker) { // return isInteresting((ConcreteMarker) node, viewer, parent); // } else { // return true; // } // } // } // } else { // ConcreteMarker marker = (ConcreteMarker) element; // return isInteresting((ConcreteMarker) element, viewer, parent); // } }
diff --git a/src/com/redhat/qe/sm/cli/tests/HelpTests.java b/src/com/redhat/qe/sm/cli/tests/HelpTests.java index 6b4b2fd9..28eda4a0 100644 --- a/src/com/redhat/qe/sm/cli/tests/HelpTests.java +++ b/src/com/redhat/qe/sm/cli/tests/HelpTests.java @@ -1,576 +1,577 @@ package com.redhat.qe.sm.cli.tests; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.redhat.qe.auto.tcms.ImplementsNitrateTest; import com.redhat.qe.auto.testng.Assert; import com.redhat.qe.auto.testng.BlockedByBzBug; import com.redhat.qe.auto.testng.TestNGUtils; import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript; import com.redhat.qe.tools.RemoteFileTasks; import com.redhat.qe.tools.SSHCommandResult; /** * @author jsefler * */ @Test(groups={"HelpTests"}) public class HelpTests extends SubscriptionManagerCLITestScript{ // Test Methods *********************************************************************** @Test( description="subscription-manager-cli: man page", groups={}, enabled=true) @ImplementsNitrateTest(caseId=41697) public void ManPageForCLI_Test() { if (clienttasks==null) throw new SkipException("A client connection is needed for this test."); String cliCommand = clienttasks.command; RemoteFileTasks.runCommandAndAssert(client,"man -P cat "+cliCommand,0); RemoteFileTasks.runCommandAndAssert(client,"whatis "+cliCommand,0,"^"+cliCommand+" ",null); log.warning("We only tested the existence of the man page; NOT the content."); } @Test( description="subscription-manager-gui: man page", groups={}, enabled=true) //@ImplementsNitrateTest(caseId=) public void ManPageForGUI_Test() { if (clienttasks==null) throw new SkipException("A client connection is needed for this test."); String guiCommand = clienttasks.command+"-gui"; // is the guiCommand installed? if (client.runCommandAndWait("rpm -q "+clienttasks.command+"-gnome").getStdout().contains("is not installed")) { RemoteFileTasks.runCommandAndAssert(client,"man -P cat "+guiCommand,1,null,"^No manual entry for "+guiCommand); RemoteFileTasks.runCommandAndAssert(client,"whatis "+guiCommand,0,"^"+guiCommand+": nothing appropriate",null); log.warning("In this test we tested only the existence of the man page; NOT the content."); throw new SkipException(guiCommand+" is not installed and therefore its man page is also not installed."); } else { RemoteFileTasks.runCommandAndAssert(client,"man -P cat "+guiCommand,0); RemoteFileTasks.runCommandAndAssert(client,"whatis "+guiCommand,0,"^"+guiCommand+" ",null); log.warning("In this test we tested only the existence of the man page; NOT the content."); } } @Test( description="subscription-manager-cli: assert only expected command line options are available", groups={}, dataProvider="ExpectedCommandLineOptionsData") @ImplementsNitrateTest(caseId=46713) //@ImplementsNitrateTest(caseId=46707) public void ExpectedCommandLineOptions_Test(Object meta, String command, String stdoutRegex, List<String> expectedOptions) { log.info("Testing subscription-manager-cli command line options '"+command+"' and verifying that only the expected options are available."); SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(client,command,0); Pattern pattern = Pattern.compile(stdoutRegex, Pattern.MULTILINE); Matcher matcher = pattern.matcher(result.getStdout()); Assert.assertTrue(matcher.find(),"Available command line options are shown with command: "+command); // find all the matches to stderrRegex List <String> actualOptions = new ArrayList<String>(); do { actualOptions.add(matcher.group().trim()); } while (matcher.find()); // assert all of the expectedOptions were found and that no unexpectedOptions were found for (String expectedOption : expectedOptions) { if (!actualOptions.contains(expectedOption)) { log.warning("Could not find the expected command '"+command+"' option '"+expectedOption+"'."); } else { Assert.assertTrue(actualOptions.contains(expectedOption),"The expected command '"+command+"' option '"+expectedOption+"' is available."); } } for (String actualOption : actualOptions) { if (!expectedOptions.contains(actualOption)) log.warning("Found an unexpected command '"+command+"' option '"+actualOption+"'."); } Assert.assertTrue(actualOptions.containsAll(expectedOptions), "All of the expected command '"+command+"' line options are available."); Assert.assertTrue(expectedOptions.containsAll(actualOptions), "All of the available command '"+command+"' line options are expected."); } @Test( description="subscription-manager-cli: assert help commands return translated text", groups={}, dataProvider="TranslatedCommandLineHelpData") //@ImplementsNitrateTest(caseId=) public void TranslatedCommandLineHelp_Test(Object meta, String lang, String command, List<String> stdoutRegexs) { SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(client,"LANG="+lang+".UTF8 "+command,0,stdoutRegexs,null); } // Candidates for an automated Test: // TODO Bug 694662 - the whitespace in the title line of man subscription-manager-gui is completely consumed // Configuration Methods *********************************************************************** @BeforeClass(groups={"setup"}) public void makewhatisBeforeClass() { // running makewhatis to ensure that the whatis database is built on Beaker provisioned systems RemoteFileTasks.runCommandAndAssert(client,"makewhatis",0); } // Protected Methods *********************************************************************** protected List<String> newList(String item) { List <String> newList = new ArrayList<String>(); newList.add(item); return newList; } // Data Providers *********************************************************************** @DataProvider(name="ExpectedCommandLineOptionsData") public Object[][] getExpectedCommandLineOptionsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getExpectedCommandLineOptionsDataAsListOfLists()); } protected List<List<Object>> getExpectedCommandLineOptionsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (clienttasks==null) return ll; // String command, String stdoutRegex, List<String> expectedOptions String module; String modulesRegex = "^ \\w+"; //DELETEME String optionsRegex = "^ --\\w+[(?:=\\w)]*|^ -\\w[(?:=\\w)]*\\, --\\w+[(?:=\\w)]*"; String optionsRegex = "^ --[\\w\\.]+(=[\\w\\.]+)*|^ -\\w(=\\w+)*\\, --\\w+(=\\w+)*"; /* EXAMPLE FOR optionsRegex -h, --help show this help message and exit --list list the configuration for this system --remove=REMOVE remove configuration entry by section.name --server.hostname=SERVER.HOSTNAME */ // MODULES List <String> modules = new ArrayList<String>(); modules.add("config"); modules.add("import"); modules.add("redeem"); modules.add("orgs"); modules.add("repos"); modules.add("clean"); modules.add("environments"); modules.add("facts"); modules.add("identity"); modules.add("list"); modules.add("refresh"); modules.add("register"); modules.add("subscribe"); modules.add("unregister"); modules.add("unsubscribe"); for (String smHelpCommand : new String[]{clienttasks.command+" -h",clienttasks.command+" --help"}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" [options] MODULENAME --help"; usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, modulesRegex, modules})); } // MODULE: config module = "config"; List <String> configOptions = new ArrayList<String>(); configOptions.add("-h, --help"); configOptions.add("--list"); configOptions.add("--remove=REMOVE"); configOptions.add("--server.ca_cert_dir=SERVER.CA_CERT_DIR"); configOptions.add("--server.hostname=SERVER.HOSTNAME"); configOptions.add("--server.insecure=SERVER.INSECURE"); configOptions.add("--server.port=SERVER.PORT"); configOptions.add("--server.prefix=SERVER.PREFIX"); configOptions.add("--server.proxy_hostname=SERVER.PROXY_HOSTNAME"); configOptions.add("--server.proxy_password=SERVER.PROXY_PASSWORD"); configOptions.add("--server.proxy_port=SERVER.PROXY_PORT"); configOptions.add("--server.proxy_user=SERVER.PROXY_USER"); configOptions.add("--server.repo_ca_cert=SERVER.REPO_CA_CERT"); configOptions.add("--server.ssl_verify_depth=SERVER.SSL_VERIFY_DEPTH"); configOptions.add("--rhsm.baseurl=RHSM.BASEURL"); configOptions.add("--rhsm.ca_cert_dir=RHSM.CA_CERT_DIR"); configOptions.add("--rhsm.consumercertdir=RHSM.CONSUMERCERTDIR"); configOptions.add("--rhsm.entitlementcertdir=RHSM.ENTITLEMENTCERTDIR"); configOptions.add("--rhsm.hostname=RHSM.HOSTNAME"); configOptions.add("--rhsm.insecure=RHSM.INSECURE"); configOptions.add("--rhsm.port=RHSM.PORT"); configOptions.add("--rhsm.prefix=RHSM.PREFIX"); configOptions.add("--rhsm.productcertdir=RHSM.PRODUCTCERTDIR"); configOptions.add("--rhsm.proxy_hostname=RHSM.PROXY_HOSTNAME"); configOptions.add("--rhsm.proxy_password=RHSM.PROXY_PASSWORD"); configOptions.add("--rhsm.proxy_port=RHSM.PROXY_PORT"); configOptions.add("--rhsm.proxy_user=RHSM.PROXY_USER"); configOptions.add("--rhsm.repo_ca_cert=RHSM.REPO_CA_CERT"); configOptions.add("--rhsm.ssl_verify_depth=RHSM.SSL_VERIFY_DEPTH"); configOptions.add("--rhsmcertd.ca_cert_dir=RHSMCERTD.CA_CERT_DIR"); configOptions.add("--rhsmcertd.certfrequency=RHSMCERTD.CERTFREQUENCY"); configOptions.add("--rhsmcertd.hostname=RHSMCERTD.HOSTNAME"); configOptions.add("--rhsmcertd.insecure=RHSMCERTD.INSECURE"); configOptions.add("--rhsmcertd.port=RHSMCERTD.PORT"); configOptions.add("--rhsmcertd.prefix=RHSMCERTD.PREFIX"); configOptions.add("--rhsmcertd.proxy_hostname=RHSMCERTD.PROXY_HOSTNAME"); configOptions.add("--rhsmcertd.proxy_password=RHSMCERTD.PROXY_PASSWORD"); configOptions.add("--rhsmcertd.proxy_port=RHSMCERTD.PROXY_PORT"); configOptions.add("--rhsmcertd.proxy_user=RHSMCERTD.PROXY_USER"); configOptions.add("--rhsmcertd.repo_ca_cert=RHSMCERTD.REPO_CA_CERT"); configOptions.add("--rhsmcertd.ssl_verify_depth=RHSMCERTD.SSL_VERIFY_DEPTH"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, configOptions})); } // MODULE: import module = "import"; List <String> importOptions = new ArrayList<String>(); importOptions.add("-h, --help"); - importOptions.add("--certificate=CERTIFICATE_FILES"); + //importOptions.add("--certificate=CERTIFICATE_FILES"); // prior to fix for Bug 735212 + importOptions.add("--certificate=CERTIFICATE_FILE"); // importOptions.add("--proxy=PROXY_URL"); // importOptions.add("--proxyuser=PROXY_USER"); // importOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, importOptions})); } // MODULE: redeem module = "redeem"; List <String> redeemOptions = new ArrayList<String>(); redeemOptions.add("-h, --help"); redeemOptions.add("--email=EMAIL"); redeemOptions.add("--locale=LOCALE"); redeemOptions.add("--proxy=PROXY_URL"); redeemOptions.add("--proxyuser=PROXY_USER"); redeemOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, redeemOptions})); } // MODULE: orgs module = "orgs"; List <String> orgsOptions = new ArrayList<String>(); orgsOptions.add("-h, --help"); orgsOptions.add("--username=USERNAME"); orgsOptions.add("--password=PASSWORD"); orgsOptions.add("--proxy=PROXY_URL"); orgsOptions.add("--proxyuser=PROXY_USER"); orgsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, orgsOptions})); } // MODULE: repos module = "repos"; List <String> reposOptions = new ArrayList<String>(); reposOptions.add("-h, --help"); reposOptions.add("--list"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, reposOptions})); } // MODULE: clean module = "clean"; List <String> cleanOptions = new ArrayList<String>(); cleanOptions.add("-h, --help"); // removed in https://bugzilla.redhat.com/show_bug.cgi?id=664581 //cleanOptions.add("--proxy=PROXY_URL"); //cleanOptions.add("--proxyuser=PROXY_USER"); //cleanOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("664581"), smHelpCommand, optionsRegex, cleanOptions})); } // MODULE: environments module = "environments"; List <String> environmentsOptions = new ArrayList<String>(); environmentsOptions.add("-h, --help"); environmentsOptions.add("--username=USERNAME"); environmentsOptions.add("--password=PASSWORD"); environmentsOptions.add("--org=ORG"); environmentsOptions.add("--proxy=PROXY_URL"); environmentsOptions.add("--proxyuser=PROXY_USER"); environmentsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, environmentsOptions})); } // MODULE: facts module = "facts"; List <String> factsOptions = new ArrayList<String>(); factsOptions.add("-h, --help"); factsOptions.add("--list"); factsOptions.add("--update"); factsOptions.add("--proxy=PROXY_URL"); factsOptions.add("--proxyuser=PROXY_USER"); factsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, factsOptions})); } // MODULE: identity module = "identity"; List <String> identityOptions = new ArrayList<String>(); identityOptions.add("-h, --help"); identityOptions.add("--username=USERNAME"); identityOptions.add("--password=PASSWORD"); identityOptions.add("--regenerate"); identityOptions.add("--force"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=678151 identityOptions.add("--proxy=PROXY_URL"); identityOptions.add("--proxyuser=PROXY_USER"); identityOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, identityOptions})); } // MODULE: list module = "list"; List <String> listOptions = new ArrayList<String>(); listOptions.add("-h, --help"); listOptions.add("--installed"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=634254 listOptions.add("--consumed"); listOptions.add("--available"); listOptions.add("--all"); listOptions.add("--ondate=ON_DATE"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=672562 listOptions.add("--proxy=PROXY_URL"); listOptions.add("--proxyuser=PROXY_USER"); listOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, listOptions})); } // MODULE: refresh module = "refresh"; List <String> refreshOptions = new ArrayList<String>(); refreshOptions.add("-h, --help"); refreshOptions.add("--proxy=PROXY_URL"); refreshOptions.add("--proxyuser=PROXY_USER"); refreshOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, refreshOptions})); } // MODULE: register module = "register"; List <String> registerOptions = new ArrayList<String>(); registerOptions.add("-h, --help"); registerOptions.add("--username=USERNAME"); registerOptions.add("--type=CONSUMERTYPE"); registerOptions.add("--name=CONSUMERNAME"); registerOptions.add("--password=PASSWORD"); registerOptions.add("--consumerid=CONSUMERID"); registerOptions.add("--org=ORG"); registerOptions.add("--environment=ENVIRONMENT"); registerOptions.add("--autosubscribe"); registerOptions.add("--force"); registerOptions.add("--activationkey=ACTIVATION_KEYS"); registerOptions.add("--proxy=PROXY_URL"); registerOptions.add("--proxyuser=PROXY_USER"); registerOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[]{null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("628589"), smHelpCommand, optionsRegex, registerOptions})); } // MODULE: subscribe module = "subscribe"; List <String> subscribeOptions = new ArrayList<String>(); subscribeOptions.add("-h, --help"); subscribeOptions.add("--pool=POOL"); subscribeOptions.add("--quantity=QUANTITY"); subscribeOptions.add("--auto"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=680399 // subscribeOptions.add("--regtoken=REGTOKEN"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--email=EMAIL"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--locale=LOCALE"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 subscribeOptions.add("--proxy=PROXY_URL"); subscribeOptions.add("--proxyuser=PROXY_USER"); subscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, subscribeOptions})); } // MODULE: unregister module = "unregister"; List <String> unregisterOptions = new ArrayList<String>(); unregisterOptions.add("-h, --help"); unregisterOptions.add("--proxy=PROXY_URL"); unregisterOptions.add("--proxyuser=PROXY_USER"); unregisterOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unregisterOptions})); } // MODULE: unsubscribe module = "unsubscribe"; List <String> unsubscribeOptions = new ArrayList<String>(); unsubscribeOptions.add("-h, --help"); unsubscribeOptions.add("--serial=SERIAL"); unsubscribeOptions.add("--all"); unsubscribeOptions.add("--proxy=PROXY_URL"); unsubscribeOptions.add("--proxyuser=PROXY_USER"); unsubscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unsubscribeOptions})); } return ll; } @DataProvider(name="TranslatedCommandLineHelpData") public Object[][] getTranslatedCommandLineHelpDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getTranslatedCommandLineHelpDataAsListOfLists()); } protected List<List<Object>> getTranslatedCommandLineHelpDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (clienttasks==null) return ll; String usage,lang,module; // MODULES for (String smHelpCommand : new String[]{clienttasks.command+" -h",clienttasks.command+" --help"}) { // # for L in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo "# LANG=$L subscription-manager --help | grep -- --help"; LANG=$L subscription-manager --help | grep -- --help; done; // TODO new BlockedByBzBug("707080") lang = "en_US"; usage = "(U|u)sage: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "de_DE"; usage = "(V|v)erbrauch: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "es_ES"; usage = "(U|u)so: subscription-manager [opciones] NOMBREDEMÓDULO --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "fr_FR"; usage = "(U|u)tilisation: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("707080"), lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "it_IT"; usage = "(U|u)tilizzo: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ja_JP"; usage = "使用法: subscription-manager [オプション] モジュール名 --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ko_KR"; usage = "사용법: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pt_BR"; usage = "(U|u)so: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ru_RU"; usage = "(Ф|ф)ормат: subscription-manager [параметры] МОДУЛЬ --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_CN"; usage = "使用: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("707080"), lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_TW"; usage = "使用方法:subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "as_IN"; usage = "ব্যৱহাৰ: subscription-manager [বিকল্পসমূহ] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "bn_IN"; usage = "ব্যবহারপ্রণালী: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "hi_IN"; usage = "प्रयोग: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "mr_IN"; usage = "(वापर|वपार): subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "gu_IN"; usage = "વપરાશ: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "kn_IN"; usage = "ಬಳಕೆ: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ml_IN"; usage = "ഉപയോഗിയ്ക്കേണ്ട വിധം: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "or_IN"; usage = "ବ୍ଯବହାର ବିଧି: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pa_IN"; usage = "ਵਰਤੋਂ: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ta_IN"; usage = "பயன்பாடு: subscription-manager [விருப்பங்கள்] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "te_IN"; usage = "వాడుక: subscription-manager [options] MODULENAME --help"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // TODO MODULE: clean // TODO MODULE: activate // TODO MODULE: facts // TODO MODULE: identity // TODO MODULE: list // TODO MODULE: refresh // MODULE: register module = "register"; lang = "en_US"; usage = "(U|u)sage: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "de_DE"; usage = "(V|v)erbrauch: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("693527"), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "es_ES"; usage = "(U|u)so: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "fr_FR"; usage = "(U|u)tilisation : subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "it_IT"; usage = "(U|u)tilizzo: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ja_JP"; usage = "使用法: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ko_KR"; usage = "사용법: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pt_BR"; usage = "(U|u)so: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ru_RU"; usage = "(Ф|ф)ормат: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_CN"; usage = "使用:subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_TW"; usage = "使用方法:subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "as_IN"; usage = "ব্যৱহাৰ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "bn_IN"; usage = "ব্যবহারপ্রণালী: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "hi_IN"; usage = "प्रयोग: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "mr_IN"; usage = "(वापर|वपार): subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "gu_IN"; usage = "વપરાશ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "kn_IN"; usage = "ಬಳಕೆ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ml_IN"; usage = "ഉപയോഗിയ്ക്കേണ്ട വിധം: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "or_IN"; usage = "ବ୍ଯବହାର ବିଧି: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pa_IN"; usage = "ਵਰਤੋਂ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ta_IN"; usage = "பயன்பாடு: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "te_IN"; usage = "వా‍డుక: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // TODO MODULE: subscribe // TODO MODULE: unregister // TODO MODULE: unsubscribe } return ll; } }
true
true
protected List<List<Object>> getExpectedCommandLineOptionsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (clienttasks==null) return ll; // String command, String stdoutRegex, List<String> expectedOptions String module; String modulesRegex = "^ \\w+"; //DELETEME String optionsRegex = "^ --\\w+[(?:=\\w)]*|^ -\\w[(?:=\\w)]*\\, --\\w+[(?:=\\w)]*"; String optionsRegex = "^ --[\\w\\.]+(=[\\w\\.]+)*|^ -\\w(=\\w+)*\\, --\\w+(=\\w+)*"; /* EXAMPLE FOR optionsRegex -h, --help show this help message and exit --list list the configuration for this system --remove=REMOVE remove configuration entry by section.name --server.hostname=SERVER.HOSTNAME */ // MODULES List <String> modules = new ArrayList<String>(); modules.add("config"); modules.add("import"); modules.add("redeem"); modules.add("orgs"); modules.add("repos"); modules.add("clean"); modules.add("environments"); modules.add("facts"); modules.add("identity"); modules.add("list"); modules.add("refresh"); modules.add("register"); modules.add("subscribe"); modules.add("unregister"); modules.add("unsubscribe"); for (String smHelpCommand : new String[]{clienttasks.command+" -h",clienttasks.command+" --help"}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" [options] MODULENAME --help"; usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, modulesRegex, modules})); } // MODULE: config module = "config"; List <String> configOptions = new ArrayList<String>(); configOptions.add("-h, --help"); configOptions.add("--list"); configOptions.add("--remove=REMOVE"); configOptions.add("--server.ca_cert_dir=SERVER.CA_CERT_DIR"); configOptions.add("--server.hostname=SERVER.HOSTNAME"); configOptions.add("--server.insecure=SERVER.INSECURE"); configOptions.add("--server.port=SERVER.PORT"); configOptions.add("--server.prefix=SERVER.PREFIX"); configOptions.add("--server.proxy_hostname=SERVER.PROXY_HOSTNAME"); configOptions.add("--server.proxy_password=SERVER.PROXY_PASSWORD"); configOptions.add("--server.proxy_port=SERVER.PROXY_PORT"); configOptions.add("--server.proxy_user=SERVER.PROXY_USER"); configOptions.add("--server.repo_ca_cert=SERVER.REPO_CA_CERT"); configOptions.add("--server.ssl_verify_depth=SERVER.SSL_VERIFY_DEPTH"); configOptions.add("--rhsm.baseurl=RHSM.BASEURL"); configOptions.add("--rhsm.ca_cert_dir=RHSM.CA_CERT_DIR"); configOptions.add("--rhsm.consumercertdir=RHSM.CONSUMERCERTDIR"); configOptions.add("--rhsm.entitlementcertdir=RHSM.ENTITLEMENTCERTDIR"); configOptions.add("--rhsm.hostname=RHSM.HOSTNAME"); configOptions.add("--rhsm.insecure=RHSM.INSECURE"); configOptions.add("--rhsm.port=RHSM.PORT"); configOptions.add("--rhsm.prefix=RHSM.PREFIX"); configOptions.add("--rhsm.productcertdir=RHSM.PRODUCTCERTDIR"); configOptions.add("--rhsm.proxy_hostname=RHSM.PROXY_HOSTNAME"); configOptions.add("--rhsm.proxy_password=RHSM.PROXY_PASSWORD"); configOptions.add("--rhsm.proxy_port=RHSM.PROXY_PORT"); configOptions.add("--rhsm.proxy_user=RHSM.PROXY_USER"); configOptions.add("--rhsm.repo_ca_cert=RHSM.REPO_CA_CERT"); configOptions.add("--rhsm.ssl_verify_depth=RHSM.SSL_VERIFY_DEPTH"); configOptions.add("--rhsmcertd.ca_cert_dir=RHSMCERTD.CA_CERT_DIR"); configOptions.add("--rhsmcertd.certfrequency=RHSMCERTD.CERTFREQUENCY"); configOptions.add("--rhsmcertd.hostname=RHSMCERTD.HOSTNAME"); configOptions.add("--rhsmcertd.insecure=RHSMCERTD.INSECURE"); configOptions.add("--rhsmcertd.port=RHSMCERTD.PORT"); configOptions.add("--rhsmcertd.prefix=RHSMCERTD.PREFIX"); configOptions.add("--rhsmcertd.proxy_hostname=RHSMCERTD.PROXY_HOSTNAME"); configOptions.add("--rhsmcertd.proxy_password=RHSMCERTD.PROXY_PASSWORD"); configOptions.add("--rhsmcertd.proxy_port=RHSMCERTD.PROXY_PORT"); configOptions.add("--rhsmcertd.proxy_user=RHSMCERTD.PROXY_USER"); configOptions.add("--rhsmcertd.repo_ca_cert=RHSMCERTD.REPO_CA_CERT"); configOptions.add("--rhsmcertd.ssl_verify_depth=RHSMCERTD.SSL_VERIFY_DEPTH"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, configOptions})); } // MODULE: import module = "import"; List <String> importOptions = new ArrayList<String>(); importOptions.add("-h, --help"); importOptions.add("--certificate=CERTIFICATE_FILES"); // importOptions.add("--proxy=PROXY_URL"); // importOptions.add("--proxyuser=PROXY_USER"); // importOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, importOptions})); } // MODULE: redeem module = "redeem"; List <String> redeemOptions = new ArrayList<String>(); redeemOptions.add("-h, --help"); redeemOptions.add("--email=EMAIL"); redeemOptions.add("--locale=LOCALE"); redeemOptions.add("--proxy=PROXY_URL"); redeemOptions.add("--proxyuser=PROXY_USER"); redeemOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, redeemOptions})); } // MODULE: orgs module = "orgs"; List <String> orgsOptions = new ArrayList<String>(); orgsOptions.add("-h, --help"); orgsOptions.add("--username=USERNAME"); orgsOptions.add("--password=PASSWORD"); orgsOptions.add("--proxy=PROXY_URL"); orgsOptions.add("--proxyuser=PROXY_USER"); orgsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, orgsOptions})); } // MODULE: repos module = "repos"; List <String> reposOptions = new ArrayList<String>(); reposOptions.add("-h, --help"); reposOptions.add("--list"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, reposOptions})); } // MODULE: clean module = "clean"; List <String> cleanOptions = new ArrayList<String>(); cleanOptions.add("-h, --help"); // removed in https://bugzilla.redhat.com/show_bug.cgi?id=664581 //cleanOptions.add("--proxy=PROXY_URL"); //cleanOptions.add("--proxyuser=PROXY_USER"); //cleanOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("664581"), smHelpCommand, optionsRegex, cleanOptions})); } // MODULE: environments module = "environments"; List <String> environmentsOptions = new ArrayList<String>(); environmentsOptions.add("-h, --help"); environmentsOptions.add("--username=USERNAME"); environmentsOptions.add("--password=PASSWORD"); environmentsOptions.add("--org=ORG"); environmentsOptions.add("--proxy=PROXY_URL"); environmentsOptions.add("--proxyuser=PROXY_USER"); environmentsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, environmentsOptions})); } // MODULE: facts module = "facts"; List <String> factsOptions = new ArrayList<String>(); factsOptions.add("-h, --help"); factsOptions.add("--list"); factsOptions.add("--update"); factsOptions.add("--proxy=PROXY_URL"); factsOptions.add("--proxyuser=PROXY_USER"); factsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, factsOptions})); } // MODULE: identity module = "identity"; List <String> identityOptions = new ArrayList<String>(); identityOptions.add("-h, --help"); identityOptions.add("--username=USERNAME"); identityOptions.add("--password=PASSWORD"); identityOptions.add("--regenerate"); identityOptions.add("--force"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=678151 identityOptions.add("--proxy=PROXY_URL"); identityOptions.add("--proxyuser=PROXY_USER"); identityOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, identityOptions})); } // MODULE: list module = "list"; List <String> listOptions = new ArrayList<String>(); listOptions.add("-h, --help"); listOptions.add("--installed"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=634254 listOptions.add("--consumed"); listOptions.add("--available"); listOptions.add("--all"); listOptions.add("--ondate=ON_DATE"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=672562 listOptions.add("--proxy=PROXY_URL"); listOptions.add("--proxyuser=PROXY_USER"); listOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, listOptions})); } // MODULE: refresh module = "refresh"; List <String> refreshOptions = new ArrayList<String>(); refreshOptions.add("-h, --help"); refreshOptions.add("--proxy=PROXY_URL"); refreshOptions.add("--proxyuser=PROXY_USER"); refreshOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, refreshOptions})); } // MODULE: register module = "register"; List <String> registerOptions = new ArrayList<String>(); registerOptions.add("-h, --help"); registerOptions.add("--username=USERNAME"); registerOptions.add("--type=CONSUMERTYPE"); registerOptions.add("--name=CONSUMERNAME"); registerOptions.add("--password=PASSWORD"); registerOptions.add("--consumerid=CONSUMERID"); registerOptions.add("--org=ORG"); registerOptions.add("--environment=ENVIRONMENT"); registerOptions.add("--autosubscribe"); registerOptions.add("--force"); registerOptions.add("--activationkey=ACTIVATION_KEYS"); registerOptions.add("--proxy=PROXY_URL"); registerOptions.add("--proxyuser=PROXY_USER"); registerOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[]{null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("628589"), smHelpCommand, optionsRegex, registerOptions})); } // MODULE: subscribe module = "subscribe"; List <String> subscribeOptions = new ArrayList<String>(); subscribeOptions.add("-h, --help"); subscribeOptions.add("--pool=POOL"); subscribeOptions.add("--quantity=QUANTITY"); subscribeOptions.add("--auto"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=680399 // subscribeOptions.add("--regtoken=REGTOKEN"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--email=EMAIL"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--locale=LOCALE"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 subscribeOptions.add("--proxy=PROXY_URL"); subscribeOptions.add("--proxyuser=PROXY_USER"); subscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, subscribeOptions})); } // MODULE: unregister module = "unregister"; List <String> unregisterOptions = new ArrayList<String>(); unregisterOptions.add("-h, --help"); unregisterOptions.add("--proxy=PROXY_URL"); unregisterOptions.add("--proxyuser=PROXY_USER"); unregisterOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unregisterOptions})); } // MODULE: unsubscribe module = "unsubscribe"; List <String> unsubscribeOptions = new ArrayList<String>(); unsubscribeOptions.add("-h, --help"); unsubscribeOptions.add("--serial=SERIAL"); unsubscribeOptions.add("--all"); unsubscribeOptions.add("--proxy=PROXY_URL"); unsubscribeOptions.add("--proxyuser=PROXY_USER"); unsubscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unsubscribeOptions})); } return ll; }
protected List<List<Object>> getExpectedCommandLineOptionsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (clienttasks==null) return ll; // String command, String stdoutRegex, List<String> expectedOptions String module; String modulesRegex = "^ \\w+"; //DELETEME String optionsRegex = "^ --\\w+[(?:=\\w)]*|^ -\\w[(?:=\\w)]*\\, --\\w+[(?:=\\w)]*"; String optionsRegex = "^ --[\\w\\.]+(=[\\w\\.]+)*|^ -\\w(=\\w+)*\\, --\\w+(=\\w+)*"; /* EXAMPLE FOR optionsRegex -h, --help show this help message and exit --list list the configuration for this system --remove=REMOVE remove configuration entry by section.name --server.hostname=SERVER.HOSTNAME */ // MODULES List <String> modules = new ArrayList<String>(); modules.add("config"); modules.add("import"); modules.add("redeem"); modules.add("orgs"); modules.add("repos"); modules.add("clean"); modules.add("environments"); modules.add("facts"); modules.add("identity"); modules.add("list"); modules.add("refresh"); modules.add("register"); modules.add("subscribe"); modules.add("unregister"); modules.add("unsubscribe"); for (String smHelpCommand : new String[]{clienttasks.command+" -h",clienttasks.command+" --help"}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" [options] MODULENAME --help"; usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, modulesRegex, modules})); } // MODULE: config module = "config"; List <String> configOptions = new ArrayList<String>(); configOptions.add("-h, --help"); configOptions.add("--list"); configOptions.add("--remove=REMOVE"); configOptions.add("--server.ca_cert_dir=SERVER.CA_CERT_DIR"); configOptions.add("--server.hostname=SERVER.HOSTNAME"); configOptions.add("--server.insecure=SERVER.INSECURE"); configOptions.add("--server.port=SERVER.PORT"); configOptions.add("--server.prefix=SERVER.PREFIX"); configOptions.add("--server.proxy_hostname=SERVER.PROXY_HOSTNAME"); configOptions.add("--server.proxy_password=SERVER.PROXY_PASSWORD"); configOptions.add("--server.proxy_port=SERVER.PROXY_PORT"); configOptions.add("--server.proxy_user=SERVER.PROXY_USER"); configOptions.add("--server.repo_ca_cert=SERVER.REPO_CA_CERT"); configOptions.add("--server.ssl_verify_depth=SERVER.SSL_VERIFY_DEPTH"); configOptions.add("--rhsm.baseurl=RHSM.BASEURL"); configOptions.add("--rhsm.ca_cert_dir=RHSM.CA_CERT_DIR"); configOptions.add("--rhsm.consumercertdir=RHSM.CONSUMERCERTDIR"); configOptions.add("--rhsm.entitlementcertdir=RHSM.ENTITLEMENTCERTDIR"); configOptions.add("--rhsm.hostname=RHSM.HOSTNAME"); configOptions.add("--rhsm.insecure=RHSM.INSECURE"); configOptions.add("--rhsm.port=RHSM.PORT"); configOptions.add("--rhsm.prefix=RHSM.PREFIX"); configOptions.add("--rhsm.productcertdir=RHSM.PRODUCTCERTDIR"); configOptions.add("--rhsm.proxy_hostname=RHSM.PROXY_HOSTNAME"); configOptions.add("--rhsm.proxy_password=RHSM.PROXY_PASSWORD"); configOptions.add("--rhsm.proxy_port=RHSM.PROXY_PORT"); configOptions.add("--rhsm.proxy_user=RHSM.PROXY_USER"); configOptions.add("--rhsm.repo_ca_cert=RHSM.REPO_CA_CERT"); configOptions.add("--rhsm.ssl_verify_depth=RHSM.SSL_VERIFY_DEPTH"); configOptions.add("--rhsmcertd.ca_cert_dir=RHSMCERTD.CA_CERT_DIR"); configOptions.add("--rhsmcertd.certfrequency=RHSMCERTD.CERTFREQUENCY"); configOptions.add("--rhsmcertd.hostname=RHSMCERTD.HOSTNAME"); configOptions.add("--rhsmcertd.insecure=RHSMCERTD.INSECURE"); configOptions.add("--rhsmcertd.port=RHSMCERTD.PORT"); configOptions.add("--rhsmcertd.prefix=RHSMCERTD.PREFIX"); configOptions.add("--rhsmcertd.proxy_hostname=RHSMCERTD.PROXY_HOSTNAME"); configOptions.add("--rhsmcertd.proxy_password=RHSMCERTD.PROXY_PASSWORD"); configOptions.add("--rhsmcertd.proxy_port=RHSMCERTD.PROXY_PORT"); configOptions.add("--rhsmcertd.proxy_user=RHSMCERTD.PROXY_USER"); configOptions.add("--rhsmcertd.repo_ca_cert=RHSMCERTD.REPO_CA_CERT"); configOptions.add("--rhsmcertd.ssl_verify_depth=RHSMCERTD.SSL_VERIFY_DEPTH"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, configOptions})); } // MODULE: import module = "import"; List <String> importOptions = new ArrayList<String>(); importOptions.add("-h, --help"); //importOptions.add("--certificate=CERTIFICATE_FILES"); // prior to fix for Bug 735212 importOptions.add("--certificate=CERTIFICATE_FILE"); // importOptions.add("--proxy=PROXY_URL"); // importOptions.add("--proxyuser=PROXY_USER"); // importOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, importOptions})); } // MODULE: redeem module = "redeem"; List <String> redeemOptions = new ArrayList<String>(); redeemOptions.add("-h, --help"); redeemOptions.add("--email=EMAIL"); redeemOptions.add("--locale=LOCALE"); redeemOptions.add("--proxy=PROXY_URL"); redeemOptions.add("--proxyuser=PROXY_USER"); redeemOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, redeemOptions})); } // MODULE: orgs module = "orgs"; List <String> orgsOptions = new ArrayList<String>(); orgsOptions.add("-h, --help"); orgsOptions.add("--username=USERNAME"); orgsOptions.add("--password=PASSWORD"); orgsOptions.add("--proxy=PROXY_URL"); orgsOptions.add("--proxyuser=PROXY_USER"); orgsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, orgsOptions})); } // MODULE: repos module = "repos"; List <String> reposOptions = new ArrayList<String>(); reposOptions.add("-h, --help"); reposOptions.add("--list"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, reposOptions})); } // MODULE: clean module = "clean"; List <String> cleanOptions = new ArrayList<String>(); cleanOptions.add("-h, --help"); // removed in https://bugzilla.redhat.com/show_bug.cgi?id=664581 //cleanOptions.add("--proxy=PROXY_URL"); //cleanOptions.add("--proxyuser=PROXY_USER"); //cleanOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("664581"), smHelpCommand, optionsRegex, cleanOptions})); } // MODULE: environments module = "environments"; List <String> environmentsOptions = new ArrayList<String>(); environmentsOptions.add("-h, --help"); environmentsOptions.add("--username=USERNAME"); environmentsOptions.add("--password=PASSWORD"); environmentsOptions.add("--org=ORG"); environmentsOptions.add("--proxy=PROXY_URL"); environmentsOptions.add("--proxyuser=PROXY_USER"); environmentsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, environmentsOptions})); } // MODULE: facts module = "facts"; List <String> factsOptions = new ArrayList<String>(); factsOptions.add("-h, --help"); factsOptions.add("--list"); factsOptions.add("--update"); factsOptions.add("--proxy=PROXY_URL"); factsOptions.add("--proxyuser=PROXY_USER"); factsOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, factsOptions})); } // MODULE: identity module = "identity"; List <String> identityOptions = new ArrayList<String>(); identityOptions.add("-h, --help"); identityOptions.add("--username=USERNAME"); identityOptions.add("--password=PASSWORD"); identityOptions.add("--regenerate"); identityOptions.add("--force"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=678151 identityOptions.add("--proxy=PROXY_URL"); identityOptions.add("--proxyuser=PROXY_USER"); identityOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, identityOptions})); } // MODULE: list module = "list"; List <String> listOptions = new ArrayList<String>(); listOptions.add("-h, --help"); listOptions.add("--installed"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=634254 listOptions.add("--consumed"); listOptions.add("--available"); listOptions.add("--all"); listOptions.add("--ondate=ON_DATE"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=672562 listOptions.add("--proxy=PROXY_URL"); listOptions.add("--proxyuser=PROXY_USER"); listOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, listOptions})); } // MODULE: refresh module = "refresh"; List <String> refreshOptions = new ArrayList<String>(); refreshOptions.add("-h, --help"); refreshOptions.add("--proxy=PROXY_URL"); refreshOptions.add("--proxyuser=PROXY_USER"); refreshOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, refreshOptions})); } // MODULE: register module = "register"; List <String> registerOptions = new ArrayList<String>(); registerOptions.add("-h, --help"); registerOptions.add("--username=USERNAME"); registerOptions.add("--type=CONSUMERTYPE"); registerOptions.add("--name=CONSUMERNAME"); registerOptions.add("--password=PASSWORD"); registerOptions.add("--consumerid=CONSUMERID"); registerOptions.add("--org=ORG"); registerOptions.add("--environment=ENVIRONMENT"); registerOptions.add("--autosubscribe"); registerOptions.add("--force"); registerOptions.add("--activationkey=ACTIVATION_KEYS"); registerOptions.add("--proxy=PROXY_URL"); registerOptions.add("--proxyuser=PROXY_USER"); registerOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[]{null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("628589"), smHelpCommand, optionsRegex, registerOptions})); } // MODULE: subscribe module = "subscribe"; List <String> subscribeOptions = new ArrayList<String>(); subscribeOptions.add("-h, --help"); subscribeOptions.add("--pool=POOL"); subscribeOptions.add("--quantity=QUANTITY"); subscribeOptions.add("--auto"); // result of https://bugzilla.redhat.com/show_bug.cgi?id=680399 // subscribeOptions.add("--regtoken=REGTOKEN"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--email=EMAIL"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 // subscribeOptions.add("--locale=LOCALE"); // https://bugzilla.redhat.com/show_bug.cgi?id=670823 subscribeOptions.add("--proxy=PROXY_URL"); subscribeOptions.add("--proxyuser=PROXY_USER"); subscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, subscribeOptions})); } // MODULE: unregister module = "unregister"; List <String> unregisterOptions = new ArrayList<String>(); unregisterOptions.add("-h, --help"); unregisterOptions.add("--proxy=PROXY_URL"); unregisterOptions.add("--proxyuser=PROXY_USER"); unregisterOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unregisterOptions})); } // MODULE: unsubscribe module = "unsubscribe"; List <String> unsubscribeOptions = new ArrayList<String>(); unsubscribeOptions.add("-h, --help"); unsubscribeOptions.add("--serial=SERIAL"); unsubscribeOptions.add("--all"); unsubscribeOptions.add("--proxy=PROXY_URL"); unsubscribeOptions.add("--proxyuser=PROXY_USER"); unsubscribeOptions.add("--proxypassword=PROXY_PASSWORD"); for (String smHelpCommand : new String[]{clienttasks.command+" -h "+module,clienttasks.command+" --help "+module}) { List <String> usages = new ArrayList<String>(); String usage = "Usage: "+clienttasks.command+" "+module+" [OPTIONS]"; if (clienttasks.redhatRelease.contains("release 5")) usage = usage.replaceFirst("^Usage", "usage"); // TOLERATE WORKAROUND FOR Bug 693527 ON RHEL5 usages.add(usage); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$", usages})); ll.add(Arrays.asList(new Object[] {null, smHelpCommand, optionsRegex, unsubscribeOptions})); } return ll; }
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/motions/ContinueFindingMotion.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/motions/ContinueFindingMotion.java index 59ade815..fe1231af 100644 --- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/motions/ContinueFindingMotion.java +++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/motions/ContinueFindingMotion.java @@ -1,61 +1,61 @@ package net.sourceforge.vrapper.vim.commands.motions; import net.sourceforge.vrapper.utils.Position; import net.sourceforge.vrapper.vim.EditorAdaptor; import net.sourceforge.vrapper.vim.commands.BorderPolicy; import net.sourceforge.vrapper.vim.commands.CommandExecutionException; public class ContinueFindingMotion extends CountAwareMotion { public static final ContinueFindingMotion NORMAL = new ContinueFindingMotion(false); public static final ContinueFindingMotion REVERSE = new ContinueFindingMotion(true); private final boolean reverse; // XXX: this is so evil private BorderPolicy borderPolicy = BorderPolicy.INCLUSIVE; private ContinueFindingMotion(boolean reverse) { this.reverse = reverse; } @Override public Position destination(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException { FindMotion findMotion = editorAdaptor.getRegisterManager().getLastFindMotion(); if (findMotion == null) { throw new CommandExecutionException("no find to repeat"); } if (reverse) { findMotion = findMotion.reversed(); } borderPolicy = findMotion.borderPolicy(); Position dest = findMotion.destination(editorAdaptor, count); //If using 't' and the cursor is before the last match, destination() //will think this position is the next match and not move the cursor. //If this happens, move the cursor forward one (so it's on top of the - //last match) and run destination() again. + //last match) and run destination() again. If 'T', go back one. if(!findMotion.upToTarget && editorAdaptor.getPosition().getModelOffset() == dest.getModelOffset()) { - int tweakOffset = reverse ? -1 : 1; + int tweakOffset = findMotion.backwards ? -1 : 1; try { //move cursor to be on top of the last match editorAdaptor.setPosition(dest.addModelOffset(tweakOffset), StickyColumnPolicy.NEVER); //try again dest = findMotion.destination(editorAdaptor, count); } catch(CommandExecutionException e) { //no match, un-tweak the cursor position editorAdaptor.setPosition(dest.addModelOffset(tweakOffset * -1), StickyColumnPolicy.NEVER); } } return dest; } public BorderPolicy borderPolicy() { return borderPolicy; } public StickyColumnPolicy stickyColumnPolicy() { return StickyColumnPolicy.ON_CHANGE; } }
false
true
public Position destination(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException { FindMotion findMotion = editorAdaptor.getRegisterManager().getLastFindMotion(); if (findMotion == null) { throw new CommandExecutionException("no find to repeat"); } if (reverse) { findMotion = findMotion.reversed(); } borderPolicy = findMotion.borderPolicy(); Position dest = findMotion.destination(editorAdaptor, count); //If using 't' and the cursor is before the last match, destination() //will think this position is the next match and not move the cursor. //If this happens, move the cursor forward one (so it's on top of the //last match) and run destination() again. if(!findMotion.upToTarget && editorAdaptor.getPosition().getModelOffset() == dest.getModelOffset()) { int tweakOffset = reverse ? -1 : 1; try { //move cursor to be on top of the last match editorAdaptor.setPosition(dest.addModelOffset(tweakOffset), StickyColumnPolicy.NEVER); //try again dest = findMotion.destination(editorAdaptor, count); } catch(CommandExecutionException e) { //no match, un-tweak the cursor position editorAdaptor.setPosition(dest.addModelOffset(tweakOffset * -1), StickyColumnPolicy.NEVER); } } return dest; }
public Position destination(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException { FindMotion findMotion = editorAdaptor.getRegisterManager().getLastFindMotion(); if (findMotion == null) { throw new CommandExecutionException("no find to repeat"); } if (reverse) { findMotion = findMotion.reversed(); } borderPolicy = findMotion.borderPolicy(); Position dest = findMotion.destination(editorAdaptor, count); //If using 't' and the cursor is before the last match, destination() //will think this position is the next match and not move the cursor. //If this happens, move the cursor forward one (so it's on top of the //last match) and run destination() again. If 'T', go back one. if(!findMotion.upToTarget && editorAdaptor.getPosition().getModelOffset() == dest.getModelOffset()) { int tweakOffset = findMotion.backwards ? -1 : 1; try { //move cursor to be on top of the last match editorAdaptor.setPosition(dest.addModelOffset(tweakOffset), StickyColumnPolicy.NEVER); //try again dest = findMotion.destination(editorAdaptor, count); } catch(CommandExecutionException e) { //no match, un-tweak the cursor position editorAdaptor.setPosition(dest.addModelOffset(tweakOffset * -1), StickyColumnPolicy.NEVER); } } return dest; }