answer
stringlengths 17
10.2M
|
|---|
package org.pentaho.di.core.vfs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Comparator;
import org.apache.commons.vfs.FileContent;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.impl.DefaultFileSystemManager;
import org.apache.commons.vfs.provider.local.LocalFile;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.UUIDUtil;
public class KettleVFS
{
private static KettleVFS kettleVFS;
private KettleVFS()
{
// Install a shutdown hook to make sure that the file system manager is closed
// This will clean up temporary files in vfs_cache
Thread thread = new Thread(new Runnable(){
public void run() {
try
{
FileSystemManager mgr = VFS.getManager();
if (mgr instanceof DefaultFileSystemManager)
{
((DefaultFileSystemManager)mgr).close();
}
}
catch (FileSystemException e)
{
e.printStackTrace();
}
}
});
Runtime.getRuntime().addShutdownHook(thread);
}
private synchronized static void checkHook() {
if (kettleVFS==null) kettleVFS=new KettleVFS();
}
public static FileObject getFileObject(String vfsFilename) throws IOException
{
checkHook();
try {
FileSystemManager fsManager = VFS.getManager();
// We have one problem with VFS: if the file is in a subdirectory of the current one: somedir/somefile
// In that case, VFS doesn't parse the file correctly.
// We need to put file: in front of it to make it work.
// However, how are we going to verify this?
// We are going to see if the filename starts with one of the known protocols like file: zip: ram: smb: jar: etc.
// If not, we are going to assume it's a file.
boolean relativeFilename=true;
String[] schemes = VFS.getManager().getSchemes();
for (int i=0;i<schemes.length && relativeFilename;i++)
{
if (vfsFilename.startsWith(schemes[i]+":")) relativeFilename=false;
}
String filename;
if (vfsFilename.startsWith("\\\\"))
{
File file = new File(vfsFilename);
filename = file.toURI().toString();
}
else
{
if (relativeFilename)
{
File file = new File(vfsFilename);
filename = file.getAbsolutePath();
}
else
{
filename = vfsFilename;
}
}
FileObject fileObject = fsManager.resolveFile( filename );
return fileObject;
}
catch(IOException e) {
throw new IOException("Unable to get VFS File object for filename '"+vfsFilename+"' : "+e.toString());
}
}
/**
* Read a text file (like an XML document). WARNING DO NOT USE FOR DATA FILES.
*
* @param vfsFilename the filename or URL to read from
* @param charSetName the character set of the string (UTF-8, ISO8859-1, etc)
* @return The content of the file as a String
* @throws IOException
*/
public static String getTextFileContent(String vfsFilename, String charSetName) throws IOException
{
InputStream inputStream = getInputStream(vfsFilename);
InputStreamReader reader = new InputStreamReader(inputStream, charSetName);
int c;
StringBuffer stringBuffer = new StringBuffer();
while ( (c=reader.read())!=-1) stringBuffer.append((char)c);
reader.close();
inputStream.close();
return stringBuffer.toString();
}
public static boolean fileExists(String vfsFilename) throws IOException
{
FileObject fileObject = getFileObject(vfsFilename);
return fileObject.exists();
}
public static InputStream getInputStream(FileObject fileObject) throws FileSystemException
{
FileContent content = fileObject.getContent();
return content.getInputStream();
}
public static InputStream getInputStream(String vfsFilename) throws IOException
{
FileObject fileObject = getFileObject(vfsFilename);
return getInputStream(fileObject);
}
public static OutputStream getOutputStream(FileObject fileObject, boolean append) throws IOException
{
FileObject parent = fileObject.getParent();
if (parent!=null)
{
if (!parent.exists())
{
throw new IOException(Messages.getString("KettleVFS.Exception.ParentDirectoryDoesNotExist", getFilename(parent)));
}
}
try
{
fileObject.createFile();
FileContent content = fileObject.getContent();
return content.getOutputStream(append);
}
catch(FileSystemException e)
{
// Perhaps if it's a local file, we can retry using the standard
// File object. This is because on Windows there is a bug in VFS.
if (fileObject instanceof LocalFile)
{
try
{
String filename = getFilename(fileObject);
return new FileOutputStream(new File(filename), append);
}
catch(Exception e2)
{
throw e; // throw the original exception: hide the retry.
}
}
else
{
throw e;
}
}
}
public static OutputStream getOutputStream(String vfsFilename, boolean append) throws IOException
{
FileObject fileObject = getFileObject(vfsFilename);
return getOutputStream(fileObject, append);
}
public static String getFilename(FileObject fileObject)
{
FileName fileName = fileObject.getName();
String root = fileName.getRootURI();
if (!root.startsWith("file:")) return fileName.getURI(); // nothing we can do about non-normal files.
if (root.endsWith(":/")) // Windows
{
root = root.substring(8,10);
}
else // *nix & OSX
{
root = "";
}
String fileString = root + fileName.getPath();
if (!"/".equals(Const.FILE_SEPARATOR))
{
fileString = Const.replace(fileString, "/", Const.FILE_SEPARATOR);
}
return fileString;
}
public static FileObject createTempFile(String prefix, String suffix, String directory) throws IOException
{
FileObject fileObject;
do
{
// Build temporary file name using UUID to ensure uniqueness. Old mechanism would fail using Sort Rows (for example)
// when there multiple nodes with multiple JVMs on each node. In this case, the temp file names would end up being
// duplicated which would cause the sort to fail.
String filename = new StringBuffer(50).append(directory).append('/').append(prefix).append('_').append(UUIDUtil.getUUIDAsString()).append(suffix).toString();
fileObject = getFileObject(filename);
}
while (fileObject.exists());
return fileObject;
}
public static Comparator<FileObject> getComparator()
{
return new Comparator<FileObject>()
{
public int compare(FileObject o1, FileObject o2)
{
String filename1 = getFilename( o1);
String filename2 = getFilename( o2);
return filename1.compareTo(filename2);
}
};
}
/**
* Get a FileInputStream for a local file. Local files can be read with NIO.
*
* @param fileObject
* @return a FileInputStream
* @throws IOException
* @deprecated because of API change in Apache VFS. As a workaround use FileObject.getName().getPathDecoded();
* Then use a regular File() object to create a File Input stream.
*/
public static FileInputStream getFileInputStream(FileObject fileObject) throws IOException {
if (!(fileObject instanceof LocalFile)) {
// We can only use NIO on local files at the moment, so that's what we limit ourselves to.
throw new IOException(Messages.getString("FixedInput.Log.OnlyLocalFilesAreSupported"));
}
return new FileInputStream( fileObject.getName().getPathDecoded() );
}
}
|
package pluginbase.plugin;
import pluginbase.command.Command;
import pluginbase.command.CommandHandler;
import pluginbase.command.CommandProvider;
import pluginbase.command.QueuedCommand;
import pluginbase.config.SerializationRegistrar;
import pluginbase.jdbc.JdbcAgent;
import pluginbase.logging.LoggablePlugin;
import pluginbase.logging.PluginLogger;
import pluginbase.messages.messaging.Messager;
import pluginbase.messages.messaging.Messaging;
import pluginbase.messages.messaging.SendablePluginBaseException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pluginbase.permission.PermFactory;
import pluginbase.plugin.Settings.Language;
import pluginbase.plugin.command.builtin.VersionCommand;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
/**
* This represents the PluginBase plugin itself.
* <p/>
* Provides numerous useful methods for general plugin self-management.
*/
public final class PluginBase<P> implements LoggablePlugin, Messaging, CommandProvider<P> {
static {
SerializationRegistrar.registerClass(Settings.class);
SerializationRegistrar.registerClass(Language.class);
}
@NotNull
private final PluginAgent<P> pluginAgent;
private PluginLogger logger;
private Settings settings = null;
PluginBase(@NotNull PluginAgent<P> pluginAgent) {
this.pluginAgent = pluginAgent;
}
public P getPlugin() {
return pluginAgent.getPlugin();
}
void onLoad() {
// Initialize our logging.
logger = PluginLogger.getLogger(this);
PermFactory.registerPermissionName(getPluginClass(), pluginAgent.getPermissionPrefix());
// Loads the configuration.
settings = pluginAgent.loadSettings();
}
void onEnable() {
// Loads the configuration.
settings = pluginAgent.loadSettings();
// Set up commands.
pluginAgent.registerCommands();
// Setup the plugin messager.
loadLanguage();
// Do any important first run stuff here.
if (getSettings().isFirstRun()) {
pluginAgent.firstRun();
getSettings().setFirstRun(false);
try {
saveSettings();
} catch (SendablePluginBaseException e) {
e.printStackTrace();
getLog().severe("Cannot save config on startup. Terminating plugin.");
pluginAgent.disablePlugin();
}
}
}
void onDisable() {
getLog().shutdown();
}
public Class getPluginClass() {
return pluginAgent.getPluginClass();
}
@NotNull
public Settings getSettings() {
return settings;
}
public void saveSettings() throws SendablePluginBaseException {
pluginAgent.saveSettings();
}
/**
* Gets the info object for this plugin.
*
* @return the info object for this plugin.
*/
@NotNull
public PluginInfo getPluginInfo() {
return pluginAgent.getPluginInfo();
}
/** {@inheritDoc} */
@NotNull
@Override
public File getDataFolder() {
return pluginAgent.getDataFolder();
}
/** {@inheritDoc} */
@NotNull
@Override
public String getCommandPrefix() {
return pluginAgent.getCommandProvider().getCommandPrefix();
}
/**
* Retrieves the JDBC agent for this plugin, if configured.
* <p/>
* This agent will provide a connection to a database which can be used to execute queries.
*
* @return the JDBC agent for this plugin or null if not configured.
*/
@Nullable
public JdbcAgent getJdbcAgent() {
return pluginAgent.getJdbcAgent();
}
/**
* Tells the plugin to reload the configuration and other data files.
*/
public void reloadConfig() {
Settings settings = pluginAgent.loadSettings();
loadLanguage();
}
private void loadLanguage() {
Language languageSettings = settings.getLanguageSettings();
pluginAgent.getCommandProvider().loadMessages(new File(getDataFolder(), languageSettings.getLanguageFile()), languageSettings.getLocale());
}
/** {@inheritDoc} */
@NotNull
@Override
public Messager getMessager() {
return pluginAgent.getCommandProvider().getMessager();
}
@Override
public void loadMessages(@NotNull final File languageFile, @NotNull final Locale locale) {
pluginAgent.getCommandProvider().loadMessages(languageFile, locale);
}
/**
* Gets a list of special data points this plugin wishes to be shown when using the version command.
*
* @return a list of special data points for version info.
*/
@NotNull
public List<String> dumpVersionInfo() {
List<String> buffer = new LinkedList<String>();
buffer.add(getMessager().getLocalizedMessage(VersionCommand.VERSION_PLUGIN_VERSION, getPluginInfo().getName(), getPluginInfo().getVersion()));
buffer.add(getMessager().getLocalizedMessage(VersionCommand.VERSION_SERVER_NAME, getServerInterface().getName()));
buffer.add(getMessager().getLocalizedMessage(VersionCommand.VERSION_SERVER_VERSION, getServerInterface().getVersion()));
buffer.add(getMessager().getLocalizedMessage(VersionCommand.VERSION_LANG_FILE, getSettings().getLanguageSettings().getLanguageFile()));
buffer.add(getMessager().getLocalizedMessage(VersionCommand.VERSION_DEBUG_MODE, getSettings().getDebugLevel()));
buffer = pluginAgent.getModifiedVersionInfo(buffer);
return buffer;
}
/** {@inheritDoc} */
@NotNull
public ServerInterface getServerInterface() {
return pluginAgent.getServerInterface();
}
/**
* Gets the command handler for this plugin.
*
* @return the command handler for this plugin.
*/
@NotNull
@Override
public CommandHandler getCommandHandler() {
return pluginAgent.getCommandProvider().getCommandHandler();
}
/**
* Gets the PluginBase logger for this PluginBase plugin.
*
* @return the PluginBase logger for this PluginBase plugin.
*/
@NotNull
@Override
public PluginLogger getLog() {
return logger;
}
/** {@inheritDoc} */
@Override
public void scheduleQueuedCommandExpiration(@NotNull QueuedCommand queuedCommand) {
if (useQueuedCommands()) {
getServerInterface().runTaskLater(queuedCommand, queuedCommand.getExpirationDuration() * 20L);
}
}
/** {@inheritDoc} */
@Override
public boolean useQueuedCommands() {
return pluginAgent.getCommandProvider().useQueuedCommands();
}
/** {@inheritDoc} */
@NotNull
@Override
public String[] getAdditionalCommandAliases(@NotNull Class<? extends Command> commandClass) {
return pluginAgent.getAdditionalCommandAliases(commandClass);
}
@Override
public void addCommandAlias(@NotNull Class<? extends Command> commandClass, @NotNull String alias) {
pluginAgent.getCommandProvider().addCommandAlias(commandClass, alias);
}
/** {@inheritDoc} */
@NotNull
@Override
public String getName() {
return getPluginInfo().getName();
}
}
|
package com.huettermann.all;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Message extends HttpServlet {
//private String userName; //As this field is shared by all users, it's obvious that this piece of information should be managed differently
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param = request.getParameter("param");
ServletContext context = getServletContext( );
if (param == null || param.equals("")) {
context.log("No message received:",
new IllegalStateException("Missing parameter"));
} else {
context.log("Here the paramater: " + param);
}
PrintWriter out = null;
try {
out = response.getWriter();
out.println("Hello: " + param);
out.flush();
out.close();
} catch (IOException io) {
io.printStackTrace();
}
}
}
|
package net.didion.jwnl.utilities;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.didion.jwnl.JWNL;
import net.didion.jwnl.JWNLException;
import net.didion.jwnl.data.DictionaryElement;
import net.didion.jwnl.data.POS;
import net.didion.jwnl.dictionary.AbstractCachingDictionary;
import net.didion.jwnl.dictionary.Dictionary;
import net.didion.jwnl.dictionary.file.DictionaryCatalogSet;
import net.didion.jwnl.dictionary.file.DictionaryFileType;
import net.didion.jwnl.dictionary.file.ObjectDictionaryFile;
/**
* DictionaryToMap allows you to populate and create an in-memory map of the WordNet
* library. The goal of this utility is to provide a performance boost to applications
* using a high quantity of API calls to the JWNL library
* (such as word sense disambiguation algorithms, or dictionary services).
* @author brett
*
*/
public class DictionaryToMap
{
/**
* Initalize with the given map destination directory, using the properties file(usually file_properties.xml)
* @param destDirectory - destination directory for in-memory map files
* @param propFile - properties file of file-based WordNet
* @throws JWNLException
* @throws IOException
*/
public DictionaryToMap(String destDirectory, String propFile)
throws JWNLException, IOException
{
JWNL.initialize(new FileInputStream(propFile));
_destFiles = new DictionaryCatalogSet(destDirectory, net.didion.jwnl.princeton.file.PrincetonObjectDictionaryFile.class);
}
/**
* Converts the current Dictionary to a MapBackedDictionary.
* @throws JWNLException
* @throws IOException
*/
public void convert()
throws JWNLException, IOException
{
_destFiles.open();
boolean canClearCache = (Dictionary.getInstance() instanceof AbstractCachingDictionary) && ((AbstractCachingDictionary)Dictionary.getInstance()).isCachingEnabled();
for(Iterator typeItr = DictionaryFileType.getAllDictionaryFileTypes().iterator(); typeItr.hasNext(); System.gc())
{
DictionaryFileType fileType = (DictionaryFileType)typeItr.next();
POS pos;
for(Iterator posItr = POS.getAllPOS().iterator(); posItr.hasNext(); serialize(pos, fileType))
{
pos = (POS)posItr.next();
System.out.println("Converting " + pos + " " + fileType + " file...");
}
if(canClearCache)
((AbstractCachingDictionary)Dictionary.getInstance()).clearCache(fileType.getElementType());
}
_destFiles.close();
}
private Iterator getIterator(POS pos, DictionaryFileType fileType)
throws JWNLException
{
if(fileType == DictionaryFileType.DATA)
return Dictionary.getInstance().getSynsetIterator(pos);
if(fileType == DictionaryFileType.INDEX)
return Dictionary.getInstance().getIndexWordIterator(pos);
if(fileType == DictionaryFileType.EXCEPTION)
return Dictionary.getInstance().getExceptionIterator(pos);
else
throw new IllegalArgumentException();
}
private void serialize(POS pos, DictionaryFileType fileType)
throws JWNLException, IOException
{
ObjectDictionaryFile file = (ObjectDictionaryFile)_destFiles.getDictionaryFile(pos, fileType);
int count = 0;
for(Iterator itr = getIterator(pos, fileType); itr.hasNext(); itr.next())
if(++count % 10000 == 0)
System.out.println("Counted and cached word " + count + "...");
Map map = new HashMap((int)Math.ceil((float)count / 0.9F) + 1, 0.9F);
DictionaryElement elt;
for(Iterator listItr = getIterator(pos, fileType); listItr.hasNext(); map.put(elt.getKey(), elt))
elt = (DictionaryElement)listItr.next();
file.writeObject(map);
file.close();
map = null;
file = null;
System.gc();
Runtime rt = Runtime.getRuntime();
System.out.println("total mem: " + rt.totalMemory() / 1024L + "K free mem: " + rt.freeMemory() / 1024L + "K");
System.out.println("Successfully serialized...");
}
public static void main(String args[])
{
String destinationDirectory = null;
String propertyFile = null;
if(args.length == 2)
{
destinationDirectory = args[0];
propertyFile = args[1];
} else
{
System.out.println("java DictionaryToMap <destination directory> <properties file>");
System.exit(-1);
}
try
{
(new DictionaryToMap(destinationDirectory, propertyFile)).convert();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(-1);
}
}
private DictionaryCatalogSet _destFiles;
}
|
package net.momodalo.app.vimtouch;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class InstallProgress extends Activity {
public static final String LOG_TAG = "VIM Installation";
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.installprogress);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
installZip(R.raw.vim);
installZip(R.raw.terminfo);
File vimrc = new File(getApplicationContext().getFilesDir()+"/vim/vimrc");
try{
BufferedInputStream is = new BufferedInputStream(getResources().openRawResource(R.raw.vimrc));
FileWriter fout = new FileWriter(vimrc);
while(is.available() > 0){
fout.write(is.read());
}
fout.close();
} catch(Exception e) {
Log.e(LOG_TAG, "install vimrc", e);
}
File tmp = new File(getApplicationContext().getFilesDir()+"/tmp");
tmp.mkdir();
finish();
}
}).start();
}
private void installZip(int resourceId) {
try {
String dirname = getApplicationContext().getFilesDir().getPath();
InputStream is = this.getResources().openRawResource(resourceId);
ZipInputStream zin = new ZipInputStream(is);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.e(LOG_TAG, "Unzipping " + ze.getName());
if(ze.isDirectory()) {
File file = new File(dirname+"/"+ze.getName());
if(!file.isDirectory())
file.mkdirs();
} else {
int size;
byte[] buffer = new byte[2048];
FileOutputStream fout = new FileOutputStream(dirname+"/"+ze.getName());
BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);
while((size = zin.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
zin.closeEntry();
}
}
zin.close();
} catch(Exception e) {
Log.e(LOG_TAG, "unzip", e);
}
}
}
|
package com.sometrik.framework;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class FWAdapter extends ArrayAdapter<View> implements ExpandableListAdapter {
enum AdapterDataType {
SHEET, DATA
}
private List<View> viewList;
private HashMap<Integer, AdapterData> dataList;
private AdapterData columnData;
private FrameWork frame;
private LinearLayout.LayoutParams listItemParams;
private boolean sheetsEnabled = false;
public FWAdapter(FrameWork frame, List<View> viewList) {
super(frame, 0, viewList);
this.frame = frame;
dataList = new HashMap<Integer, AdapterData>();
columnData = new AdapterData(new ArrayList<String>());
listItemParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
listItemParams.weight = 1;
listItemParams.leftMargin = 50;
}
public ArrayList<String> getDataRow(int row, int sheet) {
if (sheet == 0) {
AdapterData sheetData = dataList.get(sheet);
if (sheetData == null || sheetData.type == AdapterDataType.DATA) {
AdapterData data = dataList.get(row);
if (data == null) {
Log.d("adapter", "no row found");
return null;
} else {
Log.d("adapter", "row found");
return data.stringList;
}
}
if (sheetData.getChildren().size() != 0) {
AdapterData data = sheetData.getChild(row);
if (data == null) {
Log.d("adapter", "no row found");
return null;
} else {
Log.d("adapter", "row found");
return data.stringList;
}
} else {
Log.d("adapter", "no children - no row found");
return null;
}
} else {
AdapterData sheetData = dataList.get(sheet);
Log.d("adapter", "sheetData size: " + dataList.size());
if (sheetData == null) {
Log.d("adapter", "sheetData null");
return null;
}
if (sheetData.getChildren().size() != 0) {
AdapterData data = sheetData.getChild(row);
if (data == null) {
Log.d("adapter", "no row found");
return null;
} else {
Log.d("adapter", "row found");
return data.stringList;
}
} else {
Log.d("adapter", "no children - no row found");
return null;
}
}
}
public void addItem(int row, int sheet, ArrayList<String> cellItems) {
Log.d("adapter", "adding new dataList to row: " + row + " sheet: " + sheet);
if (!sheetsEnabled) {
dataList.put(row, new AdapterData(cellItems));
return;
} else {
Log.d("adapter", "datalist size: " + dataList.size());
AdapterData sheetData = dataList.get(sheet);
if (sheetData == null) {
Log.d("adapter", "no sheet found");
return;
}
sheetData.addChild(row, new AdapterData(cellItems));
}
}
public void addColumn(String columnText) {
columnData.addString(columnText);
}
public void addSheet(String sheetName) {
int size = dataList.size();
ArrayList<String> sheet = new ArrayList<String>();
sheet.add(sheetName);
Log.d("adapter", "putting sheet to " + (size));
sheetsEnabled = true;
dataList.put(size, new AdapterData(sheet, AdapterDataType.SHEET));
}
public void reshape(int sheet, int size) {
if (size == dataList.size()){
return;
}
if (size < dataList.size()) {
// Currently removes rows from the end
ArrayList<Integer> keyList = new ArrayList<Integer>();
for (Entry<Integer, AdapterData> entry : dataList.entrySet()) {
keyList.add(entry.getKey());
}
for (int i = 0; i < size; i++) {
int key = keyList.get(keyList.size() - 1);
dataList.remove(key);
}
} else {
int difference = size - dataList.size();
System.out.println("adding " + difference + " new rows");
for (int i = 0; i < difference; i++) {
ArrayList<String> newSheet = new ArrayList<String>();
dataList.put(dataList.size(), new AdapterData(newSheet, AdapterDataType.SHEET));
}
}
notifyDataSetChanged();
}
@Override
public int getCount() {
Log.d("adapter", "getCount");
int counter = 0;
for (HashMap.Entry<Integer, AdapterData> pair : dataList.entrySet()) {
if (pair.getValue().type == AdapterDataType.SHEET && pair.getValue().getChildren().size() == 0) {
continue;
} else {
counter++;
}
}
if (columnData.getSize() != 0) {
return counter + 1;
} else {
return counter;
}
}
@Override
public long getItemId(int arg0) {
Log.d("adapter", "getItemId");
return 0;
}
@Override
public void clear() {
Log.d("adapter", "clear");
Iterator<Entry<Integer, AdapterData>> iterator = dataList.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, AdapterData> entry = iterator.next();
if (entry.getValue().type == AdapterDataType.DATA) {
iterator.remove();
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("adapter", "position: " + position);
LinearLayout layout = new LinearLayout(frame);
AdapterData data;
if (position == 0) {
data = columnData;
for (int i = 0; i < data.getSize(); i++) {
TextView txtFirst = new TextView(frame);
txtFirst.setLayoutParams(listItemParams);
txtFirst.setTypeface(null, Typeface.BOLD);
txtFirst.setFocusable(false);
txtFirst.setFocusableInTouchMode(false);
txtFirst.setClickable(false);
layout.addView(txtFirst);
txtFirst.setText(data.getData(i));
}
return layout;
} else {
Log.d("adapter", "dataKList.size: " + dataList.size());
Log.d("adapter", "trying to get from index: " + (position));
data = dataList.get(position);
}
if (data == null) {
Log.d("adapter", "no data on position " + position);
return layout;
}
for (int i = 0; i < data.getSize(); i++) {
TextView txtFirst = new TextView(frame);
txtFirst.setLayoutParams(listItemParams);
txtFirst.setFocusable(false);
txtFirst.setClickable(false);
txtFirst.setFocusableInTouchMode(false);
layout.addView(txtFirst);
txtFirst.setText(data.getData(i));
}
return layout;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
Log.d("adapter", "getChild");
return null;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
Log.d("adapter", "getChildId");
return 0;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Log.d("adapter", "GetChildView position: " + groupPosition + " childPosition: " + childPosition);
if (columnData.getSize() != 0) {
groupPosition
Log.d("adapter", "GetChildView (changed) position: " + groupPosition + " childPosition: " + childPosition);
}
AdapterData sheetData = dataList.get(groupPosition);
ArrayList<AdapterData> children = sheetData.getChildren();
ScrollView scrollView = new ScrollView(frame);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.FILL;
scrollView.setLayoutParams(params);
LinearLayout expandLayout = new LinearLayout(frame);
expandLayout.setOrientation(LinearLayout.VERTICAL);
expandLayout.setLayoutParams(params);
scrollView.addView(expandLayout);
Log.d("adapter", "Children size on getChildView: " + children.size());
for (int i = 0; i < children.size(); i++) {
AdapterData childData = sheetData.getChild(i);
LinearLayout layout = new LinearLayout(frame);
layout.setBackgroundColor(Color.parseColor("#d1d1d1"));
for (int i2 = 0; i2 < childData.getSize(); i2++) {
TextView txtFirst = new TextView(frame);
txtFirst.setLayoutParams(listItemParams);
txtFirst.setFocusable(false);
txtFirst.setClickable(false);
txtFirst.setSingleLine();
txtFirst.setEllipsize(TextUtils.TruncateAt.END);
txtFirst.setFocusableInTouchMode(false);
layout.addView(txtFirst);
txtFirst.setText(childData.getData(i2));
}
expandLayout.addView(layout);
}
return scrollView;
}
@Override
public int getChildrenCount(int groupPosition) {
Log.d("adapter", "getChildrenCount " + groupPosition);
if (groupPosition == 0 || !sheetsEnabled) {
return 0;
}
Log.d("adapter", "getChildrenCount (changed) " + (groupPosition - 1));
AdapterData sheetData = dataList.get(groupPosition - 1);
if (sheetData == null) {
Log.d("adapter", "sheetData null");
return 0;
}
if (sheetData.getChildren().size() > 0) {
Log.d("adapter", "children found");
return 1;
} else {
Log.d("adapter", "no children found");
return 0;
}
}
@Override
public long getCombinedChildId(long groupId, long childId) {
Log.d("adapter", "getCombinedChildId");
return 0;
}
@Override
public long getCombinedGroupId(long groupId) {
Log.d("adapter", "getCombinedGroupId");
return 0;
}
@Override
public Object getGroup(int groupPosition) {
Log.d("adapter", "getGroup");
return null;
}
@Override
public int getGroupCount() {
if (columnData.getSize() != 0) {
return dataList.size() + 1;
} else {
return dataList.size();
}
// int counter = 0;
// for (HashMap.Entry<Integer, AdapterData> pair : dataList.entrySet()) {
// if (pair.getValue().type == AdapterDataType.SHEET &&
// pair.getValue().getChildren().size() == 0) {
// continue;
// } else {
// counter++;
// if (columnData.getSize() != 0) {
// return counter + 1;
// } else {
// return counter;
}
@Override
public long getGroupId(int groupPosition) {
Log.d("adapter", "getGroupId");
return 0;
}
@Override
public View getGroupView(int position, boolean arg1, View arg2, ViewGroup arg3) {
Log.d("adapter", "GetGroupView position: " + position);
LinearLayout layout = new LinearLayout(frame);
AdapterData data;
if (position == 0) {
data = columnData;
for (int i = 0; i < data.getSize(); i++) {
TextView txtFirst = new TextView(frame);
txtFirst.setLayoutParams(listItemParams);
txtFirst.setTypeface(null, Typeface.BOLD);
// txtFirst.setTextAppearance(frame,
// android.R.style.TextAppearance_DeviceDefault_Small);
txtFirst.setTextSize(10);
txtFirst.setFocusable(false);
txtFirst.setFocusableInTouchMode(false);
txtFirst.setClickable(false);
txtFirst.setSingleLine();
layout.addView(txtFirst);
// layout.setBackgroundColor(0xFF777777);
txtFirst.setText(data.getData(i));
}
layout.setPadding(0, 20, 0, 20);
return layout;
} else {
if (columnData.getSize() != 0) {
position
}
Log.d("adapter", "dataKList.size: " + dataList.size());
Log.d("adapter", "trying to get from index: " + (position));
data = dataList.get(position);
// if (data.type == AdapterDataType.SHEET && data.getChildren().size() ==
// layout.setVisibility(LinearLayout.INVISIBLE);
// layout.setLayoutParams(new AbsListView.LayoutParams(-1, -2));
// return layout;
for (int i = 0; i < data.getSize(); i++) {
Log.d("adapter", "looping throud data " + i);
TextView txtFirst = new TextView(frame);
txtFirst.setFocusable(false);
txtFirst.setFocusableInTouchMode(false);
txtFirst.setClickable(false);
// txtFirst.setTextAppearance(frame,
// android.R.style.TextAppearance_DeviceDefault_Small);
txtFirst.setTextSize(9);
txtFirst.setLayoutParams(listItemParams);
layout.addView(txtFirst);
txtFirst.setText(data.getData(i));
}
layout.setPadding(0, 20, 0, 20);
return layout;
}
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public void onGroupCollapsed(int groupPosition) {
Log.d("adapter", "onGroupCollapsed");
}
@Override
public void onGroupExpanded(int groupPosition) {
Log.d("adapter", "onGroupExpanded");
}
public class AdapterData {
private ArrayList<String> stringList;
private boolean columnData = false;
private ArrayList<AdapterData> children;
private AdapterDataType type = AdapterDataType.DATA;
public AdapterData(ArrayList<String> stringList) {
this.stringList = stringList;
children = new ArrayList<AdapterData>();
}
public AdapterData(ArrayList<String> stringList, AdapterDataType type) {
this.type = type;
this.stringList = stringList;
children = new ArrayList<AdapterData>();
}
public void addString(String text) {
stringList.add(text);
}
public int getSize() {
return stringList.size();
}
public void addChild(int row, AdapterData data) {
children.add(row, data);
}
public String getData(int position) {
if (position < stringList.size()) {
return stringList.get(position);
} else {
return stringList.get(0);
}
}
public AdapterData getChild(int row) {
System.out.println("getChild on AdpaterData");
if (row >= children.size()) {
System.out.println("no children");
return null;
}
return children.get(row);
}
public ArrayList<AdapterData> getChildren() {
return children;
}
public ArrayList<String> getList() {
return stringList;
}
}
}
|
package com.sometrik.framework;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import com.android.trivialdrivesample.util.IabException;
import com.android.trivialdrivesample.util.IabHelper;
import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException;
import com.android.trivialdrivesample.util.Inventory;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ConfigurationInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class FrameWork extends Activity implements NativeCommandHandler {
private RelativeLayout mainView;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private FrameWork frameWork;
private double updateTimer = 0;
private IabHelper purchaseHelper;
private static final int RESULT_SETTINGS = 1;
private Inventory inventory;
private DisplayMetrics displayMetrics;
private View currentlyShowingView;
private Charset utf8_charset;
private boolean drawMode = false;
private Locale defaultLocale;
private float screenHeight;
private float screenWidth;
public Handler mainHandler;
private Intent dialogIntent;
private Bitmap picture;
private AlertDialog.Builder builder;
private AlertDialog alert;
private float windowYcoords;
public static HashMap<Integer, NativeCommandHandler> views = new HashMap<Integer, NativeCommandHandler>();
private int appId = 0;
private int currentView = 0;
public static boolean transitionAnimation = false;
public native void endModal(double timestamp, int value, byte[] textValue);
public native void textChangedEvent(double timestamp, int id, byte[] textValue);
public native void intChangedEvent(double timestamp, int id, int changedInt);
public native void keyPressed(double timestamp, int keyId, int viewId);
public native void touchEvent(int viewId, int mode, int fingerIndex, long time, float x, float y);
public native void onInit(AssetManager assetManager, float xSize, float ySize, float displayScale);
public native void nativeSetSurface(Surface surface, int surfaceId, int gl_version);
public native void nativeSurfaceDestroyed(double timestamp, int surfaceId, int gl_version);
public native void nativeOnResume(double timestamp, int appId);
public native void nativeOnPause(double timestamp, int appId);
public native void nativeOnStop(double timestamp, int appId);
public native void nativeOnStart(double timestamp, int appId);
public native void nativeOnDestroy(double timestamp, int appId);
private native void setNativeActiveView(double timestamp, int activeView, boolean recordHistory);
private native void languageChanged(double timestamp, int appId, String language);
private native void memoryWarning(double timestamp, int appId);
public static native void onPurchaseEvent(double timestamp, int applicationId, String orderId, boolean newPurchase, double purchaseTime);
public static native void onResize(double timestamp, float width, float height, int viewId);
public static native void onUpdate(double timestamp, int viewId);
public static native void timerEvent(double timestamp, int viewId, int timerId);
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate called");
// Set default theme for the app. Commented default themes are dark versions
if (Build.VERSION.SDK_INT <= 10) {
// this.setTheme(android.R.style.Theme);
this.setTheme(android.R.style.Theme_Light);
} else if (Build.VERSION.SDK_INT >= 21) {
// this.setTheme(android.R.style.Theme_Material);
this.setTheme(android.R.style.Theme_Material_Light);
} else {
// this.setTheme(android.R.style.Theme_DeviceDefault);
// this.setTheme(android.R.style.Theme_Holo);
this.setTheme(android.R.style.Theme_Holo_Light);
}
super.onCreate(savedInstanceState);
utf8_charset = Charset.forName("UTF-8");
defaultLocale = Locale.getDefault();
System.out.println("Users preferred locale: " + defaultLocale.getCountry() + " Language: " + defaultLocale.getLanguage());
// You can disable status bar with this
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Init for screen settings
setupDisplayMetrics();
mainHandler = new Handler() {
public void handleMessage(Message msg) {
NativeCommand command = (NativeCommand) msg.obj;
command.apply(FrameWork.views.get(command.getInternalId()));
}
};
System.out.println("initing native on onCreate");
initNative();
}
public Boolean initializePurchaseHelper(String key, IabHelper.OnIabSetupFinishedListener listener) {
// Get PurchaseHelper. Requires App public key
purchaseHelper = new IabHelper(this, key);
purchaseHelper.startSetup(listener);
return true;
}
public Inventory getPurchaseHelperInventory() {
System.out.println("about to query purchaseHelper inventory");
try {
inventory = purchaseHelper.queryInventory();
return inventory;
} catch (IabException e) {
System.out.println("Exception getting inventory with message: " + e.getMessage());
e.printStackTrace();
}
return null;
}
private void initNative() {
System.out.println("Display scale: " + displayMetrics.scaledDensity);
float xSize = displayMetrics.widthPixels / displayMetrics.scaledDensity;
float ySize = displayMetrics.heightPixels / displayMetrics.scaledDensity;
onInit(getAssets(), xSize, ySize, displayMetrics.scaledDensity);
}
// Get screen settings
public DisplayMetrics setupDisplayMetrics() {
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
screenHeight = displayMetrics.heightPixels;
screenWidth = displayMetrics.widthPixels;
return displayMetrics;
}
public void setSharedPreferences(String textValue) {
prefs = getSharedPreferences(textValue, Context.MODE_PRIVATE);
editor = prefs.edit();
}
public SharedPreferences.Editor getPreferencesEditor() { return editor; }
public static void addToViewList(NativeCommandHandler view) {
System.out.println(view.getElementId() + " added to view list");
views.put(view.getElementId(), view);
}
public void launchBrowser(String url) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
public void removeViewFromList(int viewId){
FrameWork.views.remove(viewId);
}
public void setCurrentView(final View view, final boolean recordHistory) {
if (currentView != 0) {
TranslateAnimation r;
if (recordHistory) {
r = new TranslateAnimation(0, -1000, 0, 0);
} else {
r = new TranslateAnimation(0, 1000, 0, 0);
}
r.setDuration(200);
r.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
transitionAnimation = true;
}
@Override
public void onAnimationEnd(Animation animation) {
currentView = view.getId();
currentlyShowingView = view;
setContentView(view);
TranslateAnimation q;
if (recordHistory) {
q = new TranslateAnimation(1000, 0, 0, 0);
} else {
q = new TranslateAnimation(-1000, 0, 0, 0);
}
q.setAnimationListener(new Animation.AnimationListener(){
@Override
public void onAnimationEnd(Animation animation) { transitionAnimation = false; }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationStart(Animation animation) { }
});
q.setDuration(200);
view.startAnimation(q);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
View sadas = (View) FrameWork.views.get(currentView);
sadas.startAnimation(r);
} else {
currentView = view.getId();
currentlyShowingView = view;
setContentView(view);
}
setNativeActiveView(System.currentTimeMillis() / 1000.0, view.getId(), recordHistory);
}
public int getCurrentViewId() { return currentView; }
public NativeSurface createNativeOpenGLView(final int id) {
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final int gl_version = configurationInfo.reqGlEsVersion;
System.out.println("about to create native surface. gl_version: " + gl_version);
NativeSurface surfaceView = new NativeSurface(this);
surfaceView.setId(id);
surfaceView.setLayoutParams(new FrameLayout.LayoutParams((int)screenWidth, (int)screenHeight));
surfaceView.setOnTouchListener(new MyOnTouchListener(this, id));
SurfaceHolder holder = surfaceView.getHolder();
holder.setFixedSize((int)screenWidth, (int)screenHeight);
holder.addCallback(new Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surfaceDestroyed");
nativeSurfaceDestroyed(System.currentTimeMillis() / 1000.0, id, gl_version);
}
public void surfaceCreated(SurfaceHolder holder) { }
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
System.out.println("setting native surface");
nativeSetSurface(holder.getSurface(), id, gl_version);
System.out.println("native surface has been set");
}
});
System.out.println("...");
views.put(id, surfaceView);
if (currentView == 0){
System.out.println("no current view set. showing created surfaceView");
//Set value shows view
surfaceView.setValue(1);
}
System.out.println("native surface created");
return surfaceView;
}
// TODO: Add icon and sound
public void createNotification(String title, String text) {
System.out.println("Creating notification");
Intent intent = new Intent(this, FrameWork.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle(title);
builder.setContentText(text);
// builder.setSmallIcon(R.drawable.picture);
builder.setContentIntent(pIntent);
builder.setAutoCancel(true);
Notification notif = builder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notif);
}
//Screen touchevent listener. Will send information to MyGLSurfaceView messagehandler
private class MyOnTouchListener implements OnTouchListener {
FrameWork frameWork;
int viewId;
public MyOnTouchListener(FrameWork frameWork, int viewId) {
this.frameWork = frameWork;
this.viewId = viewId;
}
public void onClick(View v) {
System.out.println("Click happened");
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// On touchesBegin(), touchesEnded(), touchesMoved(), Different
// fingers (pointerId)
Message msg;
int[] intArray;
int action = event.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
int fingerId = event.getPointerId(pointerIndex);
switch (action) {
//Touch event of screen touch-down for the first finger
case MotionEvent.ACTION_DOWN:
// System.out.println("Liike alkoi: " + event.getX() + " " + event.getY() + " - id: " + event.getActionIndex() + " time: " + System.currentTimeMillis());
touchEvent(viewId, 1, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (event.getRawY() + windowYcoords));
break;
//Touch event of screen touch-down after the first touch
case MotionEvent.ACTION_POINTER_DOWN:
// System.out.println("Liike alkoi: " + event.getX() + " " + event.getY() + " - id: " + event.getActionIndex());
touchEvent(viewId, 1, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (event.getRawY() + windowYcoords));
break;
//Touch event of finger moving
case MotionEvent.ACTION_MOVE:
int pointerCount = event.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
pointerIndex = i;
int pointerId = event.getPointerId(pointerIndex);
System.out.println("finger move. FingerId: " + pointerId);
touchEvent(viewId, 2, pointerId, System.currentTimeMillis(), (int) event.getX(), (int) (event.getRawY() + windowYcoords));
}
break;
//touch event of first finger being removed from the screen
case MotionEvent.ACTION_UP:
//touch event of fingers other than the first leaving the screen
case MotionEvent.ACTION_POINTER_UP:
touchEvent(viewId, 3, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (event.getRawY() + windowYcoords));
break;
}
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
System.out.println("onCreateOptionsMenu");
return true;
}
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
System.out.println("KeyEvent. KeyCode: " + keycode + " ViewId: " + findViewById(android.R.id.content).getRootView().getId());
if (!transitionAnimation){
keyPressed(System.currentTimeMillis() / 1000.0, e.getKeyCode(), currentView);
}
return true;
}
private void createOptionsDialog(final int[] idArray, String[] names) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options Menu");
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
System.out.println("item selected: " + item);
System.out.println("item id: " + idArray[item]);
// optionSelected(idArray[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
public float getScreenWidth(){
return screenWidth;
}
public void setAppId(int id){ this.appId = id; }
public int getAppId(){ return appId; }
// returns database path
public String getDBPath(String dbName) {
System.out.println("getting DBPath _ db: " + dbName + " Path: " + String.valueOf(getDatabasePath(dbName)));
return String.valueOf(getDatabasePath(dbName));
}
public static void sendMessage(FrameWork frameWork, NativeCommand command) {
Message msg = Message.obtain(null, 1, command);
frameWork.mainHandler.sendMessage(msg);
}
public void addToPrefs(String key, String value){
editor.putString(key, value);
editor.apply();
}
public String getFromPrefs(String key){
return prefs.getString(key, "");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
// showUserSettings();
break;
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Locale locale = getResources().getConfiguration().locale;
if (locale.getLanguage() != defaultLocale.getLanguage()) {
System.out.println("Language change spotted");
System.out.println("Previous locale: " + defaultLocale.getCountry() + " Language: " + defaultLocale.getLanguage());
System.out.println("New locale: " + locale.getCountry() + " Language: " + locale.getLanguage());
languageChanged(System.currentTimeMillis() / 1000.0, appId, locale.getLanguage());
}
// super.onConfigurationChanged(newConfig);
System.out.println("onConfigChange");
boolean isLandscape = false;
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
System.out.println("Orientation conf portrait");
isLandscape = false;
onResize(System.currentTimeMillis() / 1000.0, screenHeight, screenHeight, currentView);
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
System.out.println("Orientation conf landscape");
isLandscape = true;
onResize(System.currentTimeMillis() / 1000.0, screenHeight, screenHeight, currentView);
}
displayMetrics = setupDisplayMetrics();
super.onConfigurationChanged(newConfig);
for (NativeCommandHandler handler : views.values()){
handler.onScreenOrientationChange(isLandscape);
}
}
public int measureViewLength(View view){
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((int) screenWidth, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
return view.getMeasuredHeight();
}
public int measureViewWidth(View view){
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((int) screenWidth, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
return view.getMeasuredWidth();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
System.out.println("onSaveInstanceState");
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
System.out.println("onRestoreInstanceState");
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onResume(){
super.onResume();
nativeOnResume(System.currentTimeMillis() / 1000.0, appId);
}
@Override
public void onPause(){
super.onPause();
nativeOnPause(System.currentTimeMillis() / 1000.0, appId);
}
@Override
public void onStop(){
super.onStop();
nativeOnStop(System.currentTimeMillis() / 1000.0, appId);
}
@Override
public void onStart(){
super.onStart();
nativeOnStart(System.currentTimeMillis() / 1000.0, appId);
}
@Override
public void onLowMemory(){
Log.d("Framework", "Low Memory Detected");
super.onLowMemory();
memoryWarning(System.currentTimeMillis() / 1000.0, appId);
}
@Override
public void onDestroy() {
System.out.println("onDestroy called");
// It's important to destroy native before the activity, since
// native stuff may wish to use Framework functionality in their
// destructors
nativeOnDestroy(System.currentTimeMillis() / 1000.0, appId);
if (purchaseHelper != null) {
try {
purchaseHelper.dispose();
} catch (IabAsyncInProgressException e) {
e.printStackTrace();
System.out.println("Error in disposing purchaseHelper with message: " + e.getMessage());
}
}
purchaseHelper = null;
super.onDestroy();
}
public IabHelper getPurchaseHelper() {
return purchaseHelper;
}
//Load JNI. Framework references to make file.
static {
System.loadLibrary("framework");
}
public static void handleNativeException(Throwable error){
error.printStackTrace();
System.out.println("error cause: " + error.getCause());
}
public Charset getCharset(){
return utf8_charset;
}
@Override
public int getElementId() {
return appId;
}
@Override
public void addChild(View view) {
System.out.println("FrameWork couldn't handle addChild");
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FrameWork couldn't handle addOption");
}
@Override
public void setValue(String v) {
System.out.println("FrameWork couldn't handle addOption");
}
@Override
public void setValue(int v) {
System.out.println("FrameWork couldn't handle addOption");
}
@Override
public void setViewEnabled(Boolean enabled) {
System.out.println("FrameWork couldn't handle addOption");
}
@Override
public void setStyle(String key, String value) { }
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
}
|
package gcm.gui;
import gcm.parser.GCMFile;
import gcm.util.GlobalConstants;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import main.Gui;
/**
* @author jason
*
*/
public class GridPanel extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private static GridPanel panel;
private GCMFile gcm;
private GCM2SBMLEditor gcm2sbml;
private JRadioButton spatial, cellPop;
private JComboBox componentChooser;
private ArrayList<String> componentList, compartmentList;
private static boolean built;
private boolean gridSpatial; //true if grid is spatial; false if grid is cell population
/**
* constructor that sets the gcm2sbmleditor and gcmfile
* calls the buildPanel method
* builds component and compartment lists
*
* @param gcm2sbml the gui/editor
* @param gcm the gcm file to work with
*/
private GridPanel(GCM2SBMLEditor gcm2sbml, GCMFile gcm, boolean editMode) {
//call the JPanel constructor to make this a border layout panel
super(new BorderLayout());
this.gcm = gcm;
this.gcm2sbml = gcm2sbml;
//editMode is false means creating a grid
if (!editMode) {
//component list is the gcms that can be added to a spatial grid
//but components that aren't compartments are ineligible for
//being added to a cell population
componentList = gcm2sbml.getComponentsList();
componentList.add("none");
compartmentList = new ArrayList<String>();
//find all of the comPARTments, which will be available
//to add to the cell population
for(String comp : gcm2sbml.getComponentsList()) {
GCMFile compGCM = new GCMFile(gcm.getPath());
compGCM.load(gcm.getPath() + File.separator + comp);
if (compGCM.getIsWithinCompartment())
compartmentList.add(comp);
}
compartmentList.add("none");
built = buildPanel() == true ? true : false;
}
//editMode is true means editing a grid
else {
}
}
/**
* static method to create a cell population panel
*
* @return if a population is being built or not
*/
public static boolean showGridPanel(GCM2SBMLEditor gcm2sbml, GCMFile gcm, boolean editMode) {
panel = new GridPanel(gcm2sbml, gcm, editMode);
return built;
}
/**
* does the actual panel building
*
* @return if a population is to be created
*/
private boolean buildPanel() {
JPanel tilePanel;
JPanel compPanel;
JTextField rowsChooser;
JTextField columnsChooser;
//panel that contains grid size options
tilePanel = new JPanel(new GridLayout(3, 2));
this.add(tilePanel, BorderLayout.SOUTH);
spatial = new JRadioButton("Spatial");
spatial.addActionListener(this);
spatial.setActionCommand("spatial");
cellPop = new JRadioButton("Cell Pop.");
cellPop.addActionListener(this);
cellPop.setActionCommand("cellPop");
cellPop.setSelected(true);
tilePanel.add(spatial);
tilePanel.add(cellPop, BorderLayout.LINE_START);
tilePanel.add(new JLabel("Rows"));
rowsChooser = new JTextField("3");
tilePanel.add(rowsChooser);
//options that go in the tiling panel
tilePanel.add(new JLabel("Columns"));
columnsChooser = new JTextField("3");
tilePanel.add(columnsChooser);
//create a panel for the selection of components to add to the cells
compPanel = new JPanel(new GridLayout(2,1));
compPanel.add(new JLabel("Choose a gcm to add to the grid"));
componentChooser = new JComboBox(compartmentList.toArray());
compPanel.add(componentChooser);
this.add(compPanel, BorderLayout.NORTH);
String[] options = {GlobalConstants.OK, GlobalConstants.CANCEL};
int okCancel = JOptionPane.showOptionDialog(Gui.frame, this, "Create a Grid",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
//if the user clicks "ok" on the panel
if (okCancel == JOptionPane.OK_OPTION) {
int rowCount = 0, colCount = 0;
//try to get the number of rows and columns from the user
try{
rowCount = Integer.parseInt(rowsChooser.getText());
colCount = Integer.parseInt(columnsChooser.getText());
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame,
"A number you entered could not be parsed.",
"Invalid number format",
JOptionPane.ERROR_MESSAGE);
//return false;
}
//filename of the component
String compGCM = (String)componentChooser.getSelectedItem();
//add components to the gcm
setGCMComponents(rowCount, colCount, compGCM);
//create the grid with these components
Grid grid = gcm.getGrid();
grid.createGrid(rowCount, colCount, gcm.getComponents());
grid.setGridSpatial(gridSpatial);
return true;
}
else return false;
}
/**
*
*
* @param rows number of rows of cells/components
* @param cols number of columns of cells/components
* @param compGCM name of the component's underlying gcm file
*/
private void setGCMComponents(int rows, int cols, String compGCM) {
float padding = gcm.getGrid().getPadding();
float width = GlobalConstants.DEFAULT_COMPONENT_WIDTH;
float height = GlobalConstants.DEFAULT_COMPONENT_HEIGHT;
//sets properties for all of the new components
//then adds a new component to the gcm with these properties
for (int row=0; row < rows; ++row){
for (int col=0; col < cols; ++col){
//don't put blank components onto the grid or gcm
if (!compGCM.equals("none")) {
//make a new properties field with all of the new component's properties
Properties properties = new Properties();
properties.put("gcm", compGCM); //comp is the name of the gcm that the component contains
properties.setProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_WIDTH));
properties.setProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_HEIGHT));
properties.setProperty("graphx", String.valueOf(col * (width + padding) + padding));
properties.setProperty("graphy", String.valueOf(row * (height + padding) + padding));
properties.setProperty("row", String.valueOf(row+1));
properties.setProperty("col", String.valueOf(col+1));
GCMFile compGCMFile = new GCMFile(gcm.getPath());
compGCMFile.load(gcm.getPath() + File.separator + compGCM);
//set the correct compartment status
if (compGCMFile.getIsWithinCompartment())
properties.setProperty("compartment","true");
else properties.setProperty("compartment","false");
gcm.addComponent(null, properties);
}
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand() == "spatial") {
gridSpatial = true;
//only one or the other can be selected
spatial.setSelected(true);
cellPop.setSelected(false);
//change the available components to be all components
componentChooser.removeAllItems();
for (String comp : componentList)
componentChooser.addItem(comp);
}
else if (event.getActionCommand() == "cellPop") {
gridSpatial = false;
//only one or the other can be selected
spatial.setSelected(false);
cellPop.setSelected(true);
//change the available components to be compartments only
componentChooser.removeAllItems();
for (String comp : compartmentList)
componentChooser.addItem(comp);
}
}
}
|
package mod._dbaccess;
import com.sun.star.beans.Property;
import java.io.PrintWriter;
import java.util.Vector;
import lib.Status;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.DBTools;
import util.utils;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sdb.CommandType;
import com.sun.star.sdb.ParametersRequest;
import com.sun.star.sdb.RowChangeEvent;
import com.sun.star.sdb.XInteractionSupplyParameters;
import com.sun.star.sdbc.SQLException;
import com.sun.star.sdbc.XConnection;
import com.sun.star.sdbc.XResultSet;
import com.sun.star.sdbc.XResultSetUpdate;
import com.sun.star.sdbc.XRow;
import com.sun.star.sdbc.XRowSet;
import com.sun.star.sdbc.XRowUpdate;
import com.sun.star.task.XInteractionAbort;
import com.sun.star.task.XInteractionContinuation;
import com.sun.star.task.XInteractionRequest;
import com.sun.star.ucb.AuthenticationRequest;
import com.sun.star.ucb.XSimpleFileAccess;
import com.sun.star.uno.Any;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import ifc.sdb._XCompletedExecution;
/**
* Test for object which is represented by service
* <code>com.sun.star.sdb.DataSource</code>. <p>
*
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::sdbc::RowSet</code></li>
* <li> <code>com::sun::star::sdbcx::XRowLocate</code></li>
* <li> <code>com::sun::star::sdbc::XResultSetUpdate</code></li>
* <li> <code>com::sun::star::util::XCancellable</code></li>
* <li> <code>com::sun::star::sdbc::XParameters</code></li>
* <li> <code>com::sun::star::sdbc::XResultSetMetaDataSupplier</code></li>
* <li> <code>com::sun::star::sdbcx::XDeleteRows</code></li>
* <li> <code>com::sun::star::sdbc::XCloseable</code></li>
* <li> <code>com::sun::star::sdbcx::XColumnsSupplier</code></li>
* <li> <code>com::sun::star::sdb::XResultSetAccess</code></li>
* <li> <code>com::sun::star::sdbc::XResultSet</code></li>
* <li> <code>com::sun::star::sdbc::XColumnLocate</code></li>
* <li> <code>com::sun::star::sdbc::XRowSet</code></li>
* <li> <code>com::sun::star::sdb::RowSet</code></li>
* <li> <code>com::sun::star::sdbc::XRowUpdate</code></li>
* <li> <code>com::sun::star::sdb::XRowSetApproveBroadcaster</code></li>
* <li> <code>com::sun::star::beans::XPropertySet</code></li>
* <li> <code>com::sun::star::sdbc::XRow</code></li>
* <li> <code>com::sun::star::sdbc::XWarningsSupplier</code></li>
* <li> <code>com::sun::star::lang::XComponent</code></li>
* <li> <code>com::sun::star::sdbcx::ResultSet</code></li>
* <li> <code>com::sun::star::sdbc::ResultSet</code></li>
* </ul> <p>
* The following files used by this test :
* <ul>
* <li><b> TestDB/TestDB.dbf </b> : the database file with some
* predefined fields described in <code>util.DBTools</code>.
* The copy of this file is always made in temp directory for
* testing purposes.</li>
* </ul> <p>
* The following parameters in ini-file used by this test:
* <ul>
* <li><code>test.db.url</code> - URL to MySQL database.
* For example: <code>mysql://mercury:3306/api_current</code></li>
* <li><code>test.db.user</code> - user for MySQL database</li>
* <li><code>test.db.password</code> - password for MySQL database</li>
* </ul><p>
*
* @see com.sun.star.sdbc.RowSet
* @see com.sun.star.sdbcx.XRowLocate
* @see com.sun.star.sdbc.XResultSetUpdate
* @see com.sun.star.util.XCancellable
* @see com.sun.star.sdbc.XParameters
* @see com.sun.star.sdbc.XResultSetMetaDataSupplier
* @see com.sun.star.sdbcx.XDeleteRows
* @see com.sun.star.sdbc.XCloseable
* @see com.sun.star.sdbcx.XColumnsSupplier
* @see com.sun.star.sdb.XResultSetAccess
* @see com.sun.star.sdbc.XResultSet
* @see com.sun.star.sdbc.XColumnLocate
* @see com.sun.star.sdbc.XRowSet
* @see com.sun.star.sdb.RowSet
* @see com.sun.star.sdbc.XRowUpdate
* @see com.sun.star.sdb.XRowSetApproveBroadcaster
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.sdbc.XRow
* @see com.sun.star.sdbc.XWarningsSupplier
* @see com.sun.star.lang.XComponent
* @see com.sun.star.sdbcx.ResultSet
* @see com.sun.star.sdbc.ResultSet
* @see ifc.sdbc._RowSet
* @see ifc.sdbcx._XRowLocate
* @see ifc.sdbc._XResultSetUpdate
* @see ifc.util._XCancellable
* @see ifc.sdbc._XParameters
* @see ifc.sdbc._XResultSetMetaDataSupplier
* @see ifc.sdbcx._XDeleteRows
* @see ifc.sdbc._XCloseable
* @see ifc.sdbcx._XColumnsSupplier
* @see ifc.sdb._XResultSetAccess
* @see ifc.sdbc._XResultSet
* @see ifc.sdbc._XColumnLocate
* @see ifc.sdbc._XRowSet
* @see ifc.sdb._RowSet
* @see ifc.sdbc._XRowUpdate
* @see ifc.sdb._XRowSetApproveBroadcaster
* @see ifc.beans._XPropertySet
* @see ifc.sdbc._XRow
* @see ifc.sdbc._XWarningsSupplier
* @see ifc.lang._XComponent
* @see ifc.sdbcx._ResultSet
* @see ifc.sdbc._ResultSet
*/
public class ORowSet extends TestCase {
private static int uniqueSuffix = 0 ;
private DBTools dbTools = null ;
private static String origDB = null ;
private PrintWriter log = null ;
private static String tmpDir = null ;
String tableName = null;
DBTools.DataSourceInfo srcInf = null;
boolean isMySQLDB = false;
protected final static String dbSourceName = "ORowSetDataSource";
public XConnection conn = null;
Object dbSrc = null;
String aFile = "";
/**
* Initializes some class fields. Then creates DataSource, which serves
* as a single source for all tables created in the test.
* This DataSource then registered in the global
* <code>DatabaseContext</code> service. This data source's URL
* points to SOffice temp directory where tables are copied from
* <code>TestDocuments</code> directory on every environment
* creation.
* To create DataSource for MySQL database next parameters required
* in ini-file:
* <ul>
* <li><code>test.db.url</code> - URL to MySQL database.
* For example: <code>mysql://mercury:3306/api_current</code></li>
* <li><code>test.db.user</code> - user for MySQL database</li>
* <li><code>test.db.password</code> - password for MySQL database</li>
* </ul>
*
* @throws StatusException if DataSource can not be created or
* registered.
*/
protected void initialize ( TestParameters Param, PrintWriter log)
throws StatusException {
this.log = log ;
tmpDir = (String) Param.get("TMPURL") ;
tmpDir = utils.getOfficeTemp((XMultiServiceFactory)Param.getMSF());
origDB = util.utils.getFullTestDocName("TestDB/testDB.dbf");
dbTools = new DBTools((XMultiServiceFactory)Param.getMSF()) ;
// creating DataSource and registering it in DatabaseContext
String dbURL = (String) Param.get("test.db.url");
String dbUser = (String) Param.get("test.db.user");
String dbPassword = (String) Param.get("test.db.password");
log.println("Creating and registering DataSource ...");
srcInf = dbTools.newDataSourceInfo();
if (dbURL != null && dbUser != null && dbPassword != null) {
isMySQLDB = true;
log.println("dbURL = " + dbURL);
log.println("dbUSER = " + dbUser);
log.println("dbPASSWORD = " + dbPassword);
//DataSource for mysql db
try {
tableName = "soffice_test_table";
srcInf.URL = "jdbc:" + dbURL;
srcInf.IsPasswordRequired = new Boolean(true);
srcInf.Password = dbPassword;
srcInf.User = dbUser;
PropertyValue[] propInfo = new PropertyValue[1];
propInfo[0] = new PropertyValue();
propInfo[0].Name = "JavaDriverClass";
propInfo[0].Value = "org.gjt.mm.mysql.Driver";
srcInf.Info = propInfo;
dbSrc = srcInf.getDataSourceService() ;
if (uniqueSuffix < 1)
dbTools.reRegisterDB(dbSourceName, dbSrc);
XMultiServiceFactory xMSF = (XMultiServiceFactory)Param.getMSF ();
aFile = utils.getOfficeTemp (xMSF)+dbSourceName+".odb";
} catch (com.sun.star.uno.Exception e) {
log.println("Error while object test initialization :") ;
e.printStackTrace(log) ;
throw new StatusException("Error while object test" +
" initialization", e);
}
} else {
try {
srcInf.URL = "sdbc:dbase:" + DBTools.dirToUrl(tmpDir) ;
dbSrc = srcInf.getDataSourceService() ;
if (uniqueSuffix < 1)
dbTools.reRegisterDB(dbSourceName, dbSrc) ;
} catch (com.sun.star.uno.Exception e) {
log.println("Error while object test initialization :") ;
e.printStackTrace(log) ;
throw new
StatusException("Error while object test initialization",e) ;
}
}
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* The database (DBF) file is copied from test document directory
* into SOffice temp dir with unique name for each enviroment
* creation. If the file cann't be copied (is not released)
* then another unique name is used (file name suffix incremented
* by 1).<p>
*
* <code>com.sun.star.sdb.RowSet</code> service created and its
* source is all rows from the current copy of the table. Then
* row set command ("select all rows from a table") is executed
* and cursor is positioned to the first row. <p>
*
* Object relations created :
* <ul>
* <li> <code>'ORowSet.Connection'</code> for
* internal component test usage. Is used for
* closing connection when cleaning up environment. </li>
* <li> <code>'XRowSetApproveBroadcaster.ApproveChecker'</code> for
* {@link ifc.sdb._XRowSetApproveBroadcaster} interface
* implementation which made actions required </li>
* <li> <code>'CurrentRowData'</code> for
* {@link ifc.sdbc._XRow}, {@link ifc.sdbc._XRowUpdate} :
* exports types and values of the current row data.</li>
* <li> <code>'XColumnLocate.ColumnName'</code> for
* {@link ifc.sdbc._XColumnLocate} :
* the name of the first column of the table.</li>
* <li> <code>'XParameters.ParamValues'</code> for
* {@link ifc.sdbc._XParameters} :
* Collection of parameter types presented in the query. </li>
* <li> <code>'XRowUpdate.XRow'</code> for
* {@link ifc.sdbc._XRowUpdate} :
* <code>XRow</code> interface of the current component.</li>
* <li> <code>'XResultSetUpdate.UpdateTester'</code> for
* {@link ifc.sdbc._XResultSetUpdate} </li>
* </ul>
*
* @see com.sun.star.sdb.DatabaseContext
* @see com.sun.star.sdb.DataSource
*/
protected TestEnvironment createTestEnvironment(TestParameters Param,
PrintWriter log) {
XInterface oObj = null;
Object oInterface = null;
XMultiServiceFactory xMSF = null ;
uniqueSuffix++;
boolean envCreatedOK = false ;
//initialize test table
if (isMySQLDB) {
try {
dbTools.initTestTableUsingJDBC(tableName, srcInf);
} catch(java.sql.SQLException e) {
e.printStackTrace(log);
throw new StatusException(Status.failed("Couldn't " +
" init test table. SQLException..."));
} catch(java.lang.ClassNotFoundException e) {
throw new StatusException(Status.failed("Couldn't " +
"register mysql driver"));
}
} else {
String oldF = null ;
String newF = null ;
do {
tableName = "ORowSet_tmp" + uniqueSuffix ;
oldF = utils.getFullURL(origDB);
newF = utils.getOfficeTemp((XMultiServiceFactory)Param.getMSF())+tableName+".dbf";
} while (!utils.overwriteFile((XMultiServiceFactory)Param.getMSF(),oldF,newF) &&
uniqueSuffix++ < 50);
}
XConnection connection = null ;
try {
xMSF = (XMultiServiceFactory)Param.getMSF();
Object oRowSet = xMSF.createInstance("com.sun.star.sdb.RowSet") ;
XPropertySet xSetProp = (XPropertySet) UnoRuntime.queryInterface
(XPropertySet.class, oRowSet) ;
log.println("Trying to open: " + tableName);
xSetProp.setPropertyValue("DataSourceName", dbSourceName) ;
xSetProp.setPropertyValue("Command", tableName) ;
xSetProp.setPropertyValue("CommandType",
new Integer(CommandType.TABLE)) ;
com.sun.star.sdbc.XRowSet xORowSet = (com.sun.star.sdbc.XRowSet)
UnoRuntime.queryInterface(com.sun.star.sdbc.XRowSet.class,
oRowSet) ;
xORowSet.execute() ;
connection = null;
try {
connection = (XConnection) AnyConverter.toObject(
new Type(XConnection.class),
xSetProp.getPropertyValue("ActiveConnection"));
} catch (com.sun.star.lang.IllegalArgumentException iae) {
throw new StatusException("couldn't convert Any",iae);
}
oInterface = oRowSet ;
XResultSet xRes = (XResultSet) UnoRuntime.queryInterface
(XResultSet.class, oRowSet) ;
xRes.first() ;
if (oInterface == null) {
log.println("Service wasn't created") ;
throw new StatusException("Service wasn't created",
new NullPointerException()) ;
}
oObj = (XInterface) oInterface;
log.println( " creating a new environment for object" );
TestEnvironment tEnv = new TestEnvironment( oObj );
// Adding relations for disposing object
tEnv.addObjRelation("ORowSet.Connection", connection) ;
this.conn = (XConnection) tEnv.getObjRelation("ORowSet.Connection");
// Adding obj relation for XRowSetApproveBroadcaster test
{
final XResultSet xResSet = (XResultSet)
UnoRuntime.queryInterface(XResultSet.class, oObj) ;
final XResultSetUpdate xResSetUpdate = (XResultSetUpdate)
UnoRuntime.queryInterface(XResultSetUpdate.class, oObj) ;
final XRowSet xRowSet = (XRowSet) UnoRuntime.queryInterface
(XRowSet.class, oObj) ;
final XRowUpdate xRowUpdate = (XRowUpdate)
UnoRuntime.queryInterface(XRowUpdate.class, oObj) ;
final PrintWriter logF = log ;
tEnv.addObjRelation("XRowSetApproveBroadcaster.ApproveChecker",
new ifc.sdb._XRowSetApproveBroadcaster.RowSetApproveChecker() {
public void moveCursor() {
try {
xResSet.beforeFirst() ;
xResSet.afterLast() ;
xResSet.first() ;
} catch (com.sun.star.sdbc.SQLException e) {
logF.println("### _XRowSetApproveBroadcaster." +
"RowSetApproveChecker.moveCursor() :") ;
e.printStackTrace(logF) ;
}
}
public RowChangeEvent changeRow() {
try {
xResSet.first() ;
xRowUpdate.updateString(1, "ORowSetTest2") ;
xResSetUpdate.updateRow() ;
} catch (com.sun.star.sdbc.SQLException e) {
logF.println("### _XRowSetApproveBroadcaster." +
"RowSetApproveChecker.changeRow() :") ;
e.printStackTrace(logF) ;
}
RowChangeEvent ev = new RowChangeEvent() ;
ev.Action = com.sun.star.sdb.RowChangeAction.UPDATE ;
ev.Rows = 1 ;
return ev ;
}
public void changeRowSet() {
try {
xRowSet.execute() ;
xResSet.first() ;
} catch (com.sun.star.sdbc.SQLException e) {
logF.println("### _XRowSetApproveBroadcaster."+
"RowSetApproveChecker.changeRowSet() :") ;
e.printStackTrace(logF) ;
}
}
}) ;
}
// Adding relations for XRow as a Vector with all data
// of current row of RowSet.
Vector rowData = new Vector() ;
for (int i = 0; i < DBTools.TST_TABLE_VALUES[0].length; i++) {
rowData.add(DBTools.TST_TABLE_VALUES[0][i]) ;
}
// here XRef must be added
// here XBlob must be added
// here XClob must be added
// here XArray must be added
tEnv.addObjRelation("CurrentRowData", rowData) ;
// Adding relation for XColumnLocate ifc test
tEnv.addObjRelation("XColumnLocate.ColumnName",
DBTools.TST_STRING_F) ;
// Adding relation for XCompletedExecution
tEnv.addObjRelation("InteractionHandlerChecker", new InteractionHandlerImpl());
XPropertySet xProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oObj) ;
try {
xProp.setPropertyValue("DataSourceName", dbSourceName) ;
if(isMySQLDB) {
xProp.setPropertyValue("Command", "SELECT Column0 FROM soffice_test_table WHERE ( ( Column0 = :param1 ) )");
}
else {
xProp.setPropertyValue("Command", "SELECT \"_TEXT\" FROM \"ORowSet_tmp" + uniqueSuffix + "\" WHERE ( ( \"_TEXT\" = :param1 ) )");
}
xProp.setPropertyValue("CommandType", new Integer(CommandType.COMMAND)) ;
}
catch(Exception e) {
}
// Adding relation for XParameters ifc test
Vector params = new Vector() ;
tEnv.addObjRelation("XParameters.ParamValues", params) ;
// Adding relation for XRowUpdate
XRow row = (XRow) UnoRuntime.queryInterface (XRow.class, oObj) ;
tEnv.addObjRelation("XRowUpdate.XRow", row) ;
// Adding relation for XResultSetUpdate
{
final XResultSet xResSet = (XResultSet)
UnoRuntime.queryInterface(XResultSet.class, oObj) ;
final XRowUpdate xRowUpdate = (XRowUpdate)
UnoRuntime.queryInterface(XRowUpdate.class, oObj) ;
final XRow xRow = (XRow) UnoRuntime.queryInterface
(XRow.class, oObj) ;
tEnv.addObjRelation("XResultSetUpdate.UpdateTester",
new ifc.sdbc._XResultSetUpdate.UpdateTester() {
String lastUpdate = null ;
public int rowCount() throws SQLException {
int prevPos = xResSet.getRow() ;
xResSet.last() ;
int count = xResSet.getRow() ;
xResSet.absolute(prevPos) ;
return count ;
}
public void update() throws SQLException {
lastUpdate = xRow.getString(1) ;
lastUpdate += "_" ;
xRowUpdate.updateString(1, lastUpdate) ;
}
public boolean wasUpdated() throws SQLException {
String getStr = xRow.getString(1) ;
return lastUpdate.equals(getStr) ;
}
public int currentRow() throws SQLException {
return xResSet.getRow() ;
}
}) ;
}
envCreatedOK = true ;
return tEnv;
} catch(com.sun.star.uno.Exception e) {
log.println("Can't create object" );
e.printStackTrace(log) ;
try {
connection.close() ;
} catch(Exception ex) {}
throw new StatusException("Can't create object", e) ;
} finally {
if (!envCreatedOK) {
try {
connection.close() ;
} catch(Exception ex) {}
}
}
} // finish method getTestEnvironment
/**
* Closes connection of <code>RowSet</code> instance created.
*/
protected void cleanup( TestParameters Param, PrintWriter log) {
try {
conn.close() ;
XMultiServiceFactory xMSF = (XMultiServiceFactory)Param.getMSF ();
Object sfa = xMSF.createInstance ("com.sun.star.comp.ucb.SimpleFileAccess");
XSimpleFileAccess xSFA = (XSimpleFileAccess) UnoRuntime.queryInterface (XSimpleFileAccess.class, sfa);
log.println ("deleting database file");
xSFA.kill (aFile);
log.println ("Could delete file "+aFile+": "+!xSFA.exists (aFile));
} catch (com.sun.star.uno.Exception e) {
log.println("Can't close the connection") ;
e.printStackTrace(log) ;
} catch (com.sun.star.lang.DisposedException e) {
log.println("Connection was already closed. It's OK.") ;
}
// try {
// dbTools.revokeDB(dbSourceName) ;
// XComponent db = (XComponent) UnoRuntime.queryInterface(XComponent.class,dbSrc);
// db.dispose();
// } catch (com.sun.star.uno.Exception e) {
// log.println("Error while object test cleaning up :") ;
// e.printStackTrace(log) ;
// throw new StatusException("Error while object test cleaning up",e) ;
}
/**
* Implementation of interface _XCompletedExecution.CheckInteractionHandler
* for the XCompletedExecution test
* @see ifc.sdb._XCompletedExecution
*/
public class InteractionHandlerImpl implements _XCompletedExecution.CheckInteractionHandler {
private boolean handlerWasUsed = false;
private PrintWriter log = new PrintWriter(System.out);
public boolean checkInteractionHandler() {
return handlerWasUsed;
}
public void handle(XInteractionRequest xInteractionRequest) {
log.println("### _XCompletedExecution.InteractionHandlerImpl: handle called.");
ParametersRequest req = null;
boolean abort = false;
Object o = xInteractionRequest.getRequest();
if (o instanceof ParametersRequest) {
req = (ParametersRequest)o;
}
else if (o instanceof AuthenticationRequest) {
log.println("### The request in XCompletedExecution is of type 'AuthenticationRequest'");
log.println("### This is not implemented in ORowSet.InteractionHandlerImpl test -> abort.");
abort = true;
}
else {
log.println("### Unknown request:" + o.toString());
log.println("### This is not implemented in ORowSet.InteractionHandlerImpl test -> abort.");
abort = true;
}
XInteractionContinuation[]xCont = xInteractionRequest.getContinuations();
XInteractionSupplyParameters xParamCallback = null;
for(int i=0; i<xCont.length; i++) {
if (abort) {
XInteractionAbort xAbort = null;
xAbort = (XInteractionAbort)UnoRuntime.queryInterface(XInteractionAbort.class, xCont[i]);
if (xAbort != null)
xAbort.select();
return;
}
else {
xParamCallback = (XInteractionSupplyParameters)
UnoRuntime.queryInterface(XInteractionSupplyParameters.class, xCont[i]);
if (xParamCallback != null)
break;
}
}
if (xParamCallback != null) {
log.println("### _XCompletedExecution.InteractionHandlerImpl: supplying parameters.");
handlerWasUsed = true;
PropertyValue[] prop = new PropertyValue[1];
prop[0] = new PropertyValue();
prop[0].Name = "param1";
prop[0].Value = "Hi.";
xParamCallback.setParameters(prop);
xParamCallback.select();
}
else { // we should never reach this: abort has to be true first.
log.println("### _XCompletedExecution.InteractionHandlerImpl: Got no " +
"'XInteractionSupplyParameters' and no 'XInteractionAbort'.");
}
}
public void setLog(PrintWriter log) {
this.log = log;
}
}
}
|
package org.TexasTorque.TorqueLib.util;
import com.sun.squawk.io.BufferedReader;
import com.sun.squawk.microedition.io.*;
import edu.wpi.first.wpilibj.Watchdog;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.microedition.io.*;
public class Parameters
{
private static Parameters instance;
private Watchdog watchdog;
private Hashtable map;
private String fileName;
private String filePath;
private FileConnection fileConnection = null;
private BufferedReader fileIO = null;
public synchronized static Parameters getInstance()
{
return (instance == null) ? instance = new Parameters("params.txt") : instance;
}
public Parameters(String fileNm)
{
watchdog = Watchdog.getInstance();
map = new Hashtable();
filePath = "file:///ni-rt/startup/";
fileName = fileNm;
}
public void load()
{
try
{
clearList();
fileConnection = (FileConnection)Connector.open(filePath + fileName);
if(fileConnection.exists())
{
fileIO = new BufferedReader(new InputStreamReader(fileConnection.openInputStream()));
String line;
int index;
while((line = fileIO.readLine()) != null)
{
watchdog.feed();
map.put(line.substring(0, index = line.indexOf(" ")), line.substring(index + 1));
}
System.err.println("Parameters file: " + fileName + " successfully loaded.");
fileConnection.close();
}
else
{
System.err.println("Could not load parameters file: " + fileName);
}
}
catch(IOException e)
{
System.err.println("IOException caught trying to read in parameters file.");
}
}
public synchronized int getAsInt(String name, int dflt)
{
String value = (String)map.get(name);
return (value == null) ? dflt : (int)Double.parseDouble(value);
}
public synchronized double getAsDouble(String name, double dflt)
{
String value = (String)map.get(name);
return (value == null) ? dflt : Double.parseDouble(value);
}
public synchronized boolean getAsBoolean(String name, boolean dflt)
{
String value = (String)map.get(name);
return (value == null) ? dflt : Integer.parseInt(value) != 0;
}
private void clearList()
{
map.clear();
}
}
|
package org.appwork.storage.config;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import org.appwork.shutdown.ShutdownController;
import org.appwork.shutdown.ShutdownEvent;
import org.appwork.storage.InvalidTypeException;
import org.appwork.storage.JSonStorage;
import org.appwork.storage.JsonKeyValueStorage;
import org.appwork.storage.StorageException;
import org.appwork.storage.config.annotations.CryptedStorage;
/**
* @author thomas
* @param <T>
*
*/
public class StorageHandler<T extends ConfigInterface> implements InvocationHandler {
private final Class<T> configInterface;
private HashMap<Method, MethodHandler> getterMap;
private final JsonKeyValueStorage primitiveStorage;
private boolean crypted;
private byte[] key = JSonStorage.KEY;
private File path;
private ConfigInterfaceEventSender<T> eventSender;
/**
* @param name
* @param configInterface
*/
public StorageHandler(final File name, final Class<T> configInterface) {
this.configInterface = configInterface;
this.eventSender = new ConfigInterfaceEventSender<T>();
this.path = name;
final CryptedStorage crypted = configInterface.getAnnotation(CryptedStorage.class);
if (crypted != null) {
this.crypted = true;
if (crypted.key() != null) {
this.primitiveStorage = new JsonKeyValueStorage(new File(this.path.getAbsolutePath() + ".ejs"), false, crypted.key());
this.key = crypted.key();
if (this.key.length != JSonStorage.KEY.length) { throw new InterfaceParseException("Crypt key for " + configInterface + " is invalid"); }
} else {
this.primitiveStorage = new JsonKeyValueStorage(new File(this.path.getAbsolutePath() + ".ejs"), false, this.key = JSonStorage.KEY);
}
} else {
this.crypted = false;
this.primitiveStorage = new JsonKeyValueStorage(new File(this.path.getAbsolutePath() + ".json"), true);
}
try {
this.parseInterface();
} catch (final Exception e) {
throw new InterfaceParseException(e);
}
ShutdownController.getInstance().addShutdownEvent(new ShutdownEvent() {
@Override
public void run() {
StorageHandler.this.primitiveStorage.save();
}
@Override
public String toString() {
return "Save " + StorageHandler.this.path + "[" + configInterface.getName() + "]";
}
});
}
public byte[] getKey() {
return this.key;
}
/**
* @return
*/
public File getPath() {
return this.path;
}
@SuppressWarnings("unchecked")
public Object invoke(final Object arg0, final Method m, final Object[] parameter) throws Throwable {
if (m.getName().equals("toString")) {
return this.toString();
} else if (m.getName().equals("addListener")) {
this.eventSender.addListener((ConfigEventListener) parameter[0]);
return null;
} else if (m.getName().equals("removeListener")) {
this.eventSender.removeListener((ConfigEventListener) parameter[0]);
return null;
} else {
final MethodHandler handler = this.getterMap.get(m);
if (handler.isGetter()) {
if (handler.isPrimitive()) {
if (handler.getRawClass() == Boolean.class || handler.getRawClass() == boolean.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultBoolean());
} else if (handler.getRawClass() == Long.class || handler.getRawClass() == long.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultLong());
} else if (handler.getRawClass() == Integer.class || handler.getRawClass() == int.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultInteger());
} else if (handler.getRawClass() == Float.class || handler.getRawClass() == float.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultFloat());
} else if (handler.getRawClass() == Byte.class || handler.getRawClass() == byte.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultByte());
} else if (handler.getRawClass() == String.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultString());
// } else if (handler.getRawClass() == String[].class) {
// return this.primitiveStorage.get(handler.getKey(),
// handler.getDefaultStringArray());
} else if (handler.getRawClass().isEnum()) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultEnum());
} else if (handler.getRawClass() == Double.class | handler.getRawClass() == double.class) {
return this.primitiveStorage.get(handler.getKey(), handler.getDefaultDouble());
} else {
throw new StorageException("Invalid datatype: " + handler.getRawClass());
}
} else {
return handler.read();
}
} else {
if (handler.isPrimitive()) {
if (handler.getRawClass() == Boolean.class || handler.getRawClass() == boolean.class) {
this.primitiveStorage.put(handler.getKey(), (Boolean) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == Long.class || handler.getRawClass() == long.class) {
this.primitiveStorage.put(handler.getKey(), (Long) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == Integer.class || handler.getRawClass() == int.class) {
this.primitiveStorage.put(handler.getKey(), (Integer) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == Float.class || handler.getRawClass() == float.class) {
this.primitiveStorage.put(handler.getKey(), (Float) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == Byte.class || handler.getRawClass() == byte.class) {
this.primitiveStorage.put(handler.getKey(), (Byte) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == String.class) {
this.primitiveStorage.put(handler.getKey(), (String) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
// } else if (handler.getRawClass() == String[].class) {
// this.primitiveStorage.put(handler.getKey(),
// (String[]) parameter);
} else if (handler.getRawClass().isEnum()) {
this.primitiveStorage.put(handler.getKey(), (Enum<?>) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else if (handler.getRawClass() == Double.class || handler.getRawClass() == double.class) {
this.primitiveStorage.put(handler.getKey(), (Double) parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
} else {
throw new StorageException("Invalid datatype: " + handler.getRawClass());
}
return null;
} else {
handler.write(parameter[0]);
this.eventSender.fireEvent(new ConfigEvent<T>((T) arg0, ConfigEvent.Types.VALUE_UPDATED, handler.getKey(), parameter[0]));
return null;
}
}
}
}
public boolean isCrypted() {
return this.crypted;
}
private void parseInterface() throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
this.getterMap = new HashMap<Method, MethodHandler>();
final HashMap<String, Method> keyGetterMap = new HashMap<String, Method>();
final HashMap<String, Method> keySetterMap = new HashMap<String, Method>();
String key;
Class<?> clazz = this.configInterface;
while (clazz != null && clazz != ConfigInterface.class) {
for (final Method m : clazz.getDeclaredMethods()) {
if (m.getName().startsWith("get")) {
key = m.getName().substring(3).toLowerCase();
// we do not allow to setters/getters with the same name but
// different cases. this only confuses the user when editing
// the
// later config file
if (keyGetterMap.containsKey(key)) { throw new InterfaceParseException("Key " + key + " Dupe found! " + keyGetterMap.containsKey(key) + "<
if (m.getParameterTypes().length > 0) { throw new InterfaceParseException("Getter " + m + " has parameters."); }
try {
JSonStorage.canStore(m.getGenericReturnType());
} catch (final InvalidTypeException e) {
throw new InterfaceParseException(e);
}
MethodHandler h;
this.getterMap.put(m, h = new MethodHandler(this, MethodHandler.Type.GETTER, key, m, JSonStorage.canStorePrimitive(m.getReturnType())));
keyGetterMap.put(key, m);
final MethodHandler setterhandler = this.getterMap.get(keySetterMap.get(key));
if (setterhandler != null) {
setterhandler.setGetter(h);
h.setSetter(setterhandler);
}
} else if (m.getName().startsWith("is")) {
key = m.getName().substring(2).toLowerCase();
// we do not allow to setters/getters with the same name but
// different cases. this only confuses the user when editing
// the
// later config file
if (keyGetterMap.containsKey(key)) { throw new InterfaceParseException("Key " + key + " Dupe found! " + keyGetterMap.containsKey(key) + "<
if (m.getParameterTypes().length > 0) { throw new InterfaceParseException("Getter " + m + " has parameters."); }
try {
JSonStorage.canStore(m.getGenericReturnType());
} catch (final InvalidTypeException e) {
throw new InterfaceParseException(e);
}
MethodHandler h;
this.getterMap.put(m, h = new MethodHandler(this, MethodHandler.Type.GETTER, key, m, JSonStorage.canStorePrimitive(m.getReturnType())));
keyGetterMap.put(key, m);
final MethodHandler setterhandler = this.getterMap.get(keySetterMap.get(key));
if (setterhandler != null) {
setterhandler.setGetter(h);
h.setSetter(setterhandler);
}
} else if (m.getName().startsWith("set")) {
key = m.getName().substring(3).toLowerCase();
if (keySetterMap.containsKey(key)) { throw new InterfaceParseException("Key " + key + " Dupe found! " + keySetterMap.containsKey(key) + "<
if (m.getParameterTypes().length != 1) { throw new InterfaceParseException("Setter " + m + " has !=1 parameters."); }
if (m.getReturnType() != void.class) { throw new InterfaceParseException("Setter " + m + " has a returntype != void"); }
try {
JSonStorage.canStore(m.getGenericParameterTypes()[0]);
} catch (final InvalidTypeException e) {
throw new InterfaceParseException(e);
}
MethodHandler h;
this.getterMap.put(m, h = new MethodHandler(this, MethodHandler.Type.SETTER, key, m, JSonStorage.canStorePrimitive(m.getParameterTypes()[0])));
keySetterMap.put(key, m);
final MethodHandler getterHandler = this.getterMap.get(keyGetterMap.get(key));
if (getterHandler != null) {
getterHandler.setSetter(h);
h.setGetter(getterHandler);
}
} else {
throw new InterfaceParseException("Only getter and setter allowed:" + m);
}
}
// run down the calss hirarchy to find all methods. getMethods does
// not work, because it only finds public methods
final Class<?>[] interfaces = clazz.getInterfaces();
clazz = interfaces[0];
}
}
@Override
public String toString() {
final HashMap<String, Object> ret = new HashMap<String, Object>();
for (final MethodHandler h : this.getterMap.values()) {
if (h.getType() == MethodHandler.Type.GETTER) {
try {
ret.put(h.getKey(), this.invoke(null, h.getMethod(), new Object[] {}));
} catch (final Throwable e) {
e.printStackTrace();
ret.put(h.getKey(), e.getMessage());
}
}
}
return JSonStorage.toString(ret);
}
/*
* (non-Javadoc)
*
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
* java.lang.reflect.Method, java.lang.Object[])
*/
}
|
package org.bdgp.OpenHiCAMM.Modules;
import static org.bdgp.OpenHiCAMM.Util.where;
import java.awt.Component;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bdgp.OpenHiCAMM.Dao;
import org.bdgp.OpenHiCAMM.Logger;
import org.bdgp.OpenHiCAMM.Util;
import org.bdgp.OpenHiCAMM.ValidationError;
import org.bdgp.OpenHiCAMM.WorkflowRunner;
import org.bdgp.OpenHiCAMM.DB.Config;
import org.bdgp.OpenHiCAMM.DB.Image;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.Slide;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.Task.Status;
import org.bdgp.OpenHiCAMM.DB.TaskConfig;
import org.bdgp.OpenHiCAMM.DB.TaskDispatch;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudio;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.PositionList;
//import org.micromanager.graph.MultiChannelHistograms;
//import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.MMSerializationException;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
//import ij.WindowManager;
import ij.gui.NewImage;
import ij.io.FileSaver;
import ij.process.Blitter;
import ij.process.ImageProcessor;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
public class SlideSurveyor implements Module {
private static final String SURVEY_IMAGE_DIRECTORY_PREFIX = "survey";
WorkflowRunner workflowRunner;
WorkflowModule workflowModule;
@Override
public void initialize(WorkflowRunner workflowRunner, WorkflowModule workflowModule) {
this.workflowRunner = workflowRunner;
this.workflowModule = workflowModule;
// set initial configs
workflowRunner.getModuleConfig().insertOrUpdate(
new ModuleConfig(this.workflowModule.getId(), "canImageSlides", "yes"),
"id", "key");
}
public static boolean compareImages(TaggedImage taggedImage1, TaggedImage taggedImage2) {
if (taggedImage1 == null || taggedImage2 == null)
return false;
if (taggedImage1.pix instanceof byte[] && taggedImage2.pix instanceof byte[]) {
byte[] pix1 = (byte[])taggedImage1.pix;
byte[] pix2 = (byte[])taggedImage2.pix;
if (pix1.length != pix2.length) return false;
for (int i = 0; i < pix1.length; ++i) {
if (pix1[i] != pix2[i]) return false;
}
return true;
}
if (taggedImage1.pix instanceof int[] && taggedImage2.pix instanceof int[]) {
int[] pix1 = (int[])taggedImage1.pix;
int[] pix2 = (int[])taggedImage2.pix;
if (pix1.length != pix2.length) return false;
for (int i = 0; i < pix1.length; ++i) {
if (pix1[i] != pix2[i]) return false;
}
return true;
}
if (taggedImage1.pix instanceof short[] && taggedImage2.pix instanceof short[]) {
short[] pix1 = (short[])taggedImage1.pix;
short[] pix2 = (short[])taggedImage2.pix;
if (pix1.length != pix2.length) return false;
for (int i = 0; i < pix1.length; ++i) {
if (pix1[i] != pix2[i]) return false;
}
return true;
}
if (taggedImage1.pix instanceof float[] && taggedImage2.pix instanceof float[]) {
float[] pix1 = (float[])taggedImage1.pix;
float[] pix2 = (float[])taggedImage2.pix;
if (pix1.length != pix2.length) return false;
for (int i = 0; i < pix1.length; ++i) {
if (pix1[i] != pix2[i]) return false;
}
return true;
}
return false;
}
public static boolean compareImages(ImagePlus im1, ImagePlus im2) {
int[][] im1s = im1.getProcessor().getIntArray();
int[][] im2s = im2.getProcessor().getIntArray();
if (im1s.length != im2s.length) return false;
for (int x=0; x<im1s.length; ++x) {
if (im1s[x].length != im2s[x].length) return false;
for (int y=0; y<im1s[x].length; ++y) {
if (im1s[x][y] != im2s[x][y]) return false;
}
}
return true;
}
@Override
public Status run(Task task, Map<String,Config> conf, final Logger logger) {
Dao<WorkflowModule> wmDao = workflowRunner.getWorkflow();
Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class);
Dao<Image> imageDao = workflowRunner.getWorkflowDb().table(Image.class);
Dao<TaskConfig> taskConfigDao = workflowRunner.getWorkflowDb().table(TaskConfig.class);
logger.fine(String.format("Running task: %s", task));
for (Config c : conf.values()) {
logger.fine(String.format("Using configuration: %s", c));
}
// load the position list
if (!conf.containsKey("posListFile")) {
throw new RuntimeException("Cuold not find configuration for posListFile!");
}
Config posList = conf.get("posListFile");
logger.fine(String.format("%s: Loading position list from file: %s", this.workflowModule.getName(), Util.escape(posList.getValue())));
File posListFile = new File(posList.getValue());
if (!posListFile.exists()) {
throw new RuntimeException("Cannot find position list file "+posListFile.getPath());
}
PositionList positionList = new PositionList();
try { positionList.load(posListFile.getPath()); }
catch (MMException e) {throw new RuntimeException(e);}
// get the survey folder
Config surveyFolderConf = conf.get("surveyFolder");
if (surveyFolderConf == null) throw new RuntimeException(String.format(
"%s: surveyFolder config not found!", task.getName(this.workflowRunner.getWorkflow())));
File surveyFolder = new File(surveyFolderConf.getValue());
logger.fine(String.format("Survey folder: %s", surveyFolder));
surveyFolder.mkdirs();
// load configs
Config slideIdConf = conf.get("slideId");
if (slideIdConf == null) throw new RuntimeException("Undefined conf value for slideId!");
Integer slideId = new Integer(slideIdConf.getValue());
Slide slide = slideDao.selectOneOrDie(where("id", slideId));
Config imageScaleFactorConf = conf.get("imageScaleFactor");
if (imageScaleFactorConf == null) throw new RuntimeException("Undefined conf value for scaleFactor!");
Double imageScaleFactor = new Double(imageScaleFactorConf.getValue());
Config pixelSizeConf = conf.get("pixelSize");
if (pixelSizeConf == null) throw new RuntimeException("Undefined conf value for pixelSize!");
Double pixelSize = new Double(pixelSizeConf.getValue());
Config invertXAxisConf = conf.get("invertXAxis");
if (invertXAxisConf == null) throw new RuntimeException("Undefined conf value for invertXAxis!");
Boolean invertXAxis = new Boolean(invertXAxisConf.getValue().equals("yes"));
Config invertYAxisConf = conf.get("invertYAxis");
if (invertYAxisConf == null) throw new RuntimeException("Undefined conf value for invertYAxis!");
Boolean invertYAxis = new Boolean(invertYAxisConf.getValue().equals("yes"));
Config postprocessingMacroConf = conf.get("postprocessingMacro");
String postprocessingMacro = postprocessingMacroConf != null? postprocessingMacroConf.getValue() : "";
ImagePlus slideThumb;
Double minX = null, minY = null, maxX = null, maxY = null;
CMMCore core = this.workflowRunner.getOpenHiCAMM().getApp().getMMCore();
try {
if (core.isSequenceRunning()) {
core.stopSequenceAcquisition();
Thread.sleep(1000);
}
// close all open acquisition windows
for (String name : MMStudio.getInstance().getAcquisitionNames()) {
try { MMStudio.getInstance().closeAcquisitionWindow(name); }
catch (MMScriptException e) { /* do nothing */ }
}
// get the dimensions of a normal image
core.snapImage();
TaggedImage taggedImage = core.getTaggedImage();
if (taggedImage == null) {
throw new RuntimeException("Could not get image dimensions!");
}
int hiresImageWidth = MDUtils.getWidth(taggedImage.tags);
int hiresImageHeight = MDUtils.getHeight(taggedImage.tags);
// start live mode
core.clearCircularBuffer();
core.startContinuousSequenceAcquisition(0);
// display the live mode GUI
//MMStudio.getInstance().enableLiveMode(true);
// attempt to fix the histogram scaling
//VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(WindowManager.getCurrentImage());
//if (display != null) {
// if (MultiChannelHistograms.class.isAssignableFrom(display.getHistograms().getClass())) {
// MultiChannelHistograms mch = (MultiChannelHistograms)display.getHistograms();
// if (mch != null) {
// try { mch.fullScaleChannels(); }
// catch (Throwable e) { /* do nothing */ }
// logger.info("Set histogram channels to full!");
// determine the width/height of a live view image
TaggedImage img0 = null;
ImageProcessor ip0 = null;
try { img0 = core.getLastTaggedImage(); }
catch (Throwable e) { /* do nothing */ }
if (img0 != null) ip0 = ImageUtils.makeProcessor(img0);
while (img0 == null || ip0 == null) {
Thread.sleep(10);
try { img0 = core.getLastTaggedImage(); }
catch (Throwable e) { /* do nothing */ }
if (img0 != null) ip0 = ImageUtils.makeProcessor(img0);
}
Integer imageWidth = ip0.getWidth(), imageHeight = ip0.getHeight();
// compute the live view pixel sizes
double liveViewPixelSizeX = pixelSize * (double)hiresImageWidth / (double)imageWidth;
double liveViewPixelSizeY = pixelSize * (double)hiresImageHeight / (double)imageHeight;
// determine the bounds of the stage coordinates
for (MultiStagePosition msp : positionList.getPositions()) {
if (minX == null || msp.getX() < minX) minX = msp.getX();
if (maxX == null || msp.getX() > maxX) maxX = msp.getX();
if (minY == null || msp.getY() < minY) minY = msp.getY();
if (maxY == null || msp.getY() > maxY) maxY = msp.getY();
}
logger.fine(String.format("minX = %s, minY = %s, maxX = %s, maxY = %s, imageWidth = %s, imageHeight = %s",
minX, minY, maxX, maxY, imageWidth, imageHeight));
if (minX == null || maxX == null || minY == null || maxY == null || imageWidth == null || imageHeight == null) {
throw new RuntimeException(String.format(
"Could not determine bounds of slide! minX = %s, minY = %s, maxX = %s, maxY = %s, imageWidth = %s, imageHeight = %s",
minX, minY, maxX, maxY, imageWidth, imageHeight));
}
double slideWidthPx = ((maxX - minX) / liveViewPixelSizeX) + (double)imageWidth;
double slideHeightPx = ((maxY - minY) / liveViewPixelSizeY) + (double)imageHeight;
logger.fine(String.format("slideWidthPx = %s, slideHeightPx = %s", slideWidthPx, slideHeightPx));
logger.fine(String.format("scaleFactor = %s", imageScaleFactor));
double scaledSlideWidth = imageScaleFactor * slideWidthPx;
logger.fine(String.format("slidePreviewWidth = %s", scaledSlideWidth));
double scaledSlideHeight = imageScaleFactor * slideHeightPx;
logger.fine(String.format("slidePreviewHeight = %s", scaledSlideHeight));
// set the initial Z Position
if (conf.containsKey("initialZPos")) {
Double initialZPos = new Double(conf.get("initialZPos").getValue());
logger.info(String.format("Setting initial Z Position to: %.02f", initialZPos));
String focusDevice = core.getFocusDevice();
final double EPSILON = 1.0;
try {
Double currentPos = core.getPosition(focusDevice);
while (Math.abs(currentPos-initialZPos) > EPSILON) {
core.setPosition(focusDevice, initialZPos);
core.waitForDevice(focusDevice);
Thread.sleep(500);
currentPos = core.getPosition(focusDevice);
}
}
catch (Exception e1) {throw new RuntimeException(e1);}
}
Date startAcquisition = new Date();
this.workflowRunner.getTaskConfig().insertOrUpdate(
new TaskConfig(task.getId(),
"startAcquisition",
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(startAcquisition)),
"id", "key");
logger.info(String.format("Now acquiring %s survey images for slide %s...",
positionList.getNumberOfPositions(),
slide.getName()));
// create the empty large slide image
slideThumb = NewImage.createRGBImage(String.format("%s.%s.%s", workflowModule.getName(), task.getName(wmDao), slide.getName()),
(int)Math.round(scaledSlideWidth),
(int)Math.round(scaledSlideHeight),
1, NewImage.FILL_WHITE);
// iterate through the position list, imaging using live mode to build up the large slide image
TaggedImage lastimg = null;
for (int i=0; i<positionList.getNumberOfPositions(); ++i) {
MultiStagePosition msp = positionList.getPosition(i);
logger.fine(String.format("Acquired survey image for slide %s: %s [%s/%s images]",
slide.getName(),
msp.getLabel(),
i+1, positionList.getNumberOfPositions()));
// move the stage into position
double[] xy_stage = SlideImager.moveStage(this.workflowModule.getName(), core, msp.getX(), msp.getY(), logger);
double x_stage_new = xy_stage[0];
double y_stage_new = xy_stage[1];
// acquire the live mode image
TaggedImage img = null;
ImageProcessor ip = null;
ImagePlus imp = null;
while (img == null || ip == null || ip.getPixels() == null) {
ip = null;
try { img = core.getLastTaggedImage(); }
catch (Throwable e) { /* do nothing */ }
if (img != null) {
//logger.info(String.format("Image %s/%s tags: %s", i+1, positionList.getNumberOfPositions(), img.tags.toString()));
ip = ImageUtils.makeProcessor(img);
}
if (ip != null && ip.getPixels() != null) {
imp = new ImagePlus(String.format("%s.%s.%s.x%s.y%s",
this.workflowModule.getName(), task.getName(wmDao), slide.getName(), msp.getX(), msp.getY()),
ip);
// do a bitwise check to make sure this image is not the same as the last one
if (lastimg != null && compareImages(img, lastimg)) {
logger.warning(String.format("Detected same images from live view, retrying..."));
img = null;
imp = null;
ip = null;
// re-start live mode and try again
try { core.stopSequenceAcquisition(); }
catch (Exception e) { /* do nothing */ }
Thread.sleep(5000);
core.clearCircularBuffer();
core.startContinuousSequenceAcquisition(0);
Thread.sleep(5000);
continue;
}
lastimg = img;
break;
}
Thread.sleep(1000);
}
int width = imp.getWidth(), height = imp.getHeight();
logger.fine(String.format("Image width: %s, height: %s", width, height));
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
(int)Math.round(imp.getWidth() * imageScaleFactor),
(int)Math.round(imp.getHeight() * imageScaleFactor)));
logger.fine(String.format("Resized image width: %s, height: %s", imp.getWidth(), imp.getHeight()));
double xloc = (x_stage_new - minX) / liveViewPixelSizeX;
double xlocInvert = invertXAxis? slideWidthPx - (xloc + width) : xloc;
double xlocScale = xlocInvert * imageScaleFactor;
logger.fine(String.format("xloc = %s, xlocInvert = %s, xlocScale = %s", xloc, xlocInvert, xlocScale));
double yloc = (y_stage_new - minY) / liveViewPixelSizeY;
double ylocInvert = invertYAxis? slideHeightPx - (yloc + height) : yloc;
double ylocScale = ylocInvert * imageScaleFactor;
logger.fine(String.format("yloc = %s, ylocInvert = %s, ylocScale = %s", yloc, ylocInvert, ylocScale));
// draw the thumbnail image
slideThumb.getProcessor().copyBits(imp.getProcessor(),
(int)Math.round(xlocScale),
(int)Math.round(ylocScale),
Blitter.COPY);
}
// save the unprocessed stitched image to the stitched folder using the stitch group as the
// file name.
{
FileSaver fileSaver = new FileSaver(slideThumb);
File imageFile = new File(surveyFolder, String.format("%s.unprocessed.tif", slideThumb.getTitle()));
fileSaver.saveAsTiff(imageFile.getPath());
}
// perform any necessary image postprocessing on slideThumb
if (postprocessingMacro != null && !postprocessingMacro.replaceAll("\\s+","").isEmpty()) {
slideThumb.show();
logger.info(String.format("Running postprocessing macro:%n%s", postprocessingMacro));
IJ.runMacro(postprocessingMacro);
ImagePlus modifiedImage1 = WindowManager.getImage(slideThumb.getTitle());
if (modifiedImage1 != null) {
modifiedImage1.changes = false;
modifiedImage1.close();
}
else {
slideThumb.changes = false;
slideThumb.close();
}
}
// save the stitched image to the stitched folder using the stitch group as the
// file name.
FileSaver fileSaver = new FileSaver(slideThumb);
File imageFile = new File(surveyFolder, String.format("%s.tif", slideThumb.getTitle()));
fileSaver.saveAsTiff(imageFile.getPath());
// create necessary DB records so that ROIFinder can work on the large slide image
Image image = new Image(imageFile.getPath(), slideId);
imageDao.insert(image);
logger.fine(String.format("Inserted image: %s", image));
imageDao.reload(image, "path","slideId");
// Store the Image ID as a Task Config variable
TaskConfig imageIdConf = new TaskConfig(
task.getId(),
"imageId",
new Integer(image.getId()).toString());
taskConfigDao.insertOrUpdate(imageIdConf,"id","key");
conf.put(imageIdConf.getKey(), imageIdConf);
logger.fine(String.format("Inserted/Updated imageId config: %s", imageIdConf));
// Store the pixel Size X/Y conf
TaskConfig pixelSizeXConf = new TaskConfig(
task.getId(),
"pixelSizeX",
new Double(liveViewPixelSizeX).toString());
taskConfigDao.insertOrUpdate(pixelSizeXConf,"id","key");
conf.put(pixelSizeXConf.getKey(), pixelSizeXConf);
logger.fine(String.format("Inserted/Updated pixelSizeUmX config: %s", pixelSizeXConf));
TaskConfig pixelSizeYConf = new TaskConfig(
task.getId(),
"pixelSizeY",
new Double(liveViewPixelSizeY).toString());
taskConfigDao.insertOrUpdate(pixelSizeYConf,"id","key");
conf.put(pixelSizeYConf.getKey(), pixelSizeYConf);
logger.fine(String.format("Inserted/Updated pixelSizeUmY config: %s", pixelSizeYConf));
return Status.SUCCESS;
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
// close the live mode GUI
//MMStudio.getInstance().enableLiveMode(false);
// stop live mode
try { core.stopSequenceAcquisition(); }
catch (Exception e) {throw new RuntimeException(e);}
}
}
private File createSurveyImageFolder() {
String rootDir = this.workflowRunner.getWorkflowDir().getPath();
int count = 1;
File stitchedFolder = new File(rootDir, String.format("%s_%s", SURVEY_IMAGE_DIRECTORY_PREFIX, count));
while (!stitchedFolder.mkdirs()) {
++count;
stitchedFolder = new File(rootDir, String.format("%s_%s", SURVEY_IMAGE_DIRECTORY_PREFIX, count));
}
return stitchedFolder;
}
@Override
public String getTitle() {
return this.getClass().getName();
}
@Override
public String getDescription() {
return this.getClass().getName();
}
@Override
public Configuration configure() {
return new Configuration() {
SlideSurveyorDialog slideSurveyorDialog = new SlideSurveyorDialog(SlideSurveyor.this.workflowRunner);
@Override
public Config[] retrieve() {
List<Config> configs = new ArrayList<Config>();
if (slideSurveyorDialog.posListText.getText().length()>0) {
configs.add(new Config(workflowModule.getId(),
"posListFile",
slideSurveyorDialog.posListText.getText()));
}
if (((Double)slideSurveyorDialog.pixelSize.getValue()).doubleValue() != 0.0) {
configs.add(new Config(workflowModule.getId(), "pixelSize", slideSurveyorDialog.pixelSize.getValue().toString()));
}
if (((Double)slideSurveyorDialog.imageScaleFactor.getValue()).doubleValue() != 0.0) {
configs.add(new Config(workflowModule.getId(), "imageScaleFactor", slideSurveyorDialog.imageScaleFactor.getValue().toString()));
}
if (slideSurveyorDialog.invertXAxisYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertXAxis", "yes"));
}
else if (slideSurveyorDialog.invertXAxisNo.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertXAxis", "no"));
}
if (slideSurveyorDialog.invertYAxisYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertYAxis", "yes"));
}
else if (slideSurveyorDialog.invertYAxisNo.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertYAxis", "no"));
}
if (slideSurveyorDialog.setInitZPosYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "initialZPos", slideSurveyorDialog.initialZPos.getValue().toString()));
}
if (!slideSurveyorDialog.postprocessingMacro.getText().replaceAll("\\s+","").isEmpty()) {
configs.add(new Config(workflowModule.getId(), "postprocessingMacro", slideSurveyorDialog.postprocessingMacro.getText()));
}
return configs.toArray(new Config[0]);
}
@Override
public Component display(Config[] configs) {
Map<String,Config> conf = new HashMap<String,Config>();
for (Config config : configs) {
conf.put(config.getKey(), config);
}
if (conf.containsKey("posListFile")) {
Config posList = conf.get("posListFile");
slideSurveyorDialog.posListText.setText(posList.getValue());
}
if (conf.containsKey("pixelSize")) {
slideSurveyorDialog.pixelSize.setValue(new Double(conf.get("pixelSize").getValue()));
}
if (conf.containsKey("imageScaleFactor")) {
slideSurveyorDialog.imageScaleFactor.setValue(new Double(conf.get("imageScaleFactor").getValue()));
}
if (conf.containsKey("invertXAxis")) {
if (conf.get("invertXAxis").getValue().equals("yes")) {
slideSurveyorDialog.invertXAxisYes.setSelected(true);
slideSurveyorDialog.invertXAxisNo.setSelected(false);
}
else if (conf.get("invertXAxis").getValue().equals("no")) {
slideSurveyorDialog.invertXAxisYes.setSelected(false);
slideSurveyorDialog.invertXAxisNo.setSelected(true);
}
}
if (conf.containsKey("invertYAxis")) {
if (conf.get("invertYAxis").getValue().equals("yes")) {
slideSurveyorDialog.invertYAxisYes.setSelected(true);
slideSurveyorDialog.invertYAxisNo.setSelected(false);
}
else if (conf.get("invertYAxis").getValue().equals("no")) {
slideSurveyorDialog.invertYAxisYes.setSelected(false);
slideSurveyorDialog.invertYAxisNo.setSelected(true);
}
}
if (conf.containsKey("initialZPos")) {
slideSurveyorDialog.setInitZPosYes.setSelected(true);
slideSurveyorDialog.initialZPos.setValue(new Double(conf.get("initialZPos").getValue()));
}
else {
slideSurveyorDialog.setInitZPosNo.setSelected(true);
slideSurveyorDialog.initialZPos.setValue(new Double(0.0));
}
if (conf.containsKey("postprocessingMacro")) {
slideSurveyorDialog.postprocessingMacro.setText(conf.get("postprocessingMacro").getValue());
}
return slideSurveyorDialog;
}
@Override
public ValidationError[] validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
if (slideSurveyorDialog.posListText.getText().length()>0) {
File posListFile = new File(slideSurveyorDialog.posListText.getText());
if (!posListFile.exists()) {
errors.add(new ValidationError(workflowModule.getName(), "Position list file "+posListFile.toString()+" not found."));
}
}
if ((Double)slideSurveyorDialog.pixelSize.getValue() <= 0.0) {
errors.add(new ValidationError(workflowModule.getName(),
"Pixel size must be greater than zero."));
}
if ((Double)slideSurveyorDialog.imageScaleFactor.getValue() <= 0.0) {
errors.add(new ValidationError(workflowModule.getName(),
"Image scale factor must be greater than zero."));
}
return errors.toArray(new ValidationError[0]);
}
};
}
@Override
public List<Task> createTaskRecords(List<Task> parentTasks, Map<String,Config> config, Logger logger) {
Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class);
Dao<ModuleConfig> moduleConfig = workflowRunner.getModuleConfig();
Dao<TaskConfig> taskConfigDao = workflowRunner.getTaskConfig();
// Load all the module configuration into a HashMap
Map<String,Config> moduleConf = new HashMap<String,Config>();
for (ModuleConfig c : moduleConfig.select(where("id",this.workflowModule.getId()))) {
moduleConf.put(c.getKey(), c);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using module config: %s",
this.workflowModule.getName(), c));
}
// create a folder to store the stitched images
File surveyFolder = createSurveyImageFolder();
// Create task records and connect to parent tasks
// If no parent tasks were defined, then just create a single task instance.
List<Task> tasks = new ArrayList<Task>();
for (Task parentTask : parentTasks.size()>0? parentTasks.toArray(new Task[]{}) : new Task[]{null})
{
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Connecting parent task %s",
this.workflowModule.getName(), Util.escape(parentTask)));
// get the parent task configuration
Map<String,TaskConfig> parentTaskConf = new HashMap<String,TaskConfig>();
if (parentTask != null) {
for (TaskConfig c : taskConfigDao.select(where("id",parentTask.getId()))) {
parentTaskConf.put(c.getKey(), c);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using task config: %s",
this.workflowModule.getName(), c));
}
}
// Get the associated slide.
Slide slide;
if (parentTaskConf.containsKey("slideId")) {
slide = slideDao.selectOneOrDie(where("id",new Integer(parentTaskConf.get("slideId").getValue())));
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Inherited slideId %s", this.workflowModule.getName(), parentTaskConf.get("slideId")));
}
// If no associated slide is registered, create a slide to represent this task
else {
String uuid = UUID.randomUUID().toString();
slide = new Slide(uuid);
slideDao.insertOrUpdate(slide,"experimentId");
slideDao.reload(slide, "experimentId");
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new slide: %s", this.workflowModule.getName(), slide.toString()));
}
config.put("slideId", new Config(this.workflowModule.getId(), "slideId", new Integer(slide.getId()).toString()));
// Create task record
Task task = new Task(this.workflowModule.getId(), Status.NEW);
workflowRunner.getTaskStatus().insert(task);
tasks.add(task);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task record: %s",
this.workflowModule.getName(), task));
// add the surveyFolder task config
TaskConfig surveyFolderConf = new TaskConfig(
task.getId(),
"surveyFolder", surveyFolder.toString());
taskConfigDao.insert(surveyFolderConf);
// Create taskConfig record for the image label
TaskConfig imageLabel = new TaskConfig(
task.getId(),
"imageLabel",
MDUtils.generateLabel(0, 0, 0, 0));
taskConfigDao.insert(imageLabel);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), imageLabel));
// Create taskConfig record for the MSP label (positionName)
TaskConfig positionName = new TaskConfig(
task.getId(),
"positionName",
"Pos0");
taskConfigDao.insert(positionName);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), positionName));
// load the position list
if (!moduleConf.containsKey("posListFile")) {
throw new RuntimeException("Cuold not find configuration for posListFile!");
}
Config posList = moduleConf.get("posListFile");
logger.fine(String.format("%s: Loading position list from file: %s", this.workflowModule.getName(), Util.escape(posList.getValue())));
File posListFile = new File(posList.getValue());
if (!posListFile.exists()) {
throw new RuntimeException("Cannot find position list file "+posListFile.getPath());
}
PositionList positionList = new PositionList();
try { positionList.load(posListFile.getPath()); }
catch (MMException e) {throw new RuntimeException(e);}
// determine the bounds of the stage coordinates
Double minX = null, minY = null, maxX = null, maxY = null;
for (MultiStagePosition msp : positionList.getPositions()) {
if (minX == null || msp.getX() < minX) minX = msp.getX();
if (maxX == null || msp.getX() > maxX) maxX = msp.getX();
if (minY == null || msp.getY() < minY) minY = msp.getY();
if (maxY == null || msp.getY() > maxY) maxY = msp.getY();
}
logger.fine(String.format("minX = %s, minY = %s, maxX = %s, maxY = %s", minX, minY, maxX, maxY));
if (minX == null || maxX == null || minY == null || maxY == null) {
throw new RuntimeException(String.format(
"Could not determine bounds of slide! minX = %s, minY = %s, maxX = %s, maxY = %s",
minX, minY, maxX, maxY));
}
// Store the X and Y stage positions as task config variables
double XPositionUm = ((maxX - minX) / 2.0) + minX;
TaskConfig XPositionUmConf = new TaskConfig(
task.getId(),
"XPositionUm",
new Double(XPositionUm).toString());
taskConfigDao.insertOrUpdate(XPositionUmConf,"id","key");
logger.fine(String.format("Inserted/Updated XPositionUm config: %s", XPositionUm));
double YPositionUm = ((maxY - minY) / 2.0) + minY;
TaskConfig YPositionUmConf = new TaskConfig(
task.getId(),
"YPositionUm",
new Double(YPositionUm).toString());
taskConfigDao.insertOrUpdate(YPositionUmConf,"id","key");
logger.fine(String.format("Inserted/Updated YPositionUm config: %s", YPositionUm));
// Store the MSP value as a JSON string
CMMCore core = this.workflowRunner.getOpenHiCAMM().getApp().getMMCore();
String xyStage = core.getXYStageDevice();
String focus = core.getFocusDevice();
try {
PositionList mspPosList = new PositionList();
MultiStagePosition msp = new MultiStagePosition(xyStage, XPositionUm, YPositionUm, focus, 0.0);
mspPosList.addPosition(msp);
String mspJson = new JSONObject(mspPosList.serialize()).
getJSONArray("POSITIONS").getJSONObject(0).toString();
TaskConfig mspConf = new TaskConfig(
task.getId(), "MSP", mspJson);
taskConfigDao.insert(mspConf);
config.put("MSP", mspConf);
workflowRunner.getLogger().fine(String.format(
"Inserted MultiStagePosition config: %s", mspJson));
}
catch (MMSerializationException e) {throw new RuntimeException(e);}
catch (JSONException e) {throw new RuntimeException(e);}
// create taskConfig record for the slide ID
TaskConfig slideId = new TaskConfig(
task.getId(),
"slideId",
new Integer(slide.getId()).toString());
taskConfigDao.insert(slideId);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), slideId));
// Create task dispatch record
if (parentTask != null) {
TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId());
workflowRunner.getTaskDispatch().insert(dispatch);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task dispatch record: %s",
this.workflowModule.getName(), dispatch));
}
}
return tasks;
}
@Override
public TaskType getTaskType() {
return Module.TaskType.SERIAL;
}
@Override public void cleanup(Task task, Map<String,Config> config, Logger logger) { }
@Override
public void runInitialize() { }
@Override
public Status setTaskStatusOnResume(Task task) {
for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("parentTaskId", task.getId()))) {
Task t = this.workflowRunner.getTaskStatus().selectOneOrDie(where("id", td.getTaskId()));
ModuleConfig mc = this.workflowRunner.getModuleConfig().selectOne(where("id", t.getModuleId()).
and("key", "canImageSlides").
and("value", "yes"));
if (mc != null && t.getStatus() != Status.SUCCESS) {
return Status.NEW;
}
}
return task.getStatus();
}
}
|
package org.biojava.bio.seq.io;
import java.util.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.bio.symbol.*;
/**
* Really simple SymbolList which exposes any part of an array of Symbols
* as a SymbolList. This exists primarily as a support class for
* ChunkedSymbolList.
*
* @author Thomas Down
* @since 1.1
*/
class SubArraySymbolList extends AbstractSymbolList implements Serializable{
private final Alphabet alpha;
private final int length;
private final int offset;
private final Symbol[] array;
protected void finalize() throws Throwable {
super.finalize();
alpha.removeChangeListener(ChangeListener.ALWAYS_VETO, Alphabet.SYMBOLS);
}
/**
* Construct a new SubArraySymbolList. NOTE: this ct does no
* validation, and therefore shouldn't be called from user code.
*/
SubArraySymbolList(Symbol[] array, int length, int offset, Alphabet alpha) {
this.alpha = alpha;
this.length = length;
this.offset = offset;
this.array = array;
if (length + offset > array.length)
throw new IndexOutOfBoundsException();
alpha.addChangeListener(ChangeListener.ALWAYS_VETO, Alphabet.SYMBOLS);
}
public Alphabet getAlphabet() {
return alpha;
}
public int length() {
return length;
}
public Symbol symbolAt(int pos) {
if (pos < 1 || pos > length)
throw new IndexOutOfBoundsException("Index out of range: " + pos);
return array[offset + pos - 1];
}
}
|
package org.exist.xquery.test;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.exist.storage.DBBroker;
import org.exist.xmldb.DatabaseInstanceManager;
import org.exist.xquery.XPathException;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XPathQueryService;
/** Tests for various standart XQuery functions
* @author jens
*/
public class XQueryFunctionsTest extends TestCase {
private String[] testvalues;
private String[] resultvalues;
private XPathQueryService service;
private Collection root = null;
private Database database = null;
public static void main(String[] args) throws XPathException {
TestRunner.run(XQueryFunctionsTest.class);
}
/**
* Constructor for XQueryFunctionsTest.
* @param arg0
*/
public XQueryFunctionsTest(String arg0) {
super(arg0);
}
/** Tests the XQuery-/XPath-function fn:round-half-to-even
* with the rounding value typed xs:integer
*/
public void testRoundHtE_INTEGER() throws XPathException {
ResourceSet result = null;
String query = null;
String r = "";
try {
query = "fn:round-half-to-even( xs:integer('1'), 0 )";
result = service.query( query );
r = (String) result.getResource(0).getContent();
assertEquals( "1", r );
query = "fn:round-half-to-even( xs:integer('6'), -1 )";
result = service.query( query );
r = (String) result.getResource(0).getContent();
assertEquals( "10", r );
query = "fn:round-half-to-even( xs:integer('5'), -1 )";
result = service.query( query );
r = (String) result.getResource(0).getContent();
assertEquals( "0", r );
} catch (XMLDBException e) {
System.out.println("testRoundHtE_INTEGER(): "+e);
fail(e.getMessage());
}
}
/** Tests the XQuery-/XPath-function fn:round-half-to-even
* with the rounding value typed xs:double
*/
public void testRoundHtE_DOUBLE() throws XPathException {
/* List of Values to test with Rounding */
String[] testvalues =
{ "0.5", "1.5", "2.5", "3.567812E+3", "4.7564E-3", "35612.25" };
String[] resultvalues =
{ "0.0", "2.0", "2.0", "3567.81", "0.0", "35600.0" };
int[] precision =
{ 0, 0, 0, 2, 2, -2 };
ResourceSet result = null;
String query = null;
try {
XPathQueryService service = (XPathQueryService) root.getService( "XQueryService", "1.0" );
for (int i=0; i<testvalues.length; i++) {
query = "fn:round-half-to-even( xs:double('" + testvalues[i] + "'), " + precision[i] + " )";
result = service.query( query );
String r = (String) result.getResource(0).getContent();
assertEquals( resultvalues[i], r );
}
} catch (XMLDBException e) {
System.out.println("testRoundHtE_DOUBLE(): "+e);
fail(e.getMessage());
}
}
/** Tests the XQuery-XPath function fn:tokenize() */
public void testTokenize() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "count ( tokenize('a/b' , '/') )" );
r = (String) result.getResource(0).getContent();
assertEquals( "2", r );
result = service.query( "count ( tokenize('a/b/' , '/') )" );
r = (String) result.getResource(0).getContent();
assertEquals( "3", r );
result = service.query( "count ( tokenize('' , '/') )" );
r = (String) result.getResource(0).getContent();
assertEquals( "0", r );
result = service.query(
"let $res := fn:tokenize('abracadabra', '(ab)|(a)')" +
"let $reference := ('', 'r', 'c', 'd', 'r', '')" +
"return fn:deep-equal($res, $reference)" );
r = (String) result.getResource(0).getContent();
assertEquals( "true", r );
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testDeepEqual() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query(
"let $res := ('a', 'b')" +
"let $reference := ('a', 'b')" +
"return fn:deep-equal($res, $reference)" );
r = (String) result.getResource(0).getContent();
assertEquals( "true", r );
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testCompare() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query("fn:compare(\"Strasse\", \"Stra\u00DFe\")");
r = (String) result.getResource(0).getContent();
assertEquals( "-1", r );
//result = service.query("fn:compare(\"Strasse\", \"Stra\u00DFe\", \"java:GermanCollator\")");
//r = (String) result.getResource(0).getContent();
//assertEquals( "0", r );
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testDistinctValues() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "declare variable $c { distinct-values(('a', 'a')) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "a", r );
result = service.query( "declare variable $c { distinct-values((<a>a</a>, <b>a</b>)) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "a", r );
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testSum() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "declare variable $c { sum((1, 2)) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "3", r );
result = service.query( "declare variable $c { sum((<a>1</a>, <b>2</b>)) }; $c" );
r = (String) result.getResource(0).getContent();
//Any untyped atomic values in the sequence are converted to xs:double values ([MK Xpath 2.0], p. 432)
assertEquals( "3.0", r );
result = service.query( "declare variable $c { sum((), 3) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "3", r );
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testAvg() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "declare variable $c { avg((2, 2)) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "2", r );
result = service.query( "declare variable $c { avg((<a>2</a>, <b>2</b>)) }; $c" );
r = (String) result.getResource(0).getContent();
//Any untyped atomic values in the resulting sequence
//(typically, values extracted from nodes in a schemaless document)
//are converted to xs:double values ([MK Xpath 2.0], p. 301)
assertEquals( "2.0", r );
result = service.query( "declare variable $c { avg(()) }; $c" );
assertEquals( 0, result.getSize());
} catch (XMLDBException e) {
System.out.println("testTokenize(): " + e);
fail(e.getMessage());
}
}
public void testMin() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "declare variable $c { min((1, 2)) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "1", r );
result = service.query( "declare variable $c { min((<a>1</a>, <b>2</b>)) }; $c" );
r = (String) result.getResource(0).getContent();
//Any untyped atomic values in the resulting sequence
//(typically, values extracted from nodes in a schemaless document)
//are converted to xs:double values ([MK Xpath 2.0], p. 372)
assertEquals( "1.0", r );
result = service.query( "declare variable $c { min(()) }; $c" );
assertEquals( 0, result.getSize());
} catch (XMLDBException e) {
System.out.println("testMin(): " + e);
fail(e.getMessage());
}
}
public void testMax() throws XPathException {
ResourceSet result = null;
String r = "";
try {
result = service.query( "declare variable $c { max((1, 2)) }; $c" );
r = (String) result.getResource(0).getContent();
assertEquals( "2", r );
result = service.query( "declare variable $c { max((<a>1</a>, <b>2</b>)) }; $c" );
r = (String) result.getResource(0).getContent();
//Any untyped atomic values in the resulting sequence
//(typically, values extracted from nodes in a schemaless document)
//are converted to xs:double values ([MK Xpath 2.0], p. 370)
assertEquals( "2.0", r );
result = service.query( "declare variable $c { max(()) }; $c" );
assertEquals( 0, result.getSize());
} catch (XMLDBException e) {
System.out.println("testMax(): " + e);
fail(e.getMessage());
}
}
public void testExclusiveLock() throws XPathException {
ResourceSet result = null;
String r = "";
try {
String query = "let $query1 := (<a/>)\n" +
"let $query2 := (2, 3)\n" +
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
// initialize driver
Class cl = Class.forName("org.exist.xmldb.DatabaseImpl");
database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null);
service = (XPathQueryService) root.getService( "XQueryService", "1.0" );
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
DatabaseManager.deregisterDatabase(database);
DatabaseInstanceManager dim =
(DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0");
dim.shutdown();
//System.out.println("tearDown PASSED");
}
}
|
package org.jitsi.impl.neomedia;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.protocol.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import javax.media.rtp.rtcp.*;
import org.jitsi.impl.neomedia.protocol.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.*;
import com.sun.media.rtp.*;
/**
* Implements <tt>RTPTranslator</tt> which represents an RTP translator which
* forwards RTP and RTCP traffic between multiple <tt>MediaStream</tt>s.
*
* @author Lyubomir Marinov
*/
public class RTPTranslatorImpl
implements ReceiveStreamListener,
RTPTranslator
{
/**
* The <tt>Logger</tt> used by the <tt>RTPTranslatorImpl</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(RTPTranslatorImpl.class);
/**
* The indicator which determines whether the method
* {@link #createFakeSendStreamIfNecessary()} is to be executed by
* <tt>RTPTranslatorImpl</tt>.
*/
private static final boolean CREATE_FAKE_SEND_STREAM_IF_NECESSARY = false;
/**
* An array with <tt>long</tt> element type and no elements explicitly
* defined to reduce unnecessary allocations.
*/
private static final long[] EMPTY_LONG_ARRAY = new long[0];
/**
* The <tt>RTPConnector</tt> which is used by {@link #manager} and which
* delegates to the <tt>RTPConnector</tt>s of the <tt>StreamRTPManager</tt>s
* attached to this instance.
*/
private RTPConnectorImpl connector;
private SendStream fakeSendStream;
/**
* The <tt>RTPManager</tt> which implements the actual RTP management of
* this instance.
*/
private final RTPManager manager = RTPManager.newInstance();
private final List<SendStreamDesc> sendStreams
= new LinkedList<SendStreamDesc>();
/**
* The list of <tt>StreamRTPManager</tt>s i.e. <tt>MediaStream</tt>s which
* this instance forwards RTP and RTCP traffic between.
*/
private final List<StreamRTPManagerDesc> streamRTPManagers
= new ArrayList<StreamRTPManagerDesc>();
/**
* Initializes a new <tt>RTPTranslatorImpl</tt> instance.
*/
public RTPTranslatorImpl()
{
manager.addReceiveStreamListener(this);
}
/**
* Specifies the RTP payload type (number) to be used for a specific
* <tt>Format</tt>. The association between the specified <tt>format</tt>
* and the specified <tt>payloadType</tt> is being added by a specific
* <tt>StreamRTPManager</tt> but effects the <tt>RTPTranslatorImpl</tt>
* globally.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> that is requesting
* the association of <tt>format</tt> to <tt>payloadType</tt>
* @param format the <tt>Format</tt> which is to be associated with the
* specified RTP payload type (number)
* @param payloadType the RTP payload type (number) to be associated with
* the specified <tt>format</tt>
*/
public synchronized void addFormat(
StreamRTPManager streamRTPManager,
Format format, int payloadType)
{
manager.addFormat(format, payloadType);
getStreamRTPManagerDesc(streamRTPManager, true)
.addFormat(format, payloadType);
}
/**
* Adds a <tt>ReceiveStreamListener</tt> to be notified about
* <tt>ReceiveStreamEvent</tt>s related to a specific neomedia
* <tt>MediaStream</tt> (expressed as a <tt>StreamRTPManager</tt> for the
* purposes of and in the terms of <tt>RTPTranslator</tt>). If the specified
* <tt>listener</tt> has already been added, the method does nothing.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> which specifies
* the neomedia <tt>MediaStream</tt> with which the
* <tt>ReceiveStreamEvent</tt>s delivered to the specified <tt>listener</tt>
* are to be related. In other words, a <tt>ReceiveStremEvent</tt> received
* by <tt>RTPTranslatorImpl</tt> is first examined to determine with which
* <tt>StreamRTPManager</tt> it is related to and then it is delivered to
* the <tt>ReceiveStreamListener</tt>s which have been added to this
* <tt>RTPTranslatorImpl</tt> by that <tt>StreamRTPManager</tt>.
* @param listener the <tt>ReceiveStreamListener</tt> to be notified about
* <tt>ReceiveStreamEvent</tt>s related to the specified
* <tt>streamRTPManager</tt>
*/
public synchronized void addReceiveStreamListener(
StreamRTPManager streamRTPManager,
ReceiveStreamListener listener)
{
getStreamRTPManagerDesc(streamRTPManager, true)
.addReceiveStreamListener(listener);
}
/**
* Adds a <tt>RemoteListener</tt> to be notified about <tt>RemoteEvent</tt>s
* received by this <tt>RTPTranslatorImpl</tt>. Though the request is being
* made by a specific <tt>StreamRTPManager</tt>, the addition of the
* specified <tt>listener</tt> and the deliveries of the
* <tt>RemoteEvent</tt>s are performed irrespective of any
* <tt>StreamRTPManager</tt>.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> which is requesting
* the addition of the specified <tt>RemoteListener</tt>
* @param listener the <tt>RemoteListener</tt> to be notified about
* <tt>RemoteEvent</tt>s received by this <tt>RTPTranslatorImpl</tt>
*/
public void addRemoteListener(
StreamRTPManager streamRTPManager,
RemoteListener listener)
{
manager.addRemoteListener(listener);
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public void addSendStreamListener(
StreamRTPManager streamRTPManager,
SendStreamListener listener)
{
// TODO Auto-generated method stub
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public void addSessionListener(
StreamRTPManager streamRTPManager,
SessionListener listener)
{
// TODO Auto-generated method stub
}
/**
* Closes {@link #fakeSendStream} if it exists and is considered no longer
* necessary; otherwise, does nothing.
*/
private synchronized void closeFakeSendStreamIfNotNecessary()
{
/*
* If a SendStream has been created in response to a request from the
* clients of this RTPTranslator implementation, the newly-created
* SendStream in question will disperse the received RTP and RTCP from
* remote peers so fakeSendStream will be obsolete.
*/
try
{
if ((!sendStreams.isEmpty() || (streamRTPManagers.size() < 2))
&& (fakeSendStream != null))
{
try
{
fakeSendStream.close();
}
catch (NullPointerException npe)
{
/*
* Refer to MediaStreamImpl#stopSendStreams(
* Iterable<SendStream>, boolean) for an explanation about
* the swallowing of the exception.
*/
logger.error("Failed to close fake send stream", npe);
}
finally
{
fakeSendStream = null;
}
}
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else if (logger.isDebugEnabled())
{
logger.debug(
"Failed to close the fake SendStream of this"
+ " RTPTranslator.",
t);
}
}
}
/**
* Closes a specific <tt>SendStream</tt>.
*
* @param sendStreamDesc a <tt>SendStreamDesc</tt> instance that specifies
* the <tt>SendStream</tt> to be closed
*/
private synchronized void closeSendStream(SendStreamDesc sendStreamDesc)
{
if (sendStreams.contains(sendStreamDesc)
&& (sendStreamDesc.getSendStreamCount() < 1))
{
SendStream sendStream = sendStreamDesc.sendStream;
try
{
sendStream.close();
}
catch (NullPointerException npe)
{
/*
* Refer to MediaStreamImpl#stopSendStreams(
* Iterable<SendStream>, boolean) for an explanation about the
* swallowing of the exception.
*/
logger.error("Failed to close send stream", npe);
}
sendStreams.remove(sendStreamDesc);
}
}
/**
* Creates {@link #fakeSendStream} if it does not exist yet and is
* considered necessary; otherwise, does nothing.
*/
private synchronized void createFakeSendStreamIfNecessary()
{
/*
* If no SendStream has been created in response to a request from the
* clients of this RTPTranslator implementation, it will need
* fakeSendStream in order to be able to disperse the received RTP and
* RTCP from remote peers. Additionally, the fakeSendStream is not
* necessary in the case of a single client of this RTPTranslator
* because there is no other remote peer to disperse the received RTP
* and RTCP to.
*/
if ((fakeSendStream == null)
&& sendStreams.isEmpty()
&& (streamRTPManagers.size() > 1))
{
Format supportedFormat = null;
for (StreamRTPManagerDesc s : streamRTPManagers)
{
Format[] formats = s.getFormats();
if ((formats != null) && (formats.length > 0))
{
for (Format f : formats)
{
if (f != null)
{
supportedFormat = f;
break;
}
}
if (supportedFormat != null)
break;
}
}
if (supportedFormat != null)
{
try
{
fakeSendStream
= manager.createSendStream(
new FakePushBufferDataSource(supportedFormat),
0);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
logger.error(
"Failed to create a fake SendStream to ensure"
+ " that this RTPTranslator is able to"
+ " disperse RTP and RTCP received from"
+ " remote peers even when the local peer"
+ " is not generating media to be"
+ " transmitted.",
t);
}
}
}
}
}
/**
* Creates a <tt>SendStream</tt> from the stream of a specific
* <tt>DataSource</tt> that is at a specific zero-based position within the
* array/list of streams of that <tt>DataSource</tt>.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> which is requesting
* the creation of a <tt>SendStream</tt>. Since multiple
* <tt>StreamRTPManager</tt> may request the creation of a
* <tt>SendStream</tt> from one and the same combination of
* <tt>dataSource</tt> and <tt>streamIndex</tt>, the method may not create
* a completely new <tt>SendStream</tt> but may return a
* <tt>StreamRTPManager</tt>-specific view of an existing
* <tt>SendStream</tt>.
* @param dataSource the <tt>DataSource</tt> which provides the stream from
* which a <tt>SendStream</tt> is to be created
* @param streamIndex the zero-based position within the array/list of
* streams of the specified <tt>dataSource</tt> of the stream from which a
* <tt>SendStream</tt> is to be created
* @return a <tt>SendStream</tt> created from the specified
* <tt>dataSource</tt> and <tt>streamIndex</tt>. The returned
* <tt>SendStream</tt> implementation is a
* <tt>streamRTPManager</tt>-dedicated view to an actual <tt>SendStream</tt>
* which may have been created during a previous execution of the method
* @throws IOException if an error occurs during the execution of
* {@link RTPManager#createSendStream(DataSource, int)}
* @throws UnsupportedFormatException if an error occurs during the
* execution of <tt>RTPManager.createSendStream(DataSource, int)</tt>
*/
public synchronized SendStream createSendStream(
StreamRTPManager streamRTPManager,
DataSource dataSource, int streamIndex)
throws IOException,
UnsupportedFormatException
{
SendStreamDesc sendStreamDesc = null;
for (SendStreamDesc s : sendStreams)
{
if ((s.dataSource == dataSource) && (s.streamIndex == streamIndex))
{
sendStreamDesc = s;
break;
}
}
if (sendStreamDesc == null)
{
SendStream sendStream
= manager.createSendStream(dataSource, streamIndex);
if (sendStream != null)
{
sendStreamDesc
= new SendStreamDesc(dataSource, streamIndex, sendStream);
sendStreams.add(sendStreamDesc);
closeFakeSendStreamIfNotNecessary();
}
}
return
(sendStreamDesc == null)
? null
: sendStreamDesc.getSendStream(streamRTPManager, true);
}
/**
* Releases the resources allocated by this instance in the course of its
* execution and prepares it to be garbage collected.
*/
public synchronized void dispose()
{
manager.removeReceiveStreamListener(this);
try
{
manager.dispose();
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
/*
* RTPManager.dispose() often throws at least a
* NullPointerException in relation to some RTP BYE.
*/
logger.error("Failed to dispose of RTPManager", t);
}
}
}
/**
* Releases the resources allocated by this instance for the purposes of the
* functioning of a specific <tt>StreamRTPManager</tt> in the course of its
* execution and prepares that <tt>StreamRTPManager</tt> to be garbage
* collected (as far as this <tt>RTPTranlatorImpl</tt> is concerned).
*/
public synchronized void dispose(StreamRTPManager streamRTPManager)
{
Iterator<StreamRTPManagerDesc> streamRTPManagerIter
= streamRTPManagers.iterator();
while (streamRTPManagerIter.hasNext())
{
StreamRTPManagerDesc streamRTPManagerDesc
= streamRTPManagerIter.next();
if (streamRTPManagerDesc.streamRTPManager == streamRTPManager)
{
RTPConnectorDesc connectorDesc
= streamRTPManagerDesc.connectorDesc;
if (connectorDesc != null)
{
if (this.connector != null)
this.connector.removeConnector(connectorDesc);
connectorDesc.connector.close();
streamRTPManagerDesc.connectorDesc = null;
}
streamRTPManagerIter.remove();
closeFakeSendStreamIfNotNecessary();
break;
}
}
}
/**
* Finds the first <tt>StreamRTPManager</tt> which is related to a specific
* receive/remote SSRC.
*
* @param receiveSSRC the receive/remote SSRC to which the returned
* <tt>StreamRTPManager</tt> is to be related
* @param exclusion the <tt>StreamRTPManager</tt>, if any, to be excluded
* from the search
* @return the first <tt>StreamRTPManager</tt> which is related to the
* specified <tt>receiveSSRC</tt>
*/
private synchronized StreamRTPManagerDesc
findStreamRTPManagerDescByReceiveSSRC(
long receiveSSRC,
StreamRTPManagerDesc exclusion)
{
for (int i = 0, count = streamRTPManagers.size(); i < count; i++)
{
StreamRTPManagerDesc s = streamRTPManagers.get(i);
if ((s != exclusion) && s.containsReceiveSSRC(receiveSSRC))
return s;
}
return null;
}
/**
* Exposes {@link RTPManager#getControl(String)} on the internal/underlying
* <tt>RTPManager</tt>.
*
* @param streamRTPManager ignored
* @param controlType
* @return the return value of the invocation of
* <tt>RTPManager.getControl(String)</tt> on the internal/underlying
* <tt>RTPManager</tt>
*/
public Object getControl(
StreamRTPManager streamRTPManager,
String controlType)
{
return manager.getControl(controlType);
}
/**
* Exposes {@link RTPManager#getGlobalReceptionStats()} on the
* internal/underlying <tt>RTPManager</tt>.
*
* @param streamRTPManager ignored
* @return the return value of the invocation of
* <tt>RTPManager.getGlobalReceptionStats()</tt> on the internal/underlying
* <tt>RTPManager</tt>
*/
public GlobalReceptionStats getGlobalReceptionStats(
StreamRTPManager streamRTPManager)
{
return manager.getGlobalReceptionStats();
}
/**
* Exposes {@link RTPManager#getGlobalTransmissionStats()} on the
* internal/underlying <tt>RTPManager</tt>.
*
* @param streamRTPManager ignored
* @return the return value of the invocation of
* <tt>RTPManager.getGlobalTransmissionStats()</tt> on the
* internal/underlying <tt>RTPManager</tt>
*/
public GlobalTransmissionStats getGlobalTransmissionStats(
StreamRTPManager streamRTPManager)
{
return manager.getGlobalTransmissionStats();
}
/**
* Exposes {@link RTPSessionMgr#getLocalSSRC()} on the internal/underlying
* <tt>RTPSessionMgr</tt>.
*
* @param streamRTPManager ignored
* @return the return value of the invocation of
* <tt>RTPSessionMgr.getLocalSSRC()</tt> on the internal/underlying
* <tt>RTPSessionMgr</tt>
*/
public long getLocalSSRC(StreamRTPManager streamRTPManager)
{
return ((RTPSessionMgr) manager).getLocalSSRC();
}
/**
* Gets the <tt>ReceiveStream</tt>s associated with/related to a neomedia
* <tt>MediaStream</tt> (specified in the form of a
* <tt>StreamRTPManager</tt> instance for the purposes of and in the terms
* of <tt>RTPManagerImpl</tt>).
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> to which the
* returned <tt>ReceiveStream</tt>s are to be related
* @return the <tt>ReceiveStream</tt>s related to/associated with the
* specified <tt>streamRTPManager</tt>
*/
public synchronized Vector<ReceiveStream> getReceiveStreams(
StreamRTPManager streamRTPManager)
{
StreamRTPManagerDesc streamRTPManagerDesc
= getStreamRTPManagerDesc(streamRTPManager, false);
Vector<ReceiveStream> receiveStreams = null;
if (streamRTPManagerDesc != null)
{
Vector<?> managerReceiveStreams = manager.getReceiveStreams();
if (managerReceiveStreams != null)
{
receiveStreams
= new Vector<ReceiveStream>(managerReceiveStreams.size());
for (Object s : managerReceiveStreams)
{
ReceiveStream receiveStream = (ReceiveStream) s;
if (streamRTPManagerDesc.containsReceiveSSRC(
receiveStream.getSSRC()))
receiveStreams.add(receiveStream);
}
}
}
return receiveStreams;
}
/**
* Gets the <tt>SendStream</tt>s associated with/related to a neomedia
* <tt>MediaStream</tt> (specified in the form of a
* <tt>StreamRTPManager</tt> instance for the purposes of and in the terms
* of <tt>RTPManagerImpl</tt>).
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> to which the
* returned <tt>SendStream</tt>s are to be related
* @return the <tt>SendStream</tt>s related to/associated with the specified
* <tt>streamRTPManager</tt>
*/
public synchronized Vector<SendStream> getSendStreams(
StreamRTPManager streamRTPManager)
{
Vector<?> managerSendStreams = manager.getSendStreams();
Vector<SendStream> sendStreams = null;
if (managerSendStreams != null)
{
sendStreams = new Vector<SendStream>(managerSendStreams.size());
for (SendStreamDesc sendStreamDesc : this.sendStreams)
if (managerSendStreams.contains(sendStreamDesc.sendStream))
{
SendStream sendStream
= sendStreamDesc.getSendStream(streamRTPManager, false);
if (sendStream != null)
sendStreams.add(sendStream);
}
}
return sendStreams;
}
private synchronized StreamRTPManagerDesc getStreamRTPManagerDesc(
StreamRTPManager streamRTPManager,
boolean create)
{
for (StreamRTPManagerDesc s : streamRTPManagers)
if (s.streamRTPManager == streamRTPManager)
return s;
StreamRTPManagerDesc s;
if (create)
{
s = new StreamRTPManagerDesc(streamRTPManager);
streamRTPManagers.add(s);
}
else
s = null;
return s;
}
public synchronized void initialize(
StreamRTPManager streamRTPManager,
RTPConnector connector)
{
if (this.connector == null)
{
this.connector = new RTPConnectorImpl();
manager.initialize(this.connector);
}
StreamRTPManagerDesc streamRTPManagerDesc
= getStreamRTPManagerDesc(streamRTPManager, true);
RTPConnectorDesc connectorDesc = streamRTPManagerDesc.connectorDesc;
if ((connectorDesc == null) || (connectorDesc.connector != connector))
{
if (connectorDesc != null)
this.connector.removeConnector(connectorDesc);
streamRTPManagerDesc.connectorDesc
= connectorDesc
= (connector == null)
? null
: new RTPConnectorDesc(streamRTPManagerDesc, connector);
if (connectorDesc != null)
this.connector.addConnector(connectorDesc);
}
}
/**
* Logs information about an RTCP packet using {@link #logger} for debugging
* purposes.
*
* @param obj the object which is the source of the log request
* @param methodName the name of the method on <tt>obj</tt> which is the
* source of the log request
* @param buffer the <tt>byte</tt>s which (possibly) represent an RTCP
* packet to be logged for debugging purposes
* @param offset the position within <tt>buffer</tt> at which the valid data
* begins
* @param length the number of bytes in <tt>buffer</tt> which constitute the
* valid data
*/
private static void logRTCP(
Object obj, String methodName,
byte[] buffer, int offset, int length)
{
/*
* Do the bytes in the specified buffer resemble (a header of) an RTCP
* packet?
*/
if (length > 8)
{
byte b0 = buffer[offset];
int v = (b0 & 0xc0) >>> 6;
if (v == 2)
{
byte b1 = buffer[offset + 1];
int pt = b1 & 0xff;
if (pt == 203 /* BYE */)
{
int sc = b0 & 0x1f;
long ssrc = (sc > 0) ? readInt(buffer, offset + 4) : -1;
logger.trace(
obj.getClass().getName() + '.' + methodName
+ ": RTCP BYE v=" + v + "; pt=" + pt + "; ssrc="
+ ssrc + ';');
}
}
}
}
/**
* Notifies this instance that an RTP or RTCP packet has been received from
* a peer represented by a specific <tt>PushSourceStreamDesc</tt>.
*
* @param streamDesc a <tt>PushSourceStreamDesc</tt> which identifies the
* peer from which an RTP or RTCP packet has been received
* @param buffer the buffer which contains the bytes of the received RTP or
* RTCP packet
* @param offset the zero-based index in <tt>buffer</tt> at which the bytes
* of the received RTP or RTCP packet begin
* @param length the number of bytes in <tt>buffer</tt> beginning at
* <tt>offset</tt> which are allowed to be accessed
* @param read the number of bytes in <tt>buffer</tt> beginning at
* <tt>offset</tt> which represent the received RTP or RTCP packet
* @return the number of bytes in <tt>buffer</tt> beginning at
* <tt>offset</tt> which represent the received RTP or RTCP packet
* @throws IOException if an I/O error occurs while the method processes the
* specified RTP or RTCP packet
*/
private synchronized int read(
PushSourceStreamDesc streamDesc,
byte[] buffer, int offset, int length,
int read)
throws IOException
{
boolean data = streamDesc.data;
StreamRTPManagerDesc streamRTPManagerDesc
= streamDesc.connectorDesc.streamRTPManagerDesc;
Format format = null;
if (data)
{
/*
* Do the bytes in the specified buffer resemble (a header of) an
* RTP packet?
*/
if ((length >= 12)
&& ( ((buffer[offset] & 0xc0) >>> 6) == 2))
{
long ssrc = readInt(buffer, offset + 8);
if (!streamRTPManagerDesc.containsReceiveSSRC(ssrc))
{
if (findStreamRTPManagerDescByReceiveSSRC(
ssrc,
streamRTPManagerDesc)
== null)
streamRTPManagerDesc.addReceiveSSRC(ssrc);
else
return 0;
}
int pt = buffer[offset + 1] & 0x7f;
format = streamRTPManagerDesc.getFormat(pt);
}
}
else if (logger.isTraceEnabled())
logRTCP(this, "read", buffer, offset, read);
/*
* XXX A deadlock between PushSourceStreamImpl.removeStreams and
* createFakeSendStreamIfNecessary has been reported. Since the latter
* method is disabled at the time of this writing, do not even try to
* execute it and thus avoid the deadlock in question.
*/
if (CREATE_FAKE_SEND_STREAM_IF_NECESSARY)
createFakeSendStreamIfNecessary();
OutputDataStreamImpl outputStream
= data
? connector.getDataOutputStream()
: connector.getControlOutputStream();
if (outputStream != null)
{
outputStream.write(
buffer, offset, read,
format,
streamRTPManagerDesc);
}
return read;
}
/**
* Reads an <tt>int</tt> from a specific <tt>byte</tt> buffer starting at a
* specific <tt>offset</tt>. The implementation is the same as
* {@link DataInputStream#readInt()}.
*
* @param buffer the <tt>byte</tt> buffer to read an <tt>int</tt> from
* @param offset the zero-based offset in <tt>buffer</tt> to start reading
* an <tt>int</tt> from
* @return an <tt>int</tt> read from the specified <tt>buffer</tt> starting
* at the specified <tt>offset</tt>
*/
public static int readInt(byte[] buffer, int offset)
{
return
((buffer[offset++] & 0xff) << 24)
| ((buffer[offset++] & 0xff) << 16)
| ((buffer[offset++] & 0xff) << 8)
| (buffer[offset] & 0xff);
}
/**
* Removes a <tt>ReceiveStreamListener</tt> to no longer be notified about
* <tt>ReceiveStreamEvent</tt>s related to a specific neomedia
* <tt>MediaStream</tt> (expressed as a <tt>StreamRTPManager</tt> for the
* purposes of and in the terms of <tt>RTPTranslator</tt>). Since
* {@link #addReceiveStreamListener(StreamRTPManager,
* ReceiveStreamListener)} does not add equal
* <tt>ReceiveStreamListener</tt>s, a single removal is enough to reverse
* multiple additions of equal <tt>ReceiveStreamListener</tt>s.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> which specifies
* the neomedia <tt>MediaStream</tt> with which the
* <tt>ReceiveStreamEvent</tt>s delivered to the specified <tt>listener</tt>
* are to be related
* @param listener the <tt>ReceiveStreamListener</tt> to no longer be
* notified about <tt>ReceiveStreamEvent</tt>s related to the specified
* <tt>streamRTPManager</tt>
*/
public synchronized void removeReceiveStreamListener(
StreamRTPManager streamRTPManager,
ReceiveStreamListener listener)
{
StreamRTPManagerDesc streamRTPManagerDesc
= getStreamRTPManagerDesc(streamRTPManager, false);
if (streamRTPManagerDesc != null)
streamRTPManagerDesc.removeReceiveStreamListener(listener);
}
/**
* Removes a <tt>RemoteListener</tt> to no longer be notified about
* <tt>RemoteEvent</tt>s received by this <tt>RTPTranslatorImpl</tt>.
* Though the request is being made by a specific <tt>StreamRTPManager</tt>,
* the addition of the specified <tt>listener</tt> and the deliveries of the
* <tt>RemoteEvent</tt>s are performed irrespective of any
* <tt>StreamRTPManager</tt> so the removal follows the same logic.
*
* @param streamRTPManager the <tt>StreamRTPManager</tt> which is requesting
* the removal of the specified <tt>RemoteListener</tt>
* @param listener the <tt>RemoteListener</tt> to no longer be notified
* about <tt>RemoteEvent</tt>s received by this <tt>RTPTranslatorImpl</tt>
*/
public void removeRemoteListener(
StreamRTPManager streamRTPManager,
RemoteListener listener)
{
manager.removeRemoteListener(listener);
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality. (Additionally,
* {@link #addSendStreamListener(StreamRTPManager, SendStreamListener)} is
* not implemented for the same reason.)
*/
public void removeSendStreamListener(
StreamRTPManager streamRTPManager,
SendStreamListener listener)
{
// TODO Auto-generated method stub
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality. (Additionally,
* {@link #addSessionListener(StreamRTPManager, SessionListener)} is not
* implemented for the same reason.)
*/
public void removeSessionListener(
StreamRTPManager streamRTPManager,
SessionListener listener)
{
// TODO Auto-generated method stub
}
/**
* Notifies this <tt>ReceiveStreamListener</tt> about a specific event
* related to a <tt>ReceiveStream</tt>.
*
* @param event a <tt>ReceiveStreamEvent</tt> which contains the specifics
* of the event this <tt>ReceiveStreamListener</tt> is being notified about
* @see ReceiveStreamListener#update(ReceiveStreamEvent)
*/
public void update(ReceiveStreamEvent event)
{
/*
* Because NullPointerException was seen during testing, be thorough
* with the null checks.
*/
if (event != null)
{
ReceiveStream receiveStream = event.getReceiveStream();
if (receiveStream != null)
{
StreamRTPManagerDesc streamRTPManagerDesc
= findStreamRTPManagerDescByReceiveSSRC(
receiveStream.getSSRC(),
null);
if (streamRTPManagerDesc != null)
for (ReceiveStreamListener listener
: streamRTPManagerDesc.getReceiveStreamListeners())
listener.update(event);
}
}
}
private static class OutputDataStreamDesc
{
public RTPConnectorDesc connectorDesc;
public OutputDataStream stream;
public OutputDataStreamDesc(
RTPConnectorDesc connectorDesc,
OutputDataStream stream)
{
this.connectorDesc = connectorDesc;
this.stream = stream;
}
}
private static class OutputDataStreamImpl
implements OutputDataStream,
Runnable
{
private static final int WRITE_QUEUE_CAPACITY
= RTPConnectorOutputStream
.MAX_PACKETS_PER_MILLIS_POLICY_PACKET_QUEUE_CAPACITY;
private boolean closed;
private final boolean data;
private final List<OutputDataStreamDesc> streams
= new ArrayList<OutputDataStreamDesc>();
private final RTPTranslatorBuffer[] writeQueue
= new RTPTranslatorBuffer[WRITE_QUEUE_CAPACITY];
private int writeQueueHead;
private int writeQueueLength;
private Thread writeThread;
public OutputDataStreamImpl(boolean data)
{
this.data = data;
}
public synchronized void addStream(
RTPConnectorDesc connectorDesc,
OutputDataStream stream)
{
for (OutputDataStreamDesc streamDesc : streams)
if ((streamDesc.connectorDesc == connectorDesc)
&& (streamDesc.stream == stream))
return;
streams.add(new OutputDataStreamDesc(connectorDesc, stream));
}
public synchronized void close()
{
closed = true;
writeThread = null;
notify();
}
private synchronized void createWriteThread()
{
writeThread = new Thread(this, getClass().getName());
writeThread.setDaemon(true);
writeThread.start();
}
private synchronized int doWrite(
byte[] buffer, int offset, int length,
Format format,
StreamRTPManagerDesc exclusion)
{
int write = 0;
for (int streamIndex = 0, streamCount = streams.size();
streamIndex < streamCount;
streamIndex++)
{
OutputDataStreamDesc streamDesc = streams.get(streamIndex);
StreamRTPManagerDesc streamRTPManagerDesc
= streamDesc.connectorDesc.streamRTPManagerDesc;
if (streamRTPManagerDesc != exclusion)
{
if (data)
{
if ((format != null) && (length > 0))
{
Integer payloadType
= streamRTPManagerDesc.getPayloadType(format);
if ((payloadType == null) && (exclusion != null))
payloadType = exclusion.getPayloadType(format);
if (payloadType != null)
{
int payloadTypeByteIndex = offset + 1;
buffer[payloadTypeByteIndex]
= (byte)
((buffer[payloadTypeByteIndex] & 0x80)
| (payloadType & 0x7f));
}
}
}
else if (logger.isTraceEnabled())
{
logRTCP(
this, "doWrite",
buffer, offset, length);
}
int streamWrite
= streamDesc.stream.write(buffer, offset, length);
if (write < streamWrite)
write = streamWrite;
}
}
return write;
}
public synchronized void removeStreams(RTPConnectorDesc connectorDesc)
{
Iterator<OutputDataStreamDesc> streamIter = streams.iterator();
while (streamIter.hasNext())
{
OutputDataStreamDesc streamDesc = streamIter.next();
if (streamDesc.connectorDesc == connectorDesc)
streamIter.remove();
}
}
public void run()
{
try
{
while (true)
{
int writeIndex;
byte[] buffer;
StreamRTPManagerDesc exclusion;
Format format;
int length;
synchronized (this)
{
if (closed
|| !Thread.currentThread().equals(writeThread))
break;
if (writeQueueLength < 1)
{
boolean interrupted = false;
try
{
wait();
}
catch (InterruptedException ie)
{
interrupted = true;
}
if (interrupted)
Thread.currentThread().interrupt();
continue;
}
writeIndex = writeQueueHead;
RTPTranslatorBuffer write = writeQueue[writeIndex];
buffer = write.data;
write.data = null;
exclusion = write.exclusion;
write.exclusion = null;
format = write.format;
write.format = null;
length = write.length;
write.length = 0;
writeQueueHead++;
if (writeQueueHead >= writeQueue.length)
writeQueueHead = 0;
writeQueueLength
}
try
{
doWrite(buffer, 0, length, format, exclusion);
}
finally
{
synchronized (this)
{
RTPTranslatorBuffer write = writeQueue[writeIndex];
if ((write != null) && (write.data == null))
write.data = buffer;
}
}
}
}
catch (Throwable t)
{
logger.error("Failed to translate RTP packet", t);
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
finally
{
synchronized (this)
{
if (Thread.currentThread().equals(writeThread))
writeThread = null;
if (!closed
&& (writeThread == null)
&& (writeQueueLength > 0))
createWriteThread();
}
}
}
public int write(byte[] buffer, int offset, int length)
{
return doWrite(buffer, offset, length, null, null);
}
public synchronized void write(
byte[] buffer, int offset, int length,
Format format,
StreamRTPManagerDesc exclusion)
{
if (closed)
return;
int writeIndex;
if (writeQueueLength < writeQueue.length)
{
writeIndex
= (writeQueueHead + writeQueueLength) % writeQueue.length;
}
else
{
writeIndex = writeQueueHead;
writeQueueHead++;
if (writeQueueHead >= writeQueue.length)
writeQueueHead = 0;
writeQueueLength
logger.warn("Will not translate RTP packet.");
}
RTPTranslatorBuffer write
= writeQueue[writeIndex];
if (write == null)
writeQueue[writeIndex] = write = new RTPTranslatorBuffer();
byte[] data = write.data;
if ((data == null) || (data.length < length))
write.data = data = new byte[length];
System.arraycopy(buffer, offset, data, 0, length);
write.exclusion = exclusion;
write.format = format;
write.length = length;
writeQueueLength++;
if (writeThread == null)
createWriteThread();
else
notify();
}
}
private static class PushSourceStreamDesc
{
public final RTPConnectorDesc connectorDesc;
public final boolean data;
public final PushSourceStream stream;
public PushSourceStreamDesc(
RTPConnectorDesc connectorDesc,
PushSourceStream stream,
boolean data)
{
this.connectorDesc = connectorDesc;
this.stream = stream;
this.data = data;
}
}
private class PushSourceStreamImpl
implements PushSourceStream,
SourceTransferHandler
{
private final boolean data;
private final List<PushSourceStreamDesc> streams
= new LinkedList<PushSourceStreamDesc>();
private PushSourceStreamDesc streamToReadFrom;
private SourceTransferHandler transferHandler;
public PushSourceStreamImpl(boolean data)
{
this.data = data;
}
public synchronized void addStream(
RTPConnectorDesc connectorDesc,
PushSourceStream stream)
{
for (PushSourceStreamDesc streamDesc : streams)
if ((streamDesc.connectorDesc == connectorDesc)
&& (streamDesc.stream == stream))
return;
streams.add(
new PushSourceStreamDesc(connectorDesc, stream, this.data));
stream.setTransferHandler(this);
}
public void close()
{
// TODO Auto-generated method stub
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public boolean endOfStream()
{
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public ContentDescriptor getContentDescriptor()
{
// TODO Auto-generated method stub
return null;
}
public long getContentLength()
{
return LENGTH_UNKNOWN;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public Object getControl(String controlType)
{
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public Object[] getControls()
{
// TODO Auto-generated method stub
return null;
}
public synchronized int getMinimumTransferSize()
{
int minimumTransferSize = 0;
for (PushSourceStreamDesc streamDesc : streams)
{
int streamMinimumTransferSize
= streamDesc.stream.getMinimumTransferSize();
if (minimumTransferSize < streamMinimumTransferSize)
minimumTransferSize = streamMinimumTransferSize;
}
return minimumTransferSize;
}
public int read(byte[] buffer, int offset, int length)
throws IOException
{
PushSourceStreamDesc streamDesc;
int read;
synchronized (this)
{
streamDesc = streamToReadFrom;
read
= (streamDesc == null)
? 0
: streamDesc.stream.read(buffer, offset, length);
}
if (read > 0)
{
read
= RTPTranslatorImpl.this.read(
streamDesc,
buffer, offset, length,
read);
}
return read;
}
public synchronized void removeStreams(RTPConnectorDesc connectorDesc)
{
Iterator<PushSourceStreamDesc> streamIter = streams.iterator();
while (streamIter.hasNext())
{
PushSourceStreamDesc streamDesc = streamIter.next();
if (streamDesc.connectorDesc == connectorDesc)
{
streamDesc.stream.setTransferHandler(null);
streamIter.remove();
if (streamToReadFrom == streamDesc)
streamToReadFrom = null;
}
}
}
public synchronized void setTransferHandler(
SourceTransferHandler transferHandler)
{
if (this.transferHandler != transferHandler)
{
this.transferHandler = transferHandler;
for (PushSourceStreamDesc streamDesc : streams)
streamDesc.stream.setTransferHandler(this);
}
}
/**
* {@inheritDoc}
*
* Implements
* {@link SourceTransferHandler#transferData(PushSourceStream)}. This
* instance sets itself as the <tt>transferHandler</tt> of all
* <tt>PushSourceStream</tt>s that get added to it (i.e.
* {@link #streams}). When either one of these pushes media data, this
* instance pushes that media data.
*/
public void transferData(PushSourceStream stream)
{
SourceTransferHandler transferHandler = null;
/*
* XXX SourceTransferHandler.transferData(PushSourceStream) will
* have to be invoked outside the synchronized block in order to
* avoid a deadlock involving removeStreams(RTPConnectorDesc).
*/
synchronized (this)
{
for (PushSourceStreamDesc streamDesc : streams)
{
if (streamDesc.stream == stream)
{
streamToReadFrom = streamDesc;
transferHandler = this.transferHandler;
break;
}
}
}
if (transferHandler != null)
transferHandler.transferData(this);
}
}
private static class RTPConnectorDesc
{
public final RTPConnector connector;
public final StreamRTPManagerDesc streamRTPManagerDesc;
public RTPConnectorDesc(
StreamRTPManagerDesc streamRTPManagerDesc,
RTPConnector connector)
{
this.streamRTPManagerDesc = streamRTPManagerDesc;
this.connector = connector;
}
}
/**
* Implements the <tt>RTPConnector</tt> with which this instance initializes
* its <tt>RTPManager</tt>. It delegates to the <tt>RTPConnector</tt> of the
* various <tt>StreamRTPManager</tt>s.
*/
private class RTPConnectorImpl
implements RTPConnector
{
/**
* The <tt>RTPConnector</tt>s this instance delegates to.
*/
private final List<RTPConnectorDesc> connectors
= new LinkedList<RTPConnectorDesc>();
private PushSourceStreamImpl controlInputStream;
private OutputDataStreamImpl controlOutputStream;
private PushSourceStreamImpl dataInputStream;
private OutputDataStreamImpl dataOutputStream;
public synchronized void addConnector(RTPConnectorDesc connector)
{
if (!connectors.contains(connector))
{
connectors.add(connector);
if (this.controlInputStream != null)
{
PushSourceStream controlInputStream = null;
try
{
controlInputStream
= connector.connector.getControlInputStream();
}
catch (IOException ioe)
{
throw new UndeclaredThrowableException(ioe);
}
if (controlInputStream != null)
{
this.controlInputStream.addStream(
connector,
controlInputStream);
}
}
if (this.controlOutputStream != null)
{
OutputDataStream controlOutputStream = null;
try
{
controlOutputStream
= connector.connector.getControlOutputStream();
}
catch (IOException ioe)
{
throw new UndeclaredThrowableException(ioe);
}
if (controlOutputStream != null)
{
this.controlOutputStream.addStream(
connector,
controlOutputStream);
}
}
if (this.dataInputStream != null)
{
PushSourceStream dataInputStream = null;
try
{
dataInputStream
= connector.connector.getDataInputStream();
}
catch (IOException ioe)
{
throw new UndeclaredThrowableException(ioe);
}
if (dataInputStream != null)
{
this.dataInputStream.addStream(
connector,
dataInputStream);
}
}
if (this.dataOutputStream != null)
{
OutputDataStream dataOutputStream = null;
try
{
dataOutputStream
= connector.connector.getDataOutputStream();
}
catch (IOException ioe)
{
throw new UndeclaredThrowableException(ioe);
}
if (dataOutputStream != null)
{
this.dataOutputStream.addStream(
connector,
dataOutputStream);
}
}
}
}
public synchronized void close()
{
if (controlInputStream != null)
{
controlInputStream.close();
controlInputStream = null;
}
if (controlOutputStream != null)
{
controlOutputStream.close();
controlOutputStream = null;
}
if (dataInputStream != null)
{
dataInputStream.close();
dataInputStream = null;
}
if (dataOutputStream != null)
{
dataOutputStream.close();
dataOutputStream = null;
}
for (RTPConnectorDesc connectorDesc : connectors)
connectorDesc.connector.close();
}
public synchronized PushSourceStream getControlInputStream()
throws IOException
{
if (this.controlInputStream == null)
{
this.controlInputStream = new PushSourceStreamImpl(false);
for (RTPConnectorDesc connectorDesc : connectors)
{
PushSourceStream controlInputStream
= connectorDesc.connector.getControlInputStream();
if (controlInputStream != null)
{
this.controlInputStream.addStream(
connectorDesc,
controlInputStream);
}
}
}
return this.controlInputStream;
}
public synchronized OutputDataStreamImpl getControlOutputStream()
throws IOException
{
if (this.controlOutputStream == null)
{
this.controlOutputStream = new OutputDataStreamImpl(false);
for (RTPConnectorDesc connectorDesc : connectors)
{
OutputDataStream controlOutputStream
= connectorDesc.connector.getControlOutputStream();
if (controlOutputStream != null)
{
this.controlOutputStream.addStream(
connectorDesc,
controlOutputStream);
}
}
}
return this.controlOutputStream;
}
public synchronized PushSourceStream getDataInputStream()
throws IOException
{
if (this.dataInputStream == null)
{
this.dataInputStream = new PushSourceStreamImpl(true);
for (RTPConnectorDesc connectorDesc : connectors)
{
PushSourceStream dataInputStream
= connectorDesc.connector.getDataInputStream();
if (dataInputStream != null)
{
this.dataInputStream.addStream(
connectorDesc,
dataInputStream);
}
}
}
return this.dataInputStream;
}
public synchronized OutputDataStreamImpl getDataOutputStream()
throws IOException
{
if (this.dataOutputStream == null)
{
this.dataOutputStream = new OutputDataStreamImpl(true);
for (RTPConnectorDesc connectorDesc : connectors)
{
OutputDataStream dataOutputStream
= connectorDesc.connector.getDataOutputStream();
if (dataOutputStream != null)
{
this.dataOutputStream.addStream(
connectorDesc,
dataOutputStream);
}
}
}
return this.dataOutputStream;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public int getReceiveBufferSize()
{
return -1;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public double getRTCPBandwidthFraction()
{
return -1;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public double getRTCPSenderBandwidthFraction()
{
return -1;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public int getSendBufferSize()
{
return -1;
}
public synchronized void removeConnector(RTPConnectorDesc connector)
{
if (connectors.contains(connector))
{
if (controlInputStream != null)
controlInputStream.removeStreams(connector);
if (controlOutputStream != null)
controlOutputStream.removeStreams(connector);
if (dataInputStream != null)
dataInputStream.removeStreams(connector);
if (dataOutputStream != null)
dataOutputStream.removeStreams(connector);
connectors.remove(connector);
}
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public void setReceiveBufferSize(int receiveBufferSize)
throws IOException
{
// TODO Auto-generated method stub
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public void setSendBufferSize(int sendBufferSize)
throws IOException
{
// TODO Auto-generated method stub
}
}
private static class RTPTranslatorBuffer
{
public byte[] data;
public StreamRTPManagerDesc exclusion;
public Format format;
public int length;
}
private class SendStreamDesc
{
/**
* The <tt>DataSource</tt> from which {@link #sendStream} has been
* created.
*/
public final DataSource dataSource;
/**
* The <tt>SendStream</tt> created from the stream of
* {@link #dataSource} at index {@link #streamIndex}.
*/
public final SendStream sendStream;
/**
* The list of <tt>StreamRTPManager</tt>-specific views to
* {@link #sendStream}.
*/
private final List<SendStreamImpl> sendStreams
= new LinkedList<SendStreamImpl>();
/**
* The number of <tt>StreamRTPManager</tt>s which have started their
* views of {@link #sendStream}.
*/
private int started;
/**
* The index of the stream of {@link #dataSource} from which
* {@link #sendStream} has been created.
*/
public final int streamIndex;
public SendStreamDesc(
DataSource dataSource, int streamIndex,
SendStream sendStream)
{
this.dataSource = dataSource;
this.sendStream = sendStream;
this.streamIndex = streamIndex;
}
void close(SendStreamImpl sendStream)
{
boolean close = false;
synchronized (this)
{
if (sendStreams.contains(sendStream))
{
sendStreams.remove(sendStream);
close = sendStreams.isEmpty();
}
}
if (close)
RTPTranslatorImpl.this.closeSendStream(this);
}
public synchronized SendStreamImpl getSendStream(
StreamRTPManager streamRTPManager,
boolean create)
{
for (SendStreamImpl sendStream : sendStreams)
if (sendStream.streamRTPManager == streamRTPManager)
return sendStream;
if (create)
{
SendStreamImpl sendStream
= new SendStreamImpl(streamRTPManager, this);
sendStreams.add(sendStream);
return sendStream;
}
else
return null;
}
public synchronized int getSendStreamCount()
{
return sendStreams.size();
}
synchronized void start(SendStreamImpl sendStream)
throws IOException
{
if (sendStreams.contains(sendStream))
{
if (started < 1)
{
this.sendStream.start();
started = 1;
}
else
started++;
}
}
synchronized void stop(SendStreamImpl sendStream)
throws IOException
{
if (sendStreams.contains(sendStream))
{
if (started == 1)
{
this.sendStream.stop();
started = 0;
}
else if (started > 1)
started
}
}
}
private static class SendStreamImpl
implements SendStream
{
private boolean closed;
public final SendStreamDesc sendStreamDesc;
private boolean started;
public final StreamRTPManager streamRTPManager;
public SendStreamImpl(
StreamRTPManager streamRTPManager,
SendStreamDesc sendStreamDesc)
{
this.sendStreamDesc = sendStreamDesc;
this.streamRTPManager = streamRTPManager;
}
public void close()
{
if (!closed)
{
try
{
if (started)
stop();
}
catch (IOException ioe)
{
throw new UndeclaredThrowableException(ioe);
}
finally
{
sendStreamDesc.close(this);
closed = true;
}
}
}
public DataSource getDataSource()
{
return sendStreamDesc.sendStream.getDataSource();
}
public Participant getParticipant()
{
return sendStreamDesc.sendStream.getParticipant();
}
public SenderReport getSenderReport()
{
return sendStreamDesc.sendStream.getSenderReport();
}
public TransmissionStats getSourceTransmissionStats()
{
return sendStreamDesc.sendStream.getSourceTransmissionStats();
}
public long getSSRC()
{
return sendStreamDesc.sendStream.getSSRC();
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public int setBitRate(int bitRate)
{
// TODO Auto-generated method stub
return 0;
}
/**
* Not implemented because there are currently no uses of the underlying
* functionality.
*/
public void setSourceDescription(SourceDescription[] sourceDescription)
{
// TODO Auto-generated method stub
}
public void start()
throws IOException
{
if (closed)
{
throw
new IOException(
"Cannot start SendStream"
+ " after it has been closed.");
}
if (!started)
{
sendStreamDesc.start(this);
started = true;
}
}
public void stop()
throws IOException
{
if (!closed && started)
{
sendStreamDesc.stop(this);
started = false;
}
}
}
private static class StreamRTPManagerDesc
{
public RTPConnectorDesc connectorDesc;
private final Map<Integer, Format> formats
= new HashMap<Integer, Format>();
private long[] receiveSSRCs = EMPTY_LONG_ARRAY;
private final List<ReceiveStreamListener> receiveStreamListeners
= new LinkedList<ReceiveStreamListener>();
public final StreamRTPManager streamRTPManager;
public StreamRTPManagerDesc(StreamRTPManager streamRTPManager)
{
this.streamRTPManager = streamRTPManager;
}
public void addFormat(Format format, int payloadType)
{
synchronized (formats)
{
formats.put(payloadType, format);
}
}
public synchronized void addReceiveSSRC(long receiveSSRC)
{
if (!containsReceiveSSRC(receiveSSRC))
{
int receiveSSRCCount = receiveSSRCs.length;
long[] newReceiveSSRCs = new long[receiveSSRCCount + 1];
System.arraycopy(
receiveSSRCs, 0,
newReceiveSSRCs, 0,
receiveSSRCCount);
newReceiveSSRCs[receiveSSRCCount] = receiveSSRC;
receiveSSRCs = newReceiveSSRCs;
}
}
public void addReceiveStreamListener(ReceiveStreamListener listener)
{
synchronized (receiveStreamListeners)
{
if (!receiveStreamListeners.contains(listener))
receiveStreamListeners.add(listener);
}
}
public Format getFormat(int payloadType)
{
synchronized (formats)
{
return formats.get(payloadType);
}
}
public Format[] getFormats()
{
synchronized (this.formats)
{
Collection<Format> formats = this.formats.values();
return formats.toArray(new Format[formats.size()]);
}
}
public Integer getPayloadType(Format format)
{
synchronized (formats)
{
for (Map.Entry<Integer, Format> entry : formats.entrySet())
{
Format entryFormat = entry.getValue();
if (entryFormat.matches(format)
|| format.matches(entryFormat))
return entry.getKey();
}
}
return null;
}
public ReceiveStreamListener[] getReceiveStreamListeners()
{
synchronized (receiveStreamListeners)
{
return
receiveStreamListeners.toArray(
new ReceiveStreamListener[
receiveStreamListeners.size()]);
}
}
public synchronized boolean containsReceiveSSRC(long receiveSSRC)
{
for (int i = 0; i < receiveSSRCs.length; i++)
if (receiveSSRCs[i] == receiveSSRC)
return true;
return false;
}
public void removeReceiveStreamListener(ReceiveStreamListener listener)
{
synchronized (receiveStreamListeners)
{
receiveStreamListeners.remove(listener);
}
}
}
}
|
package org.nschmidt.ldparteditor.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.nschmidt.ldparteditor.enums.Threshold;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.helpers.composite3d.Edger2Settings;
import org.nschmidt.ldparteditor.helpers.math.Vector3d;
import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow;
class VM06Edger2 extends VM05Distance {
private ArrayList<Vertex> verticesToCheck = new ArrayList<>();
protected VM06Edger2(DatFile linkedDatFile) {
super(linkedDatFile);
}
/**
* Investigates the BFC orientation of type 2-5 lines
* @param g the data to analyse
* @return {@code BFC.CW|BFC.CCW|BFC.NOCERTIFY|BFC.NOCLIP}
*/
private byte getBFCorientation(GData g) {
if (bfcMap.containsKey(g)) {
return bfcMap.get(g);
}
return BFC.NOCERTIFY;
}
private void addEdgeEdger2(TreeSet<Vertex> h1, TreeSet<Vertex> h2) {
for (Vertex v1 : h1) {
for (Vertex v2 : h2) {
// if v1 is connected with v2 draw a line from v1 to v2
if (isNeighbour(v1, v2)) {
addLine(v1, v2);
return;
}
}
}
}
private void addLineEdger2(TreeSet<Vertex> h1, TreeSet<Vertex> h2, Edger2Settings es) {
Vertex[] rv1 = new Vertex[1];
Vertex[] rv2 = new Vertex[1];
ArrayList<GData> faces = linkedCommonFaces(h1, h2, rv1, rv2);
if (faces.size() == 2) {
Vertex v1 = rv1[0];
Vertex v2 = rv2[0];
GData g1 = faces.get(0);
GData g2 = faces.get(1);
Vertex v3 = null;
Vertex v4 = null;
Vector3d n1;
Vector3d n2;
if (g1.type() == 3) {
GData3 g3 = (GData3) g1;
Vertex[] vt = triangles.get(g3);
TreeSet<Vertex> tvs = new TreeSet<Vertex>();
tvs.add(vt[0]);
tvs.add(vt[1]);
tvs.add(vt[2]);
tvs.remove(v1);
tvs.remove(v2);
v3 = tvs.iterator().next();
n1 = Vector3d.getNormal(new Vector3d(vt[2]), new Vector3d(vt[0]), new Vector3d(vt[1]));
} else {
GData4 g4 = (GData4) g1;
Vertex[] vq = quads.get(g4);
if (vq[0].equals(v1) && vq[1].equals(v2)) {
n1 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v3 = vq[2];
} else if (vq[1].equals(v1) && vq[2].equals(v2)) {
n1 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v3 = vq[0];
} else if (vq[2].equals(v1) && vq[3].equals(v2)) {
n1 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // 22 3-4-1
v3 = vq[0];
} else if (vq[3].equals(v1) && vq[0].equals(v2)) {
n1 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // 22 3-4-1
v3 = vq[2];
} else if (vq[0].equals(v2) && vq[1].equals(v1)) {
n1 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v3 = vq[2];
} else if (vq[1].equals(v2) && vq[2].equals(v1)) {
n1 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v3 = vq[0];
} else if (vq[2].equals(v2) && vq[3].equals(v1)) {
n1 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // T2 3-4-1
v3 = vq[0];
} else {
n1 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // T2 3-4-1
v3 = vq[2];
}
}
if (g2.type() == 3) {
GData3 g3 = (GData3) g2;
Vertex[] vt = triangles.get(g3);
TreeSet<Vertex> tvs = new TreeSet<Vertex>();
tvs.add(vt[0]);
tvs.add(vt[1]);
tvs.add(vt[2]);
tvs.remove(v1);
tvs.remove(v2);
v4 = tvs.iterator().next();
n2 = Vector3d.getNormal(new Vector3d(vt[2]), new Vector3d(vt[0]), new Vector3d(vt[1]));
} else {
GData4 g4 = (GData4) g2;
Vertex[] vq = quads.get(g4);
if (vq[0].equals(v1) && vq[1].equals(v2)) {
n2 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v4 = vq[2];
} else if (vq[1].equals(v1) && vq[2].equals(v2)) {
n2 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v4 = vq[0];
} else if (vq[2].equals(v1) && vq[3].equals(v2)) {
n2 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // 22 3-4-1
v4 = vq[0];
} else if (vq[3].equals(v1) && vq[0].equals(v2)) {
n2 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // 22 3-4-1
v4 = vq[2];
} else if (vq[0].equals(v2) && vq[1].equals(v1)) {
n2 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v4 = vq[2];
} else if (vq[1].equals(v2) && vq[2].equals(v1)) {
n2 = Vector3d.getNormal(new Vector3d(vq[2]), new Vector3d(vq[0]), new Vector3d(vq[1])); // T1 1-2-3
v4 = vq[0];
} else if (vq[2].equals(v2) && vq[3].equals(v1)) {
n2 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // T2 3-4-1
v4 = vq[0];
} else {
n2 = Vector3d.getNormal(new Vector3d(vq[0]), new Vector3d(vq[1]), new Vector3d(vq[3])); // T2 3-4-1
v4 = vq[2];
}
}
double angle;
if (es.isExtendedRange()) {
if (getBFCorientation(g1) == BFC.CCW) {
n1.negate();
}
if (getBFCorientation(g2) == BFC.CCW) {
n2.negate();
}
angle = Vector3d.angle(n1, n2);
} else {
angle = Vector3d.angle(n1, n2);
if(angle > 90.0) angle = 180.0 - angle;
}
if (angle <= es.getAf().doubleValue()) {
// No Line
} else if (angle > es.getAf().doubleValue() && angle <= es.getAc().doubleValue()) {
// Condline
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addCondline(v1, v2, v3, v4);
} else if (angle > es.getAc().doubleValue() && angle <= es.getAe().doubleValue()) {
// Condline + Edge Line
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addCondline(v1, v2, v3, v4);
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(2));
addLine(v1, v2);
} else {
// Edge Line
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addLine(v1, v2);
}
} else {
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addLine(h1.iterator().next(), h2.iterator().next());
}
}
private void addLineQuadEdger2(GData4 g4, HashSet<AccurateEdge> presentEdges, Edger2Settings es, TreeMap<Vertex, Vertex> snap) {
Vertex[] verts = quads.get(g4);
Vertex v1 = verts[0];
Vertex v2 = verts[2];
if (presentEdges.contains(new AccurateEdge(snap.get(v1), snap.get(v2)))) return;
Vector3d n1;
Vector3d n2;
Vertex v3 = verts[1];
Vertex v4 = verts[3];
n1 = Vector3d.getNormal(new Vector3d(verts[2]), new Vector3d(verts[0]), new Vector3d(verts[1])); // T1 1-2-3
n2 = Vector3d.getNormal(new Vector3d(verts[0]), new Vector3d(verts[1]), new Vector3d(verts[3])); // T2 3-4-1
double angle;
if (es.isExtendedRange()) {
if (getBFCorientation(g4) == BFC.CCW) {
n1.negate();
n2.negate();
}
angle = Vector3d.angle(n1, n2);
} else {
angle = Vector3d.angle(n1, n2);
if(angle > 90.0) angle = 180.0 - angle;
}
if (angle <= es.getAf().doubleValue()) {
// No Line
} else if (angle > es.getAf().doubleValue() && angle <= es.getAc().doubleValue()) {
// Condline
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addCondline(v1, v2, v3, v4);
} else if (angle > es.getAc().doubleValue() && angle <= es.getAe().doubleValue()) {
// Condline + Edge Line
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addCondline(v1, v2, v3, v4);
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(2));
addLine(v1, v2);
} else {
// Edge Line
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
addLine(v1, v2);
}
}
public void addEdges(Edger2Settings es) {
if (linkedDatFile.isReadOnly()) return;
initBFCmap();
verticesToCheck.clear();
final double edsquare = es.getEqualDistance().multiply(es.getEqualDistance(), Threshold.mc).doubleValue() * 1E6;
TreeMap<Vertex, Vertex> snap = new TreeMap<Vertex, Vertex>();
TreeMap<Vertex, TreeSet<Vertex>> snapToOriginal = new TreeMap<Vertex, TreeSet<Vertex>>();
HashMap<AccurateEdge, Integer> edges = new HashMap<AccurateEdge, Integer>();
HashSet<AccurateEdge> presentEdges = new HashSet<AccurateEdge>();
switch (es.getScope()) {
case 0: // All Data
{
Set<Vertex> allVerts = vertexLinkedToPositionInFile.keySet();
for (Vertex vertex : allVerts) {
if (!snap.containsKey(vertex)) snap.put(vertex, vertexWithinDist(edsquare, vertex));
if (snapToOriginal.containsKey(snap.get(vertex))) {
snapToOriginal.get(snap.get(vertex)).add(vertex);
} else {
TreeSet<Vertex> h = new TreeSet<Vertex>();
h.add(vertex);
snapToOriginal.put(snap.get(vertex), h);
}
}
Set<GData2> lins = lines.keySet();
for (GData2 g2 : lins) {
if (!g2.isLine) {
continue;
}
Vertex[] verts = lines.get(g2);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData5> clins = condlines.keySet();
for (GData5 g5 : clins) {
Vertex[] verts = condlines.get(g5);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData3> tris = triangles.keySet();
for (GData3 g3 : tris) {
if (!g3.isTriangle) {
continue;
}
Vertex[] verts = triangles.get(g3);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
Set<GData4> qs = quads.keySet();
for (GData4 g4 : qs) {
if (es.isCondlineOnQuads()) addLineQuadEdger2(g4, presentEdges, es, snap);
Vertex[] verts = quads.get(g4);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[3]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[3]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
GColour tmpCol = Editor3DWindow.getWindow().getLastUsedColour();
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
if (es.getUnmatchedMode() < 2) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) > 1) {
addLineEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2), es);
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(4));
if (es.getUnmatchedMode() != 1) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) == 1) {
addEdgeEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2));
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(tmpCol);
}
break;
case 1: // No Subfile Facets
{
Set<Vertex> allVerts = vertexLinkedToPositionInFile.keySet();
for (Vertex vertex : allVerts) {
if (!snap.containsKey(vertex)) snap.put(vertex, vertexWithinDist(edsquare, vertex));
if (snapToOriginal.containsKey(snap.get(vertex))) {
snapToOriginal.get(snap.get(vertex)).add(vertex);
} else {
TreeSet<Vertex> h = new TreeSet<Vertex>();
h.add(vertex);
snapToOriginal.put(snap.get(vertex), h);
}
}
Set<GData2> lins = lines.keySet();
for (GData2 g2 : lins) {
if (!g2.isLine) {
continue;
}
Vertex[] verts = lines.get(g2);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData5> clins = condlines.keySet();
for (GData5 g5 : clins) {
Vertex[] verts = condlines.get(g5);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData3> tris = triangles.keySet();
for (GData3 g3 : tris) {
if (!lineLinkedToVertices.containsKey(g3) || !g3.isTriangle) continue;
Vertex[] verts = triangles.get(g3);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
Set<GData4> qs = quads.keySet();
for (GData4 g4 : qs) {
if (!lineLinkedToVertices.containsKey(g4)) continue;
addLineQuadEdger2(g4, presentEdges, es, snap);
Vertex[] verts = quads.get(g4);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[3]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[3]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
GColour tmpCol = Editor3DWindow.getWindow().getLastUsedColour();
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
if (es.getUnmatchedMode() < 2) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) > 1) {
addLineEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2), es);
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(4));
if (es.getUnmatchedMode() != 1) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) == 1) {
addEdgeEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2));
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(tmpCol);
}
break;
case 2: // Selected Data Only
{
Set<Vertex> allVerts = vertexLinkedToPositionInFile.keySet();
for (Vertex vertex : allVerts) {
if (!snap.containsKey(vertex)) snap.put(vertex, vertexWithinDist(edsquare, vertex));
if (snapToOriginal.containsKey(snap.get(vertex))) {
snapToOriginal.get(snap.get(vertex)).add(vertex);
} else {
TreeSet<Vertex> h = new TreeSet<Vertex>();
h.add(vertex);
snapToOriginal.put(snap.get(vertex), h);
}
}
Set<GData2> lins = lines.keySet();
for (GData2 g2 : lins) {
if (!g2.isLine) {
continue;
}
Vertex[] verts = lines.get(g2);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData5> clins = condlines.keySet();
for (GData5 g5 : clins) {
Vertex[] verts = condlines.get(g5);
AccurateEdge e1 = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
presentEdges.add(e1);
}
Set<GData3> tris = triangles.keySet();
for (GData3 g3 : tris) {
if (!lineLinkedToVertices.containsKey(g3) || !g3.isTriangle) continue;
Vertex[] verts = triangles.get(g3);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
Set<GData4> qs = quads.keySet();
for (GData4 g4 : qs) {
if (!lineLinkedToVertices.containsKey(g4)) continue;
Vertex[] verts = quads.get(g4);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[3]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[3]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
if (edges.containsKey(e)) {
edges.put(e, edges.get(e) + 1);
} else {
edges.put(e, 1);
}
}
}
}
{
HashSet<AccurateEdge> selectedEdges = new HashSet<AccurateEdge>();
for (GData3 g3 : selectedTriangles) {
if (!g3.isTriangle) continue;
Vertex[] verts = triangles.get(g3);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
}
for (GData4 g4 : selectedQuads) {
addLineQuadEdger2(g4, presentEdges, es, snap);
Vertex[] verts = quads.get(g4);
{
AccurateEdge e = new AccurateEdge(snap.get(verts[0]), snap.get(verts[1]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[1]), snap.get(verts[2]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[2]), snap.get(verts[3]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
{
AccurateEdge e = new AccurateEdge(snap.get(verts[3]), snap.get(verts[0]));
if (!presentEdges.contains(e)) {
selectedEdges.add(e);
}
}
}
Set<AccurateEdge> keySet = edges.keySet();
for(Iterator<AccurateEdge> it = keySet.iterator(); it.hasNext();) {
if (!selectedEdges.contains(it.next())) {
it.remove();
}
}
}
GColour tmpCol = Editor3DWindow.getWindow().getLastUsedColour();
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(16));
if (es.getUnmatchedMode() < 2) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) > 1) {
addLineEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2), es);
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(View.getLDConfigColour(4));
if (es.getUnmatchedMode() != 1) {
Set<AccurateEdge> ee = edges.keySet();
for (AccurateEdge e : ee) {
if (edges.get(e) == 1) {
addEdgeEdger2(snapToOriginal.get(e.v1), snapToOriginal.get(e.v2));
}
}
}
Editor3DWindow.getWindow().setLastUsedColour(tmpCol);
}
break;
default:
break;
}
verticesToCheck.clear();
disposeBFCmap();
if (isModified()) {
setModified(true, true);
}
validateState();
}
private Vertex vertexWithinDist(double edsquare, Vertex ov) {
for (Vertex v : verticesToCheck) {
double dx = v.x - ov.x;
double dy = v.y - ov.y;
double dz = v.z - ov.z;
dx = dx * dx;
dy = dy * dy;
dz = dz * dz;
double total_dist = dx + dy+ dz;
if (total_dist < edsquare) {
return v;
}
}
final Vertex result = new Vertex(ov.X, ov.Y, ov.Z);
verticesToCheck.add(result);
return result;
}
private void initBFCmap() {
linkedDatFile.getBFCorientationMap(bfcMap);
}
private void disposeBFCmap() {
bfcMap.clear();
}
}
|
package org.objectweb.asm.commons;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodAdapter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* A {@link MethodAdapter} that keeps track of stack map frame changes between
* {@link #visitFrame(int, int, Object[], int, Object[]) visitFrame} calls. This
* adapter must be used with the
* {@link org.objectweb.asm.ClassReader#EXPAND_FRAMES} option. Each visit<i>X</i>
* instruction delegates to the next visitor in the chain, if any, and then
* simulates the effect of this instruction on the stack map frame, represented
* by {@link #locals} and {@link #stack}. The next visitor in the chain can get
* the state of the stack map frame <i>before</i> each instruction by reading
* the value of these fields in its visit<i>X</i> methods (this requires a
* reference to the AnalyzerAdapter that is before it in the chain).
* If this adapter is used with a class that does not contain stack map table
* attributes (i.e., pre Java 6 classes) then this adapter may not be able to
* compute the stack map frame for each instruction. In this case no exception
* is thrown but the {@link #locals} and {@link #stack} fields will be null for
* these instructions.
*
* @author Eric Bruneton
*/
public class AnalyzerAdapter extends MethodAdapter {
/**
* <code>List</code> of the local variable slots for current execution
* frame. Primitive types are represented by {@link Opcodes#TOP},
* {@link Opcodes#INTEGER}, {@link Opcodes#FLOAT}, {@link Opcodes#LONG},
* {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or
* {@link Opcodes#UNINITIALIZED_THIS} (long and double are represented by a
* two elements, the second one being TOP). Reference types are represented
* by String objects (representing internal names), and uninitialized types
* by Label objects (this label designates the NEW instruction that created
* this uninitialized value). This field is <tt>null</tt> for unreacheable
* instructions.
*/
public List locals;
/**
* <code>List</code> of the operand stack slots for current execution
* frame. Primitive types are represented by {@link Opcodes#TOP},
* {@link Opcodes#INTEGER}, {@link Opcodes#FLOAT}, {@link Opcodes#LONG},
* {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or
* {@link Opcodes#UNINITIALIZED_THIS} (long and double are represented by a
* two elements, the second one being TOP). Reference types are represented
* by String objects (representing internal names), and uninitialized types
* by Label objects (this label designates the NEW instruction that created
* this uninitialized value). This field is <tt>null</tt> for unreacheable
* instructions.
*/
public List stack;
/**
* The labels that designate the next instruction to be visited. May be
* <tt>null</tt>.
*/
private List labels;
/**
* Information about uninitialized types in the current execution frame.
* This map associates internal names to Label objects. Each label
* designates a NEW instruction that created the currently uninitialized
* types, and the associated internal name represents the NEW operand, i.e.
* the final, initialized type value.
*/
public Map uninitializedTypes;
/**
* The maximum stack size of this method.
*/
private int maxStack;
/**
* The maximum number of local variables of this method.
*/
private int maxLocals;
/**
* Creates a new {@link AnalyzerAdapter}.
*
* @param owner the owner's class name.
* @param access the method's access flags (see {@link Opcodes}).
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
* @param mv the method visitor to which this adapter delegates calls. May
* be <tt>null</tt>.
*/
public AnalyzerAdapter(
final String owner,
final int access,
final String name,
final String desc,
final MethodVisitor mv)
{
super(mv);
locals = new ArrayList();
stack = new ArrayList();
uninitializedTypes = new HashMap();
if ((access & Opcodes.ACC_STATIC) == 0) {
if ("<init>".equals(name)) {
locals.add(Opcodes.UNINITIALIZED_THIS);
} else {
locals.add(owner);
}
}
Type[] types = Type.getArgumentTypes(desc);
for (int i = 0; i < types.length; ++i) {
Type type = types[i];
switch (type.getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
case Type.INT:
locals.add(Opcodes.INTEGER);
break;
case Type.FLOAT:
locals.add(Opcodes.FLOAT);
break;
case Type.LONG:
locals.add(Opcodes.LONG);
locals.add(Opcodes.TOP);
break;
case Type.DOUBLE:
locals.add(Opcodes.DOUBLE);
locals.add(Opcodes.TOP);
break;
case Type.ARRAY:
locals.add(types[i].getDescriptor());
break;
// case Type.OBJECT:
default:
locals.add(types[i].getInternalName());
}
}
}
public void visitFrame(
final int type,
final int nLocal,
final Object[] local,
final int nStack,
final Object[] stack)
{
if (type != Opcodes.F_NEW) { // uncompressed frame
throw new IllegalStateException("ClassReader.accept() should be called with EXPAND_FRAMES flag");
}
if (mv != null) {
mv.visitFrame(type, nLocal, local, nStack, stack);
}
if (this.locals != null) {
this.locals.clear();
this.stack.clear();
} else {
this.locals = new ArrayList();
this.stack = new ArrayList();
}
visitFrameTypes(nLocal, local, this.locals);
visitFrameTypes(nStack, stack, this.stack);
maxStack = Math.max(maxStack, this.stack.size());
}
private static void visitFrameTypes(
final int n,
final Object[] types,
final List result)
{
for (int i = 0; i < n; ++i) {
Object type = types[i];
result.add(type);
if (type == Opcodes.LONG || type == Opcodes.DOUBLE) {
result.add(Opcodes.TOP);
}
}
}
public void visitInsn(final int opcode) {
if (mv != null) {
mv.visitInsn(opcode);
}
execute(opcode, 0, null);
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN)
|| opcode == Opcodes.ATHROW)
{
this.locals = null;
this.stack = null;
}
}
public void visitIntInsn(final int opcode, final int operand) {
if (mv != null) {
mv.visitIntInsn(opcode, operand);
}
execute(opcode, operand, null);
}
public void visitVarInsn(final int opcode, final int var) {
if (mv != null) {
mv.visitVarInsn(opcode, var);
}
execute(opcode, var, null);
}
public void visitTypeInsn(final int opcode, final String type) {
if (opcode == Opcodes.NEW) {
if (labels == null) {
Label l = new Label();
labels = new ArrayList(3);
labels.add(l);
if (mv != null) {
mv.visitLabel(l);
}
}
for (int i = 0; i < labels.size(); ++i) {
uninitializedTypes.put(labels.get(i), type);
}
}
if (mv != null) {
mv.visitTypeInsn(opcode, type);
}
execute(opcode, 0, type);
}
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc)
{
if (mv != null) {
mv.visitFieldInsn(opcode, owner, name, desc);
}
execute(opcode, 0, desc);
}
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String desc)
{
if (mv != null) {
mv.visitMethodInsn(opcode, owner, name, desc);
}
if (this.locals == null) {
labels = null;
return;
}
pop(desc);
if (opcode != Opcodes.INVOKESTATIC && opcode != Opcodes.INVOKEDYNAMIC) {
Object t = pop();
if (opcode == Opcodes.INVOKESPECIAL && name.charAt(0) == '<') {
Object u;
if (t == Opcodes.UNINITIALIZED_THIS) {
u = owner;
} else {
u = uninitializedTypes.get(t);
}
for (int i = 0; i < locals.size(); ++i) {
if (locals.get(i) == t) {
locals.set(i, u);
}
}
for (int i = 0; i < stack.size(); ++i) {
if (stack.get(i) == t) {
stack.set(i, u);
}
}
}
}
pushDesc(desc);
labels = null;
}
public void visitJumpInsn(final int opcode, final Label label) {
if (mv != null) {
mv.visitJumpInsn(opcode, label);
}
execute(opcode, 0, null);
if (opcode == Opcodes.GOTO) {
this.locals = null;
this.stack = null;
}
}
public void visitLabel(final Label label) {
if (mv != null) {
mv.visitLabel(label);
}
if (labels == null) {
labels = new ArrayList(3);
}
labels.add(label);
}
public void visitLdcInsn(final Object cst) {
if (mv != null) {
mv.visitLdcInsn(cst);
}
if (this.locals == null) {
labels = null;
return;
}
if (cst instanceof Integer) {
push(Opcodes.INTEGER);
} else if (cst instanceof Long) {
push(Opcodes.LONG);
push(Opcodes.TOP);
} else if (cst instanceof Float) {
push(Opcodes.FLOAT);
} else if (cst instanceof Double) {
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
} else if (cst instanceof String) {
push("java/lang/String");
} else if (cst instanceof Type) {
push("java/lang/Class");
} else {
throw new IllegalArgumentException();
}
labels = null;
}
public void visitIincInsn(final int var, final int increment) {
if (mv != null) {
mv.visitIincInsn(var, increment);
}
execute(Opcodes.IINC, var, null);
}
public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label[] labels)
{
if (mv != null) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
}
execute(Opcodes.TABLESWITCH, 0, null);
this.locals = null;
this.stack = null;
}
public void visitLookupSwitchInsn(
final Label dflt,
final int[] keys,
final Label[] labels)
{
if (mv != null) {
mv.visitLookupSwitchInsn(dflt, keys, labels);
}
execute(Opcodes.LOOKUPSWITCH, 0, null);
this.locals = null;
this.stack = null;
}
public void visitMultiANewArrayInsn(final String desc, final int dims) {
if (mv != null) {
mv.visitMultiANewArrayInsn(desc, dims);
}
execute(Opcodes.MULTIANEWARRAY, dims, desc);
}
public void visitMaxs(final int maxStack, final int maxLocals) {
if (mv != null) {
this.maxStack = Math.max(this.maxStack, maxStack);
this.maxLocals = Math.max(this.maxLocals, maxLocals);
mv.visitMaxs(this.maxStack, this.maxLocals);
}
}
private Object get(final int local) {
maxLocals = Math.max(maxLocals, local);
return local < locals.size() ? locals.get(local) : Opcodes.TOP;
}
private void set(final int local, final Object type) {
maxLocals = Math.max(maxLocals, local);
while (local >= locals.size()) {
locals.add(Opcodes.TOP);
}
locals.set(local, type);
}
private void push(final Object type) {
stack.add(type);
maxStack = Math.max(maxStack, stack.size());
}
private void pushDesc(final String desc) {
int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0;
switch (desc.charAt(index)) {
case 'V':
return;
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
push(Opcodes.INTEGER);
return;
case 'F':
push(Opcodes.FLOAT);
return;
case 'J':
push(Opcodes.LONG);
push(Opcodes.TOP);
return;
case 'D':
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
return;
case '[':
if (index == 0) {
push(desc);
} else {
push(desc.substring(index, desc.length()));
}
break;
// case 'L':
default:
if (index == 0) {
push(desc.substring(1, desc.length() - 1));
} else {
push(desc.substring(index + 1, desc.length() - 1));
}
}
}
private Object pop() {
return stack.remove(stack.size() - 1);
}
private void pop(final int n) {
int size = stack.size();
int end = size - n;
for (int i = size - 1; i >= end; --i) {
stack.remove(i);
}
}
private void pop(final String desc) {
char c = desc.charAt(0);
if (c == '(') {
int n = 0;
Type[] types = Type.getArgumentTypes(desc);
for (int i = 0; i < types.length; ++i) {
n += types[i].getSize();
}
pop(n);
} else if (c == 'J' || c == 'D') {
pop(2);
} else {
pop(1);
}
}
private void execute(final int opcode, final int iarg, final String sarg) {
if (this.locals == null) {
labels = null;
return;
}
Object t1, t2, t3, t4;
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
case Opcodes.GOTO:
case Opcodes.RETURN:
break;
case Opcodes.ACONST_NULL:
push(Opcodes.NULL);
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
push(Opcodes.INTEGER);
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
push(Opcodes.LONG);
push(Opcodes.TOP);
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
push(Opcodes.FLOAT);
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
break;
case Opcodes.ILOAD:
case Opcodes.FLOAD:
case Opcodes.ALOAD:
push(get(iarg));
break;
case Opcodes.LLOAD:
case Opcodes.DLOAD:
push(get(iarg));
push(Opcodes.TOP);
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
pop(2);
push(Opcodes.INTEGER);
break;
case Opcodes.LALOAD:
case Opcodes.D2L:
pop(2);
push(Opcodes.LONG);
push(Opcodes.TOP);
break;
case Opcodes.FALOAD:
pop(2);
push(Opcodes.FLOAT);
break;
case Opcodes.DALOAD:
case Opcodes.L2D:
pop(2);
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
break;
case Opcodes.AALOAD:
pop(1);
t1 = pop();
pushDesc(((String) t1).substring(1));
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
t1 = pop();
set(iarg, t1);
if (iarg > 0) {
t2 = get(iarg - 1);
if (t2 == Opcodes.LONG || t2 == Opcodes.DOUBLE) {
set(iarg - 1, Opcodes.TOP);
}
}
break;
case Opcodes.LSTORE:
case Opcodes.DSTORE:
pop(1);
t1 = pop();
set(iarg, t1);
set(iarg + 1, Opcodes.TOP);
if (iarg > 0) {
t2 = get(iarg - 1);
if (t2 == Opcodes.LONG || t2 == Opcodes.DOUBLE) {
set(iarg - 1, Opcodes.TOP);
}
}
break;
case Opcodes.IASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
pop(3);
break;
case Opcodes.LASTORE:
case Opcodes.DASTORE:
pop(4);
break;
case Opcodes.POP:
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.TABLESWITCH:
case Opcodes.LOOKUPSWITCH:
case Opcodes.ATHROW:
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
pop(1);
break;
case Opcodes.POP2:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
pop(2);
break;
case Opcodes.DUP:
t1 = pop();
push(t1);
push(t1);
break;
case Opcodes.DUP_X1:
t1 = pop();
t2 = pop();
push(t1);
push(t2);
push(t1);
break;
case Opcodes.DUP_X2:
t1 = pop();
t2 = pop();
t3 = pop();
push(t1);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.DUP2:
t1 = pop();
t2 = pop();
push(t2);
push(t1);
push(t2);
push(t1);
break;
case Opcodes.DUP2_X1:
t1 = pop();
t2 = pop();
t3 = pop();
push(t2);
push(t1);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.DUP2_X2:
t1 = pop();
t2 = pop();
t3 = pop();
t4 = pop();
push(t2);
push(t1);
push(t4);
push(t3);
push(t2);
push(t1);
break;
case Opcodes.SWAP:
t1 = pop();
t2 = pop();
push(t1);
push(t2);
break;
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
case Opcodes.IDIV:
case Opcodes.IREM:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.L2I:
case Opcodes.D2I:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
pop(2);
push(Opcodes.INTEGER);
break;
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
case Opcodes.LDIV:
case Opcodes.LREM:
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
pop(4);
push(Opcodes.LONG);
push(Opcodes.TOP);
break;
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
case Opcodes.FDIV:
case Opcodes.FREM:
case Opcodes.L2F:
case Opcodes.D2F:
pop(2);
push(Opcodes.FLOAT);
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
case Opcodes.DDIV:
case Opcodes.DREM:
pop(4);
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
pop(3);
push(Opcodes.LONG);
push(Opcodes.TOP);
break;
case Opcodes.IINC:
set(iarg, Opcodes.INTEGER);
break;
case Opcodes.I2L:
case Opcodes.F2L:
pop(1);
push(Opcodes.LONG);
push(Opcodes.TOP);
break;
case Opcodes.I2F:
pop(1);
push(Opcodes.FLOAT);
break;
case Opcodes.I2D:
case Opcodes.F2D:
pop(1);
push(Opcodes.DOUBLE);
push(Opcodes.TOP);
break;
case Opcodes.F2I:
case Opcodes.ARRAYLENGTH:
case Opcodes.INSTANCEOF:
pop(1);
push(Opcodes.INTEGER);
break;
case Opcodes.LCMP:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
pop(4);
push(Opcodes.INTEGER);
break;
case Opcodes.JSR:
case Opcodes.RET:
throw new RuntimeException("JSR/RET are not supported");
case Opcodes.GETSTATIC:
pushDesc(sarg);
break;
case Opcodes.PUTSTATIC:
pop(sarg);
break;
case Opcodes.GETFIELD:
pop(1);
pushDesc(sarg);
break;
case Opcodes.PUTFIELD:
pop(sarg);
pop();
break;
case Opcodes.NEW:
push(labels.get(0));
break;
case Opcodes.NEWARRAY:
pop();
switch (iarg) {
case Opcodes.T_BOOLEAN:
pushDesc("[Z");
break;
case Opcodes.T_CHAR:
pushDesc("[C");
break;
case Opcodes.T_BYTE:
pushDesc("[B");
break;
case Opcodes.T_SHORT:
pushDesc("[S");
break;
case Opcodes.T_INT:
pushDesc("[I");
break;
case Opcodes.T_FLOAT:
pushDesc("[F");
break;
case Opcodes.T_DOUBLE:
pushDesc("[D");
break;
// case Opcodes.T_LONG:
default:
pushDesc("[J");
break;
}
break;
case Opcodes.ANEWARRAY:
pop();
pushDesc("[" + Type.getObjectType(sarg));
break;
case Opcodes.CHECKCAST:
pop();
pushDesc(Type.getObjectType(sarg).getDescriptor());
break;
// case Opcodes.MULTIANEWARRAY:
default:
pop(iarg);
pushDesc(sarg);
break;
}
labels = null;
}
}
|
package org.opencms.xml.sitemap;
import org.opencms.configuration.CmsSystemConfiguration;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlSitemap;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.loader.CmsLoaderException;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsResourceInit;
import org.opencms.main.OpenCms;
import org.opencms.monitor.CmsMemoryMonitor;
import org.opencms.site.CmsSite;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.content.CmsXmlContentProperty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.apache.commons.logging.Log;
/**
* Sitemap Manager.<p>
*
* Provides all relevant functions for using the sitemap.<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.9 $
*
* @since 7.9.2
*/
public class CmsSitemapManager {
/**
* Entry data. As a result from calling the {@link #getEntry()} method.<p>
*
* @see #getEntry()
*/
protected class EntryData {
/** The entry. */
private CmsSiteEntryBean m_entry;
/** The properties. */
private Map<String, String> m_properties;
/** The sitemap. */
private CmsXmlSitemap m_sitemap;
/**
* Default constructor.<p>
*
* @param entry the entry
* @param properties the properties
* @param sitemap the sitemap
*/
public EntryData(CmsSiteEntryBean entry, Map<String, String> properties, CmsXmlSitemap sitemap) {
m_entry = entry;
m_properties = properties;
m_sitemap = sitemap;
}
/**
* Returns the entry.<p>
*
* @return the entry
*/
public CmsSiteEntryBean getEntry() {
return m_entry;
}
/**
* Returns the properties.<p>
*
* @return the properties
*/
public Map<String, String> getProperties() {
return m_properties;
}
/**
* Returns the sitemap.<p>
*
* @return the sitemap
*/
public CmsXmlSitemap getSitemap() {
return m_sitemap;
}
}
/** Request attribute name constant fro the current sitemap URI. */
public static final String ATTR_SITEMAP_CURRENT_URI = "__currentSitemapURI";
/** Request attribute name constant for the current sitemap entry bean. */
public static final String ATTR_SITEMAP_ENTRY = "__currentSitemapEntry";
/** Constant property name for sub-sitemap reference. */
public static final String PROPERTY_SITEMAP = "sitemap";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsSitemapManager.class);
/** The cache instance. */
protected CmsSitemapCache m_cache;
/**
* Creates a new sitemap manager.<p>
*
* @param memoryMonitor the memory monitor instance
* @param systemConfiguration the system configuration
*/
public CmsSitemapManager(CmsMemoryMonitor memoryMonitor, CmsSystemConfiguration systemConfiguration) {
// initialize the sitemap cache
CmsSitemapCacheSettings cacheSettings = systemConfiguration.getSitemapCacheSettings();
if (cacheSettings == null) {
cacheSettings = new CmsSitemapCacheSettings();
}
m_cache = new CmsSitemapCache(memoryMonitor, cacheSettings);
// check for the resource init handler
for (I_CmsResourceInit initHandler : systemConfiguration.getResourceInitHandlers()) {
if (initHandler instanceof CmsSitemapResourceHandler) {
// found
return;
}
}
// not found
LOG.warn(Messages.get().getBundle().key(
Messages.LOG_WARN_SITEMAP_HANDLER_NOT_CONFIGURED_1,
CmsSitemapResourceHandler.class.getName()));
}
/**
* Creates a new element of a given type at the configured location.<p>
*
* @param cms the current opencms context
* @param sitemapUri the sitemap uri
* @param request the current request
* @param type the type of the element to be created
*
* @return the CmsResource representing the newly created element
*
* @throws CmsException if something goes wrong
*/
public CmsResource createNewElement(CmsObject cms, String sitemapUri, ServletRequest request, String type)
throws CmsException {
// TODO: implement this
int todo;
return OpenCms.getADEManager().createNewElement(cms, sitemapUri, request, type);
}
/**
* Creates a new empty sitemap from a list of sitemap entries.<p>
*
* @param cms the CmsObject to use for VFS operations
* @param title the title for the new sitemap
* @param sitemapUri the URI of the current sitemap
* @param request the HTTP request
*
* @return the resource representing the new sitemap
*
* @throws CmsException if something goes wrong
*/
public CmsResource createSitemap(CmsObject cms, String title, String sitemapUri, ServletRequest request)
throws CmsException {
CmsResource newSitemapRes = createNewElement(
cms,
sitemapUri,
request,
CmsResourceTypeXmlSitemap.getStaticTypeName());
String sitemapPath = cms.getSitePath(newSitemapRes);
CmsProperty titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, title, title);
List<CmsProperty> props = new ArrayList<CmsProperty>();
props.add(titleProp);
cms.writePropertyObjects(sitemapPath, props);
cms.unlockResource(sitemapPath);
return newSitemapRes;
}
/**
* Returns the list of creatable elements.<p>
*
* @param cms the current opencms context
* @param sitemapUri the sitemap uri
* @param request the current request
*
* @return the list of creatable elements
*
* @throws CmsException if something goes wrong
*/
public List<CmsResource> getCreatableElements(CmsObject cms, String sitemapUri, ServletRequest request)
throws CmsException {
// TODO: implement this
int todo;
return OpenCms.getADEManager().getCreatableElements(cms, sitemapUri, request);
}
/**
* Reads the current sitemap entry bean from the request.<p>
*
* @param req the servlet request
*
* @return the sitemap entry bean, or <code>null</code> if not found
*/
public CmsSiteEntryBean getCurrentEntry(ServletRequest req) {
return (CmsSiteEntryBean)req.getAttribute(ATTR_SITEMAP_ENTRY);
}
/**
* Reads the current sitemap URI from the request.<p>
*
* @param req the servlet request
*
* @return the sitemap URI, or <code>null</code> if the sitemap is not used
*/
public String getCurrentUri(ServletRequest req) {
return (String)req.getAttribute(ATTR_SITEMAP_CURRENT_URI);
}
/**
* Returns the property configuration for a given resource.<p>
*
* @param cms the current cms context
* @param resource the resource
*
* @return the property configuration
*
* @throws CmsException if something goes wrong
*/
public Map<String, CmsXmlContentProperty> getElementPropertyConfiguration(CmsObject cms, CmsResource resource)
throws CmsException {
return CmsXmlContentDefinition.getContentHandlerForResource(cms, resource).getProperties();
}
/**
* Returns the site entry for the given URI, or <code>null</code> if not found.<p>
*
* @param cms the current CMS context
* @param uri the URI to look for
*
* @return the site entry for the given URI, or <code>null</code> if not found
*
* @throws CmsException if something goes wrong
*/
public CmsSiteEntryBean getEntryForUri(CmsObject cms, String uri) throws CmsException {
String path = cms.getRequestContext().addSiteRoot(uri);
// check the cache
boolean online = cms.getRequestContext().currentProject().isOnlineProject();
CmsSiteEntryBean uriEntry = m_cache.getUri(path, online);
if (uriEntry != null) {
// found in cache
return uriEntry;
}
// check the missed cache
if (m_cache.getMissingUri(path, online) != null) {
// already marked as not found
return null;
}
// get it
EntryData data = getEntry(cms, uri, online, false);
if (data == null) {
// cache the missed attempt
m_cache.setMissingUri(path, online);
return null;
}
// cache the found entry
uriEntry = data.getEntry();
m_cache.setUri(path, uriEntry, online);
return uriEntry;
}
/**
* Returns the searchable resource types.<p>
*
* @return the resource types
*/
public List<I_CmsResourceType> getSearchableResourceTypes() {
//TODO: the searchable resource types should be read from configuration
List<I_CmsResourceType> types = new ArrayList<I_CmsResourceType>();
try {
types.add(OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlContainerPage.getStaticTypeName()));
} catch (CmsLoaderException e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return types;
}
/**
* Returns the sitemap properties for a given URI, with search.<p>
*
* @param cms the current cms context
* @param uri the URI
*
* @return the properties, taken also into account default values, could be <code>null</code> if URI not found
*
* @throws CmsException if something goes wrong
*/
public Map<String, String> getSearchProperties(CmsObject cms, String uri) throws CmsException {
String path = cms.getRequestContext().addSiteRoot(uri);
// check the cache
boolean online = cms.getRequestContext().currentProject().isOnlineProject();
Map<String, String> properties = m_cache.getSearchProps(path, online);
if (properties != null) {
// found in cache
return properties;
}
// check the missed cache
if (m_cache.getMissingUri(path, online) != null) {
// already marked as not found
return null;
}
// try to find the sitemap entry with its properties
EntryData data = getEntry(cms, path, online, true);
if (data == null) {
// cache the missed attempt
m_cache.setMissingUri(path, online);
return null;
}
// merge default properties
properties = new HashMap<String, String>();
properties.putAll(getDefaultProperties(cms, data.getSitemap().getFile(), online));
properties.putAll(data.getProperties());
// cache the found properties
m_cache.setSearchProps(path, properties, online);
return properties;
}
/**
* Clean up at shutdown time. Only intended to be called at system shutdown.<p>
*
* @see org.opencms.main.OpenCmsCore#shutDown
*/
public void shutdown() {
m_cache.shutdown();
}
/**
* Returns the default sitemap properties.<p>
*
* @param cms the current cms context
* @param resource the resource, should a sitemap
* @param online if online or offline, the same as in the cms context, but just to not access it again
*
* @return the default sitemap properties
*
* @throws CmsException if something goes wrong
*/
protected Map<String, String> getDefaultProperties(CmsObject cms, CmsResource resource, boolean online)
throws CmsException {
Map<String, String> defProps = m_cache.getDefaultProps(online);
if (defProps != null) {
return defProps;
}
defProps = new HashMap<String, String>();
Map<String, CmsXmlContentProperty> propertiesConf = OpenCms.getADEManager().getElementPropertyConfiguration(
cms,
resource);
Iterator<Map.Entry<String, CmsXmlContentProperty>> itProperties = propertiesConf.entrySet().iterator();
while (itProperties.hasNext()) {
Map.Entry<String, CmsXmlContentProperty> entry = itProperties.next();
String propertyName = entry.getKey();
CmsXmlContentProperty conf = entry.getValue();
CmsMacroResolver.resolveMacros(conf.getWidgetConfiguration(), cms, Messages.get().getBundle());
defProps.put(propertyName, conf.getDefault());
}
m_cache.setDefaultProps(defProps, online);
return defProps;
}
/**
* Returns the site entry for the given URI, or <code>null</code> if not found.<p>
*
* @param cms the current CMS context
* @param uri the URI to look for
* @param online if online or offline, the same than in the cms context, but just to not access it again
* @param collectProperties if to collect parent entries properties
*
* @return the site entry for the given URI, or <code>null</code> if not found
*
* @throws CmsException if something goes wrong
*/
protected EntryData getEntry(CmsObject cms, String uri, boolean online, boolean collectProperties)
throws CmsException {
CmsUUID logId = null;
if (LOG.isDebugEnabled()) {
logId = new CmsUUID(); // unique id to identify the request
LOG.debug(Messages.get().container(Messages.LOG_DEBUG_SITEMAP_ENTRY_3, logId, uri, Boolean.valueOf(online)).key());
}
// find the sitemap
CmsXmlSitemap sitemapXml = null;
String sitemapFolder = uri;
while (sitemapFolder != null) {
if (cms.existsResource(sitemapFolder)) {
String prop = cms.readPropertyObject(sitemapFolder, CmsPropertyDefinition.PROPERTY_SITEMAP, true).getValue();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(prop)) {
if (cms.getRequestContext().getSiteRoot().equals("")) {
// adjust the property path, since it will be a site path, and we are in the root
CmsSite site = OpenCms.getSiteManager().getSiteForRootPath(uri);
if (site != null) {
prop = site.getSiteRoot() + prop;
}
}
if (cms.existsResource(prop)) {
sitemapXml = CmsXmlSitemapFactory.unmarshal(cms, cms.readResource(prop));
break;
}
}
}
sitemapFolder = CmsResource.getParentFolder(sitemapFolder);
}
if ((sitemapXml == null) || (sitemapFolder == null)) {
// sitemap not found
return null;
}
CmsSitemapBean sitemap = sitemapXml.getSitemap(cms, cms.getRequestContext().getLocale());
if ((sitemap == null) || sitemap.getSiteEntries().isEmpty()) {
return null;
}
LinkedList<String> entryPaths = new LinkedList<String>(CmsStringUtil.splitAsList(
normalizePath(uri.substring(sitemapFolder.length())),
"/"));
// property collection
Map<String, String> properties = new HashMap<String, String>();
if (collectProperties) {
// start with the root entry properties
properties.putAll(sitemap.getSiteEntries().get(0).getProperties());
}
// special case for '/'
if (entryPaths.isEmpty()) {
if (sitemap.getSiteEntries().isEmpty()) {
return null;
}
CmsSiteEntryBean entry = sitemap.getSiteEntries().get(0);
entry.setPosition(0);
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_FOUND_3,
logId,
new Integer(0),
entry.getName()).key());
return new EntryData(entry, properties, sitemapXml);
}
// get started
String uriPath = cms.getRequestContext().getSiteRoot() + sitemapFolder;
List<CmsSiteEntryBean> subEntries = sitemap.getSiteEntries().get(0).getSubEntries();
boolean finished = false;
while (!finished) {
String name = entryPaths.removeFirst();
LOG.debug(Messages.get().container(Messages.LOG_DEBUG_SITEMAP_ENTRY_CHECK_2, logId, uriPath).key());
uriPath += "/" + name;
// check the missed cache
if (m_cache.getMissingUri(uriPath, online) != null) {
// already marked as not found
LOG.debug(Messages.get().container(Messages.LOG_DEBUG_SITEMAP_ENTRY_MISSING_2, logId, uriPath).key());
return null;
}
int position = 0;
int size = subEntries.size();
for (; position < size; position++) {
CmsSiteEntryBean entry = subEntries.get(position);
if (!entry.getName().equals(name)) {
// no match
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_NO_MATCH_3,
logId,
new Integer(position),
entry.getName()).key());
continue;
}
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_MATCH_3,
logId,
new Integer(position),
entry.getName()).key());
if (collectProperties) {
properties.putAll(entry.getProperties());
}
if (entryPaths.isEmpty()) {
// if nothing left, we got a match
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_FOUND_3,
logId,
new Integer(position),
entry.getName()).key());
entry.setPosition(position);
return new EntryData(entry, properties, sitemapXml);
} else {
// continue with sub-entries
subEntries = entry.getSubEntries();
if (subEntries.isEmpty()) {
// check sitemap property
String subSitemapId = entry.getProperties().get(CmsSitemapManager.PROPERTY_SITEMAP);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(subSitemapId)) {
// switch to sub-sitemap
CmsResource subSitemap = cms.readResource(new CmsUUID(subSitemapId));
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_SUBSITEMAP_2,
logId,
cms.getSitePath(subSitemap)).key());
sitemapXml = CmsXmlSitemapFactory.unmarshal(cms, subSitemap);
sitemap = sitemapXml.getSitemap(cms, cms.getRequestContext().getLocale());
if (sitemap == null) {
// no sitemap found
return null;
}
subEntries = sitemap.getSiteEntries();
}
}
finished = subEntries.isEmpty();
if (finished) {
LOG.debug(Messages.get().container(
Messages.LOG_DEBUG_SITEMAP_NO_SUBENTRIES_3,
logId,
new Integer(position),
entry.getName()).key());
}
}
break;
}
if (position == size) {
// not found
finished = true;
LOG.debug(Messages.get().container(Messages.LOG_DEBUG_SITEMAP_NOT_FOUND_2, logId, uriPath).key());
}
}
return null;
}
/**
* Normalizes the given path by removing any leading and trailing slashes.<p>
*
* @param path the path to normalize
*
* @return the normalized path
*/
protected String normalizePath(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
}
|
package org.royaldev.royalcommands.rcommands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
public class Time implements CommandExecutor {
RoyalCommands plugin;
public Time(RoyalCommands plugin) {
this.plugin = plugin;
}
public static void smoothTimeChange(long time, World world) {
if (time >= world.getTime()) for (long i = world.getTime(); i < time; i++) world.setTime(i);
else for (long i = world.getTime(); i > time; i--) world.setTime(i);
}
public static Long getValidTime(String time) {
Long vtime;
try {
vtime = Long.valueOf(time);
} catch (Exception e) {
if (time.equalsIgnoreCase("day")) vtime = 0L;
else if (time.equalsIgnoreCase("midday")) vtime = 6000L;
else if (time.equalsIgnoreCase("sunset")) vtime = 12000L;
else if (time.equalsIgnoreCase("night")) vtime = 14000L;
else if (time.equalsIgnoreCase("midnight")) vtime = 18000L;
else if (time.equalsIgnoreCase("sunrise")) vtime = 23000L;
else return null;
}
return vtime;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("time")) {
if (!plugin.isAuthorized(cs, "rcmds.time")) {
RUtils.dispNoPerms(cs);
return true;
}
if (cs instanceof ConsoleCommandSender) {
if (args.length < 1) {
cs.sendMessage(cmd.getDescription());
return false;
}
if (getValidTime(args[0]) == null) {
cs.sendMessage(ChatColor.RED + "Invalid time specified!");
return true;
}
long time = getValidTime(args[0]);
if (time < 0) {
cs.sendMessage(ChatColor.RED + "The time entered was invalid!");
return true;
}
if (args.length == 1) {
for (World w : plugin.getServer().getWorlds()) {
if (plugin.smoothTime) smoothTimeChange(time, w);
w.setTime(time);
}
cs.sendMessage(ChatColor.BLUE + "Time in all worlds set to " + ChatColor.GRAY + time + ChatColor.BLUE + ".");
}
if (args.length > 1) {
World w = plugin.getServer().getWorld(args[1].trim());
if (w == null) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
if (plugin.smoothTime) smoothTimeChange(time, w);
w.setTime(time);
cs.sendMessage(ChatColor.BLUE + "Time in world " + ChatColor.GRAY + w.getName() + ChatColor.BLUE + " set to " + ChatColor.GRAY + time + ChatColor.BLUE + ".");
}
return true;
}
if (args.length < 1) {
cs.sendMessage(cmd.getDescription());
return false;
}
Player p = (Player) cs;
World world = (args.length > 1) ? plugin.getServer().getWorld(args[1]) : p.getWorld();
if (world == null) world = p.getWorld();
if (getValidTime(args[0]) == null) {
cs.sendMessage(ChatColor.RED + "Invalid time specified!");
return true;
}
long time = getValidTime(args[0]);
if (time < 0) {
cs.sendMessage(ChatColor.RED + "The time entered was invalid!");
return true;
}
if (plugin.smoothTime) smoothTimeChange(time, world);
world.setTime(time);
p.sendMessage(ChatColor.BLUE + "Set time in " + ChatColor.GRAY + world.getName() + ChatColor.BLUE + " to " + ChatColor.GRAY + time + ChatColor.BLUE + " ticks.");
return true;
}
return false;
}
}
|
package org.subethamail.web.security;
import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.java.Log;
import com.caucho.security.Authenticator;
import com.caucho.security.BasicLogin;
import com.caucho.security.BasicPrincipal;
import com.caucho.security.ClusterSingleSignon;
import com.caucho.security.Credentials;
import com.caucho.security.MemorySingleSignon;
import com.caucho.security.PasswordCredentials;
/**
* Login class which makes programmatic login available. You can inject
* this in your servlet.
*
* @author Jeff Schnitzer
* @author Scott Hernandez
*/
@Log
@ApplicationScoped
public class SubEthaLogin extends BasicLogin
{
/**
*
* Logs in the user/pass to the container, if the credentials are valid.
*
* @param email the email address
* @param pass the cleartext password
*
* @return true if success, false if the credentials were bad.
*/
public boolean login(String email, String pass, HttpServletRequest request)
{
Authenticator auth = this.getAuthenticator();
/** send a null id, it will be fixed over there */
BasicPrincipal user = new BasicPrincipal(email);
Credentials credentials = new PasswordCredentials(pass);
Principal principal = auth.authenticate(user, credentials, null);
log.log(Level.FINE,"authenticated: {0} -> {1}", new Object[]{user, principal});
if (principal == null)
{
return false;
}
else
{
log.log(Level.FINE,"saving user with request: {0}",request);
this.saveUser(request, principal);
return true;
}
}
/**
* Logs out the user as far as the container is concerned.
*/
public void logout(HttpServletRequest request)
{
this.logout(null, request, null);
}
}
|
package org.usfirst.frc.team3414.sensors;
import edu.wpi.first.wpilibj.AnalogInput;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class Infrared implements IMeasureDistance
{
private AnalogInput channel;
public Infrared(AnalogInput channel) {
super();
if(channel != null)
{
this.channel = channel;
}
else
{
throw new RuntimeException("The Channel should nopt be null");
}
}
public Infrared(int channelNumber) {
super();
channel = new AnalogInput(channelNumber);
}
@Override
public double getCm() {
double voltage = channel.getVoltage();
return 61.573 * Math.pow(voltage/1000, -1.1068);
}
/**
* Use average voltage to get distance in feet
*
* @generated
* @ordered
*/
public double getFeet() {
return DistanceConversion.cmToInches(getCm());
}
/**
* Gets distance in feet and converts to inches
*
* @generated
* @ordered
*/
public double getInches() {
return DistanceConversion.inToFeet(getFeet());
}
}
|
package org.spine3.base;
import com.google.common.base.Converter;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spine3.util.Exceptions.newIllegalArgumentException;
/**
* Encloses and discloses the {@code String} objects with double quotes.
*
* @author Illia Shepilov
* @author Alexander Yevsyukov
*/
class Quoter extends Converter<String, String> {
private static final char QUOTE_CHAR = '"';
private static final String QUOTE = String.valueOf(QUOTE_CHAR);
private static final String BACKSLASH_QUOTE = "\\\"";
private static final String DOUBLE_BACKSLASH = "\\\\";
private static final String ESCAPED_QUOTE = DOUBLE_BACKSLASH + QUOTE_CHAR;
private static final Pattern DOUBLE_BACKSLASH_PATTERN = Pattern.compile(DOUBLE_BACKSLASH);
private static final Pattern QUOTE_PATTERN = Pattern.compile(QUOTE);
private static final String TRIPLE_BACKSLASH = "\\\\\\";
private static final String DELIMITER_PATTERN_PREFIX = "(?<!" + DOUBLE_BACKSLASH + ')'
+ TRIPLE_BACKSLASH;
@Override
protected String doForward(String s) {
return quote(s);
}
@Override
protected String doBackward(String s) {
checkNotNull(s);
return unquote(s);
}
/**
* Prepends quote characters in the passed string with two leading backslashes,
* and then wraps the string into quotes.
*/
private static String quote(String stringToQuote) {
checkNotNull(stringToQuote);
final String escapedString = QUOTE_PATTERN.matcher(stringToQuote)
.replaceAll(ESCAPED_QUOTE);
final String result = QUOTE_CHAR + escapedString + QUOTE_CHAR;
return result;
}
/**
* Unquotes the passed string and removes double backslash prefixes for quote symbols
* found inside the passed value.
*/
private static String unquote(String value) {
checkQuoted(value);
final String unquoted = value.substring(2, value.length() - 2);
final String unescaped = DOUBLE_BACKSLASH_PATTERN.matcher(unquoted)
.replaceAll("");
return unescaped;
}
private static void checkQuoted(String str) {
if (!(str.startsWith(BACKSLASH_QUOTE)
&& str.endsWith(BACKSLASH_QUOTE))) {
throw newIllegalArgumentException("The passed string is not quoted: %s", str);
}
}
/**
* Creates the pattern to match the escaped delimiters.
*
* @param delimiter the character to match
* @return the created pattern
*/
static String createDelimiterPattern(char delimiter) {
return Pattern.compile(DELIMITER_PATTERN_PREFIX + delimiter)
.pattern();
}
private enum Singleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Quoter value = new Quoter();
}
static Quoter instance() {
return Singleton.INSTANCE.value;
}
}
|
package net.silentchaos512.gems.item;
import java.util.List;
import org.lwjgl.input.Keyboard;
import com.google.common.collect.Lists;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.api.lib.EnumMaterialGrade;
import net.silentchaos512.gems.api.lib.EnumMaterialTier;
import net.silentchaos512.gems.lib.EnumGem;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.lib.item.ItemSL;
import net.silentchaos512.lib.util.LocalizationHelper;
import net.silentchaos512.lib.util.RecipeHelper;
public class ItemGem extends ItemSL {
public ItemGem() {
super(64, SilentGems.MOD_ID, Names.GEM);
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advanced) {
EnumGem gem = EnumGem.getFromStack(stack);
EnumMaterialTier tier = stack.getItemDamage() > 31 ? EnumMaterialTier.SUPER
: EnumMaterialTier.REGULAR;
LocalizationHelper loc = SilentGems.instance.localizationHelper;
String line;
boolean controlDown = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)
|| Keyboard.isKeyDown(Keyboard.KEY_RCONTROL);
if (gem != null && controlDown) {
int multi = 100 + EnumMaterialGrade.fromStack(stack).bonusPercent;
line = loc.getMiscText("Tooltip.Durability");
list.add(String.format(line, gem.getDurability(tier) * multi / 100));
line = loc.getMiscText("Tooltip.HarvestSpeed");
list.add(String.format(line, gem.getMiningSpeed(tier) * multi / 100));
line = loc.getMiscText("Tooltip.HarvestLevel");
list.add(String.format(line, gem.getHarvestLevel(tier) * multi / 100));
line = loc.getMiscText("Tooltip.MeleeDamage");
list.add(String.format(line, gem.getMeleeDamage(tier) * multi / 100));
line = loc.getMiscText("Tooltip.MagicDamage");
list.add(String.format(line, gem.getMagicDamage(tier) * multi / 100));
line = loc.getMiscText("Tooltip.ChargeSpeed");
list.add(String.format(line, gem.getChargeSpeed(tier) * multi / 100));
line = loc.getMiscText("Tooltip.Enchantability");
list.add(String.format(line, gem.getEnchantability(tier) * multi / 100));
} else {
list.add(TextFormatting.GOLD + loc.getMiscText("PressCtrl"));
}
}
@Override
public void addRecipes() {
for (EnumGem gem : EnumGem.values()) {
// Supercharged gems
GameRegistry.addRecipe(new ShapedOreRecipe(gem.getItemSuper(), "cgc", "cdc", "cgc", 'g',
gem.getItem(), 'd', "dustGlowstone", 'c', "gemChaos"));
// Gems <--> shards
RecipeHelper.addCompressionRecipe(gem.getShard(), gem.getItem(), 9);
}
}
@Override
public void addOreDict() {
for (EnumGem gem : EnumGem.values()) {
OreDictionary.registerOre(gem.getItemOreName(), gem.getItem());
OreDictionary.registerOre(gem.getItemSuperOreName(), gem.getItemSuper());
}
}
@Override
public boolean hasEffect(ItemStack stack) {
return stack.getItemDamage() > 31;
}
@Override
public List<ModelResourceLocation> getVariants() {
List<ModelResourceLocation> models = Lists.newArrayList();
int i;
for (i = 0; i < 16; ++i) {
models.add(new ModelResourceLocation(getFullName() + i, "inventory"));
}
for (i = 0; i < 16; ++i) {
models.add(new ModelResourceLocation(getFullName() + "Dark" + i, "inventory"));
}
for (i = 0; i < 16; ++i) {
models.add(new ModelResourceLocation(getFullName() + "Super" + i, "inventory"));
}
for (i = 0; i < 16; ++i) {
models.add(new ModelResourceLocation(getFullName() + "SuperDark" + i, "inventory"));
}
return models;
}
}
|
// DataTools.java
package loci.common;
import java.io.*;
import java.text.*;
import java.util.Date;
import java.util.Hashtable;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public final class DataTools {
// -- Constants --
/** Timestamp formats. */
public static final int UNIX = 0; // January 1, 1970
public static final int COBOL = 1; // January 1, 1601
public static final int MICROSOFT = 2; // December 30, 1899
public static final int ZVI = 3;
/** Milliseconds until UNIX epoch. */
public static final long UNIX_EPOCH = 0;
public static final long COBOL_EPOCH = 11644444800000L;
public static final long MICROSOFT_EPOCH = 2272060800000L;
public static final long ZVI_EPOCH = 2921084975759000L;
/** Factory for generating SAX parsers. */
public static final SAXParserFactory SAX_FACTORY =
SAXParserFactory.newInstance();
// -- Static fields --
/**
* Persistent byte array for calling
* {@link java.io.DataInput#readFully(byte[], int, int)} efficiently.
*/
private static ThreadLocal eightBytes = new ThreadLocal() {
protected synchronized Object initialValue() {
return new byte[8];
}
};
// -- Constructor --
private DataTools() { }
// -- Data reading --
/** Reads 1 signed byte [-128, 127]. */
public static byte readSignedByte(DataInput in) throws IOException {
byte[] b = (byte[]) eightBytes.get();
in.readFully(b, 0, 1);
return b[0];
}
/** Reads 1 unsigned byte [0, 255]. */
public static short readUnsignedByte(DataInput in) throws IOException {
short q = readSignedByte(in);
if (q < 0) q += 256;
return q;
}
/** Reads 2 signed bytes [-32768, 32767]. */
public static short read2SignedBytes(DataInput in, boolean little)
throws IOException
{
byte[] b = (byte[]) eightBytes.get();
in.readFully(b, 0, 2);
return bytesToShort(b, little);
}
/** Reads 2 unsigned bytes [0, 65535]. */
public static int read2UnsignedBytes(DataInput in, boolean little)
throws IOException
{
int q = read2SignedBytes(in, little);
if (q < 0) q += 65536;
return q;
}
/** Reads 4 signed bytes [-2147483648, 2147483647]. */
public static int read4SignedBytes(DataInput in, boolean little)
throws IOException
{
byte[] b = (byte[]) eightBytes.get();
in.readFully(b, 0, 4);
return bytesToInt(b, little);
}
/** Reads 4 unsigned bytes [0, 4294967296]. */
public static long read4UnsignedBytes(DataInput in, boolean little)
throws IOException
{
long q = read4SignedBytes(in, little);
if (q < 0) q += 4294967296L;
return q;
}
/** Reads 8 signed bytes [-9223372036854775808, 9223372036854775807]. */
public static long read8SignedBytes(DataInput in, boolean little)
throws IOException
{
byte[] b = (byte[]) eightBytes.get();
in.readFully(b, 0, 8);
return bytesToLong(b, little);
}
/** Reads 4 bytes in single precision IEEE format. */
public static float readFloat(DataInput in, boolean little)
throws IOException
{
return Float.intBitsToFloat(read4SignedBytes(in, little));
}
/** Reads 8 bytes in double precision IEEE format. */
public static double readDouble(DataInput in, boolean little)
throws IOException
{
return Double.longBitsToDouble(read8SignedBytes(in, little));
}
// -- Data writing --
/** Writes a string to the given data output destination. */
public static void writeString(DataOutput out, String s)
throws IOException
{
byte[] b = s.getBytes("UTF-8");
out.write(b);
}
/** Writes a long to the given data output destination. */
public static void writeLong(DataOutput out, long v, boolean little)
throws IOException
{
if (little) {
out.write((int) (v & 0xff));
out.write((int) ((v >>> 8) & 0xff));
out.write((int) ((v >>> 16) & 0xff));
out.write((int) ((v >>> 24) & 0xff));
out.write((int) ((v >>> 32) & 0xff));
out.write((int) ((v >>> 40) & 0xff));
out.write((int) ((v >>> 48) & 0xff));
out.write((int) ((v >>> 56) & 0xff));
}
else {
out.write((int) ((v >>> 56) & 0xff));
out.write((int) ((v >>> 48) & 0xff));
out.write((int) ((v >>> 40) & 0xff));
out.write((int) ((v >>> 32) & 0xff));
out.write((int) ((v >>> 24) & 0xff));
out.write((int) ((v >>> 16) & 0xff));
out.write((int) ((v >>> 8) & 0xff));
out.write((int) (v & 0xff));
}
}
/** Writes an integer to the given data output destination. */
public static void writeInt(DataOutput out, int v, boolean little)
throws IOException
{
if (little) {
out.write(v & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 24) & 0xFF);
}
else {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write(v & 0xFF);
}
}
/** Writes a short to the given data output destination. */
public static void writeShort(DataOutput out, int v, boolean little)
throws IOException
{
if (little) {
out.write(v & 0xFF);
out.write((v >>> 8) & 0xFF);
}
else {
out.write((v >>> 8) & 0xFF);
out.write(v & 0xFF);
}
}
// -- Word decoding --
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a short. If there are fewer than 2 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array beyond the given
* offset to a short. If there are fewer than 2 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array byond the given
* offset to a short. If there are fewer than 2 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array byond the given
* offset to a short. If there are fewer than 2 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to a float.
* If there are fewer than 4 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, int off, int len,
boolean little)
{
return Float.intBitsToFloat(bytesToInt(bytes, off, len, little));
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256L + bytes[ndx] :
(long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes in the array,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes to be translated,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes to be translated,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes in the array, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates the specified number of bytes of a byte array to a double.
* If there are fewer than 8 bytes in the array, the MSBs are all assumed
* to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, int offset, int len,
boolean little)
{
return Double.longBitsToDouble(bytesToLong(bytes, offset, len, little));
}
/**
* Translates the short value into two bytes, and places them in a byte
* array at the given index.
*/
public static void unpackShort(short value, byte[] buf, int ndx,
boolean little)
{
if (little) {
buf[ndx] = (byte) (value & 0xff);
buf[ndx + 1] = (byte) ((value >> 8) & 0xff);
}
else {
buf[ndx + 1] = (byte) (value & 0xff);
buf[ndx] = (byte) ((value >> 8) & 0xff);
}
}
/**
* Translates nBytes of the given long and places the result in the
* given byte array.
*/
public static void unpackBytes(long value, byte[] buf, int ndx,
int nBytes, boolean little)
{
if (little) {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*i)) & 0xff);
}
}
else {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*(nBytes - i - 1))) & 0xff);
}
}
}
/** Convert a byte array to a signed byte array. */
public static byte[] makeSigned(byte[] b) {
for (int i=0; i<b.length; i++) {
b[i] = (byte) (b[i] + 128);
}
return b;
}
/** Convert a short array to a signed short array. */
public static short[] makeSigned(short[] s) {
for (int i=0; i<s.length; i++) {
s[i] = (short) (s[i] + 32768);
}
return s;
}
/** Convert an int array to a signed int array. */
public static int[] makeSigned(int[] i) {
for (int j=0; j<i.length; j++) {
i[j] = (int) (i[j] + 2147483648L);
}
return i;
}
/**
* Convert a byte array to the appropriate primitive type array.
* @param b Byte array to convert.
* @param bpp Denotes the number of bytes in the returned primitive type
* (e.g. if bpp == 2, we should return an array of type short).
* @param fp If set and bpp == 4 or bpp == 8, then return floats or doubles.
* @param little Whether byte array is in little-endian order.
*/
public static Object makeDataArray(byte[] b,
int bpp, boolean fp, boolean little)
{
if (bpp == 1) return b;
else if (bpp == 2) {
short[] s = new short[b.length / 2];
for (int i=0; i<s.length; i++) {
s[i] = bytesToShort(b, i*2, 2, little);
}
return s;
}
else if (bpp == 4 && fp) {
float[] f = new float[b.length / 4];
for (int i=0; i<f.length; i++) {
f[i] = Float.intBitsToFloat(bytesToInt(b, i*4, 4, little));
}
return f;
}
else if (bpp == 4) {
int[] i = new int[b.length / 4];
for (int j=0; j<i.length; j++) {
i[j] = bytesToInt(b, j*4, 4, little);
}
return i;
}
else if (bpp == 8 && fp) {
double[] d = new double[b.length / 8];
for (int i=0; i<d.length; i++) {
d[i] = Double.longBitsToDouble(bytesToLong(b, i*8, 8, little));
}
return d;
}
else if (bpp == 8) {
long[] l = new long[b.length / 8];
for (int i=0; i<l.length; i++) {
l[i] = bytesToLong(b, i*8, 8, little);
}
return l;
}
return null;
}
// -- Byte swapping --
public static short swap(short x) {
return (short) ((x << 8) | ((x >> 8) & 0xFF));
}
public static char swap(char x) {
return (char) ((x << 8) | ((x >> 8) & 0xFF));
}
public static int swap(int x) {
return (int) ((swap((short) x) << 16) | (swap((short) (x >> 16)) & 0xFFFF));
}
public static long swap(long x) {
return (long) (((long) swap((int) x) << 32) |
((long) swap((int) (x >> 32)) & 0xFFFFFFFFL));
}
public static float swap(float x) {
return Float.intBitsToFloat(swap(Float.floatToIntBits(x)));
}
public static double swap(double x) {
return Double.longBitsToDouble(swap(Double.doubleToLongBits(x)));
}
// -- Miscellaneous --
/** Remove null bytes from a string. */
public static String stripString(String toStrip) {
char[] toRtn = new char[toStrip.length()];
int counter = 0;
for (int i=0; i<toRtn.length; i++) {
if (toStrip.charAt(i) != 0) {
toRtn[counter] = toStrip.charAt(i);
counter++;
}
}
toStrip = new String(toRtn);
toStrip = toStrip.trim();
return toStrip;
}
/** Check if two filenames have the same prefix. */
public static boolean samePrefix(String s1, String s2) {
if (s1 == null || s2 == null) return false;
int n1 = s1.indexOf(".");
int n2 = s2.indexOf(".");
if ((n1 == -1) || (n2 == -1)) return false;
int slash1 = s1.lastIndexOf(File.pathSeparator);
int slash2 = s2.lastIndexOf(File.pathSeparator);
String sub1 = s1.substring((slash1 == -1) ? 0 : slash1 + 1, n1);
String sub2 = s2.substring((slash2 == -1) ? 0 : slash2 + 1, n2);
return sub1.equals(sub2) || sub1.startsWith(sub2) || sub2.startsWith(sub1);
}
/** Remove unprintable characters from the given string. */
public static String sanitize(String s) {
if (s == null) return null;
StringBuffer buf = new StringBuffer(s);
for (int i=0; i<buf.length(); i++) {
char c = buf.charAt(i);
if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) {
buf = buf.deleteCharAt(i
}
}
return buf.toString();
}
/** Remove invalid characters from an XML string. */
public static String sanitizeXML(String s) {
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c) || c > '~') {
s = s.replace(c, ' ');
}
}
return s;
}
/**
* Load a list of metadata tags and their corresponding descriptions.
*/
public static Hashtable getMetadataTags(String baseClass, String file) {
try {
return getMetadataTags(Class.forName(baseClass), file);
}
catch (ClassNotFoundException e) { }
return null;
}
/**
* Load a list of metadata tags and their corresponding descriptions.
*/
public static Hashtable getMetadataTags(Class c, String file) {
Hashtable h = new Hashtable();
BufferedReader in = new BufferedReader(new InputStreamReader(
c.getResourceAsStream(file)));
String line = null, key = null, value = null;
while (true) {
try {
line = in.readLine();
}
catch (IOException e) {
line = null;
}
if (line == null) break;
key = line.substring(0, line.indexOf("=>")).trim();
value = line.substring(line.indexOf("=>") + 2).trim();
h.put(key, value);
}
return h;
}
/**
* Normalize the given float array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static float[] normalizeFloats(float[] data) {
float[] rtn = new float[data.length];
// make a quick pass through to determine the real min and max values
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] < min) min = data[i];
if (data[i] > max) {
max = data[i];
}
}
// now normalize; min => 0.0, max => 1.0
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / (max - min);
}
return rtn;
}
/**
* Normalize the given double array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static double[] normalizeDoubles(double[] data) {
double[] rtn = new double[data.length];
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] < min) min = data[i];
if (data[i] > max) max = data[i];
}
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / (max - min);
}
return rtn;
}
public static void parseXML(String xml, DefaultHandler handler)
throws IOException
{
parseXML(xml.getBytes(), handler);
}
public static void parseXML(RandomAccessStream stream, DefaultHandler handler)
throws IOException
{
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(stream, handler);
}
catch (ParserConfigurationException exc) {
IOException e = new IOException();
e.setStackTrace(exc.getStackTrace());
throw e;
}
catch (SAXException exc) {
IOException e = new IOException();
e.setStackTrace(exc.getStackTrace());
throw e;
}
}
public static void parseXML(byte[] xml, DefaultHandler handler)
throws IOException
{
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml), handler);
}
catch (ParserConfigurationException exc) {
IOException e = new IOException();
e.setStackTrace(exc.getStackTrace());
throw e;
}
catch (SAXException exc) {
IOException e = new IOException();
e.setStackTrace(exc.getStackTrace());
throw e;
}
}
// -- Date handling --
/** Converts the given timestamp into an ISO 8601 date. */
public static String convertDate(long stamp, int format) {
// dates than you will ever need (or want)
long ms = stamp;
switch (format) {
case UNIX:
ms -= UNIX_EPOCH;
break;
case COBOL:
ms -= COBOL_EPOCH;
break;
case MICROSOFT:
ms -= MICROSOFT_EPOCH;
break;
case ZVI:
ms -= ZVI_EPOCH;
break;
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
StringBuffer sb = new StringBuffer();
Date d = new Date(ms);
fmt.format(d, sb, new FieldPosition(0));
return sb.toString();
}
/** Return given date in ISO 8601 format. */
public static String formatDate(String date, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
Date d = f.parse(date, new ParsePosition(0));
f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
return f.format(d);
}
}
|
// DataTools.java
package loci.common;
import java.io.File;
import java.io.IOException;
public final class DataTools {
// -- Constants --
// -- Static fields --
// -- Constructor --
private DataTools() { }
// -- Data reading --
/** Reads the contents of the given file into a string. */
public static String readFile(String id) throws IOException {
RandomAccessInputStream in = new RandomAccessInputStream(id);
long idLen = in.length();
if (idLen > Integer.MAX_VALUE) {
throw new IOException("File too large");
}
int len = (int) idLen;
String data = in.readString(len);
in.close();
return data;
}
// -- Word decoding - bytes to primitive types --
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a short. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array beyond the given
* offset to a short. If there are fewer than 2 bytes available
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array byond the given
* offset to a short. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= bytes[ndx] << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array byond the given
* offset to a short. If there are fewer than 2 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= bytes[ndx] << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a float. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, int off, int len,
boolean little)
{
return Float.intBitsToFloat(bytesToInt(bytes, off, len, little));
}
/**
* Translates up to the first 4 bytes of a byte array beyond a given
* offset to a float. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, int off, boolean little) {
return bytesToFloat(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to a float.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, boolean little) {
return bytesToFloat(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond a given
* offset to a float. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, int off, int len,
boolean little)
{
return Float.intBitsToFloat(bytesToInt(bytes, off, len, little));
}
/**
* Translates up to the first 4 bytes of a byte array beyond a given
* offset to a float. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to a float.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256L + bytes[ndx] :
(long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a double. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, int off, int len,
boolean little)
{
return Double.longBitsToDouble(bytesToLong(bytes, off, len, little));
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a double. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, int off,
boolean little)
{
return bytesToDouble(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a double.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, boolean little) {
return bytesToDouble(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a double. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, int off, int len,
boolean little)
{
return Double.longBitsToDouble(bytesToLong(bytes, off, len, little));
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a double. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, int off,
boolean little)
{
return bytesToDouble(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a double.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, boolean little) {
return bytesToDouble(bytes, 0, 8, little);
}
/** Translates the given byte array into a String of hexadecimal digits. */
public static String bytesToHex(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<b.length; i++) {
String a = Integer.toHexString(b[i] & 0xff);
if (a.length() == 1) sb.append("0");
sb.append(a);
}
return sb.toString();
}
// -- Word decoding - primitive types to bytes --
/** Translates the short value into an array of two bytes. */
public static byte[] shortToBytes(short value, boolean little) {
byte[] v = new byte[2];
unpackBytes(value, v, 0, 2, little);
return v;
}
/** Translates the int value into an array of four bytes. */
public static byte[] intToBytes(int value, boolean little) {
byte[] v = new byte[4];
unpackBytes(value, v, 0, 4, little);
return v;
}
/** Translates the float value into an array of four bytes. */
public static byte[] floatToBytes(float value, boolean little) {
byte[] v = new byte[4];
unpackBytes(Float.floatToIntBits(value), v, 0, 4, little);
return v;
}
/** Translates the long value into an array of eight bytes. */
public static byte[] longToBytes(long value, boolean little) {
byte[] v = new byte[8];
unpackBytes(value, v, 0, 8, little);
return v;
}
/** Translates the double value into an array of eight bytes. */
public static byte[] doubleToBytes(double value, boolean little) {
byte[] v = new byte[8];
unpackBytes(Double.doubleToLongBits(value), v, 0, 8, little);
return v;
}
/** Translates an array of short values into an array of byte values. */
public static byte[] shortsToBytes(short[] values, boolean little) {
byte[] v = new byte[values.length * 2];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 2, 2, little);
}
return v;
}
/** Translates an array of int values into an array of byte values. */
public static byte[] intsToBytes(int[] values, boolean little) {
byte[] v = new byte[values.length * 4];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 4, 4, little);
}
return v;
}
/** Translates an array of float values into an array of byte values. */
public static byte[] floatsToBytes(float[] values, boolean little) {
byte[] v = new byte[values.length * 4];
for (int i=0; i<values.length; i++) {
unpackBytes(Float.floatToIntBits(values[i]), v, i * 4, 4, little);
}
return v;
}
/** Translates an array of long values into an array of byte values. */
public static byte[] longsToBytes(long[] values, boolean little) {
byte[] v = new byte[values.length * 8];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 8, 8, little);
}
return v;
}
/** Translates an array of double values into an array of byte values. */
public static byte[] doublesToBytes(double[] values, boolean little) {
byte[] v = new byte[values.length * 8];
for (int i=0; i<values.length; i++) {
unpackBytes(Double.doubleToLongBits(values[i]), v, i * 8, 8, little);
}
return v;
}
/** @deprecated Use {@link #unpackBytes(long, byte[], int, int, boolean) */
@Deprecated
public static void unpackShort(short value, byte[] buf, int ndx,
boolean little)
{
unpackBytes(value, buf, ndx, 2, little);
}
public static void unpackBytes(long value, byte[] buf, int ndx,
int nBytes, boolean little)
{
if (buf.length < ndx + nBytes) {
throw new IllegalArgumentException("Invalid indices: buf.length=" +
buf.length + ", ndx=" + ndx + ", nBytes=" + nBytes);
}
if (little) {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*i)) & 0xff);
}
}
else {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*(nBytes - i - 1))) & 0xff);
}
}
}
/**
* Convert a byte array to the appropriate 1D primitive type array.
*
* @param b Byte array to convert.
* @param bpp Denotes the number of bytes in the returned primitive type
* (e.g. if bpp == 2, we should return an array of type short).
* @param fp If set and bpp == 4 or bpp == 8, then return floats or doubles.
* @param little Whether byte array is in little-endian order.
*/
public static Object makeDataArray(byte[] b,
int bpp, boolean fp, boolean little)
{
if (bpp == 1) {
return b;
}
else if (bpp == 2) {
short[] s = new short[b.length / 2];
for (int i=0; i<s.length; i++) {
s[i] = bytesToShort(b, i*2, 2, little);
}
return s;
}
else if (bpp == 4 && fp) {
float[] f = new float[b.length / 4];
for (int i=0; i<f.length; i++) {
f[i] = bytesToFloat(b, i * 4, 4, little);
}
return f;
}
else if (bpp == 4) {
int[] i = new int[b.length / 4];
for (int j=0; j<i.length; j++) {
i[j] = bytesToInt(b, j*4, 4, little);
}
return i;
}
else if (bpp == 8 && fp) {
double[] d = new double[b.length / 8];
for (int i=0; i<d.length; i++) {
d[i] = bytesToDouble(b, i * 8, 8, little);
}
return d;
}
else if (bpp == 8) {
long[] l = new long[b.length / 8];
for (int i=0; i<l.length; i++) {
l[i] = bytesToLong(b, i*8, 8, little);
}
return l;
}
return null;
}
/**
* @param signed The signed parameter is ignored.
* @deprecated Use {@link #makeDataArray(byte[], int, boolean, boolean)}
* regardless of signedness.
*/
@Deprecated
public static Object makeDataArray(byte[] b,
int bpp, boolean fp, boolean little, boolean signed)
{
return makeDataArray(b, bpp, fp, little);
}
public static Object makeDataArray2D(byte[] b,
int bpp, boolean fp, boolean little, int height)
{
if (b.length % (bpp * height) != 0) {
throw new IllegalArgumentException("Array length mismatch: " +
"b.length=" + b.length + "; bpp=" + bpp + "; height=" + height);
}
final int width = b.length / (bpp * height);
if (bpp == 1) {
byte[][] b2 = new byte[height][width];
for (int y=0; y<height; y++) {
int index = width*y;
System.arraycopy(b, index, b2[y], 0, width);
}
return b2;
}
else if (bpp == 2) {
short[][] s = new short[height][width];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = 2*(width*y + x);
s[y][x] = bytesToShort(b, index, 2, little);
}
}
return s;
}
else if (bpp == 4 && fp) {
float[][] f = new float[height][width];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = 4*(width*y + x);
f[y][x] = bytesToFloat(b, index, 4, little);
}
}
return f;
}
else if (bpp == 4) {
int[][] i = new int[height][width];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = 4*(width*y + x);
i[y][x] = bytesToInt(b, index, 4, little);
}
}
return i;
}
else if (bpp == 8 && fp) {
double[][] d = new double[height][width];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = 8*(width*y + x);
d[y][x] = bytesToDouble(b, index, 8, little);
}
}
return d;
}
else if (bpp == 8) {
long[][] l = new long[height][width];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int index = 8*(width*y + x);
l[y][x] = bytesToLong(b, index, 8, little);
}
}
return l;
}
return null;
}
// -- Byte swapping --
public static short swap(short x) {
return (short) ((x << 8) | ((x >> 8) & 0xFF));
}
public static char swap(char x) {
return (char) ((x << 8) | ((x >> 8) & 0xFF));
}
public static int swap(int x) {
return (swap((short) x) << 16) | (swap((short) (x >> 16)) & 0xFFFF);
}
public static long swap(long x) {
return ((long) swap((int) x) << 32) | (swap((int) (x >> 32)) & 0xFFFFFFFFL);
}
public static float swap(float x) {
return Float.intBitsToFloat(swap(Float.floatToIntBits(x)));
}
public static double swap(double x) {
return Double.longBitsToDouble(swap(Double.doubleToLongBits(x)));
}
// -- Strings --
/** Convert byte array to a hexadecimal string. */
public static String getHexString(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<b.length; i++) {
String a = Integer.toHexString(b[i] & 0xff);
if (a.length() == 1) sb.append("0");
sb.append(a);
}
return sb.toString();
}
/** Remove null bytes from a string. */
public static String stripString(String toStrip) {
StringBuffer s = new StringBuffer();
for (int i=0; i<toStrip.length(); i++) {
if (toStrip.charAt(i) != 0) {
s.append(toStrip.charAt(i));
}
}
return s.toString().trim();
}
/** Check if two filenames have the same prefix. */
public static boolean samePrefix(String s1, String s2) {
if (s1 == null || s2 == null) return false;
int n1 = s1.indexOf(".");
int n2 = s2.indexOf(".");
if ((n1 == -1) || (n2 == -1)) return false;
int slash1 = s1.lastIndexOf(File.pathSeparator);
int slash2 = s2.lastIndexOf(File.pathSeparator);
String sub1 = s1.substring(slash1 + 1, n1);
String sub2 = s2.substring(slash2 + 1, n2);
return sub1.equals(sub2) || sub1.startsWith(sub2) || sub2.startsWith(sub1);
}
/** Remove unprintable characters from the given string. */
public static String sanitize(String s) {
if (s == null) return null;
StringBuffer buf = new StringBuffer(s);
for (int i=0; i<buf.length(); i++) {
char c = buf.charAt(i);
if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) {
buf = buf.deleteCharAt(i
}
}
return buf.toString();
}
// -- Normalization --
/**
* Normalize the given float array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static float[] normalizeFloats(float[] data) {
float[] rtn = new float[data.length];
// determine the finite min and max values
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] == Float.POSITIVE_INFINITY ||
data[i] == Float.NEGATIVE_INFINITY)
{
continue;
}
if (data[i] < min) min = data[i];
if (data[i] > max) max = data[i];
}
// normalize infinity values
for (int i=0; i<data.length; i++) {
if (data[i] == Float.POSITIVE_INFINITY) data[i] = max;
else if (data[i] == Float.NEGATIVE_INFINITY) data[i] = min;
}
// now normalize; min => 0.0, max => 1.0
float range = max - min;
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / range;
}
return rtn;
}
/**
* Normalize the given double array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static double[] normalizeDoubles(double[] data) {
double[] rtn = new double[data.length];
// determine the finite min and max values
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] == Double.POSITIVE_INFINITY ||
data[i] == Double.NEGATIVE_INFINITY)
{
continue;
}
if (data[i] < min) min = data[i];
if (data[i] > max) max = data[i];
}
// normalize infinity values
for (int i=0; i<data.length; i++) {
if (data[i] == Double.POSITIVE_INFINITY) data[i] = max;
else if (data[i] == Double.NEGATIVE_INFINITY) data[i] = min;
}
// now normalize; min => 0.0, max => 1.0
double range = max - min;
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / range;
}
return rtn;
}
// -- Array handling --
/** Returns true if the given value is contained in the given array. */
public static boolean containsValue(int[] array, int value) {
return indexOf(array, value) != -1;
}
/**
* Returns the index of the first occurrence of the given value in the given
* array. If the value is not in the array, returns -1.
*/
public static int indexOf(int[] array, int value) {
for (int i=0; i<array.length; i++) {
if (array[i] == value) return i;
}
return -1;
}
/**
* Returns the index of the first occurrence of the given value in the given
* Object array. If the value is not in the array, returns -1.
*/
public static int indexOf(Object[] array, Object value) {
for (int i=0; i<array.length; i++) {
if (value == null) {
if (array[i] == null) return i;
}
else if (value.equals(array[i])) return i;
}
return -1;
}
// -- Signed data conversion --
public static byte[] makeSigned(byte[] b) {
for (int i=0; i<b.length; i++) {
b[i] = (byte) (b[i] + 128);
}
return b;
}
public static short[] makeSigned(short[] s) {
for (int i=0; i<s.length; i++) {
s[i] = (short) (s[i] + 32768);
}
return s;
}
public static int[] makeSigned(int[] i) {
for (int j=0; j<i.length; j++) {
i[j] = (int) (i[j] + 2147483648L);
}
return i;
}
}
|
public class SinglyLinkedList<Item extends Comparable> {
private Node head;
private int size;
private class Node {
Item data;
Node next;
}
public void append(Item data) {
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node();
current.next.data = data;
}
size++;
}
public void insert(Item data) {
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node first = new Node();
first.data = data;
first.next = head;
head = first;
}
size++;
}
public Item remove(Item data) {
if (isEmpty()) {
throw new java.util.NoSuchElementException("The list is empty!");
} else {
if (head.data == data) {
Item victim = head.data;
head = head.next;
size
return victim;
} else {
Node current = head;
while (current.next != null) {
if (current.next.data == data) {
Item victim = current.next.data;
current.next = current.next.next;
size
return victim;
}
current = current.next;
}
return null;
}
}
}
public Item nthFromEnd(int n) {
if (n > size) {
return null;
}
Node ahead = head;
Node behind = head;
for (int i = 0; i < n; i++) {
ahead = ahead.next;
}
while (ahead != null) {
behind = behind.next;
ahead = ahead.next;
}
return behind.data;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
public boolean contains(Item data) {
Node current = head;
while (current != null) {
if (current.data == data) {
return true;
} else {
current = current.next;
}
}
return false;
}
public Item getMiddle() {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
}
public void deleteList() {
head = null;
}
public int countOccurences(Item data) {
nullCheck(data);
Node current = head;
int count = 0;
while (current != null) {
if (current.data == data) {
count++;
}
current = current.next;
}
return count;
}
public boolean hasLoop() {
Node slow = head;
Node fast = head.next;
while (slow != null && fast != null && fast.next != null) {
if (slow == fast) {
return true;
} else {
slow = slow.next;
fast = fast.next;
}
}
return false;
}
public void reverse() {
if (size == 1 || isEmpty()) {
return;
}
Node current = head;
Node next = head;
Node previous = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head = previous;
}
public boolean isPalindrome() {
if (isEmpty() || size == 1) {
return true;
}
Node slow = head;
Node fast = head.next;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node previous = null;
Node current = head;
Node next = head;
Node flag = slow.next;
while (current != flag) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
if (fast == null){
previous = previous.next;
}
while (previous != null && current != null) {
if (previous.data != current.data) {
return false;
} else {
previous = previous.next;
current = current.next;
}
}
return true;
}
public void sortedInsert(Item data) {
nullCheck(data);
if (isEmpty()) {
head = new Node();
head.data = data;
} else {
Node lower = head;
Node higher = head.next;
while (lower != null) {
if ((higher == null) ||
(data.compareTo(lower.data) >= 0) && (data.compareTo(higher.data) <= 0)) {
Node n = new Node();
n.data = data;
n.next = higher;
lower.next = n;
return;
} else if (data.compareTo(lower.data) <= 0) {
Node n = new Node();
n.data = data;
n.next = lower;
if (lower == head) {
head = n; // If lower is head, reset head
}
return;
}
lower = lower.next;
higher = higher.next;
}
}
size++;
}
private Node intersectionPoint(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return null;
}
Node firstHead = head1;
Node secondHead = head2;
int firstLength = 0;
int secondLength = 0;
while (firstHead != null || secondHead != null) {
if (firstHead == null) {
secondHead = secondHead.next;
secondLength++;
} else if (secondHead == null) {
firstHead = firstHead.next;
firstLength++;
} else {
firstHead = firstHead.next;
secondHead = secondHead.next;
firstLength++;
secondLength++;
}
}
firstHead = head1;
secondHead = head2;
if (firstLength > secondLength) {
int difference = firstLength-secondLength;
while (difference != 0) {
firstHead = firstHead.next;
difference
}
} else if (secondLength > firstLength) {
int difference = secondLength-firstLength;
while (difference != 0) {
secondHead = secondHead.next;
difference
}
}
while (firstHead != null && secondHead != null) {
if (firstHead == secondHead) {
return firstHead;
}
}
return null; // If the lists are not connected
}
public void printReverse() {
if (size == 1 || isEmpty()) {
return;
}
printReverse(head);
}
private void printReverse(Node current) {
if (current.next == null) {
System.out.print("[ " + current.data + ", ");
} else {
printReverse(current.next);
System.out.print(current.data + (current == head ? " ]\n" : ", "));
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (isEmpty()) {
sb.append("[]");
} else {
sb.append("[ ");
for (Node cur = head; cur != null; cur = cur.next) {
if (cur.next != null) {
sb.append(cur.data + ", ");
} else {
sb.append(cur.data + " ]");
}
}
}
return sb.toString();
}
/* Helper Methods */
private void nullCheck(Item data) {
if (data == null) {
throw new NullPointerException("Null items are not allowed in the list.");
}
}
private void emptyCheck() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Cannot remove from empty list!");
}
}
/* For testing purposes */
public static void main(String[] args) {
SinglyLinkedList<String> animals = new SinglyLinkedList<String>();
System.out.println("List is initially empty: " + animals);
animals.append("cat");
animals.append("dog");
animals.append("horse");
animals.append("pigeon");
animals.append("fish");
animals.append("seagull");
System.out.println("After adding some animals: " + animals);
animals.reverse();
System.out.println("Reversed the list: " + animals);
System.out.println("Middle element: " + animals.getMiddle());
System.out.println("Does the list contain pigeon? " + animals.contains("pigeon"));
System.out.println("Does the list contain BMW? " + animals.contains("BMW"));
System.out.println("The size of the list is: " + animals.size());
System.out.println("2nd from end: " + animals.nthFromEnd(2));
animals.deleteList();
System.out.println("Deleted list: " + animals);
palindromeTest(animals);
animals.deleteList();
System.out.print("Appending cat, dog, horse, pigeon, fish and seagull: ");
animals.append("cat");
animals.append("dog");
animals.append("horse");
animals.append("pigeon");
animals.append("fish");
animals.append("seagull");
System.out.println(animals);
System.out.print("Printing the reverse of the list recursively: ");
animals.printReverse();
SinglyLinkedList<Integer> numbers = new SinglyLinkedList<Integer>();
numbers.append(1);
numbers.append(2);
numbers.append(3);
numbers.append(5);
System.out.println("looking at new list of numbers:" + numbers);
sortedInsertTest(numbers);
}
public static void palindromeTest(SinglyLinkedList<String> list) {
list.append("A");
list.append("B");
list.append("C");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
list.deleteList();
list.append("A");
list.append("B");
list.append("C");
list.append("B");
list.append("A");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
list.deleteList();
list.append("A");
list.append("B");
list.append("C");
list.append("C");
list.append("B");
list.append("A");
System.out.println("Is the list " + list + " a palindrome? " + list.isPalindrome());
}
public static void sortedInsertTest(SinglyLinkedList<Integer> list) {
System.out.print("Insert 4 in sorted order into the list: ");
list.sortedInsert(4);
System.out.println(list);
System.out.print("Inserting 6 in sorted order into the list: ");
list.sortedInsert(6);
System.out.println(list);
System.out.print("Inserting 0 in sorted order into the list: ");
list.sortedInsert(0);
System.out.println(list);
}
}
|
package nxt;
import nxt.crypto.Crypto;
import nxt.util.Convert;
import nxt.util.Listener;
import nxt.util.Listeners;
import nxt.util.Logger;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class Account {
public static enum Event {
BALANCE, UNCONFIRMED_BALANCE, ASSET_BALANCE, UNCONFIRMED_ASSET_BALANCE
}
public static class AccountAsset {
public final Long accountId;
public final Long assetId;
public final Long quantityQNT;
private AccountAsset(Long accountId, Long assetId, Long quantityQNT) {
this.accountId = accountId;
this.assetId = assetId;
this.quantityQNT = quantityQNT;
}
}
static {
Nxt.getBlockchainProcessor().addListener(new Listener<Block>() {
@Override
public void notify(Block block) {
int height = block.getHeight();
Iterator<Map.Entry<Long, Account>> iterator = leasingAccounts.entrySet().iterator();
while (iterator.hasNext()) {
Account account = iterator.next().getValue();
if (height == account.currentLeasingHeightFrom) {
Account.getAccount(account.currentLesseeId).leaserIds.add(account.getId());
} else if (height == account.currentLeasingHeightTo) {
Account.getAccount(account.currentLesseeId).leaserIds.remove(account.getId());
if (account.nextLeasingHeightFrom == Integer.MAX_VALUE) {
account.currentLeasingHeightFrom = Integer.MAX_VALUE;
iterator.remove();
} else {
account.currentLeasingHeightFrom = account.nextLeasingHeightFrom;
account.currentLeasingHeightTo = account.nextLeasingHeightTo;
account.currentLesseeId = account.nextLesseeId;
account.nextLeasingHeightFrom = Integer.MAX_VALUE;
if (height == account.currentLeasingHeightFrom) {
Account.getAccount(account.currentLesseeId).leaserIds.add(account.getId());
}
}
}
}
}
}, BlockchainProcessor.Event.AFTER_BLOCK_APPLY);
}
private static final int maxTrackedBalanceConfirmations = 2881;
private static final ConcurrentMap<Long, Account> accounts = new ConcurrentHashMap<>();
private static final Collection<Account> allAccounts = Collections.unmodifiableCollection(accounts.values());
private static final ConcurrentMap<Long, Account> leasingAccounts = new ConcurrentHashMap<>();
private static final Listeners<Account,Event> listeners = new Listeners<>();
private static final Listeners<AccountAsset,Event> assetListeners = new Listeners<>();
public static boolean addListener(Listener<Account> listener, Event eventType) {
return listeners.addListener(listener, eventType);
}
public static boolean removeListener(Listener<Account> listener, Event eventType) {
return listeners.removeListener(listener, eventType);
}
public static boolean addAssetListener(Listener<AccountAsset> listener, Event eventType) {
return assetListeners.addListener(listener, eventType);
}
public static boolean removeAssetListener(Listener<AccountAsset> listener, Event eventType) {
return assetListeners.removeListener(listener, eventType);
}
public static Collection<Account> getAllAccounts() {
return allAccounts;
}
public static Account getAccount(Long id) {
return accounts.get(id);
}
public static Account getAccount(byte[] publicKey) {
return accounts.get(getId(publicKey));
}
public static Long getId(byte[] publicKey) {
byte[] publicKeyHash = Crypto.sha256().digest(publicKey);
BigInteger bigInteger = new BigInteger(1, new byte[] {publicKeyHash[7], publicKeyHash[6], publicKeyHash[5],
publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0]});
return bigInteger.longValue();
}
static Account addOrGetAccount(Long id) {
Account account = new Account(id);
Account oldAccount = accounts.putIfAbsent(id, account);
return oldAccount != null ? oldAccount : account;
}
static void clear() {
accounts.clear();
leasingAccounts.clear();
}
private final Long id;
private final int height;
private volatile byte[] publicKey;
private volatile int keyHeight;
private long balanceNQT;
private long unconfirmedBalanceNQT;
private final List<GuaranteedBalance> guaranteedBalances = new ArrayList<>();
private volatile int currentLeasingHeightFrom;
private volatile int currentLeasingHeightTo;
private volatile Long currentLesseeId;
private volatile int nextLeasingHeightFrom;
private volatile int nextLeasingHeightTo;
private volatile Long nextLesseeId;
private Set<Long> leaserIds = Collections.newSetFromMap(new ConcurrentHashMap<Long,Boolean>());
private final Map<Long, Long> assetBalances = new HashMap<>();
private final Map<Long, Long> unconfirmedAssetBalances = new HashMap<>();
private volatile String name;
private volatile String description;
private Account(Long id) {
this.id = id;
this.height = Nxt.getBlockchain().getLastBlock().getHeight();
currentLeasingHeightFrom = Integer.MAX_VALUE;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
void setAccountInfo(String name, String description) {
this.name = Convert.emptyToNull(name.trim());
this.description = Convert.emptyToNull(description.trim());
}
public synchronized byte[] getPublicKey() {
return publicKey;
}
public synchronized long getBalanceNQT() {
return balanceNQT;
}
public synchronized long getUnconfirmedBalanceNQT() {
return unconfirmedBalanceNQT;
}
public long getEffectiveBalanceNXT() {
Block lastBlock = Nxt.getBlockchain().getLastBlock();
if (lastBlock.getHeight() >= Constants.TRANSPARENT_FORGING_BLOCK_6
&& (publicKey == null || keyHeight == -1 || lastBlock.getHeight() - keyHeight <= 1440)) {
return 0; // cfb: Accounts with the public key revealed less than 1440 blocks ago are not allowed to generate blocks
}
if (lastBlock.getHeight() < Constants.TRANSPARENT_FORGING_BLOCK_3
&& this.height < Constants.TRANSPARENT_FORGING_BLOCK_2) {
if (this.height == 0) {
return getBalanceNQT() / Constants.ONE_NXT;
}
if (lastBlock.getHeight() - this.height < 1440) {
return 0;
}
long receivedInlastBlock = 0;
for (Transaction transaction : lastBlock.getTransactions()) {
if (transaction.getRecipientId().equals(id)) {
receivedInlastBlock += transaction.getAmountNQT();
}
}
return (getBalanceNQT() - receivedInlastBlock) / Constants.ONE_NXT;
}
if (lastBlock.getHeight() < currentLeasingHeightFrom) {
return (getGuaranteedBalanceNQT(1440) + getExtraEffectiveBalanceNQT()) / Constants.ONE_NXT;
}
return getExtraEffectiveBalanceNQT() / Constants.ONE_NXT;
}
private long getExtraEffectiveBalanceNQT() {
long extraEffectiveBalanceNQT = 0;
for (Long accountId : leaserIds) {
extraEffectiveBalanceNQT += Account.getAccount(accountId).getGuaranteedBalanceNQT(1440);
}
return extraEffectiveBalanceNQT;
}
public synchronized long getGuaranteedBalanceNQT(final int numberOfConfirmations) {
if (numberOfConfirmations >= Nxt.getBlockchain().getLastBlock().getHeight()) {
return 0;
}
if (numberOfConfirmations > maxTrackedBalanceConfirmations || numberOfConfirmations < 0) {
throw new IllegalArgumentException("Number of required confirmations must be between 0 and " + maxTrackedBalanceConfirmations);
}
if (guaranteedBalances.isEmpty()) {
return 0;
}
int i = Collections.binarySearch(guaranteedBalances, new GuaranteedBalance(Nxt.getBlockchain().getLastBlock().getHeight() - numberOfConfirmations, 0));
if (i == -1) {
return 0;
}
if (i < -1) {
i = -i - 2;
}
if (i > guaranteedBalances.size() - 1) {
i = guaranteedBalances.size() - 1;
}
GuaranteedBalance result;
while ((result = guaranteedBalances.get(i)).ignore && i > 0) {
i
}
return result.ignore || result.balance < 0 ? 0 : result.balance;
}
public synchronized Long getUnconfirmedAssetBalanceQNT(Long assetId) {
return unconfirmedAssetBalances.get(assetId);
}
public Map<Long, Long> getAssetBalancesQNT() {
return Collections.unmodifiableMap(assetBalances);
}
public Map<Long, Long> getUnconfirmedAssetBalancesQNT() {
return Collections.unmodifiableMap(unconfirmedAssetBalances);
}
public Long getCurrentLesseeId() {
return currentLesseeId;
}
public Long getNextLesseeId() {
return nextLesseeId;
}
public int getCurrentLeasingHeightFrom() {
return currentLeasingHeightFrom;
}
public int getCurrentLeasingHeightTo() {
return currentLeasingHeightTo;
}
public int getNextLeasingHeightFrom() {
return nextLeasingHeightFrom;
}
public int getNextLeasingHeightTo() {
return nextLeasingHeightTo;
}
public Set<Long> getLeaserIds() {
return Collections.unmodifiableSet(leaserIds);
}
void leaseEffectiveBalance(Long lesseeId, short period) {
Account lessee = Account.getAccount(lesseeId);
if (lessee != null && lessee.getPublicKey() != null) {
Block lastBlock = Nxt.getBlockchain().getLastBlock();
leasingAccounts.put(this.getId(), this);
if (currentLeasingHeightFrom == Integer.MAX_VALUE) {
currentLeasingHeightFrom = lastBlock.getHeight() + 1440;
currentLeasingHeightTo = currentLeasingHeightFrom + period;
currentLesseeId = lesseeId;
nextLeasingHeightFrom = Integer.MAX_VALUE;
} else {
nextLeasingHeightFrom = lastBlock.getHeight() + 1440;
if (nextLeasingHeightFrom < currentLeasingHeightTo) {
nextLeasingHeightFrom = currentLeasingHeightTo;
}
nextLeasingHeightTo = nextLeasingHeightFrom + period;
nextLesseeId = lesseeId;
}
}
}
// returns true iff:
// this.publicKey is set to null (in which case this.publicKey also gets set to key)
// this.publicKey is already set to an array equal to key
synchronized boolean setOrVerify(byte[] key, int height) {
if (this.publicKey == null) {
this.publicKey = key;
this.keyHeight = -1;
return true;
} else if (Arrays.equals(this.publicKey, key)) {
return true;
} else if (this.keyHeight == -1) {
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Account key for " + Convert.toUnsignedLong(id) + " was already set to a different one at the same height "
+ ", current height is " + height + ", rejecting new key");
return false;
} else if (this.keyHeight >= height) {
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Changing key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was previously set to a different one at height " + keyHeight);
this.publicKey = key;
this.keyHeight = height;
return true;
}
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Invalid key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was already set to a different one at height " + keyHeight);
return false;
}
synchronized void apply(byte[] key, int height) {
if (! setOrVerify(key, this.height)) {
throw new IllegalStateException("Generator public key mismatch");
}
if (this.publicKey == null) {
throw new IllegalStateException("Public key has not been set for account " + Convert.toUnsignedLong(id)
+" at height " + height + ", key height is " + keyHeight);
}
if (this.keyHeight == -1 || this.keyHeight > height) {
this.keyHeight = height;
}
}
synchronized void undo(int height) {
if (this.keyHeight >= height) {
Logger.logDebugMessage("Unsetting key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was previously set at height " + keyHeight);
this.publicKey = null;
this.keyHeight = -1;
}
if (this.height == height) {
Logger.logDebugMessage("Removing account " + Convert.toUnsignedLong(id) + " which was created in the popped off block");
accounts.remove(this.getId());
}
}
synchronized long getAssetBalanceQNT(Long assetId) {
return Convert.nullToZero(assetBalances.get(assetId));
}
void addToAssetBalanceQNT(Long assetId, long quantityQNT) {
synchronized (this) {
Long assetBalance = assetBalances.get(assetId);
if (assetBalance == null) {
assetBalances.put(assetId, quantityQNT);
} else {
assetBalances.put(assetId, Convert.safeAdd(assetBalance, quantityQNT));
}
}
listeners.notify(this, Event.ASSET_BALANCE);
assetListeners.notify(new AccountAsset(id, assetId, assetBalances.get(assetId)), Event.ASSET_BALANCE);
}
void addToUnconfirmedAssetBalanceQNT(Long assetId, long quantityQNT) {
synchronized (this) {
Long unconfirmedAssetBalance = unconfirmedAssetBalances.get(assetId);
if (unconfirmedAssetBalance == null) {
unconfirmedAssetBalances.put(assetId, quantityQNT);
} else {
unconfirmedAssetBalances.put(assetId, Convert.safeAdd(unconfirmedAssetBalance, quantityQNT));
}
}
listeners.notify(this, Event.UNCONFIRMED_ASSET_BALANCE);
assetListeners.notify(new AccountAsset(id, assetId, unconfirmedAssetBalances.get(assetId)), Event.UNCONFIRMED_ASSET_BALANCE);
}
void addToAssetAndUnconfirmedAssetBalanceQNT(Long assetId, long quantityQNT) {
synchronized (this) {
Long assetBalance = assetBalances.get(assetId);
if (assetBalance == null) {
assetBalances.put(assetId, quantityQNT);
} else {
assetBalances.put(assetId, Convert.safeAdd(assetBalance, quantityQNT));
}
Long unconfirmedAssetBalance = unconfirmedAssetBalances.get(assetId);
if (unconfirmedAssetBalance == null) {
unconfirmedAssetBalances.put(assetId, quantityQNT);
} else {
unconfirmedAssetBalances.put(assetId, Convert.safeAdd(unconfirmedAssetBalance, quantityQNT));
}
}
listeners.notify(this, Event.ASSET_BALANCE);
listeners.notify(this, Event.UNCONFIRMED_ASSET_BALANCE);
assetListeners.notify(new AccountAsset(id, assetId, assetBalances.get(assetId)), Event.ASSET_BALANCE);
assetListeners.notify(new AccountAsset(id, assetId, unconfirmedAssetBalances.get(assetId)), Event.UNCONFIRMED_ASSET_BALANCE);
}
void addToBalanceNQT(long amountNQT) {
synchronized (this) {
this.balanceNQT = Convert.safeAdd(this.balanceNQT, amountNQT);
addToGuaranteedBalanceNQT(amountNQT);
}
if (amountNQT != 0) {
listeners.notify(this, Event.BALANCE);
}
}
void addToUnconfirmedBalanceNQT(long amountNQT) {
if (amountNQT == 0) {
return;
}
synchronized (this) {
this.unconfirmedBalanceNQT = Convert.safeAdd(this.unconfirmedBalanceNQT, amountNQT);
}
listeners.notify(this, Event.UNCONFIRMED_BALANCE);
}
void addToBalanceAndUnconfirmedBalanceNQT(long amountNQT) {
synchronized (this) {
this.balanceNQT = Convert.safeAdd(this.balanceNQT, amountNQT);
this.unconfirmedBalanceNQT = Convert.safeAdd(this.unconfirmedBalanceNQT, amountNQT);
addToGuaranteedBalanceNQT(amountNQT);
}
if (amountNQT != 0) {
listeners.notify(this, Event.BALANCE);
listeners.notify(this, Event.UNCONFIRMED_BALANCE);
}
}
private synchronized void addToGuaranteedBalanceNQT(long amountNQT) {
int blockchainHeight = Nxt.getBlockchain().getLastBlock().getHeight();
GuaranteedBalance last = null;
if (guaranteedBalances.size() > 0 && (last = guaranteedBalances.get(guaranteedBalances.size() - 1)).height > blockchainHeight) {
// this only happens while last block is being popped off
if (amountNQT > 0) {
// this is a reversal of a withdrawal or a fee, so previous gb records need to be corrected
for (GuaranteedBalance gb : guaranteedBalances) {
gb.balance += amountNQT;
}
} // deposits don't need to be reversed as they have never been applied to old gb records to begin with
last.ignore = true; // set dirty flag
return; // block popped off, no further processing
}
int trimTo = 0;
for (int i = 0; i < guaranteedBalances.size(); i++) {
GuaranteedBalance gb = guaranteedBalances.get(i);
if (gb.height < blockchainHeight - maxTrackedBalanceConfirmations
&& i < guaranteedBalances.size() - 1
&& guaranteedBalances.get(i + 1).height >= blockchainHeight - maxTrackedBalanceConfirmations) {
trimTo = i; // trim old gb records but keep at least one at height lower than the supported maxTrackedBalanceConfirmations
if (blockchainHeight >= Constants.TRANSPARENT_FORGING_BLOCK_4 && blockchainHeight < Constants.TRANSPARENT_FORGING_BLOCK_5) {
gb.balance += amountNQT; // because of a bug which leads to a fork
} else if (blockchainHeight >= Constants.TRANSPARENT_FORGING_BLOCK_5 && amountNQT < 0) {
gb.balance += amountNQT;
}
} else if (amountNQT < 0) {
gb.balance += amountNQT; // subtract current block withdrawals from all previous gb records
}
// ignore deposits when updating previous gb records
}
if (trimTo > 0) {
Iterator<GuaranteedBalance> iter = guaranteedBalances.iterator();
while (iter.hasNext() && trimTo > 0) {
iter.next();
iter.remove();
trimTo
}
}
if (guaranteedBalances.size() == 0 || last.height < blockchainHeight) {
// this is the first transaction affecting this account in a newly added block
guaranteedBalances.add(new GuaranteedBalance(blockchainHeight, balanceNQT));
} else if (last.height == blockchainHeight) {
// following transactions for same account in a newly added block
// for the current block, guaranteedBalance (0 confirmations) must be same as balance
last.balance = balanceNQT;
last.ignore = false;
} else {
// should have been handled in the block popped off case
throw new IllegalStateException("last guaranteed balance height exceeds blockchain height");
}
}
private static class GuaranteedBalance implements Comparable<GuaranteedBalance> {
final int height;
long balance;
boolean ignore;
private GuaranteedBalance(int height, long balance) {
this.height = height;
this.balance = balance;
this.ignore = false;
}
@Override
public int compareTo(GuaranteedBalance o) {
if (this.height < o.height) {
return -1;
} else if (this.height > o.height) {
return 1;
}
return 0;
}
@Override
public String toString() {
return "height: " + height + ", guaranteed: " + balance;
}
}
}
|
package nxt;
import nxt.crypto.Crypto;
import nxt.util.Convert;
import nxt.util.Listener;
import nxt.util.Listeners;
import nxt.util.Logger;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class Account {
public static enum Event {
BALANCE, UNCONFIRMED_BALANCE
}
private static final int maxTrackedBalanceConfirmations = 2881;
private static final ConcurrentMap<Long, Account> accounts = new ConcurrentHashMap<>();
private static final Collection<Account> allAccounts = Collections.unmodifiableCollection(accounts.values());
private static final Listeners<Account,Event> listeners = new Listeners<>();
public static boolean addListener(Listener<Account> listener, Event eventType) {
return listeners.addListener(listener, eventType);
}
public static boolean removeListener(Listener<Account> listener, Event eventType) {
return listeners.removeListener(listener, eventType);
}
public static Collection<Account> getAllAccounts() {
return allAccounts;
}
public static Account getAccount(Long id) {
return accounts.get(id);
}
public static Account getAccount(byte[] publicKey) {
return accounts.get(getId(publicKey));
}
public static Long getId(byte[] publicKey) {
byte[] publicKeyHash = Crypto.sha256().digest(publicKey);
BigInteger bigInteger = new BigInteger(1, new byte[] {publicKeyHash[7], publicKeyHash[6], publicKeyHash[5],
publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0]});
return bigInteger.longValue();
}
static Account addOrGetAccount(Long id) {
Account account = new Account(id);
Account oldAccount = accounts.putIfAbsent(id, account);
return oldAccount != null ? oldAccount : account;
}
static void clear() {
accounts.clear();
}
private final Long id;
private final int height;
private byte[] publicKey;
private int keyHeight;
private long balance;
private long unconfirmedBalance;
private final List<GuaranteedBalance> guaranteedBalances = new ArrayList<>();
private final Map<Long, Integer> assetBalances = new HashMap<>();
private final Map<Long, Integer> unconfirmedAssetBalances = new HashMap<>();
private Account(Long id) {
this.id = id;
this.height = Nxt.getBlockchain().getLastBlock().getHeight();
}
public Long getId() {
return id;
}
public synchronized byte[] getPublicKey() {
return publicKey;
}
public synchronized long getBalance() {
return balance;
}
public synchronized long getUnconfirmedBalance() {
return unconfirmedBalance;
}
public int getEffectiveBalance() {
Block lastBlock = Nxt.getBlockchain().getLastBlock();
if (lastBlock.getHeight() < Nxt.TRANSPARENT_FORGING_BLOCK_3 && this.height < Nxt.TRANSPARENT_FORGING_BLOCK_2) {
if (this.height == 0) {
return (int)(getBalance() / 100);
}
if (lastBlock.getHeight() - this.height < 1440) {
return 0;
}
int receivedInlastBlock = 0;
for (Transaction transaction : lastBlock.getTransactions()) {
if (transaction.getRecipientId().equals(id)) {
receivedInlastBlock += transaction.getAmount();
}
}
return (int)(getBalance() / 100) - receivedInlastBlock;
} else {
return (int)(getGuaranteedBalance(1440) / 100);
}
}
public synchronized long getGuaranteedBalance(final int numberOfConfirmations) {
if (numberOfConfirmations >= Nxt.getBlockchain().getLastBlock().getHeight()) {
return 0;
}
if (numberOfConfirmations > maxTrackedBalanceConfirmations || numberOfConfirmations < 0) {
throw new IllegalArgumentException("Number of required confirmations must be between 0 and " + maxTrackedBalanceConfirmations);
}
if (guaranteedBalances.isEmpty()) {
return 0;
}
int i = Collections.binarySearch(guaranteedBalances, new GuaranteedBalance(Nxt.getBlockchain().getLastBlock().getHeight() - numberOfConfirmations, 0));
if (i == -1) {
return 0;
}
if (i < -1) {
i = -i - 2;
}
if (i > guaranteedBalances.size() - 1) {
i = guaranteedBalances.size() - 1;
}
GuaranteedBalance result;
while ((result = guaranteedBalances.get(i)).ignore && i > 0) {
i
}
return result.ignore ? 0 : result.balance;
}
public synchronized Integer getUnconfirmedAssetBalance(Long assetId) {
return unconfirmedAssetBalances.get(assetId);
}
public Map<Long, Integer> getAssetBalances() {
return Collections.unmodifiableMap(assetBalances);
}
// returns true iff:
// this.publicKey is set to null (in which case this.publicKey also gets set to key)
// this.publicKey is already set to an array equal to key
synchronized boolean setOrVerify(byte[] key, int height) {
if (this.publicKey == null) {
this.publicKey = key;
this.keyHeight = -1;
return true;
} else if (Arrays.equals(this.publicKey, key)) {
return true;
} else if (this.keyHeight == -1) {
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Account key for " + Convert.toUnsignedLong(id) + " was already set to a different one at the same height "
+ ", current height is " + height + ", rejecting new key");
return false;
} else if (this.keyHeight >= height) {
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Changing key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was previously set to a different one at height " + keyHeight);
this.publicKey = key;
this.keyHeight = height;
return true;
}
Logger.logMessage("DUPLICATE KEY!!!");
Logger.logMessage("Invalid key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was already set to a different one at height " + keyHeight);
return false;
}
synchronized void apply(int height) {
if (this.publicKey == null) {
throw new IllegalStateException("Public key has not been set for account " + Convert.toUnsignedLong(id)
+" at height " + height + ", key height is " + keyHeight);
}
if (this.keyHeight == -1 || this.keyHeight > height) {
this.keyHeight = height;
}
}
synchronized void undo(int height) {
if (this.keyHeight >= height) {
Logger.logDebugMessage("Unsetting key for account " + Convert.toUnsignedLong(id) + " at height " + height
+ ", was previously set at height " + keyHeight);
this.publicKey = null;
this.keyHeight = -1;
}
if (this.height == height) {
Logger.logDebugMessage("Removing account " + Convert.toUnsignedLong(id) + " which was created in the popped off block");
accounts.remove(this.getId());
}
}
synchronized int getAssetBalance(Long assetId) {
return Convert.nullToZero(assetBalances.get(assetId));
}
synchronized void addToAssetBalance(Long assetId, int quantity) {
Integer assetBalance = assetBalances.get(assetId);
if (assetBalance == null) {
assetBalances.put(assetId, quantity);
} else {
assetBalances.put(assetId, assetBalance + quantity);
}
}
synchronized void addToUnconfirmedAssetBalance(Long assetId, int quantity) {
Integer unconfirmedAssetBalance = unconfirmedAssetBalances.get(assetId);
if (unconfirmedAssetBalance == null) {
unconfirmedAssetBalances.put(assetId, quantity);
} else {
unconfirmedAssetBalances.put(assetId, unconfirmedAssetBalance + quantity);
}
}
synchronized void addToAssetAndUnconfirmedAssetBalance(Long assetId, int quantity) {
Integer assetBalance = assetBalances.get(assetId);
if (assetBalance == null) {
assetBalances.put(assetId, quantity);
unconfirmedAssetBalances.put(assetId, quantity);
} else {
assetBalances.put(assetId, assetBalance + quantity);
unconfirmedAssetBalances.put(assetId, unconfirmedAssetBalances.get(assetId) + quantity);
}
}
void addToBalance(long amount) {
synchronized (this) {
this.balance += amount;
addToGuaranteedBalance(amount);
}
listeners.notify(this, Event.BALANCE);
}
void addToUnconfirmedBalance(long amount) {
synchronized (this) {
this.unconfirmedBalance += amount;
}
listeners.notify(this, Event.UNCONFIRMED_BALANCE);
}
void addToBalanceAndUnconfirmedBalance(long amount) {
synchronized (this) {
this.balance += amount;
this.unconfirmedBalance += amount;
addToGuaranteedBalance(amount);
}
listeners.notify(this, Event.BALANCE);
listeners.notify(this, Event.UNCONFIRMED_BALANCE);
}
private synchronized void addToGuaranteedBalance(long amount) {
int blockchainHeight = Nxt.getBlockchain().getLastBlock().getHeight();
GuaranteedBalance last = null;
if (guaranteedBalances.size() > 0 && (last = guaranteedBalances.get(guaranteedBalances.size() - 1)).height > blockchainHeight) {
// this only happens while last block is being popped off
if (amount > 0) {
// this is a reversal of a withdrawal or a fee, so previous gb records need to be corrected
for (GuaranteedBalance gb : guaranteedBalances) {
gb.balance += amount;
}
} // deposits don't need to be reversed as they have never been applied to old gb records to begin with
last.ignore = true; // set dirty flag
return; // block popped off, no further processing
}
int trimTo = 0;
for (int i = 0; i < guaranteedBalances.size(); i++) {
GuaranteedBalance gb = guaranteedBalances.get(i);
if (gb.height < blockchainHeight - maxTrackedBalanceConfirmations
&& i < guaranteedBalances.size() - 1
&& guaranteedBalances.get(i + 1).height >= blockchainHeight - maxTrackedBalanceConfirmations) {
trimTo = i; // trim old gb records but keep at least one at height lower than the supported maxTrackedBalanceConfirmations
if (blockchainHeight >= Nxt.TRANSPARENT_FORGING_BLOCK_4 && blockchainHeight < Nxt.TRANSPARENT_FORGING_BLOCK_5) {
gb.balance += amount; // because of a bug which leads to a fork
} else if (blockchainHeight >= Nxt.TRANSPARENT_FORGING_BLOCK_5 && amount < 0) {
gb.balance += amount;
}
} else if (amount < 0) {
gb.balance += amount; // subtract current block withdrawals from all previous gb records
}
// ignore deposits when updating previous gb records
}
if (trimTo > 0) {
Iterator<GuaranteedBalance> iter = guaranteedBalances.iterator();
while (iter.hasNext() && trimTo > 0) {
iter.next();
iter.remove();
trimTo
}
}
if (guaranteedBalances.size() == 0 || last.height < blockchainHeight) {
// this is the first transaction affecting this account in a newly added block
guaranteedBalances.add(new GuaranteedBalance(blockchainHeight, balance));
} else if (last.height == blockchainHeight) {
// following transactions for same account in a newly added block
// for the current block, guaranteedBalance (0 confirmations) must be same as balance
last.balance = balance;
last.ignore = false;
} else {
// should have been handled in the block popped off case
throw new IllegalStateException("last guaranteed balance height exceeds blockchain height");
}
}
private static class GuaranteedBalance implements Comparable<GuaranteedBalance> {
final int height;
long balance;
boolean ignore;
private GuaranteedBalance(int height, long balance) {
this.height = height;
this.balance = balance;
this.ignore = false;
}
@Override
public int compareTo(GuaranteedBalance o) {
if (this.height < o.height) {
return -1;
} else if (this.height > o.height) {
return 1;
}
return 0;
}
@Override
public String toString() {
return "height: " + height + ", guaranteed: " + balance;
}
}
}
|
package language;
import entity.GameBoard;
import entity.Player;
public class English implements Language{
public English(){
}
@Override
public String notifyLangChange(){
return "The language is now english!";
}
@Override
public String fieldNames(int fieldNumber) {
String fieldName;
switch (fieldNumber) {
case 0: fieldName = "START";
break;
case 1: fieldName = "Tribe Encampment";
break;
case 2: fieldName = "Second Sail";
break;
case 3: fieldName = "Crater";
break;
case 4: fieldName = "Huts in the Mountain";
break;
case 5: fieldName = "Mountain";
break;
case 6: fieldName = "Monastery";
break;
case 7: fieldName = "Cold Desert";
break;
case 8: fieldName = "Sea Grover";
break;
case 9: fieldName = "Black Cave";
break;
case 10: fieldName = "Goldmine";
break;
case 11: fieldName = "The Werewall";
break;
case 12: fieldName = "The Pit";
break;
case 13: fieldName = "Mountain Village";
break;
case 14: fieldName = "The Buccaneers";
break;
case 15: fieldName = "South Citadel";
break;
case 16: fieldName = "Walled City";
break;
case 17: fieldName = "Palace Gates";
break;
case 18: fieldName = "Caravan";
break;
case 19: fieldName = "Tower";
break;
case 20: fieldName = "Privateer Armade";
break;
case 21: fieldName = "Castle";
break;
default: fieldName = "Unknown field!";
break;
}
return fieldName;
}
@Override
public String fieldPrices(int fieldNumber, GameBoard gameBoard) {
String fieldPrice;
switch (fieldNumber) {
case 0: fieldPrice = "Refuge";
break;
case 1: fieldPrice = "Price: 1000";
break;
case 2: fieldPrice = "Price: 4000";
break;
case 3: fieldPrice = "Price: 1500";
break;
case 4: fieldPrice = "Price: 2500";
break;
case 5: fieldPrice = "Price: 2000";
break;
case 6: fieldPrice = "Monastery";
break;
case 7: fieldPrice = "Price: 3000";
break;
case 8: fieldPrice = "Price: 4000";
break;
case 9: fieldPrice = "Price: 4000";
break;
case 10: fieldPrice = "Goldmine";
break;
case 11: fieldPrice = "Price: 4300";
break;
case 12: fieldPrice = "Price: 2500";
break;
case 13: fieldPrice = "Price: 4700";
break;
case 14: fieldPrice = "Price: 4000";
break;
case 15: fieldPrice = "Price: 5000";
break;
case 16: fieldPrice = "Walled City";
break;
case 17: fieldPrice = "Price: 5500";
break;
case 18: fieldPrice = "Caravan";
break;
case 19: fieldPrice = "Price: 6000";
break;
case 20: fieldPrice = "Price: 4000";
break;
case 21: fieldPrice = "Price: 8000";
break;
default: fieldPrice = "Unknown field!";
break;
}
return fieldPrice;
}
@Override
public String fieldDescription(int fieldNumber) {
String fieldName;
switch (fieldNumber) {
case 6: fieldName = "Recieve 500 coins";
break;
case 10: fieldName = "Pay 2000 coins";
break;
case 16: fieldName = "Recieve 5000 coins";
break;
case 18: fieldName = "Pay 4000 or 10% of you coins";
break;
default: fieldName = "Unknown field!";
break;
}
return fieldName;
}
@Override
public String welcomeMsg(){
return "Welcome to the game!";
}
@Override
public String askForNumberOfPlayers() {
return "How many players do you want to play? You can choose inbetween 2 and 6 players to be in the game";
}
@Override
public String askForPlayerName(int playerNumber){
return "Enter name of player " + playerNumber;
}
@Override
public String readyToBegin(){
return "The game will now start. The game is won by the player who stands when everyone else is broke";
}
public String preMsg(Player player){
return "It's " + player.getName() + "s turn, press the button to roll!";
}
@Override
public String fieldMsg(int fieldNumber){
String fieldString;
switch (fieldNumber) {
case 1: fieldString = "You're invited to a party at the Tribe Encampment!";
break;
case 2: fieldString = "You sail with the Second Sail!";
break;
case 3: fieldString = "You find a big crater and examine it!";
break;
case 4: fieldString = "You further examine the mountain and find some huts in the mountain!";
break;
case 5: fieldString = "You're arrived at a huge mountain!";
break;
case 6: fieldString = "You see a monastery in the distance and walk closer!";
break;
case 7: fieldString = "You're arrived at the cold desert!";
break;
case 8: fieldString = "You sail with the Sea Grover";
break;
case 9: fieldString = "You find a black cave!";
break;
case 10: fieldString = "You explore a cave that looks like a goldmine";
break;
case 11: fieldString = "You're arrived at the Werewall!";
break;
case 12: fieldString = "You fell into a black hole!";
break;
case 13: fieldString = "You're arrived at the famous mountain village!";
break;
case 14: fieldString = "You sail with the The Buccaneers";
break;
case 15: fieldString = "You're arrived at the South Citadel!";
break;
case 16: fieldString = "You walk carefully through the Walled City";
break;
case 17: fieldString = "You pass the large Palace Gates";
break;
case 18: fieldString = "You found an abandoned Caravan!";
break;
case 19: fieldString = "You try to clib the Tower!";
break;
case 20: fieldString = "You go on a sailing adventure with the Privateer Armade";
break;
case 21: fieldString = "You're invited into the big Castle!";
break;
default: fieldString = "Unknown field!";
break;
}
return fieldString;
}
@Override
public String buyingOfferMsg(int price) {
return "This field is not owned by anyone, do you want to buy it for " + price + " coins?";
}
@Override
public String yes() {
return "Yes!";
}
@Override
public String no() {
return "No!";
}
@Override
public String purchaseConfirmation() {
return "You have now bought this field!";
}
@Override
public String notEnoughMoney() {
return "You have not enough coins left..";
}
public String landedOnOwnedField(Player owner) {
return "This field is already owned by someone, you'll have to pay rent!";
}
@Override
public String youPaidThisMuchToThisPerson(int amountPayed, Player owner) {
return "You paid " + amountPayed
+ " coins to " + owner.getName() + ".";
}
@Override
public String getTaxChoice() {
return "You can either choose to pay 4000 coins or 10% of your current balance,"
+ "\ndo you want to pay 10%?";
}
@Override
public String nonOwnableFieldEffectMsg(int fieldNumber) {
String message;
switch (fieldNumber) {
case 6: message = "You landed on the Monastery, you'll recieve 500 coins!";
break;
case 10: message = "You landed on the Goldmine, you'll have to pay 2000 coins!";
break;
case 16: message = "You landed on the Walled City, you'll recieve 5000 coins";
break;
default: message = "Unknown field!";
break;
}
return message;
}
@Override
public String youAreBroke() {
return "Sorry, you are broke, thanks for playing!";
}
@Override
public String winnerMsg(Player player){
return player.getName() + " have won the game with " + player.getBankAccount().getBalance() + " coins!";
}
@Override
public String menu(){
return "Tast 1 for at skifte antal sider på terningerne.\n" +
"Tast 2 for at ændre sprog.\n" +
"Tast 3 for at vise scoren.\n"+
"Tast 4 for at afslutte spillet.\n" +
"Tast 5 for at fortsætte spillet.";
}
@Override
public String printRules(){
return "Dette spil er et terningespil mellem 2 personer. Du slår med terninger og lander på et felt fra 2-12. \nDisse felter har enten en negativ eller positiv effekt på din beholdning. Her er vist listen over felterne: \n"
+ "2. Tower: +250 \n"
+ "3. Crater: -100 \n"
+ "4. Palace gates: +100 \n"
+ "5. Cold Desert: -20 \n"
+ "6. Walled city: +180 \n"
+ "7. Monastery: 0 \n"
+ "8. Black cave: -70 \n"
+ "9. Huts in the mountain: +60 \n"
+ "10. The Werewall (werewolf-wall): -80, men spilleren får en ekstra tur \n"
+ "11. The pit: -50 \n"
+ "12. Goldmine: +650";
}
@Override
public String printScore(Player[] players){
StringBuilder str = new StringBuilder();
str.append("The score is:");
for (int i = 0; i < players.length; i++)
str.append("\n" + players[i].getName() + " has " + players[i].getBankAccount().getBalance());
return str.toString();
}
@Override
public String changeDices(){
return "Enter how many eyes you want them to have, in the form \"x,y\" - the sum of them must be 12";
}
@Override
public String printDiceChangeSucces(){
return "Dice are now changed!";
}
@Override
public String printDiceChangeNotExecuted(){
return "Dice could not be changed";
}
@Override
public String youOwnThisField() {
return "You already own this field";
}
}
|
package be.fedict.dcat.scrapers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.openrdf.repository.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Bart Hanssens <bart.hanssens@fedict.be>
*/
public class Main {
private final static Logger logger = LoggerFactory.getLogger(Main.class);
private final static Properties prop = new Properties();
/**
* Exit cleanly
*
* @param code return code
*/
protected static void exit(int code) {
logger.info("-- STOP --");
System.exit(code);
}
/**
* Set proxy, if needed.
*
* @param s Scraper instance.
*/
private static void setProxy(Scraper s) {
String proxy = prop.getProperty(Scraper.PROP_PREFIX + ".proxy.host", "");
String port = prop.getProperty(Scraper.PROP_PREFIX + ".proxy.port", "");
if (!proxy.isEmpty()) {
s.setProxy(proxy, Integer.parseInt(port));
}
}
/**
* Load a scraper and scrape the site.
*
* @param prefix properties prefix for additional configuration
*/
private static Scraper getScraper() {
String name = prop.getProperty(Scraper.PROP_PREFIX + ".classname");
String cache = prop.getProperty(Scraper.PROP_PREFIX + ".cache", "");
String store = prop.getProperty(Scraper.PROP_PREFIX + ".store", "");
String url = prop.getProperty(Scraper.PROP_PREFIX + ".url", "");
Scraper s = null;
try {
Class<? extends Scraper> c = Class.forName(name).asSubclass(Scraper.class);
s = c.getConstructor(File.class, File.class, URL.class).
newInstance(new File(cache), new File(store), new URL(url));
s.setProperties(prop, Scraper.PROP_PREFIX);
setProxy(s);
} catch (ClassNotFoundException|InstantiationException|NoSuchMethodException|
IllegalAccessException|InvocationTargetException ex) {
logger.error("Scraper class {} could not be loaded", name, ex);
exit(-3);
} catch (MalformedURLException ex) {
logger.error("Base URL invalid {}", url, ex);
exit(-3);
}
return s;
}
/**
* Write result of scrape to DCAT file
*
* @param scraper
*/
private static void writeDcat(Scraper scraper) {
String out = prop.getProperty(Scraper.PROP_PREFIX + ".rdfout");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(out)));
scraper.writeDcat(bw);
} catch (IOException ex) {
logger.error("Error writing output file {}", out, ex);
exit(-5);
} catch (RepositoryException ex) {
logger.error("Repository error", ex);
exit(-6);
}
}
public static void main(String[] args) {
logger.info("-- START --");
if (args.length == 0) {
logger.error("No config file");
exit(-1);
}
File config = new File(args[0]);
try {
prop.load(new FileInputStream(config));
} catch (IOException ex) {
logger.error("I/O Exception while reading {}", config, ex);
exit(-2);
}
Scraper scraper = getScraper();
try {
scraper.scrape();
} catch (IOException ex) {
logger.error("Error while scraping", ex);
exit(-4);
}
writeDcat(scraper);
exit(0);
}
}
|
package com.podio.sdk.provider;
import com.podio.sdk.Filter;
import com.podio.sdk.Request;
import com.podio.sdk.domain.Conversation;
import com.podio.sdk.volley.VolleyProvider;
public class ConversationProvider extends VolleyProvider {
static class Path extends Filter {
protected Path() {
super("conversation");
}
Path withCreate() {
addPathSegment("v2");
return this;
}
Path withEvent(long id) {
addPathSegment("event");
addPathSegment(Long.toString(id));
return this;
}
Path withEvents(long id) {
addPathSegment(Long.toString(id, 10));
addPathSegment("event");
return this;
}
Path withFlag(String key, String value) {
addQueryParameter(key, value);
return this;
}
Path withId(long id) {
addPathSegment(Long.toString(id, 10));
return this;
}
Path withReadFlag(long id) {
addPathSegment(Long.toString(id, 10));
addPathSegment("read");
return this;
}
Path withReply(long id) {
addPathSegment(Long.toString(id, 10));
addPathSegment("reply");
addPathSegment("v2");
return this;
}
Path withSearch(String text) {
addPathSegment("search");
addQueryParameter("text", text);
return this;
}
Path withSpan(int limit, int offset) {
addQueryParameter("limit", Integer.toString(limit, 10));
addQueryParameter("offset", Integer.toString(offset, 10));
return this;
}
}
/**
* Creates a new conversation as of the parameters in the given template.
*
* @param data
* The parameters for the new conversation.
* @return A creation result.
*/
public Request<Conversation> createConversation(Conversation.Create data) {
Path filter = new Path().withCreate();
return post(filter, data, Conversation.class);
}
/**
* Fetches the given Conversation span.
*
* @param limit
* The number of conversations to fetch.
* @param offset
* The number of conversations to skip before start fetching.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation[]> getConversations(int limit, int offset) {
Path filter = new Path().withSpan(limit, offset);
return get(filter, Conversation[].class);
}
/**
* Fetches the Conversation with the given id.
*
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation> getConversation(long id) {
Path filter = new Path().withId(id);
return get(filter, Conversation.class);
}
/**
* Fetches the events for the conversation with the given id.
*
* @param id
* The id of the conversation.
* @param limit
* The number of events to fetch.
* @param offset
* The number of events to skip before start fetching.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation.Event[]> getConversationEvents(long id, int limit, int offset) {
Path filter = new Path().withEvents(id).withSpan(limit, offset);
return get(filter, Conversation.Event[].class);
}
/**
* Fetches a single conversation event with the given id.
*
* @param id
* The id of the conversation event.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation.Event> getConversationEvent(long id) {
Path filter = new Path().withEvent(id);
return get(filter, Conversation.Event.class);
}
/**
* Marks the conversation with the given id as "read".
*
* @param conversationId
* The id of the conversation.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Void> markConversationAsRead(long conversationId) {
Path filter = new Path().withReadFlag(conversationId);
return post(filter, null, Void.class);
}
/**
* Sends a reply to the conversation with the given id. The request result
* will deliver the generated conversation event.
*
* @param message
* The reply body.
* @param link
* The embedded link (if any).
* @param fileIds
* The list of ids of any files attached to the reply.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation.Event> replyToConversation(long conversationId, String message, String link, long[] fileIds) {
Path filter = new Path().withReply(conversationId);
Conversation.Reply reply = new Conversation.Reply(message, link, fileIds);
return post(filter, reply, Conversation.Event.class);
}
/**
* Searches the conversations for the given text snippet.
*
* @param text
* The text to match conversations to.
* @param limit
* The maximum number of replies to return.
* @param offset
* The number of replies to skip before start counting the number of
* replies to pick.
* @param searchParticipants
* Whether to search for participant names or not.
* @return A ticket which the caller can use to identify this request with.
*/
public Request<Conversation[]> searchConversations(String text, int limit, int offset, boolean searchParticipants) {
Path filter = new Path().withSearch(text).withSpan(limit, offset);
if (searchParticipants) {
filter.withFlag("participants", "true");
}
return get(filter, Conversation[].class);
}
}
|
package com.horcrux.svg;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.Base64;
import android.view.View;
import android.view.ViewParent;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.DisplayMetricsHolder;
import com.facebook.react.uimanager.ReactCompoundView;
import com.facebook.react.uimanager.ReactCompoundViewGroup;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.view.ReactViewGroup;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Custom {@link View} implementation that draws an RNSVGSvg React view and its children.
*/
@SuppressLint("ViewConstructor")
public class SvgView extends ReactViewGroup implements ReactCompoundView, ReactCompoundViewGroup {
@Override
public boolean interceptsTouchEvent(float touchX, float touchY) {
return true;
}
@SuppressWarnings("unused")
public enum Events {
EVENT_DATA_URL("onDataURL");
private final String mName;
Events(final String name) {
mName = name;
}
public String toString() {
return mName;
}
}
private @Nullable Bitmap mBitmap;
public SvgView(ReactContext reactContext) {
super(reactContext);
mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density;
}
@Override
public void setId(int id) {
super.setId(id);
SvgViewManager.setSvgView(id, this);
}
@Override
public void invalidate() {
super.invalidate();
ViewParent parent = getParent();
if (parent instanceof VirtualView) {
if (!mRendered) {
return;
}
mRendered = false;
((VirtualView) parent).getSvgView().invalidate();
return;
}
if (mBitmap != null) {
mBitmap.recycle();
}
mBitmap = null;
}
@Override
protected void onDraw(Canvas canvas) {
if (getParent() instanceof VirtualView) {
return;
}
super.onDraw(canvas);
if (mBitmap == null) {
mBitmap = drawOutput();
}
if (mBitmap != null)
canvas.drawBitmap(mBitmap, 0, 0, null);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.invalidate();
}
@Override
public int reactTagForTouch(float touchX, float touchY) {
return hitTest(touchX, touchY);
}
private boolean mResponsible = false;
private final Map<String, VirtualView> mDefinedClipPaths = new HashMap<>();
private final Map<String, VirtualView> mDefinedTemplates = new HashMap<>();
private final Map<String, VirtualView> mDefinedMasks = new HashMap<>();
private final Map<String, Brush> mDefinedBrushes = new HashMap<>();
private Canvas mCanvas;
private final float mScale;
private float mMinX;
private float mMinY;
private float mVbWidth;
private float mVbHeight;
private SVGLength mbbWidth;
private SVGLength mbbHeight;
private String mAlign;
private int mMeetOrSlice;
private final Matrix mInvViewBoxMatrix = new Matrix();
private boolean mInvertible = true;
private boolean mRendered = false;
int mTintColor = 0;
private void clearChildCache() {
if (!mRendered) {
return;
}
mRendered = false;
for (int i = 0; i < getChildCount(); i++) {
View node = getChildAt(i);
if (node instanceof VirtualView) {
VirtualView n = ((VirtualView)node);
n.clearChildCache();
}
}
}
@ReactProp(name = "tintColor", customType = "Color")
public void setTintColor(@Nullable Integer tintColor) {
if (tintColor == null) {
mTintColor = 0;
} else {
mTintColor = tintColor;
}
}
@ReactProp(name = "minX")
public void setMinX(float minX) {
mMinX = minX;
invalidate();
clearChildCache();
}
@ReactProp(name = "minY")
public void setMinY(float minY) {
mMinY = minY;
invalidate();
clearChildCache();
}
@ReactProp(name = "vbWidth")
public void setVbWidth(float vbWidth) {
mVbWidth = vbWidth;
invalidate();
clearChildCache();
}
@ReactProp(name = "vbHeight")
public void setVbHeight(float vbHeight) {
mVbHeight = vbHeight;
invalidate();
clearChildCache();
}
@ReactProp(name = "bbWidth")
public void setBbWidth(Dynamic bbWidth) {
mbbWidth = SVGLength.from(bbWidth);
invalidate();
clearChildCache();
}
@ReactProp(name = "bbHeight")
public void setBbHeight(Dynamic bbHeight) {
mbbHeight = SVGLength.from(bbHeight);
invalidate();
clearChildCache();
}
@ReactProp(name = "align")
public void setAlign(String align) {
mAlign = align;
invalidate();
clearChildCache();
}
@ReactProp(name = "meetOrSlice")
public void setMeetOrSlice(int meetOrSlice) {
mMeetOrSlice = meetOrSlice;
invalidate();
clearChildCache();
}
private Bitmap drawOutput() {
mRendered = true;
float width = getWidth();
float height = getHeight();
boolean early = Float.isNaN(width) || Float.isNaN(height) || width * height == 0 || (Math.log10(width) + Math.log10(height) > 42);
if (early) {
ViewParent viewParent = getParent();
View parent = null;
if ((viewParent instanceof View)) {
parent = (View)viewParent;
}
float parentWidth = parent == null ? 0 : parent.getWidth();
float parentHeight = parent == null ? 0 : parent.getHeight();
width = (float) PropHelper.fromRelative(mbbWidth, parentWidth, 0, mScale, 12);
height = (float) PropHelper.fromRelative(mbbHeight, parentHeight, 0, mScale, 12);
setMeasuredDimension((int)Math.ceil(width), (int)Math.ceil(height));
}
if (width <= 0 || height <= 0) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(
(int) width,
(int) height,
Bitmap.Config.ARGB_8888);
drawChildren(new Canvas(bitmap));
return bitmap;
}
Rect getCanvasBounds() {
return mCanvas.getClipBounds();
}
void drawChildren(final Canvas canvas) {
mRendered = true;
mCanvas = canvas;
if (mAlign != null) {
RectF vbRect = getViewBox();
float width = canvas.getWidth();
float height = canvas.getHeight();
boolean nested = getParent() instanceof VirtualView;
if (nested) {
width = (float) PropHelper.fromRelative(mbbWidth, width, 0f, mScale, 12);
height = (float) PropHelper.fromRelative(mbbHeight, height, 0f, mScale, 12);
}
RectF eRect = new RectF(0,0, width, height);
if (nested) {
canvas.clipRect(eRect);
}
Matrix mViewBoxMatrix = ViewBox.getTransform(vbRect, eRect, mAlign, mMeetOrSlice);
mInvertible = mViewBoxMatrix.invert(mInvViewBoxMatrix);
canvas.concat(mViewBoxMatrix);
}
final Paint paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
paint.setTypeface(Typeface.DEFAULT);
for (int i = 0; i < getChildCount(); i++) {
View node = getChildAt(i);
if (node instanceof VirtualView) {
((VirtualView)node).saveDefinition();
}
}
for (int i = 0; i < getChildCount(); i++) {
View lNode = getChildAt(i);
if (lNode instanceof VirtualView) {
VirtualView node = (VirtualView)lNode;
int count = node.saveAndSetupCanvas(canvas);
node.render(canvas, paint, 1f);
node.restoreCanvas(canvas, count);
if (node.isResponsible() && !mResponsible) {
mResponsible = true;
}
}
}
}
private RectF getViewBox() {
return new RectF(mMinX * mScale, mMinY * mScale, (mMinX + mVbWidth) * mScale, (mMinY + mVbHeight) * mScale);
}
String toDataURL() {
Bitmap bitmap = Bitmap.createBitmap(
getWidth(),
getHeight(),
Bitmap.Config.ARGB_8888);
drawChildren(new Canvas(bitmap));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmap.recycle();
byte[] bitmapBytes = stream.toByteArray();
return Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
void enableTouchEvents() {
if (!mResponsible) {
mResponsible = true;
}
}
boolean isResponsible() {
return mResponsible;
}
private int hitTest(float touchX, float touchY) {
if (!mResponsible || !mInvertible) {
return getId();
}
float[] transformed = { touchX, touchY };
mInvViewBoxMatrix.mapPoints(transformed);
int count = getChildCount();
int viewTag = -1;
for (int i = count - 1; i >= 0; i
View child = getChildAt(i);
if (child instanceof VirtualView) {
viewTag = ((VirtualView) child).hitTest(transformed);
} else if (child instanceof SvgView) {
viewTag = ((SvgView) child).hitTest(touchX, touchY);
}
if (viewTag != -1) {
break;
}
}
return viewTag == -1 ? getId() : viewTag;
}
void defineClipPath(VirtualView clipPath, String clipPathRef) {
mDefinedClipPaths.put(clipPathRef, clipPath);
}
VirtualView getDefinedClipPath(String clipPathRef) {
return mDefinedClipPaths.get(clipPathRef);
}
void defineTemplate(VirtualView template, String templateRef) {
mDefinedTemplates.put(templateRef, template);
}
VirtualView getDefinedTemplate(String templateRef) {
return mDefinedTemplates.get(templateRef);
}
void defineBrush(Brush brush, String brushRef) {
mDefinedBrushes.put(brushRef, brush);
}
Brush getDefinedBrush(String brushRef) {
return mDefinedBrushes.get(brushRef);
}
void defineMask(VirtualView mask, String maskRef) {
mDefinedMasks.put(maskRef, mask);
}
VirtualView getDefinedMask(String maskRef) {
return mDefinedMasks.get(maskRef);
}
}
|
package com.ddiehl.android.htn.view.fragments;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import com.ddiehl.android.htn.BusProvider;
import com.ddiehl.android.htn.IdentityManager;
import com.ddiehl.android.htn.R;
import com.ddiehl.android.htn.SettingsManager;
import com.ddiehl.android.htn.events.requests.GetUserSettingsEvent;
import com.ddiehl.android.htn.events.requests.UpdateUserSettingsEvent;
import com.ddiehl.android.htn.events.responses.UserSettingsRetrievedEvent;
import com.ddiehl.android.htn.view.BaseView;
import com.ddiehl.android.htn.view.MainView;
import com.ddiehl.reddit.identity.UserIdentity;
import com.ddiehl.reddit.identity.UserSettings;
import com.flurry.android.FlurryAgent;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import java.util.HashMap;
import java.util.Map;
public class SettingsFragment extends PreferenceFragment
implements BaseView, SharedPreferences.OnSharedPreferenceChangeListener {
private Bus mBus = BusProvider.getInstance();
private IdentityManager mIdentityManager;
private SettingsManager mSettingsManager;
private boolean mSettingsRetrievedFromRemote = false;
private boolean isChanging = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIdentityManager = IdentityManager.getInstance(getActivity());
mSettingsManager = SettingsManager.getInstance(getActivity());
getPreferenceManager().setSharedPreferencesName(SettingsManager.PREFS_USER);
addPreferencesFromResource(R.xml.preferences_all);
if (mSettingsRetrievedFromRemote) {
addUserPreferences();
}
}
private void addUserPreferences() {
addPreferencesFromResource(R.xml.preferences_user);
UserIdentity user = mIdentityManager.getUserIdentity();
if (user.isGold()) {
addPreferencesFromResource(R.xml.preferences_gold);
}
}
@Override
public void onStart() {
super.onStart();
mBus.register(this);
getActivity().setTitle(R.string.settings_fragment_title);
updateAllPrefs();
}
@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
if (!mSettingsRetrievedFromRemote && mIdentityManager.getUserIdentity() != null) {
showSpinner(null);
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
mBus.post(new GetUserSettingsEvent());
}
}
@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onStop() {
mBus.unregister(this);
super.onStop();
}
@Subscribe
public void onSettingsRetrieved(UserSettingsRetrievedEvent event) {
if (event.isFailed()) {
dismissSpinner();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
return;
}
UserSettings settings = event.getSettings();
mSettingsManager.saveSettings(settings);
mSettingsRetrievedFromRemote = true;
addUserPreferences();
updateAllPrefs();
dismissSpinner();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
public void updateAllPrefs() {
Preference root = getPreferenceScreen();
updateAllPrefs(root);
}
private void updateAllPrefs(Preference root) {
if (root instanceof PreferenceGroup) {
PreferenceGroup pGrp = (PreferenceGroup) root;
for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
updateAllPrefs(pGrp.getPreference(i));
}
} else {
updatePref(root);
}
}
public void updatePref(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
String s = editTextPref.getText();
p.setSummary(s.equals("null") ? "" : s);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
updatePref(findPreference(key));
if (isChanging)
return;
isChanging = true;
Map<String, String> changedSettings = new HashMap<>(); // Track changed keys and values
switch (key) {
case SettingsManager.PREF_ENABLE_ADS:
if (sp.getBoolean(SettingsManager.PREF_ENABLE_ADS, false)) {
// Show appreciation for users enabling ads
showToast(R.string.pref_enable_ads_thanks);
}
break;
default:
Preference p = findPreference(key);
if (p instanceof CheckBoxPreference) {
boolean value = ((CheckBoxPreference) p).isChecked();
changedSettings.put(key, String.valueOf(value));
} else if (p instanceof ListPreference) {
String value = ((ListPreference) p).getValue();
changedSettings.put(key, value);
} else if (p instanceof EditTextPreference) {
String value = ((EditTextPreference) p).getEditText().getText().toString();
changedSettings.put(key, value);
}
break;
}
// Force "make safe(r) for work" to be true if "over 18" is false
if (!sp.getBoolean(SettingsManager.PREF_OVER_18, false)) {
CheckBoxPreference pref = ((CheckBoxPreference) findPreference(SettingsManager.PREF_NO_PROFANITY));
if (!pref.isChecked()) {
changedSettings.put(SettingsManager.PREF_NO_PROFANITY, String.valueOf(true));
pref.setChecked(true);
}
}
// Force "label nsfw" to be true if "make safe(r) for work" is true
if (sp.getBoolean(SettingsManager.PREF_NO_PROFANITY, true)) {
CheckBoxPreference pref = ((CheckBoxPreference) findPreference(SettingsManager.PREF_LABEL_NSFW));
if (!pref.isChecked()) {
changedSettings.put(SettingsManager.PREF_LABEL_NSFW, String.valueOf(true));
pref.setChecked(true);
}
}
if (changedSettings.size() > 0) {
// Post SettingsUpdate event with changed keys and values
mBus.post(new UpdateUserSettingsEvent(changedSettings));
}
// Send Flurry event
Map<String, String> params = new HashMap<>();
params.put("key", key);
Map prefs = sp.getAll();
params.put("value", String.valueOf(prefs.get(key)));
FlurryAgent.logEvent("setting changed", params);
isChanging = false;
}
@Override
public void setTitle(CharSequence title) {
getActivity().setTitle(title);
}
@Override
public void showSpinner(String msg) {
((MainView) getActivity()).showSpinner(msg);
}
@Override
public void showSpinner(int resId) {
((MainView) getActivity()).showSpinner(resId);
}
@Override
public void dismissSpinner() {
((MainView) getActivity()).dismissSpinner();
}
@Override
public void showToast(String msg) {
((MainView) getActivity()).showToast(msg);
}
@Override
public void showToast(int resId) {
((MainView) getActivity()).showToast(resId);
}
}
|
package com.futurice.freesound.feature.common;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.futurice.freesound.inject.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import javax.inject.Inject;
public final class DefaultAnalytics implements Analytics {
private static final String SINGLE_TEST_EVENT = "SingleEvent";
@NonNull
private final FirebaseAnalytics firebaseAnalytics;
@Inject
public DefaultAnalytics(@Application @NonNull final Context context) {
firebaseAnalytics = FirebaseAnalytics.getInstance(context);
}
@Override
public void log(@NonNull final String event) {
Bundle bundle = new Bundle();
bundle.putString(SINGLE_TEST_EVENT, event);
firebaseAnalytics.logEvent(SINGLE_TEST_EVENT, bundle);
}
}
|
package com.rnergachev.propertylisting.handler;
public interface ProgressHandler {
/**
* Starts progress bar
*/
void startProgress();
/**
* Stops progress bar
*/
void stopProgress();
}
|
package com.satsumasoftware.timetable.ui;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import com.satsumasoftware.timetable.R;
import com.satsumasoftware.timetable.TimetableApplication;
import com.satsumasoftware.timetable.db.ClassTimesSchema;
import com.satsumasoftware.timetable.db.TimetableDbHelper;
import com.satsumasoftware.timetable.db.util.ClassUtils;
import com.satsumasoftware.timetable.db.util.TermUtils;
import com.satsumasoftware.timetable.db.util.TimetableUtils;
import com.satsumasoftware.timetable.framework.ClassTime;
import com.satsumasoftware.timetable.framework.Term;
import com.satsumasoftware.timetable.framework.Timetable;
import com.satsumasoftware.timetable.ui.adapter.TermsAdapter;
import com.satsumasoftware.timetable.util.TextUtilsKt;
import com.satsuware.usefulviews.LabelledSpinner;
import org.threeten.bp.LocalDate;
import org.threeten.bp.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TimetableEditActivity extends AppCompatActivity implements LabelledSpinner.OnItemChosenListener {
protected static final String EXTRA_TIMETABLE = "extra_timetable";
private static final int REQUEST_CODE_TERM_EDIT = 1;
private boolean mIsFirst;
private Timetable mTimetable;
private boolean mIsNew;
private EditText mEditTextName;
private TextView mStartDateText, mEndDateText;
private LocalDate mStartDate, mEndDate;
private LabelledSpinner mSpinnerScheduling, mSpinnerWeekRotations;
private int mWeekRotations;
private TermsAdapter mAdapter;
private ArrayList<Term> mTerms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timetable_edit);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
mTimetable = extras.getParcelable(EXTRA_TIMETABLE);
}
mIsNew = mTimetable == null;
mIsFirst = ((TimetableApplication) getApplication()).getCurrentTimetable() == null;
int titleResId = mIsNew ? R.string.title_activity_timetable_new :
R.string.title_activity_timetable_edit;
getSupportActionBar().setTitle(getResources().getString(titleResId));
toolbar.setNavigationIcon(R.drawable.ic_close_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handleCloseAction();
}
});
mEditTextName = (EditText) findViewById(R.id.editText_name);
if (!mIsNew) {
mEditTextName.setText(mTimetable.getName());
}
mStartDateText = (TextView) findViewById(R.id.textView_start_date);
mEndDateText = (TextView) findViewById(R.id.textView_end_date);
if (!mIsNew) {
mStartDate = mTimetable.getStartDate();
mEndDate = mTimetable.getEndDate();
updateDateTexts();
}
mStartDateText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// note: -1 and +1s in code because Android month values are from 0-11 (to
// correspond with java.util.Calendar) but LocalDate month values are from 1-12
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
mStartDate = LocalDate.of(year, month + 1, dayOfMonth);
updateDateTexts();
}
};
new DatePickerDialog(
TimetableEditActivity.this,
listener,
mIsNew ? LocalDate.now().getYear() : mStartDate.getYear(),
mIsNew ? LocalDate.now().getMonthValue() - 1 : mStartDate.getMonthValue() - 1,
mIsNew ? LocalDate.now().getDayOfMonth() : mStartDate.getDayOfMonth()
).show();
}
});
mEndDateText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
mEndDate = LocalDate.of(year, month + 1, dayOfMonth);
updateDateTexts();
}
};
new DatePickerDialog(
TimetableEditActivity.this,
listener,
mIsNew ? LocalDate.now().getYear() : mEndDate.getYear(),
mIsNew ? LocalDate.now().getMonthValue() - 1 : mEndDate.getMonthValue() - 1,
mIsNew ? LocalDate.now().getDayOfMonth() : mEndDate.getDayOfMonth()
).show();
}
});
mSpinnerScheduling = (LabelledSpinner) findViewById(R.id.spinner_scheduling_type);
mSpinnerWeekRotations = (LabelledSpinner) findViewById(R.id.spinner_scheduling_detail);
mSpinnerScheduling.setOnItemChosenListener(this);
mSpinnerWeekRotations.setOnItemChosenListener(this);
mWeekRotations = mIsNew ? 1 : mTimetable.getWeekRotations();
updateSchedulingSpinners();
mTerms = TermUtils.getTerms(this, findTimetableId());
sortList();
mAdapter = new TermsAdapter(mTerms);
mAdapter.setOnEntryClickListener(new TermsAdapter.OnEntryClickListener() {
@Override
public void onEntryClick(View view, int position) {
Intent intent = new Intent(TimetableEditActivity.this, TermEditActivity.class);
intent.putExtra(TermEditActivity.EXTRA_TERM, mTerms.get(position));
intent.putExtra(TermEditActivity.EXTRA_TIMETABLE_ID, findTimetableId());
startActivityForResult(intent, REQUEST_CODE_TERM_EDIT);
}
});
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this) {
@Override
public boolean canScrollVertically() {
return false;
}
});
recyclerView.setAdapter(mAdapter);
Button btnAddTerm = (Button) findViewById(R.id.button_add_term);
btnAddTerm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(TimetableEditActivity.this, TermEditActivity.class);
intent.putExtra(TermEditActivity.EXTRA_TIMETABLE_ID, findTimetableId());
startActivityForResult(intent, REQUEST_CODE_TERM_EDIT);
}
});
}
private void updateDateTexts() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM uuuu");
if (mStartDate != null) {
mStartDateText.setText(mStartDate.format(formatter));
mStartDateText.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.mdu_text_black));
}
if (mEndDate != null) {
mEndDateText.setText(mEndDate.format(formatter));
mEndDateText.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.mdu_text_black));
}
}
private void updateSchedulingSpinners() {
if (mWeekRotations == 1) {
mSpinnerScheduling.setSelection(0);
mSpinnerWeekRotations.setVisibility(View.GONE);
} else {
mSpinnerScheduling.setSelection(1);
mSpinnerWeekRotations.setVisibility(View.VISIBLE);
// e.g. weekRotations of 2 will be position 0 as in the string-array
mSpinnerWeekRotations.setSelection(mWeekRotations - 2);
}
}
@Override
public void onItemChosen(View labelledSpinner, AdapterView<?> adapterView, View itemView,
int position, long id) {
switch (labelledSpinner.getId()) {
case R.id.spinner_scheduling_type:
boolean isFixedScheduling = position == 0;
if (isFixedScheduling) {
mWeekRotations = 1;
} else {
mWeekRotations = (mIsNew || mTimetable.getWeekRotations() == 1) ?
2 : mTimetable.getWeekRotations();
}
updateSchedulingSpinners();
break;
case R.id.spinner_scheduling_detail:
if (mWeekRotations != 1) { // only modify mWeekRotations if not fixed scheduling
mWeekRotations = position + 2; // as '2 weeks' is position 0
}
updateSchedulingSpinners();
break;
}
}
private void refreshList() {
mTerms.clear();
mTerms.addAll(TermUtils.getTerms(this, findTimetableId()));
sortList();
mAdapter.notifyDataSetChanged();
}
private void sortList() {
Collections.sort(mTerms, new Comparator<Term>() {
@Override
public int compare(Term t1, Term t2) {
return t1.getStartDate().compareTo(t2.getStartDate());
}
});
}
private int findTimetableId() {
return mTimetable == null ?
TimetableUtils.getHighestTimetableId(this) + 1 : mTimetable.getId();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_TERM_EDIT) {
if (resultCode == Activity.RESULT_OK) {
refreshList();
}
}
}
@Override
public void onNothingChosen(View labelledSpinner, AdapterView<?> adapterView) {}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item_edit, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mIsNew) {
menu.findItem(R.id.action_delete).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_done:
handleDoneAction();
break;
case R.id.action_delete:
handleDeleteAction();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
handleCloseAction();
super.onBackPressed();
}
private void handleCloseAction() {
if (mIsFirst) {
Snackbar.make(findViewById(R.id.rootView),
R.string.message_first_timetable_required, Snackbar.LENGTH_SHORT);
return;
}
setResult(Activity.RESULT_CANCELED);
finish();
}
private void handleDoneAction() {
String name = TextUtilsKt.title(mEditTextName.getText().toString());
if (mStartDate == null || mEndDate == null) {
Snackbar.make(findViewById(R.id.rootView),
R.string.message_times_required, Snackbar.LENGTH_SHORT).show();
return;
}
if (mStartDate.equals(mEndDate)) {
Snackbar.make(findViewById(R.id.rootView),
R.string.message_start_time_equal_end, Snackbar.LENGTH_SHORT).show();
return;
}
if (mStartDate.isAfter(mEndDate)) {
Snackbar.make(findViewById(R.id.rootView),
R.string.message_start_time_after_end, Snackbar.LENGTH_SHORT).show();
return;
}
if (!mIsNew) {
// delete class times with an invalid week number
if (mWeekRotations < mTimetable.getWeekRotations()) {
TimetableDbHelper helper = TimetableDbHelper.getInstance(this);
Cursor cursor = helper.getReadableDatabase().query(
ClassTimesSchema.TABLE_NAME,
null,
ClassTimesSchema.COL_WEEK_NUMBER + ">?",
new String[]{String.valueOf(mWeekRotations)},
null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ClassTime classTime = new ClassTime(cursor);
ClassUtils.completelyDeleteClassTime(this, classTime.getId());
cursor.moveToNext();
}
cursor.close();
}
}
mTimetable = new Timetable(findTimetableId(), name, mStartDate, mEndDate, mWeekRotations);
if (mIsNew) {
TimetableUtils.addTimetable(this, mTimetable);
} else {
TimetableUtils.replaceTimetable(this, mTimetable.getId(), mTimetable);
}
TimetableApplication application = (TimetableApplication) getApplication();
application.setCurrentTimetable(mTimetable);
application.refreshAlarms(this);
setResult(Activity.RESULT_OK);
finish();
}
private void handleDeleteAction() {
if (TimetableUtils.getTimetables(this).size() == 1) {
// there needs to be at least one timetable for the app to work
Snackbar.make(findViewById(R.id.rootView), R.string.message_first_timetable_required,
Snackbar.LENGTH_SHORT).show();
return;
}
TimetableUtils.completelyDeleteTimetable(this, mTimetable.getId());
int highestId = TimetableUtils.getHighestTimetableId(this);
Timetable newCurrentTimetable = Timetable.create(this, highestId);
TimetableApplication application = (TimetableApplication) getApplication();
application.setCurrentTimetable(newCurrentTimetable);
application.refreshAlarms(this);
setResult(Activity.RESULT_OK);
finish();
}
}
|
package com.ternaryop.photoshelf.fragment;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.PopupMenu;
import com.ternaryop.photoshelf.Constants;
import com.ternaryop.photoshelf.R;
import com.ternaryop.photoshelf.activity.ImageViewerActivity;
import com.ternaryop.photoshelf.activity.TagPhotoBrowserActivity;
import com.ternaryop.photoshelf.adapter.OnPhotoBrowseClickMultiChoice;
import com.ternaryop.photoshelf.adapter.PhotoAdapter;
import com.ternaryop.photoshelf.adapter.PhotoShelfPost;
import com.ternaryop.photoshelf.adapter.Selection;
import com.ternaryop.photoshelf.db.DBHelper;
import com.ternaryop.photoshelf.dialogs.TumblrPostDialog;
import com.ternaryop.tumblr.Tumblr;
import com.ternaryop.tumblr.TumblrAltSize;
import com.ternaryop.tumblr.TumblrPhotoPost;
import com.ternaryop.utils.AbsProgressIndicatorAsyncTask;
import com.ternaryop.utils.DialogUtils;
import com.ternaryop.utils.drawer.counter.CountChangedListener;
import com.ternaryop.utils.drawer.counter.CountProvider;
public abstract class AbsPostsListFragment extends AbsPhotoShelfFragment implements CountProvider, OnPhotoBrowseClickMultiChoice, SearchView.OnQueryTextListener, ActionMode.Callback {
protected static final int POST_ACTION_PUBLISH = 1;
protected static final int POST_ACTION_DELETE = 2;
protected static final int POST_ACTION_EDIT = 3;
public static final int POST_ACTION_ERROR = 0;
public static final int POST_ACTION_OK = -1;
public static final int POST_ACTION_FIRST_USER = 1;
private static final String LOADER_PREFIX_POSTS_THUMB = "postsThumb";
protected PhotoAdapter photoAdapter;
protected int offset;
protected boolean hasMorePosts;
protected boolean isScrolling;
protected long totalPosts;
protected RecyclerView recyclerView;
protected SearchView searchView;
private int[] singleSelectionMenuIds;
private CountChangedListener countChangedListener;
ActionMode actionMode;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(getPostListViewResource(), container, false);
photoAdapter = new PhotoAdapter(getActivity(), LOADER_PREFIX_POSTS_THUMB);
recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(photoAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItem = ((LinearLayoutManager)layoutManager).findFirstVisibleItemPosition();
boolean loadMore = totalItemCount > 0 &&
(firstVisibleItem + visibleItemCount >= totalItemCount);
if (loadMore && hasMorePosts && !isScrolling) {
offset += Tumblr.MAX_POST_PER_REQUEST;
readPhotoPosts();
}
}
});
setHasOptionsMenu(true);
return rootView;
}
protected int getPostListViewResource() {
return R.layout.fragment_photo_list;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean isMenuVisible = !fragmentActivityStatus.isDrawerOpen();
menu.setGroupVisible(R.id.menu_photo_action_bar, isMenuVisible);
setupSearchView(menu);
super.onPrepareOptionsMenu(menu);
}
protected abstract void readPhotoPosts();
protected abstract int getActionModeMenuId();
protected void saveAsDraft(final ActionMode mode, final List<PhotoShelfPost> postList) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
new ActionExecutor(getActivity(), R.string.saving_posts_to_draft_title, mode, postList) {
@Override
protected void executeAction(PhotoShelfPost post) {
Tumblr.getSharedTumblr(getContext()).saveDraft(
getBlogName(),
post.getPostId());
}
}.execute();
break;
}
}
};
String message = getResources().getQuantityString(R.plurals.save_to_draft_confirm,
postList.size(),
postList.size(),
postList.get(0).getFirstTag());
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton(android.R.string.yes, dialogClickListener)
.setNegativeButton(android.R.string.no, dialogClickListener)
.show();
}
private void deletePost(final ActionMode mode, final List<PhotoShelfPost> postList) {
new ActionExecutor(getActivity(), R.string.deleting_posts_title, mode, postList) {
@Override
protected void executeAction(PhotoShelfPost post) {
Tumblr.getSharedTumblr(getContext()).deletePost(getBlogName(),
post.getPostId());
DBHelper.getInstance(getContext()).getPostDAO().deleteById(post.getPostId());
onPostAction(post, POST_ACTION_DELETE, POST_ACTION_OK);
}
}.execute();
}
public void finish(TumblrPhotoPost post) {
Intent data = new Intent();
data.putExtra(Constants.EXTRA_POST, post);
// Activity finished ok, return the data
getActivity().setResult(Activity.RESULT_OK, data);
getActivity().finish();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle(R.string.select_posts);
mode.setSubtitle(getResources().getQuantityString(R.plurals.selected_items, 1, 1));
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(getActionModeMenuId(), menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return handleMenuItem(item, photoAdapter.getSelectedPosts(), mode);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
this.actionMode = null;
photoAdapter.getSelection().clear();
}
public void updateMenuItems() {
int selectCount = photoAdapter.getSelection().getItemCount();
boolean singleSelection = selectCount == 1;
for (int itemId : getSingleSelectionMenuIds()) {
MenuItem item = actionMode.getMenu().findItem(itemId);
if (item != null) {
item.setVisible(singleSelection);
}
}
}
protected int[] getSingleSelectionMenuIds() {
if (singleSelectionMenuIds == null) {
singleSelectionMenuIds = new int[] {R.id.post_schedule, R.id.post_edit, R.id.group_menu_image_dimension, R.id.show_post};
}
return singleSelectionMenuIds;
}
public void browseImageBySize(final PhotoShelfPost post) {
final ArrayAdapter<TumblrAltSize> arrayAdapter = new ArrayAdapter<>(
getActivity(),
android.R.layout.select_dialog_item,
post.getFirstPhotoAltSize());
// Show the cancel button without setting a listener
// because it isn't necessary
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.menu_header_show_image, post.getFirstTag()))
.setNegativeButton(android.R.string.cancel, null);
builder.setAdapter(arrayAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String url = arrayAdapter.getItem(which).getUrl();
ImageViewerActivity.startImageViewer(getActivity(), url, post);
}
});
builder.show();
}
public void showPost(final PhotoShelfPost post) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(post.getPostUrl()));
startActivity(i);
}
private void showConfirmDialog(final int postAction, final ActionMode mode, final List<PhotoShelfPost> postsList) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
switch (postAction) {
case POST_ACTION_PUBLISH:
publishPost(mode, postsList);
break;
case POST_ACTION_DELETE:
deletePost(mode, postsList);
break;
}
break;
}
}
};
String message = null;
switch (postAction) {
case POST_ACTION_PUBLISH:
message = getResources().getQuantityString(R.plurals.publish_post_confirm,
postsList.size(),
postsList.size(),
postsList.get(0).getFirstTag());
break;
case POST_ACTION_DELETE:
message = getResources().getQuantityString(R.plurals.delete_post_confirm,
postsList.size(),
postsList.size(),
postsList.get(0).getFirstTag());
break;
}
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton(android.R.string.yes, dialogClickListener)
.setNegativeButton(android.R.string.no, dialogClickListener)
.show();
}
private void publishPost(ActionMode mode, final List<PhotoShelfPost> postList) {
new ActionExecutor(getActivity(), R.string.publishing_posts_title, mode, postList) {
@Override
protected void executeAction(PhotoShelfPost post) {
Tumblr.getSharedTumblr(getContext()).publishPost(getBlogName(),
post.getPostId());
onPostAction(post, POST_ACTION_PUBLISH, POST_ACTION_OK);
}
}.execute();
}
protected void refreshUI() {
if (searchView != null && searchView.isIconified()) {
if (hasMorePosts) {
getSupportActionBar().setSubtitle(getString(R.string.post_count_1_of_x,
photoAdapter.getItemCount(),
totalPosts));
} else {
getSupportActionBar().setSubtitle(getResources().getQuantityString(
R.plurals.posts_count,
photoAdapter.getItemCount(),
photoAdapter.getItemCount()));
if (countChangedListener != null) {
countChangedListener.onChangeCount(this, photoAdapter.getItemCount());
}
}
}
// use post to resolve the error
// Cannot call this method in a scroll callback. Scroll callbacks mightbe run during a measure & layout pass where you cannot change theRecyclerView data.
// Any method call that might change the structureof the RecyclerView or the adapter contents should be postponed tothe next frame.
recyclerView.post(new Runnable() {
public void run() {
photoAdapter.notifyDataSetChanged();
}
});
}
abstract class ActionExecutor extends AbsProgressIndicatorAsyncTask<Void, PhotoShelfPost, List<PhotoShelfPost>> {
private final ActionMode mode;
private final List<PhotoShelfPost> postList;
Exception error; // contains the last error found
public ActionExecutor(Context context, int resId, ActionMode mode, List<PhotoShelfPost> postList) {
super(context, context.getString(resId));
this.mode = mode;
this.postList = postList;
}
@Override
protected void onProgressUpdate(PhotoShelfPost... values) {
PhotoShelfPost post = values[0];
photoAdapter.remove(post);
setProgressMessage(post.getTagsAsString());
}
@Override
protected void onPostExecute(List<PhotoShelfPost> notDeletedPosts) {
super.onPostExecute(null);
refreshUI();
// all posts have been deleted so call actionMode.finish()
if (notDeletedPosts.size() == 0) {
if (mode != null) {
mode.finish();
}
return;
}
// leave posts not processed checked
photoAdapter.getSelection().clear();
for (PhotoShelfPost post : notDeletedPosts) {
int position = photoAdapter.getPosition(post);
photoAdapter.getSelection().setSelected(position, true);
}
DialogUtils.showSimpleMessageDialog(getContext(),
R.string.generic_error,
getContext().getResources().getQuantityString(
R.plurals.general_posts_error,
notDeletedPosts.size(),
error.getMessage(),
notDeletedPosts.size()));
}
@Override
protected List<PhotoShelfPost> doInBackground(Void... voidParams) {
List<PhotoShelfPost> notDeletedPosts = new ArrayList<>();
for (final PhotoShelfPost post : postList) {
try {
executeAction(post);
this.publishProgress(post);
} catch (Exception e) {
error = e;
notDeletedPosts.add(post);
}
}
return notDeletedPosts;
}
protected abstract void executeAction(PhotoShelfPost post);
}
@Override
public void onTagClick(int position) {
final PhotoShelfPost post = photoAdapter.getItem(position);
TagPhotoBrowserActivity.startPhotoBrowserActivity(getActivity(), getBlogName(), post.getFirstTag(), false);
}
@Override
public void onThumbnailImageClick(int position) {
final PhotoShelfPost post = photoAdapter.getItem(position);
ImageViewerActivity.startImageViewer(getActivity(), post.getFirstPhotoAltSize().get(0).getUrl(), post);
}
@Override
public void onOverflowClick(View view, int position) {
final PhotoShelfPost post = photoAdapter.getItem(position);
PopupMenu popupMenu = new PopupMenu(getActivity(), view);
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(getActionModeMenuId(), popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
ArrayList<PhotoShelfPost> postList = new ArrayList<>();
postList.add(post);
return handleMenuItem(item, postList, null);
}
});
popupMenu.show();
}
@Override
public void onItemClick(int position) {
if (actionMode == null) {
handleClickedThumbnail(position);
} else {
updateSelection(position);
}
}
@Override
public void onItemLongClick(int position) {
if (actionMode == null) {
actionMode = getActivity().startActionMode(this);
}
photoAdapter.getSelection().toggle(position);
}
private void handleClickedThumbnail(int position) {
final PhotoShelfPost post = photoAdapter.getItem(position);
if (getActivity().getCallingActivity() == null) {
onThumbnailImageClick(position);
} else {
finish(post);
}
}
private void updateSelection(int position) {
Selection selection = photoAdapter.getSelection();
selection.toggle(position);
if (selection.getItemCount() == 0) {
actionMode.finish();
} else {
updateMenuItems();
int selectionCount = selection.getItemCount();
actionMode.setSubtitle(getResources().getQuantityString(
R.plurals.selected_items,
selectionCount,
selectionCount));
}
}
protected boolean handleMenuItem(MenuItem item, List<PhotoShelfPost> postList, ActionMode mode) {
switch (item.getItemId()) {
case R.id.post_publish:
showConfirmDialog(POST_ACTION_PUBLISH, mode, postList);
return true;
case R.id.group_menu_image_dimension:
browseImageBySize(postList.get(0));
return true;
case R.id.post_delete:
showConfirmDialog(POST_ACTION_DELETE, mode, postList);
return true;
case R.id.post_edit:
showEditDialog(postList.get(0), mode);
return true;
case R.id.post_save_draft:
saveAsDraft(mode, postList);
return true;
case R.id.show_post:
showPost(postList.get(0));
return true;
default:
return false;
}
}
@Override
public void setCountChangedListener(CountChangedListener countChangedListener) {
this.countChangedListener = countChangedListener;
}
@Override
public CountChangedListener getCountChangedListener() {
return countChangedListener;
}
protected SearchView setupSearchView(Menu menu) {
MenuItem searchMenu = menu.findItem(R.id.action_search);
if (searchMenu != null) {
searchView = (SearchView)MenuItemCompat.getActionView(searchMenu);
searchView.setQueryHint(getString(R.string.enter_tag_hint));
searchView.setOnQueryTextListener(this);
}
return searchView;
}
@Override
public boolean onQueryTextChange(String newText) {
photoAdapter.getFilter().filter(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
protected void resetAndReloadPhotoPosts() {
offset = 0;
totalPosts = 0;
hasMorePosts = true;
photoAdapter.clear();
readPhotoPosts();
}
/**
* Overridden (if necessary) by subclasses to be informed about post action result,
* the default implementation does nothing
* @param post the post processed by action
* @param postAction the action executed
* @param resultCode on success POST_ACTION_OK
*/
public void onPostAction(@SuppressWarnings("UnusedParameters") TumblrPhotoPost post, @SuppressWarnings("UnusedParameters") int postAction, @SuppressWarnings({"SameParameterValue", "UnusedParameters"}) int resultCode) {
}
@Override
public void onEditDone(TumblrPostDialog dialog, TumblrPhotoPost post) {
super.onEditDone(dialog, post);
onPostAction(post, POST_ACTION_EDIT, POST_ACTION_OK);
}
}
|
package com.tnovoselec.beautifulweather.ui.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tnovoselec.beautifulweather.R;
import com.tnovoselec.beautifulweather.model.DaySectionData;
import com.tnovoselec.beautifulweather.ui.util.VisualUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
import static com.tnovoselec.beautifulweather.ui.util.FormatUtils.formatDescription;
public class DaySectionView extends LinearLayout {
@Bind(R.id.day_section_name)
TextView name;
@Bind(R.id.day_section_description)
TextView description;
@Bind(R.id.day_section_temperature)
TextView temperature;
@Bind(R.id.day_section_wind)
TextView wind;
@Bind(R.id.day_section_humidity)
TextView humidity;
@Bind(R.id.day_section_icon)
WeatherIconView icon;
@Bind(R.id.animation_data_container)
View animationDataContainer;
private DaySectionData daySectionData;
private Interpolator accelerateInterpolator = new AccelerateInterpolator();
private Interpolator decelerateInterpolator = new DecelerateInterpolator();
public DaySectionView(Context context) {
this(context, null);
}
public DaySectionView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DaySectionView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
ButterKnife.bind(this);
}
private void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.item_section, this);
final int screenHeight = VisualUtils.getScreenHeight();
this.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) getLayoutParams();
params.height = screenHeight / 2;
setLayoutParams(params);
return true;
}
});
}
public void setDaySectionData(DaySectionData daySectionData) {
this.daySectionData = daySectionData;
fillViews();
}
private void fillViews() {
this.name.setText(daySectionData.getDaySection().getDescription());
this.description.setText(formatDescription(daySectionData.getDescription()));
this.temperature.setText(Math.round(daySectionData.getTemperature()) + "° C");
this.wind.setText("Wind: " + Math.round(daySectionData.getWind()));
this.humidity.setText("Humidity: " + Math.round(daySectionData.getHumidity()));
this.setBackgroundColor(getResources().getColor(daySectionData.getBackground()));
this.icon.setIconViewEnum(daySectionData.getIconViewEnum());
}
public void hideIcon() {
icon.setVisibility(INVISIBLE);
}
public void showIcon() {
icon.setVisibility(VISIBLE);
}
public void animateDataContainer() {
animationDataContainer.setTranslationY(this.getHeight());
animationDataContainer.setVisibility(VISIBLE);
animationDataContainer.animate().translationY(0).setDuration(300).setInterpolator(decelerateInterpolator);
}
public void hideDataContainer() {
animationDataContainer.setVisibility(GONE);
}
public void animateIcon(boolean up, final boolean isCurrent) {
final float from = isCurrent ? 0 : up ? icon.getHeight() : -icon.getHeight();
float to = isCurrent ? up ? -icon.getHeight() : icon.getHeight() : 0;
Interpolator interpolator = isCurrent ? accelerateInterpolator : decelerateInterpolator;
Log.e("animateIcon", "from: " + from + " to: " + to + " up: " + up + " isCurrent: " + isCurrent);
icon.setTranslationY(from);
icon.setVisibility(VISIBLE);
icon.animate()
.translationY(to)
.setDuration(250)
.setInterpolator(interpolator)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (isCurrent) {
hideIcon();
}
}
});
}
}
|
package es.npatarino.android.gotchallenge.chat.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import es.npatarino.android.gotchallenge.GotChallengeApplication;
import es.npatarino.android.gotchallenge.R;
import es.npatarino.android.gotchallenge.base.di.modules.ActivityModule;
import es.npatarino.android.gotchallenge.base.ui.CircleTransform;
import es.npatarino.android.gotchallenge.base.ui.Utilities;
import es.npatarino.android.gotchallenge.base.ui.messages.ErrorManager;
import es.npatarino.android.gotchallenge.chat.conversation.domain.model.Conversation;
import es.npatarino.android.gotchallenge.chat.conversation.presenter.ConversationPresenter;
import es.npatarino.android.gotchallenge.chat.conversation.view.ConversationView;
import es.npatarino.android.gotchallenge.chat.di.DaggerChatComponent;
import es.npatarino.android.gotchallenge.common.view.activities.DetailActivity;
import javax.inject.Inject;
public class ChatActivity extends AppCompatActivity implements ConversationView {
public static final String CONVER_ID_KEY = "_conver_id_key";
private View rootView;
private Toolbar toolbar;
@Inject
ErrorManager errorManager;
@Inject
ConversationPresenter presenter;
@Inject
Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
initDagger();
rootView = findViewById(R.id.container);
final String id = getIntent().getStringExtra(DetailActivity.HOUSE_ID);
presenter.setView(this);
presenter.init(new Conversation(id, null, null, null, null));
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
private void initDagger() {
GotChallengeApplication app = (GotChallengeApplication) getApplication();
DaggerChatComponent.builder()
.appComponent(app.getAppComponent())
.activityModule(new ActivityModule(this))
.build().inject(this);
}
@Override
public void show(Conversation conversation) {
getAvatarDrawable(conversation.getImageUrl());
toolbar.setTitle(conversation.getName());
toolbar.setSubtitle(conversation.getParticipants()
.toString()
.replace("[", "")
.replace("]", "")); //Todo could be house words
}
private void getAvatarDrawable(String imageUrl) {
int px = Utilities.dp(context, 40);
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
setAvatar(new BitmapDrawable(getResources(), bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
setAvatar(errorDrawable);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
setAvatar(placeHolderDrawable);
}
};
Picasso.with(getApplicationContext())
.load(imageUrl)
.transform(new CircleTransform())
.resize(px, px)
.centerCrop()
.into(target);
toolbar.setTag(target);
}
@Override
public void initChat() {
attachFragment(new ChatFragment());
}
@Override
public void initUi() {
initToolbar();
}
@Override
public void error() {
errorManager.showError(rootView, "ERROR :(");
}
private void attachFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_layout, fragment, "chat_activity_fragment")
.commitAllowingStateLoss();
}
public void setAvatar(Drawable avatar) {
if (avatar == null) return;
toolbar.setLogo(avatar);
toolbar.setTitleMarginStart(Utilities.dp(context, 25));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) onBackPressed();
return true;
}
}
|
package hm.orz.chaos114.android.slideviewer.ui;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import hm.orz.chaos114.android.slideviewer.R;
import hm.orz.chaos114.android.slideviewer.databinding.ActivityWebViewBinding;
import hm.orz.chaos114.android.slideviewer.util.UrlHelper;
public class WebViewActivity extends AppCompatActivity {
private static final String TAG = WebViewActivity.class.getSimpleName();
public static final String EXTRA_URL = "extra_url";
private ActivityWebViewBinding binding;
static void start(Context context, @NonNull String url) {
Intent intent = new Intent(context, WebViewActivity.class);
intent.putExtra(EXTRA_URL, url);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_web_view);
init();
if (savedInstanceState == null) {
final String url = getIntent().getStringExtra(EXTRA_URL);
binding.webView.loadUrl(url);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void init() {
setSupportActionBar(binding.toolbar);
ActionBar bar = getSupportActionBar();
if (bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayShowTitleEnabled(false);
bar.setHomeButtonEnabled(true);
}
binding.webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "url: " + url);
Uri uri = Uri.parse(url);
if (UrlHelper.isSpeakerDeckUrl(uri)
&& UrlHelper.canOpen(uri)) {
SlideActivity.start(WebViewActivity.this, url);
finish();
return true;
}
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
binding.toolbar.setTitle(view.getTitle());
}
});
binding.webView.getSettings().setJavaScriptEnabled(true);
binding.webView.getSettings().setBuiltInZoomControls(true);
binding.webView.getSettings().setLoadWithOverviewMode(true);
binding.webView.getSettings().setUseWideViewPort(true);
}
}
|
package org.ieatta.activity.fragments;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tableview.RecycleViewManager;
import com.tableview.adapter.NSIndexPath;
import com.tableview.adapter.RecyclerOnItemClickListener;
import com.tableview.utils.CollectionUtil;
import org.ieatta.IEAApp;
import org.ieatta.R;
import org.ieatta.activity.DetailPageLoadStrategy;
import org.ieatta.activity.JsonPageLoadStrategy;
import org.ieatta.activity.Page;
import org.ieatta.activity.PageActivity;
import org.ieatta.activity.PageBackStackItem;
import org.ieatta.activity.PageLoadStrategy;
import org.ieatta.activity.PageViewModel;
import org.ieatta.activity.editing.EditHandler;
import org.ieatta.activity.fragments.search.SearchBarHideHandler;
import org.ieatta.activity.leadimages.ArticleHeaderView;
import org.ieatta.activity.leadimages.LeadImagesHandler;
import org.ieatta.cells.IEARestaurantEventsCell;
import org.ieatta.cells.header.IEARestaurantDetailHeaderCell;
import org.ieatta.cells.model.IEARestaurantDetailHeader;
import org.ieatta.cells.model.SectionTitleCellModel;
import org.ieatta.database.models.DBEvent;
import org.ieatta.provide.IEAEditKey;
import org.ieatta.tasks.RestaurantDetailTask;
import org.ieatta.views.ObservableWebView;
import org.wikipedia.analytics.PageScrollFunnel;
import org.wikipedia.analytics.SavedPagesFunnel;
import org.wikipedia.analytics.TabFunnel;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.views.SwipeRefreshLayoutWithScroll;
import org.wikipedia.views.WikiDrawerLayout;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import bolts.Continuation;
import bolts.Task;
import static butterknife.ButterKnife.findById;
public class RestaurantDetailFragment extends DetailFragment {
public static final RecyclerOnItemClickListener itemClickListener = new RecyclerOnItemClickListener() {
@Override
public void onItemClick(View view, NSIndexPath indexPath, Object model, int position, boolean isLongClick) {
}
};
enum RestaurantDetailSection {
section_leadimage,
section_events,
section_photogallery,
section_reviews,
}
private RecycleViewManager manager;
private RestaurantDetailTask task = new RestaurantDetailTask();
public static final int TOC_ACTION_SHOW = 0;
public static final int TOC_ACTION_HIDE = 1;
public static final int TOC_ACTION_TOGGLE = 2;
private boolean pageSaved;
private boolean pageRefreshed;
private boolean savedPageCheckComplete;
private boolean errorState = false;
private static final int TOC_BUTTON_HIDE_DELAY = 2000;
private static final int REFRESH_SPINNER_ADDITIONAL_OFFSET = (int) (16 * IEAApp.getInstance().getScreenDensity());
@NonNull
private TabFunnel tabFunnel = new TabFunnel();
@Nullable
private PageScrollFunnel pageScrollFunnel;
/**
* Whether to save the full page content as soon as it's loaded.
* Used in the following cases:
* - Stored page content is corrupted
* - Page bookmarks are imported from the old app.
* In the above cases, loading of the saved page will "fail", and will
* automatically bounce to the online version of the page. Once the online page
* loads successfully, the content will be saved, thereby reconstructing the
* stored version of the page.
*/
private boolean saveOnComplete = false;
private ArticleHeaderView articleHeaderView;
private LeadImagesHandler leadImagesHandler;
private SearchBarHideHandler searchBarHideHandler;
private ObservableWebView webView;
private SwipeRefreshLayoutWithScroll refreshView;
private WikiDrawerLayout tocDrawer;
private EditHandler editHandler;
private SavedPagesFunnel savedPagesFunnel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
webView = (ObservableWebView) rootView.findViewById(R.id.recycleView);
initWebViewListeners();
tocDrawer = (WikiDrawerLayout) rootView.findViewById(R.id.page_toc_drawer);
tocDrawer.setDragEdgeWidth(getResources().getDimensionPixelSize(R.dimen.drawer_drag_margin));
refreshView = (SwipeRefreshLayoutWithScroll) rootView
.findViewById(R.id.page_refresh_container);
int swipeOffset = DimenUtil.getContentTopOffsetPx(getActivity()) + REFRESH_SPINNER_ADDITIONAL_OFFSET;
refreshView.setProgressViewOffset(false, -swipeOffset, swipeOffset);
// if we want to give it a custom color:
//refreshView.setProgressBackgroundColor(R.color.swipe_refresh_circle);
refreshView.setScrollableChild(webView);
// TODO: initialize View references in onCreateView().
articleHeaderView = (ArticleHeaderView) rootView.findViewById(R.id.page_header_view);
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
manager = new RecycleViewManager(this.getActivity().getApplicationContext());
}
private void setupUI() {
this.manager.setRegisterCellClass(IEARestaurantEventsCell.getType(), RestaurantDetailSection.section_events.ordinal());
this.manager.appendSectionTitleCell(new SectionTitleCellModel(IEAEditKey.Section_Title, R.string.Events_Recorded), RestaurantDetailSection.section_events.ordinal());
}
@Override
public void loadPage() {
manager.startManagingWithDelegate(webView);
manager.setOnItemClickListener(itemClickListener);
this.setupUI();
// String uuid = "1CE562A4-A978-4B75-9B7B-2F3CF9F42A04"; // The Flying Falafel
String uuid = "33ED9F31-F6A5-43A4-8D11-8E511CA0BD39"; // The Spice Jar
task.executeTask(uuid).onSuccess(new Continuation<Void, Object>() {
@Override
public Object then(Task<Void> task) throws Exception {
RestaurantDetailFragment.this.reloadPage();
return null;
}
}).continueWith(new Continuation<Object, Object>() {
@Override
public Object then(Task<Object> task) throws Exception {
return null;
}
});
}
private void reloadPage() {
this.manager.setSectionItems(CollectionUtil.createList(new IEARestaurantDetailHeader(this.task.restaurant)), RestaurantDetailSection.section_leadimage.ordinal());
this.manager.setSectionItems(task.events, RestaurantDetailSection.section_events.ordinal());
model.setPage(task.getPage());
searchBarHideHandler = getPageActivity().getSearchBarHideHandler();
searchBarHideHandler.setScrollView(webView);
leadImagesHandler = new LeadImagesHandler(this, webView, articleHeaderView);
pageLoadStrategy.setUp(this, refreshView, webView, searchBarHideHandler,
leadImagesHandler, new LinkedList<PageBackStackItem>());
pageLoadStrategy.onLeadSectionLoaded(0);
}
@Override
public void onPause() {
super.onPause();
closePageScrollFunnel();
}
@Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("");
initPageScrollFunnel();
}
private void initPageScrollFunnel() {
// if (model.getPage() != null) {
// pageScrollFunnel = new PageScrollFunnel(app, model.getPage().getPageProperties().getPageId());
}
private void closePageScrollFunnel() {
// if (pageScrollFunnel != null && webView.getContentHeight() > 0) {
// pageScrollFunnel.setViewportHeight(webView.getHeight());
// pageScrollFunnel.setPageHeight(webView.getContentHeight());
// pageScrollFunnel.logDone();
pageScrollFunnel = null;
}
// TODO: don't assume host is PageActivity. Use Fragment callbacks pattern.
private PageActivity getPageActivity() {
return (PageActivity) getActivity();
}
private void initWebViewListeners() {
webView.addOnUpOrCancelMotionEventListener(new ObservableWebView.OnUpOrCancelMotionEventListener() {
@Override
public void onUpOrCancelMotionEvent() {
// queue the button to be hidden when the user stops scrolling.
// hideToCButton(true);
// update our session, since it's possible for the user to remain on the page for
// a long time, and we wouldn't want the session to time out.
// app.getSessionFunnel().touchSession();
}
});
webView.setOnFastScrollListener(new ObservableWebView.OnFastScrollListener() {
@Override
public void onFastScroll() {
// show the ToC button...
// showToCButton();
// and immediately queue it to be hidden after a short delay, but only if we're
// not at the top of the page.
if (webView.getScrollY() > 0) {
// hideToCButton(true);
}
}
});
webView.addOnScrollChangeListener(new ObservableWebView.OnScrollChangeListener() {
@Override
public void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll) {
if (scrollY <= 0) {
// always show the ToC button when we're at the top of the page.
// showToCButton();
}
if (pageScrollFunnel != null) {
pageScrollFunnel.onPageScrolled(oldScrollY, scrollY, isHumanScroll);
}
}
});
}
}
|
package nl.mpi.arbil.ui.favourites;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeContainer;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.favourites.ArbilFavourites;
import nl.mpi.arbil.favourites.FavouritesExporter;
import nl.mpi.arbil.favourites.FavouritesExporterImpl;
import nl.mpi.arbil.favourites.FavouritesImporterImpl;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.ApplicationVersion;
import nl.mpi.arbil.util.TreeHelper;
import nl.mpi.flap.plugin.PluginDialogHandler;
/**
* GUI that shows all favourites provided by a {@link TreeHelper}, allows the user to select a subset of these and perform an export on it
* or to re-import favourites from disk.
*
* @author Twan Goosen <twan.goosen@mpi.nl>
*/
public class FavouritesImportExportGUI implements ArbilDataNodeContainer {
private static final ResourceBundle widgets = ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets");
// UI components
private final JPanel panel;
private final DefaultListModel nodesListModel;
private final ListSelectionModel nodesListSelectionModel;
// Controller actions
private final Action importAction;
private final Action exportAction;
private final Action refreshAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
update();
}
};
// Arbil services
private final TreeHelper treeHelper;
private ArbilDataNode[] allFavourites = {};
public FavouritesImportExportGUI(PluginDialogHandler dialog, SessionStorage sessionStorage, TreeHelper treeHelper, ApplicationVersion appVersion) {
this(new ImportAction(dialog, new FavouritesImporterImpl(ArbilFavourites.getSingleInstance())),
new ExportAction(dialog, new FavouritesExporterImpl(sessionStorage, appVersion)), treeHelper);
}
/**
*
* @param importAction action that will be bound to the import button
* @param exportAction action that will be bound to the export button
* @param treeHelper tree helper from which the collection of all favourites will be retrieved
*/
public FavouritesImportExportGUI(Action importAction, Action exportAction, TreeHelper treeHelper) {
this.importAction = importAction;
this.exportAction = exportAction;
this.treeHelper = treeHelper;
this.nodesListModel = new DefaultListModel();
this.nodesListSelectionModel = new DefaultListSelectionModel();
this.panel = createPanel();
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
update();
}
});
update();
}
private JPanel createPanel() {
final JPanel importExportPanel = new JPanel();
importExportPanel.setLayout(new BoxLayout(importExportPanel, BoxLayout.PAGE_AXIS));
importExportPanel.setPreferredSize(new Dimension(600, 400));
final JPanel importPanel = createImportPanel();
importPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), widgets.getString("IMPORT FAVOURITES")));
importExportPanel.add(importPanel);
final JPanel exportPanel = createExportPanel();
exportPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), widgets.getString("EXPORT FAVOURITES")));
importExportPanel.add(exportPanel);
return importExportPanel;
}
private JPanel createImportPanel() {
final JPanel importPanel = new JPanel(new BorderLayout());
final JTextArea importInstructions = new JTextArea(MessageFormat.format(
widgets.getString("FAVOURITES_PRESS THE IMPORT BUTTON")
+ widgets.getString("FAVOURITES_THE DIRECTORY SHOULD CONTAIN A FILE CALLED"),
FavouritesExporter.FAVOURITES_LIST_FILE));
importInstructions.setEditable(false);
importInstructions.setLineWrap(true);
importInstructions.setWrapStyleWord(true);
importInstructions.setOpaque(false);
importPanel.add(importInstructions, BorderLayout.NORTH);
final JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.LINE_AXIS));
buttonsPanel.add(Box.createHorizontalGlue()); // horizontal glue to align to right
importPanel.add(buttonsPanel, BorderLayout.SOUTH);
final JButton importButton = new ImportButton(importAction);
importButton.setText(widgets.getString("IMPORT FROM DISK"));
buttonsPanel.add(importButton);
return importPanel;
}
private JPanel createExportPanel() {
final JPanel exportPanel = new JPanel(new BorderLayout());
final JTextArea exportInstructions = new JTextArea(widgets.getString("FAVOURITES_SELECT ONE OR MORE FAVOURITES THAT YOU WISH TO EXPORT"));
exportInstructions.setEditable(false);
exportInstructions.setLineWrap(true);
exportInstructions.setWrapStyleWord(true);
exportInstructions.setOpaque(false);
exportPanel.add(exportInstructions, BorderLayout.NORTH);
final JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.LINE_AXIS));
buttonsPanel.add(Box.createHorizontalGlue()); // horizontal glue to align to right
exportPanel.add(buttonsPanel, BorderLayout.SOUTH);
final JButton refreshButton = new JButton(refreshAction);
refreshButton.setText(widgets.getString("REFRESH"));
buttonsPanel.add(refreshButton);
final JButton exportButton = new ExportButton(exportAction);
exportButton.setText(widgets.getString("EXPORT SELECTION"));
buttonsPanel.add(exportButton);
JList nodesList = new JList(nodesListModel);
nodesList.setSelectionModel(nodesListSelectionModel);
nodesList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setIcon(((ArbilDataNode) value).getIcon());
return this;
}
});
nodesList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
exportButton.setEnabled(!nodesListSelectionModel.isSelectionEmpty());
}
});
nodesList.setBorder(BorderFactory.createLineBorder(Color.BLACK));
exportPanel.add(nodesList, BorderLayout.CENTER);
return exportPanel;
}
public final void update() {
getAllFavourites();
updateFavouritesList();
// Select all nodes. TODO: keep previous selection
nodesListSelectionModel.addSelectionInterval(0, nodesListModel.getSize());
}
private void getAllFavourites() {
// Unregister this as container from current set
for (ArbilDataNode node : allFavourites) {
node.removeContainer(this);
}
// Renew set
allFavourites = treeHelper.getFavouriteNodes();
// Register this as container
for (ArbilDataNode node : allFavourites) {
node.registerContainer(this);
}
}
private void updateFavouritesList() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
nodesListModel.removeAllElements();
for (ArbilDataNode node : allFavourites) {
nodesListModel.addElement(node);
}
}
});
}
public JPanel getPanel() {
return panel;
}
/*
* ArbilDataNodeContainer methods
*/
public void dataNodeRemoved(ArbilNode an) {
update();
}
public void dataNodeIconCleared(final ArbilNode an) {
// Something has changed, update
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int index = nodesListModel.indexOf(an);
if (index >= 0) {
nodesListModel.set(index, an);
}
}
});
}
public void dataNodeChildAdded(ArbilNode an, ArbilNode an1) {
update();
}
public boolean isFullyLoadedNodeRequired() {
return false;
}
public void showDialog(JFrame owner) {
JDialog dialog = new JDialog(owner);
dialog.add(getPanel());
dialog.setSize(600, 400);
dialog.setVisible(true);
}
/**
* Extension of button that implements ExportUI so that the ExportAction controller class can get the actual favourites selection
* through the button object.
*/
private class ExportButton extends JButton implements ExportUI {
public ExportButton(Action a) {
super(a);
}
public List<ArbilDataNode> getSelectedFavourites() {
// Get list model contents as data nodes array
final List<ArbilDataNode> selectedNodes = new ArrayList<ArbilDataNode>(nodesListModel.getSize());
for (int i = 0; i < nodesListModel.getSize(); i++) {
if (nodesListSelectionModel.isSelectedIndex(i)) {
selectedNodes.add((ArbilDataNode) nodesListModel.elementAt(i));
}
}
return selectedNodes;
}
}
/**
* Extension of button that implements ImportUI so that the ImportAction controller class can trigger a refresh after an import.
*/
private class ImportButton extends JButton implements ImportUI {
public ImportButton(Action a) {
super(a);
}
public void refresh() {
FavouritesImportExportGUI.this.update();
}
}
}
|
package search;
import lejos.util.Delay;
import lejos.nxt.TouchSensor;
import lejos.robotics.navigation.DifferentialPilot;
public class RoomMappingA {
// The drive is global
private DifferentialPilot marvin;
private TouchSensor touch1;
private TouchSensor touch2;
// Initiating the class
public RoomMappingA(DifferentialPilot drive, TouchSensor a, TouchSensor b) {
marvin = drive;
touch1 = a;
touch2 = b;
}
public int mapping(int a) {
// Set the wheels so the left is whatever a is and the right is 30
marvin.steer(100);
// Start a counter i
// Keep going till either i reaches a certain value or the bumper is pressed
int i = 0;
while (!touch1.isPressed() && !touch2.isPressed() && i < (a+1)*30) {
Delay.msDelay(40);
i++;
}
// Recursion so it runs 30 times
if (a < 30) {
return mapping(a+1);
}
else {
return a;
}
}
public int bouncing(int a) {
// Drive forward until it hits something
marvin.setTravelSpeed(10);
marvin.steer(0);
waitForBumperPress();
// Back up
marvin.backward();
Delay.msDelay(200);
// Turn
marvin.rotateLeft();
Delay.msDelay(700);
// Thing for recursion
if (a > 1) {
return bouncing(a-=1);
}
else {
return 0;
}
}
public void waitForBumperPress() {
while (!touch1.isPressed() && !touch2.isPressed()) {
Delay.msDelay(20);
}
}
}
|
package at.medevit.elexis.inbox.ui.part;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import at.medevit.elexis.inbox.model.IInboxElementService;
import at.medevit.elexis.inbox.model.IInboxElementService.State;
import at.medevit.elexis.inbox.model.IInboxUpdateListener;
import at.medevit.elexis.inbox.model.InboxElement;
import at.medevit.elexis.inbox.ui.InboxServiceComponent;
import at.medevit.elexis.inbox.ui.part.action.InboxFilterAction;
import at.medevit.elexis.inbox.ui.part.model.PatientInboxElements;
import at.medevit.elexis.inbox.ui.part.provider.IInboxElementUiProvider;
import at.medevit.elexis.inbox.ui.part.provider.InboxElementContentProvider;
import at.medevit.elexis.inbox.ui.part.provider.InboxElementLabelProvider;
import at.medevit.elexis.inbox.ui.part.provider.InboxElementUiExtension;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.events.ElexisEvent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.ui.events.ElexisUiEventListenerImpl;
import ch.elexis.data.Mandant;
import ch.elexis.data.Patient;
public class InboxView extends ViewPart {
private Text filterText;
private CheckboxTreeViewer viewer;
private boolean reloadPending;
private InboxElementViewerFilter filter = new InboxElementViewerFilter();
private ElexisUiEventListenerImpl mandantChanged = new ElexisUiEventListenerImpl(Mandant.class,
ElexisEvent.EVENT_MANDATOR_CHANGED) {
@Override
public void runInUi(ElexisEvent ev){
reload();
}
};
@Override
public void createPartControl(Composite parent){
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
Composite filterComposite = new Composite(composite, SWT.NONE);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
filterComposite.setLayoutData(data);
filterComposite.setLayout(new GridLayout(2, false));
filterText = new Text(filterComposite, SWT.SEARCH);
filterText.setMessage("Filter");
data = new GridData(GridData.FILL_HORIZONTAL);
filterText.setLayoutData(data);
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e){
if (filterText.getText().length() > 1) {
filter.setSearchText(filterText.getText());
viewer.refresh();
} else {
filter.setSearchText("");
viewer.refresh();
}
}
});
ToolBarManager menuManager = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL | SWT.WRAP);
menuManager.createControl(filterComposite);
viewer =
new CheckboxTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
viewer.getControl().setLayoutData(gd);
ViewerFilter[] filters = new ViewerFilter[1];
filters[0] = filter;
viewer.setFilters(filters);
viewer.setContentProvider(new InboxElementContentProvider());
viewer.setLabelProvider(new InboxElementLabelProvider());
viewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event){
if (event.getElement() instanceof PatientInboxElements) {
PatientInboxElements patientInbox = (PatientInboxElements) event.getElement();
for (InboxElement inboxElement : patientInbox.getElements()) {
State newState = toggleInboxElementState(inboxElement);
if (newState == State.NEW) {
viewer.setChecked(inboxElement, false);
} else {
viewer.setChecked(inboxElement, true);
}
}
} else if (event.getElement() instanceof InboxElement) {
InboxElement inboxElement = (InboxElement) event.getElement();
toggleInboxElementState(inboxElement);
}
reload();
}
});
viewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event){
StructuredSelection selection = (StructuredSelection) viewer.getSelection();
if (!selection.isEmpty()) {
Object selectedObj = selection.getFirstElement();
if (selectedObj instanceof InboxElement) {
InboxElementUiExtension extension = new InboxElementUiExtension();
extension.fireDoubleClicked((InboxElement) selectedObj);
}
}
}
});
addFilterActions(menuManager);
InboxServiceComponent.getService().addUpdateListener(new IInboxUpdateListener() {
public void update(InboxElement element){
Display.getDefault().asyncExec(new Runnable() {
public void run(){
reload();
}
});
}
});
reload();
ElexisEventDispatcher.getInstance().addListeners(mandantChanged);
}
private void addFilterActions(ToolBarManager menuManager){
InboxElementUiExtension extension = new InboxElementUiExtension();
List<IInboxElementUiProvider> providers = extension.getProviders();
for (IInboxElementUiProvider iInboxElementUiProvider : providers) {
ViewerFilter extensionFilter = iInboxElementUiProvider.getFilter();
if (extensionFilter != null) {
InboxFilterAction action =
new InboxFilterAction(viewer, extensionFilter,
iInboxElementUiProvider.getFilterImage());
menuManager.add(action);
}
}
menuManager.update(true);
}
private State toggleInboxElementState(InboxElement inboxElement){
if (inboxElement.getState() == State.NEW) {
inboxElement.setState(State.SEEN);
return State.SEEN;
} else if (inboxElement.getState() == State.SEEN) {
inboxElement.setState(State.NEW);
return State.NEW;
}
return State.NEW;
}
@Override
public void setFocus(){
filterText.setFocus();
if (reloadPending) {
reload();
}
}
@SuppressWarnings("deprecation")
private ArrayList<PatientInboxElements> getOpenInboxElements(){
HashMap<Patient, PatientInboxElements> map = new HashMap<Patient, PatientInboxElements>();
List<InboxElement> openElements =
InboxServiceComponent.getService().getInboxElements(CoreHub.actMandant, null,
IInboxElementService.State.NEW);
// create PatientInboxElements for all InboxElements
for (InboxElement inboxElement : openElements) {
Patient patient = inboxElement.getPatient();
PatientInboxElements patientInbox = map.get(patient);
if (patientInbox == null) {
patientInbox = new PatientInboxElements(patient);
map.put(patient, patientInbox);
}
patientInbox.addElement(inboxElement);
}
return new ArrayList<PatientInboxElements>(map.values());
}
private class InboxElementViewerFilter extends ViewerFilter {
protected String searchString;
protected LabelProvider labelProvider = new InboxElementLabelProvider();
public void setSearchText(String s){
// Search must be a substring of the existing value
this.searchString = ".*" + s + ".*";
}
private boolean isSelect(Object leaf){
String label = labelProvider.getText(leaf);
if (label != null && label.matches(searchString)) {
return true;
}
return false;
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element){
if (searchString == null || searchString.length() == 0) {
return true;
}
StructuredViewer sviewer = (StructuredViewer) viewer;
ITreeContentProvider provider = (ITreeContentProvider) sviewer.getContentProvider();
Object[] children = provider.getChildren(element);
if (children != null && children.length > 0) {
for (Object child : children) {
if (select(viewer, element, child)) {
return true;
}
}
}
return isSelect(element);
}
}
public void reload(){
if (!viewer.getControl().isVisible()) {
reloadPending = true;
return;
}
reloadPending = false;
viewer.setInput(getOpenInboxElements());
viewer.expandAll();
}
@Override
public void dispose(){
ElexisEventDispatcher.getInstance().removeListeners(mandantChanged);
super.dispose();
}
}
|
package org.intermine.bio.postprocess;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.util.DynamicUtil;
import org.flymine.model.genomic.Assembly;
import org.flymine.model.genomic.Chromosome;
import org.flymine.model.genomic.ChromosomeBand;
import org.flymine.model.genomic.Exon;
import org.flymine.model.genomic.Gene;
import org.flymine.model.genomic.LocatedSequenceFeature;
import org.flymine.model.genomic.Location;
import org.flymine.model.genomic.Sequence;
import org.flymine.model.genomic.Supercontig;
import org.flymine.model.genomic.Transcript;
import org.flymine.model.genomic.CDS;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.SymbolList;
/**
* Transfer sequences from the Assembly objects to the other objects that are located on the
* Assemblys and to the objects that the Assemblys are located on (eg. Chromosomes).
*
* @author Kim Rutherford
*/
public class TransferSequences
{
protected ObjectStoreWriter osw;
private static final Logger LOG = Logger.getLogger(TransferSequences.class);
/**
* Create a new TransferSequences object from the given ObjectStoreWriter
* @param osw writer on genomic ObjectStore
*/
public TransferSequences (ObjectStoreWriter osw) {
this.osw = osw;
}
/**
* Copy the Assembly sequences to the appropriate place in the chromosome sequences and store a
* Sequence object for each Chromosome. Uses the ObjectStoreWriter that was passed to the
* constructor
* @throws Exception if there are problems with the transfer
*/
public void transferToChromosome()
throws Exception {
ObjectStore os = osw.getObjectStore();
Results results =
PostProcessUtil.findLocationAndObjects(os, Chromosome.class, Assembly.class, false);
// could try reducing further if still OutOfMemeory problems
results.setBatchSize(20);
results.setNoPrefetch();
Map chromosomeTempFiles = new HashMap();
Iterator resIter = results.iterator();
Chromosome currentChr = null;
RandomAccessFile currentChrBases = null;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
Chromosome chr = (Chromosome) os.getObjectById(chrId);
Assembly assembly = (Assembly) rr.get(1);
Location assemblyOnChrLocation = (Location) rr.get(2);
if (assembly instanceof Supercontig) {
continue;
}
if (currentChr == null || !chr.equals(currentChr)) {
if (currentChr != null) {
currentChrBases.close();
LOG.info("finished writing temp file for Chromosome: "
+ currentChr.getIdentifier());
}
File tempFile = getTempFile(chr);
currentChrBases = getChromosomeTempSeqFile(chr, tempFile);
chromosomeTempFiles.put(chr, tempFile);
currentChr = chr;
}
copySeqArray(currentChrBases, assembly.getSequence().getResidues(),
assemblyOnChrLocation.getStart().intValue(),
assemblyOnChrLocation.getStrand());
}
if (currentChrBases == null) {
LOG.error("in transferToChromosome(): no Assembly sequences found");
} else {
currentChrBases.close();
storeTempSequences(chromosomeTempFiles);
LOG.info("finished writing temp file for Chromosome: " + currentChr.getIdentifier());
}
}
private File getTempFile(Chromosome chr) throws IOException {
String prefix = "transfer_sequences_temp_" + chr.getId() + "_" + chr.getIdentifier();
return File.createTempFile(prefix, null, new File ("build"));
}
/**
* Initialise the given File by setting it's length to the length of the Chromosome and
* initialising it with "." characters.
* @throws IOException
*/
private RandomAccessFile getChromosomeTempSeqFile(Chromosome chr, File tempFile)
throws IOException {
RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
byte[] bytes;
try {
bytes = ("......................................................................."
+ ".............................................").getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("unexpected exception", e);
}
int writeCount = chr.getLength().intValue() / bytes.length + 1;
// fill with '.' so we can see the parts of the Chromosome sequence that haven't
// been set
for (int i = 0; i < writeCount; i++) {
raf.write(bytes);
}
raf.setLength(chr.getLength().longValue());
return raf;
}
private void storeTempSequences(Map chromosomeTempFiles)
throws ObjectStoreException, IOException {
Iterator chromosomeTempFilesIter = chromosomeTempFiles.keySet().iterator();
while (chromosomeTempFilesIter.hasNext()) {
Chromosome chr = (Chromosome) chromosomeTempFilesIter.next();
File file = (File) chromosomeTempFiles.get(chr);
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String sequenceString = bufferedReader.readLine();
osw.beginTransaction();
LOG.info("Storing sequence for chromosome: " + chr.getIdentifier());
storeNewSequence(chr, sequenceString);
osw.commitTransaction();
}
}
private void storeNewSequence(LocatedSequenceFeature feature, String sequenceString)
throws ObjectStoreException {
Sequence sequence =
(Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
sequence.setResidues(sequenceString);
sequence.setLength(sequenceString.length());
osw.store(sequence);
feature.proxySequence(new ProxyReference(osw.getObjectStore(),
sequence.getId(), Sequence.class));
feature.setLength(new Integer(sequenceString.length()));
osw.store(feature);
}
/**
* Use the Location relations to copy the sequence from the Chromosomes to every
* LocatedSequenceFeature that is located on a Chromosome and which doesn't already have a
* sequence (ie. don't copy to Assembly). Uses the ObjectStoreWriter that was passed to the
* constructor
* @throws Exception if there are problems with the transfer
*/
public void transferToLocatedSequenceFeatures()
throws Exception {
ObjectStore os = osw.getObjectStore();
osw.beginTransaction();
Results results =
PostProcessUtil.findLocationAndObjects(os, Chromosome.class,
LocatedSequenceFeature.class, true);
results.setBatchSize(500);
Iterator resIter = results.iterator();
long start = System.currentTimeMillis();
int i = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer chrId = (Integer) rr.get(0);
LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1);
Location locationOnChr = (Location) rr.get(2);
if (feature instanceof Assembly) {
LOG.warn("in transferToLocatedSequenceFeatures() ignoring: "
+ feature);
continue;
}
if (feature instanceof ChromosomeBand) {
LOG.warn("in transferToLocatedSequenceFeatures() ignoring: "
+ feature);
continue;
}
if (feature instanceof Transcript) {
LOG.warn("in transferToLocatedSequenceFeatures() ignoring: "
+ feature);
continue;
}
if (feature instanceof CDS) {
LOG.warn("in transferToLocatedSequenceFeatures() ignoring: "
+ feature);
continue;
}
if (feature.getSequence() != null) {
LOG.warn("in transferToLocatedSequenceFeatures() ignooring: "
+ feature + " - already has a sequence");
}
if (feature instanceof Gene) {
Gene gene = (Gene) feature;
if (gene.getLength() != null && gene.getLength().intValue() > 2000000) {
LOG.error("gene too long in transferToLocatedSequenceFeatures() ignoring: "
+ gene);
continue;
}
}
Chromosome chr = (Chromosome) os.getObjectById(chrId);
LOG.info("Chromosome id: " + chrId);
Sequence chromosomeSequence = chr.getSequence();
if (chromosomeSequence == null) {
LOG.warn("no sequence found for: " + chr.getIdentifier() + " id: " + chr.getId());
continue;
}
String featureSeq = getSubSequence(chromosomeSequence, locationOnChr);
if (featureSeq == null) {
// probably the locationOnChr is out of range
continue;
}
Sequence sequence =
(Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
sequence.setResidues(featureSeq);
sequence.setLength(featureSeq.length());
osw.store(sequence);
feature.proxySequence(new ProxyReference(osw.getObjectStore(),
sequence.getId(), Sequence.class));
osw.store(feature);
i++;
if (i % 1000 == 0) {
long now = System.currentTimeMillis();
LOG.info("Set sequences for " + i + " features"
+ " (avg = " + ((60000L * i) / (now - start)) + " per minute)");
}
}
osw.commitTransaction();
}
private String getSubSequence(Sequence chromosomeSequence, Location locationOnChr)
throws IllegalSymbolException, IllegalAlphabetException {
int charsToCopy =
locationOnChr.getEnd().intValue() - locationOnChr.getStart().intValue() + 1;
String chromosomeSequenceString = chromosomeSequence.getResidues();
if (charsToCopy > chromosomeSequenceString.length()) {
LOG.error("LocatedSequenceFeature too long, ignoring - Location: "
+ locationOnChr.getId() + " LSF id: " + locationOnChr.getObject());
return null;
}
int startPos = locationOnChr.getStart().intValue() - 1;
int endPos = startPos + charsToCopy;
if (startPos < 0 || endPos < 0) {
LOG.error("LocatedSequenceFeature has negative coordinate, ignoring Location: "
+ locationOnChr.getId() + " LSF id: " + locationOnChr.getObject());
return null;
// Do we really want an exception? Not much we can do about it. (rns 22/10/06)
// TODO XXX FIXME - uncomment this
// throw new RuntimeException("in TransferSequences.getSubSequence(): locationOnChr "
// + locationOnChr
// + "\n startPos: " + startPos + " endPos " + endPos
// + "\n chromosomeSequence.substr(0,1000) " +
// chromosomeSequenceString.substring(0,1000)
// + "\n location.getObject() "
// + locationOnChr.getObject().toString()
// + " location.getSubject() " +
// locationOnChr.getSubject().toString() + " "
// + "\n location.getSubject().getId() " +
// locationOnChr.getSubject().getId() +
// "\n location.getObject().getId() ");
}
if (endPos > chromosomeSequenceString.length()) {
LOG.error("LocatedSequenceFeature has end coordinate greater than chromsome length."
+ "ignoring Location: "
+ locationOnChr.getId() + " LSF id: " + locationOnChr.getObject());
return null;
}
String subSeqString;
if (startPos < endPos) {
subSeqString = new String(chromosomeSequenceString.substring(startPos, endPos));
} else {
subSeqString = new String(chromosomeSequenceString.substring(endPos, startPos));
}
if (locationOnChr.getStrand().equals("-1")) {
SymbolList symbolList = DNATools.createDNA(subSeqString);
symbolList = DNATools.reverseComplement(symbolList);
subSeqString = symbolList.seqString();
}
return subSeqString;
}
private void copySeqArray(RandomAccessFile raf, String sourceSequence,
int start, String strand)
throws IllegalSymbolException, IllegalAlphabetException, IOException {
byte[] byteArray = new byte[sourceSequence.length()];
if (strand.equals("-1")) {
SymbolList symbolList = DNATools.createDNA(sourceSequence);
symbolList = DNATools.reverseComplement(symbolList);
byteArray = symbolList.seqString().getBytes("US-ASCII");
} else {
byteArray = sourceSequence.toLowerCase().getBytes("US-ASCII");
}
raf.seek(start - 1);
raf.write(byteArray);
}
/**
* For each Transcript, join and transfer the sequences from the child Exons to a new Sequence
* object for the Transcript. Uses the ObjectStoreWriter that was passed to the constructor
* @throws Exception if there are problems with the transfer
*/
public void transferToTranscripts()
throws Exception {
osw.beginTransaction();
ObjectStore os = osw.getObjectStore();
Query q = new Query();
q.setDistinct(false);
QueryClass qcTranscript = new QueryClass(Transcript.class);
q.addFrom(qcTranscript);
q.addToSelect(qcTranscript);
q.addToOrderBy(qcTranscript);
QueryClass qcExon = new QueryClass(Exon.class);
q.addFrom(qcExon);
q.addToSelect(qcExon);
QueryClass qcExonSequence = new QueryClass(Sequence.class);
q.addFrom(qcExonSequence);
q.addToSelect(qcExonSequence);
QueryClass qcExonLocation = new QueryClass(Location.class);
q.addFrom(qcExonLocation);
q.addToSelect(qcExonLocation);
QueryField qfExonStart = new QueryField(qcExonLocation, "start");
q.addToOrderBy(qfExonStart);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference exonsRef =
new QueryCollectionReference(qcTranscript, "exons");
ContainsConstraint cc1 =
new ContainsConstraint(exonsRef, ConstraintOp.CONTAINS, qcExon);
cs.addConstraint(cc1);
QueryObjectReference locRef =
new QueryObjectReference(qcExon, "chromosomeLocation");
ContainsConstraint cc2 =
new ContainsConstraint(locRef, ConstraintOp.CONTAINS, qcExonLocation);
cs.addConstraint(cc2);
QueryObjectReference sequenceRef = new QueryObjectReference(qcExon, "sequence");
ContainsConstraint cc3 =
new ContainsConstraint(sequenceRef, ConstraintOp.CONTAINS, qcExonSequence);
cs.addConstraint(cc3);
q.setConstraint(cs);
((ObjectStoreInterMineImpl) os).precompute(q, PostProcessOperationsTask
.PRECOMPUTE_CATEGORY);
Results res = os.execute(q);
res.setBatchSize(200);
Iterator resIter = res.iterator();
Transcript currentTranscript = null;
StringBuffer currentTranscriptBases = new StringBuffer();
long start = System.currentTimeMillis();
int i = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Transcript transcript = (Transcript) rr.get(0);
if (currentTranscript == null || !transcript.equals(currentTranscript)) {
if (currentTranscript != null) {
storeNewSequence(currentTranscript,
currentTranscriptBases.toString());
i++;
}
currentTranscriptBases = new StringBuffer();
currentTranscript = transcript;
}
Sequence exonSequence = (Sequence) rr.get(2);
Location location = (Location) rr.get(3);
if (location.getStrand() != null && location.getStrand().equals("-1")) {
currentTranscriptBases.insert(0, exonSequence.getResidues());
} else {
currentTranscriptBases.append(exonSequence.getResidues());
}
if (i % 100 == 0) {
long now = System.currentTimeMillis();
LOG.info("Set sequences for " + i + " Transcripts"
+ " (avg = " + ((60000L * i) / (now - start)) + " per minute)");
}
}
if (currentTranscript == null) {
LOG.error("in transferToTranscripts(): no Transcripts found");
} else {
storeNewSequence(currentTranscript, currentTranscriptBases.toString());
}
osw.commitTransaction();
}
}
|
package no.tornado.brap.client;
import no.tornado.brap.common.InputStreamArgumentPlaceholder;
import no.tornado.brap.common.InvocationRequest;
import no.tornado.brap.common.InvocationResponse;
import no.tornado.brap.common.ModificationList;
import no.tornado.brap.exception.RemotingException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import no.tornado.brap.common.InputStreamArgumentPlaceholder;
import no.tornado.brap.common.InvocationRequest;
import no.tornado.brap.common.InvocationResponse;
import no.tornado.brap.common.ModificationList;
import no.tornado.brap.exception.RemotingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
/**
* The MethodInvocationHandler is used by the <code>ServiceProxyFactory</code> to provide an implementation
* of the supplied interface. It intercepts all method-calls and sends them
* to the server and returns the invocation result.
* <p/>
* The recommended way to retrieve a service proxy is to call one of the static methods
* in the <code>ServiceProxyFactory</code>.
*/
public class MethodInvocationHandler implements InvocationHandler, Serializable {
private String serviceURI;
private Serializable credentials;
private static final String REGEXP_PROPERTY_DELIMITER = "\\.";
private TransportProvider transportProvider;
private static TransportProvider defaultTransportProvider = new HttpURLConnectionTransportProvider();
/**
* Default constructor to use if you override <code>getServiceURI</code>
* and <code>getCredentials</code> to provide "dynamic" service-uri and credentials.
*
* You can also provide a custom TransportProvider.
*/
public MethodInvocationHandler() {
}
/**
* Creates the service proxy on the given URI with the given credentials and TransportProvider
* <p/>
* Credentials can be changed using the ServiceProxyFactory#setCredentials method.
* ServiceURI can be changed using the ServiceProxyFactory#setServiceURI method.
*
* @param serviceURI The URI to the remote service
* @param credentials An object used to authenticate/authorize the request
*/
public MethodInvocationHandler(String serviceURI, Serializable credentials, TransportProvider transportProvider) {
this.serviceURI = serviceURI;
this.credentials = credentials;
this.transportProvider = transportProvider;
}
/**
* Creates the service proxy on the given URI with the given credentials, using the default TransportProvider.
* <p/>
* Credentials can be changed using the ServiceProxyFactory#setCredentials method.
* ServiceURI can be changed using the ServiceProxyFactory#setServiceURI method.
*
* @param serviceURI The URI to the remote service
* @param credentials An object used to authenticate/authorize the request
*/
public MethodInvocationHandler(String serviceURI, Serializable credentials) {
this(serviceURI, credentials, null);
}
/**
* Creates the service proxy on the given URI.
* <p/>
* ServiceURI can be changed using the ServiceProxyFactory#setServiceURI method.
*
* @param serviceURI The URI to the remote service
*/
public MethodInvocationHandler(String serviceURI) {
this(serviceURI, null);
}
/**
* Intercepts the method call towards the proxy and sends the call over HTTP.
* <p/>
* If an exception is thrown on the server-side, it will be re-thrown to the caller.
* <p/>
* The return value of the method invocation is returned.
*
* @return Object the result of the method invocation
*/
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
InvocationResponse response;
TransportProvider currentProvider = transportProvider != null ? transportProvider : defaultTransportProvider;
TransportSession session = currentProvider.createSession(this);
try {
InvocationRequest request = new InvocationRequest(method, args, getCredentials());
// Look for the first argument that is an input stream, remove the argument data from the argument array
// and prepare to transfer the data via the connection outputstream after serializing the invocation request.
InputStream streamArgument = null;
if (args != null) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null && InputStream.class.isAssignableFrom(args[i].getClass())) {
streamArgument = (InputStream) args[i];
args[i] = new InputStreamArgumentPlaceholder();
break;
}
}
}
InputStream inputStream = session.sendInvocationRequest(method, request, streamArgument);
if (!method.getReturnType().equals(Object.class) && method.getReturnType().isAssignableFrom(InputStream.class))
return inputStream;
ObjectInputStream in = new ObjectInputStream(inputStream);
response = (InvocationResponse) in.readObject();
applyModifications(args, response.getModifications());
} catch (IOException e) {
throw new RemotingException(e);
} finally {
currentProvider.endSession(session, this);
}
if (response.getException() != null) {
throw appendLocalStack(response.getException());
}
return response.getResult();
}
private Throwable appendLocalStack(Throwable exception)
{
Throwable stack = new Throwable();
StackTraceElement[] thisStack = stack.getStackTrace();
StackTraceElement[] thatStack = exception.getStackTrace();
StackTraceElement[] st = new StackTraceElement[thisStack.length + 1 + thatStack.length];
System.arraycopy(thatStack, 0, st, 0, thatStack.length);
st[thatStack.length] = new StackTraceElement("REMOTE", "DELIMITER", "brap_http", 1);
System.arraycopy(thisStack, 0, st, thatStack.length + 1, thisStack.length);
exception.setStackTrace(st);
return exception;
}
private void applyModifications(Object[] args, ModificationList[] modifications) {
if (modifications != null) {
for (int i = 0; i < modifications.length; i++) {
ModificationList mods = modifications[i];
if (mods != null) {
for (Map.Entry<String, Object> entry : mods.getModifiedProperties().entrySet()) {
try {
setModifiedValue(entry.getKey(), entry.getValue(), args[i]);
} catch (Exception ignored) {
}
}
}
}
}
}
private void setModifiedValue(String key, Object value, Object object) throws NoSuchFieldException, IllegalAccessException {
String[] propertyGraph = key.split(REGEXP_PROPERTY_DELIMITER);
int i = 0;
for (; i < propertyGraph.length - 1; i++)
object = getValue(object, object.getClass().getDeclaredField(propertyGraph[i]));
setValue(object, object.getClass().getDeclaredField(propertyGraph[i]), value);
}
private void setValue(Object object, Field field, Object value) throws IllegalAccessException {
boolean accessible = field.isAccessible();
if (!accessible) field.setAccessible(true);
field.set(object, value);
if (!accessible) field.setAccessible(false);
}
private Object getValue(Object object, Field field) throws IllegalAccessException {
boolean accessible = field.isAccessible();
if (!accessible) field.setAccessible(true);
Object value = field.get(object);
if (!accessible) field.setAccessible(false);
return value;
}
/**
* Getter for the ServiceURI. Override if you need a more dynamic serviceURI
* than just setting the value.
*
* @return The serviceURI for subsequent method invocations.
* @see no.tornado.brap.client.ServiceProxyFactory#setServiceURI(Object, String)
*/
public String getServiceURI() {
return serviceURI;
}
public void setServiceURI(String serviceURI) {
this.serviceURI = serviceURI;
}
/**
* Getter for the credentials. Override if you need more dynamic credentials
* than just setting the values.
*
* @return The credentials to use for subsequent method invocations.
* @see no.tornado.brap.client.ServiceProxyFactory#setCredentials(Object, java.io.Serializable)
*/
public Serializable getCredentials() {
return credentials;
}
public void setCredentials(Serializable credentials) {
this.credentials = credentials;
}
public TransportProvider getTransportProvider() {
return transportProvider;
}
public void setTransportProvider(TransportProvider transportProvider) {
this.transportProvider = transportProvider;
}
public static TransportProvider getDefaultTransportProvider() {
return defaultTransportProvider;
}
public static void setDefaultTransportProvider(TransportProvider defaultTransportProvider) {
MethodInvocationHandler.defaultTransportProvider = defaultTransportProvider;
}
}
|
import java.util.*;
public class Process{
// Used as default pool (equal temperament 12 semi-tones):
private List<String> et12Pool = Arrays.asList("Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G");
private int et12Length = 12;
// !!! Throw error when note is not found in pool
// stepCount: returns the distance between two notes using an input pool of type List
public int stepCount(Note note1, Note note2, List<String> pool){
int result = pool.indexOf(note2.getName()) - pool.indexOf(note1.getName());
if (result > 0){
return result;
}
else{
return result + et12Length;
}
}
// stepCount: overloaded: no input pool, uses default pool
public int stepCount(Note note1, Note note2){
return stepCount(note1, note2, et12Pool);
}
// scalize: returns a Scale object derived from the formula applied to the pool with note as root
// !!! implement overloads for pool inputs, both array and list
public Scale scalize(Note note, int[] formula, List<String> pool){
List<Note> noteList = new ArrayList<Note>();
int currentIndex = pool.indexOf(note.getName());
for (int e : formula){
noteList.add(new Note(pool.get(currentIndex)));
currentIndex = (currentIndex + e) % pool.size();
}
return new Scale(noteList);
}
// scalize: overloaded: array as input pull
public Scale scalize(Note note, int[] formula, String[] pool){
return scalize(note, formula, new ArrayList<String>(Arrays.asList(pool)));
}
// scalize: overloaded: no input pool, uses default pool as input
public Scale scalize(Note note, int[] formula){
return scalize(note, formula, et12Pool);
}
}
|
package com.edmodo.rangebar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class VerticalRangeBar extends View {
private static final String TAG = VerticalRangeBar.class.getName();
// Default values for variables
private static final int DEFAULT_TICK_COUNT = 3;
private static final float DEFAULT_TICK_HEIGHT_DP = 24;
private static final float DEFAULT_BAR_WEIGHT_PX = 2;
private static final int DEFAULT_BAR_COLOR = Color.LTGRAY;
private static final float DEFAULT_CONNECTING_LINE_WEIGHT_PX = 4;
private static final int DEFAULT_THUMB_IMAGE_NORMAL = R.drawable.seek_thumb_normal;
private static final int DEFAULT_THUMB_IMAGE_PRESSED = R.drawable.seek_thumb_pressed;
private static final int DEFAULT_BAR_ORIENTATION = 0;
// O FOR HORIZONTAL, 1 FOR VERTICAL
// Corresponds to android.R.color.holo_blue_light.
private static final int DEFAULT_CONNECTING_LINE_COLOR = 0xff33b5e5;
// Indicator value tells Thumb.java whether it should draw the circle or not
private static final float DEFAULT_THUMB_RADIUS_DP = -1;
private static final int DEFAULT_THUMB_COLOR_NORMAL = -1;
private static final int DEFAULT_THUMB_COLOR_PRESSED = -1;
private static final int DEFAULT_TICK_MARK_STEP = 1;
// Instance variables for all of the customizable attributes
private int mTickCount = DEFAULT_TICK_COUNT;
private float mTickHeightDP = DEFAULT_TICK_HEIGHT_DP;
private float mBarWeight = DEFAULT_BAR_WEIGHT_PX;
private int mBarColor = DEFAULT_BAR_COLOR;
private float mConnectingLineWeight = DEFAULT_CONNECTING_LINE_WEIGHT_PX;
private int mConnectingLineColor = DEFAULT_CONNECTING_LINE_COLOR;
private int mThumbImageNormal = DEFAULT_THUMB_IMAGE_NORMAL;
private int mThumbImagePressed = DEFAULT_THUMB_IMAGE_PRESSED;
private float mThumbRadiusDP = DEFAULT_THUMB_RADIUS_DP;
private int mThumbColorNormal = DEFAULT_THUMB_COLOR_NORMAL;
private int mThumbColorPressed = DEFAULT_THUMB_COLOR_PRESSED;
private int mTickMarkStep = 1;
private VerticalRangeBar.OnRangeBarChangeListener mListener;
private int mLeftIndex = 0;
private int mRightIndex = mTickCount - 1;
private int mDefaultWidth = 200;
private int mDefaultHeight = 400;
private Thumb mLeftThumb;
private Thumb mRightThumb;
private VerticalBar mVerticalBar;
private VerticalConnectingLine mConnectingLine;
// setTickCount only resets indices before a thumb has been pressed or a
// setThumbIndices() is called, to correspond with intended usage
private boolean mFirstSetTickCount = true;
//// constructors //////
public VerticalRangeBar(Context context) {
super(context);
}
public VerticalRangeBar(Context context, AttributeSet attrs) {
super(context, attrs);
rangeBarInit(context, attrs);
}
public VerticalRangeBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
rangeBarInit(context, attrs);
}
// View Methods ////////////////////////////////////////////////////////////
@Override
public Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putInt("TICK_COUNT", mTickCount);
bundle.putFloat("TICK_HEIGHT_DP", mTickHeightDP);
bundle.putInt("TICK_MARK_STEP", mTickMarkStep);
bundle.putFloat("BAR_WEIGHT", mBarWeight);
bundle.putInt("BAR_COLOR", mBarColor);
bundle.putFloat("CONNECTING_LINE_WEIGHT", mConnectingLineWeight);
bundle.putInt("CONNECTING_LINE_COLOR", mConnectingLineColor);
bundle.putInt("THUMB_IMAGE_NORMAL", mThumbImageNormal);
bundle.putInt("THUMB_IMAGE_PRESSED", mThumbImagePressed);
bundle.putFloat("THUMB_RADIUS_DP", mThumbRadiusDP);
bundle.putInt("THUMB_COLOR_NORMAL", mThumbColorNormal);
bundle.putInt("THUMB_COLOR_PRESSED", mThumbColorPressed);
bundle.putInt("LEFT_INDEX", mLeftIndex);
bundle.putInt("RIGHT_INDEX", mRightIndex);
bundle.putBoolean("FIRST_SET_TICK_COUNT", mFirstSetTickCount);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
mTickCount = bundle.getInt("TICK_COUNT");
mTickHeightDP = bundle.getFloat("TICK_HEIGHT_DP");
mBarWeight = bundle.getFloat("BAR_WEIGHT");
mBarColor = bundle.getInt("BAR_COLOR");
mConnectingLineWeight = bundle.getFloat("CONNECTING_LINE_WEIGHT");
mConnectingLineColor = bundle.getInt("CONNECTING_LINE_COLOR");
mThumbImageNormal = bundle.getInt("THUMB_IMAGE_NORMAL");
mThumbImagePressed = bundle.getInt("THUMB_IMAGE_PRESSED");
mThumbRadiusDP = bundle.getFloat("THUMB_RADIUS_DP");
mThumbColorNormal = bundle.getInt("THUMB_COLOR_NORMAL");
mThumbColorPressed = bundle.getInt("THUMB_COLOR_PRESSED");
bundle.getInt("TICK_MARK_STEP");
mLeftIndex = bundle.getInt("LEFT_INDEX");
mRightIndex = bundle.getInt("RIGHT_INDEX");
mFirstSetTickCount = bundle.getBoolean("FIRST_SET_TICK_COUNT");
mTickMarkStep = bundle.getInt("TICK_MARK_STEP");
setThumbIndices(mLeftIndex, mRightIndex);
super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
} else {
super.onRestoreInstanceState(state);
}
}
/**
* Does all the functions of the constructor for RangeBar. Called by both
* RangeBar constructors in lieu of copying the code for each constructor.
*
* @param context Context from the constructor.
* @param attrs AttributeSet from the constructor.
* @return none
*/
private void rangeBarInit(Context context, AttributeSet attrs)
{
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RangeBar, 0, 0);
try {
// Sets the values of the user-defined attributes based on the XML
// attributes.
final Integer tickCount = ta.getInteger(R.styleable.RangeBar_tickCount, DEFAULT_TICK_COUNT);
if (isValidTickCount(tickCount)) {
// Similar functions performed above in setTickCount; make sure
// you know how they interact
mTickCount = tickCount;
mLeftIndex = 0;
mRightIndex = mTickCount - 1;
} else {
Log.e(TAG, "tickCount less than 2; invalid tickCount. XML input ignored.");
}
mTickHeightDP = ta.getDimension(R.styleable.RangeBar_tickHeight, DEFAULT_TICK_HEIGHT_DP);
mBarWeight = ta.getDimension(R.styleable.RangeBar_barWeight, DEFAULT_BAR_WEIGHT_PX);
mBarColor = ta.getColor(R.styleable.RangeBar_barColor, DEFAULT_BAR_COLOR);
mConnectingLineWeight = ta.getDimension(R.styleable.RangeBar_connectingLineWeight,
DEFAULT_CONNECTING_LINE_WEIGHT_PX);
mConnectingLineColor = ta.getColor(R.styleable.RangeBar_connectingLineColor,
DEFAULT_CONNECTING_LINE_COLOR);
mThumbRadiusDP = ta.getDimension(R.styleable.RangeBar_thumbRadius, DEFAULT_THUMB_RADIUS_DP);
mThumbImageNormal = ta.getResourceId(R.styleable.RangeBar_thumbImageNormal,
DEFAULT_THUMB_IMAGE_NORMAL);
mThumbImagePressed = ta.getResourceId(R.styleable.RangeBar_thumbImagePressed,
DEFAULT_THUMB_IMAGE_PRESSED);
mThumbColorNormal = ta.getColor(R.styleable.RangeBar_thumbColorNormal, DEFAULT_THUMB_COLOR_NORMAL);
mThumbColorPressed = ta.getColor(R.styleable.RangeBar_thumbColorPressed,
DEFAULT_THUMB_COLOR_PRESSED);
mTickMarkStep = ta.getInteger(R.styleable.RangeBar_tickMarkStep, DEFAULT_TICK_MARK_STEP);
} finally {
ta.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width;
int height;
// Get measureSpec mode and size values.
final int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
final int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
final int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
final int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
//Log.i(RangeBar.class.getName(), "onMeasure: "+ measureWidth + " x " + measureHeight);
// The RangeBar width should be as large as possible.
// height should be max, width should be min
if (measureWidthMode == MeasureSpec.AT_MOST || measureWidthMode == MeasureSpec.EXACTLY) {
width = Math.min(mDefaultWidth, measureWidth);
} else {
width = mDefaultWidth;
}
// The RangeBar height should be as small as possible.
if (measureHeightMode == MeasureSpec.AT_MOST) {
height = Math.max(mDefaultHeight, measureHeight);
} else if (measureHeightMode == MeasureSpec.EXACTLY) {
height = measureHeight;
} else {
height = mDefaultHeight;
}
//Log.i(RangeBar.class.getName(), "Vertical onMeasure calculation: "+ width + " x " + height);
setMeasuredDimension(width, height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.i(RangeBar.class.getName(), "onSizeChanged");
final Context ctx = getContext();
// This is the initial point at which we know the size of the View.
// Create the two thumb objects.
final float xPos = mDefaultWidth /4f;
mLeftThumb = new Thumb(ctx,
xPos,
mThumbColorNormal,
mThumbColorPressed,
mThumbRadiusDP,
mThumbImageNormal,
mThumbImagePressed);
mRightThumb = new Thumb(ctx,
xPos,
mThumbColorNormal,
mThumbColorPressed,
mThumbRadiusDP,
mThumbImageNormal,
mThumbImagePressed);
// Create the underlying bar.
final float marginBottom = mRightThumb.getHalfWidth();
final float barLength = h - 2 * marginBottom;
mVerticalBar = new VerticalBar(ctx, marginBottom, xPos, barLength, mTickCount, mTickHeightDP, mBarWeight, mBarColor, mTickMarkStep);
// Initialize thumbs to the desired indices
mLeftThumb.setY(marginBottom + barLength);
mRightThumb.setY(marginBottom + barLength);
// Create the line connecting the two thumbs.
mConnectingLine = new VerticalConnectingLine(ctx, marginBottom, mConnectingLineWeight, mConnectingLineColor);
}
public boolean isFirstTouchEvent() {
return firstTouchEvent;
}
public void setFirstTouchEvent(boolean firstTouchEvent) {
this.firstTouchEvent = firstTouchEvent;
}
private boolean firstTouchEvent;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mVerticalBar.draw(canvas);
if (isFirstTouchEvent()){
mConnectingLine.draw(canvas, mLeftThumb, mRightThumb);
//mLeftThumb.draw(canvas);
mRightThumb.draw(canvas);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// If this View is not enabled, don't allow for touch interactions.
if (!isEnabled()) {
return false;
}
setFirstTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onActionDown(event.getX(), event.getY());
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
this.getParent().requestDisallowInterceptTouchEvent(false);
onActionUp(event.getX(), event.getY());
return true;
case MotionEvent.ACTION_MOVE:
onActionMove(event.getY());
this.getParent().requestDisallowInterceptTouchEvent(true);
return true;
default:
return false;
}
}
/**
* Handles a {@link MotionEvent#ACTION_UP} or
* {@link MotionEvent#ACTION_CANCEL} event.
*
* @param x the x-coordinate of the up action
* @param y the y-coordinate of the up action
*/
private void onActionUp(float x, float y) {
if (mRightThumb.isPressed()) {
releaseThumb(mRightThumb);
} else {
if (y < mVerticalBar.getTopY()) {
// Do nothing.
mRightThumb.setY(mVerticalBar.getTopY());
releaseThumb(mRightThumb);
}else if ( y > mVerticalBar.getBottomY()){
mRightThumb.setY(mVerticalBar.getBottomY());
releaseThumb(mRightThumb);
}else {
mRightThumb.setY(y);
releaseThumb(mRightThumb);
}
// Get the updated nearest tick marks for each thumb.
//final int newLeftIndex = mVerticalBar.getNearestTickIndex(mLeftThumb);
final int newRightIndex = mVerticalBar.getNearestTickIndex(mRightThumb);
// If either of the indices have changed, update and call the listener.
if (newRightIndex != mRightIndex) {
//mLeftIndex = newLeftIndex;
mRightIndex = newRightIndex;
if (mListener != null) {
mListener.onIndexChangeListener(this, mLeftIndex, mRightIndex);
}
}
}
}
/**
* Handles a {@link MotionEvent#ACTION_DOWN} event.
*
* @param x the x-coordinate of the down action
* @param y the y-coordinate of the down action
*/
private void onActionDown(float x, float y) {
if (!mLeftThumb.isPressed() && mLeftThumb.isInTargetZone(x, y)) {
pressThumb(mLeftThumb);
} else if (!mLeftThumb.isPressed() && mRightThumb.isInTargetZone(x,y)) {
pressThumb(mRightThumb);
}
}
/**
* Handles a {@link MotionEvent#ACTION_MOVE} event.
*
* @param y the y-coordinate of the move event
*/
private void onActionMove(float y) {
// Move the pressed thumb to the new x-position.
// if (mLeftThumb.isPressed()) {
// moveThumb(mLeftThumb, x);
// } else if (mRightThumb.isPressed()) {
// moveThumb(mRightThumb, x);
if (mRightThumb.isPressed()) {
moveThumb(mRightThumb, y);
}
// If the thumbs have switched order, fix the references.
// if (mLeftThumb.getY() > mRightThumb.getY()) {
// final Thumb temp = mLeftThumb;
// mLeftThumb = mRightThumb;
// mRightThumb = temp;
// Get the updated nearest tick marks for each thumb.
//final int newLeftIndex = mVerticalBar.getNearestTickIndex(mLeftThumb);
final int newRightIndex = mVerticalBar.getNearestTickIndex(mRightThumb);
// If either of the indices have changed, update and call the listener.
if (newRightIndex != mRightIndex) {
//mLeftIndex = newLeftIndex;
mRightIndex = newRightIndex;
if (mListener != null) {
mListener.onIndexChangeListener(this, mLeftIndex, mRightIndex);
}
}
}
/**
* Set the thumb to be in the pressed state and calls invalidate() to redraw
* the canvas to reflect the updated state.
*
* @param thumb the thumb to press
*/
private void pressThumb(Thumb thumb) {
if (mFirstSetTickCount == true) {
mFirstSetTickCount = false;
}
thumb.press();
invalidate();
}
/**
* Set the thumb to be in the normal/un-pressed state and calls invalidate()
* to redraw the canvas to reflect the updated state.
*
* @param thumb the thumb to release
*/
private void releaseThumb(Thumb thumb) {
final float nearestTickX = mVerticalBar.getNearestTickCoordinate(thumb);
thumb.setY(nearestTickX);
thumb.release();
invalidate();
}
/**
* Moves the thumb to the given y-coordinate.
*
* @param thumb the thumb to move
* @param y the y-coordinate to move the thumb to
*/
private void moveThumb(Thumb thumb, float y) {
// If the user has moved their finger outside the range of the bar,
// do not move the thumbs past the edge.
// Log.i(RangeBar.class.getName(), "moveThumb: " + x );
if (y < mVerticalBar.getTopY() || y > mVerticalBar.getBottomY()) {
// Do nothing.
} else {
thumb.setY(y);
invalidate();
}
}
/**
* Sets the location of each thumb according to the developer's choice.
* Numbered from 0 to mTickCount - 1 from the left.
*
* @param leftThumbIndex Integer specifying the index of the left thumb
* @param rightThumbIndex Integer specifying the index of the right thumb
*/
public void setThumbIndices(int leftThumbIndex, int rightThumbIndex)
{
if (indexOutOfRange(leftThumbIndex, rightThumbIndex)) {
Log.e(TAG, "A thumb index is out of bounds. Check that it is between 0 and mTickCount - 1");
throw new IllegalArgumentException("A thumb index is out of bounds. Check that it is between 0 and mTickCount - 1");
} else {
if (mFirstSetTickCount == true)
mFirstSetTickCount = false;
mLeftIndex = leftThumbIndex;
mRightIndex = rightThumbIndex;
createThumbs();
if (mListener != null) {
mListener.onIndexChangeListener(this, mLeftIndex, mRightIndex);
}
}
invalidate();
requestLayout();
}
/**
* Creates two new Thumbs.
*/
private void createThumbs() {
Context ctx = getContext();
// mLeftThumb = new Thumb(ctx,
// yPos,
// mThumbColorNormal,
// mThumbColorPressed,
// mThumbRadiusDP,
// mThumbImageNormal,
// mThumbImagePressed);
mRightThumb = new Thumb(ctx,
getWidth()/2f,
mThumbColorNormal,
mThumbColorPressed,
mThumbRadiusDP,
mThumbImageNormal,
mThumbImagePressed);
final float marginBottom = mRightThumb.getHalfWidth();
final float barLength = getHeight() - 2 * marginBottom;
// Initialize thumbs to the desired indices
//mLeftThumb.setX(marginLeft + (mLeftIndex / (float) (mTickCount - 1)) * barLength);
mRightThumb.setY(marginBottom + barLength);
invalidate();
}
/**
* Set the color of the bar line and the tick lines in the range bar.
*
* @param barColor Integer specifying the color of the bar line.
*/
public void setBarColor(int barColor) {
Log.i(VerticalRangeBar.class.getName(), "setBarColor");
mBarColor = barColor;
createBar();
}
/**
* Creates a new mBar
*
*/
private void createBar() {
// Create the underlying bar.
mVerticalBar = new VerticalBar(getContext(), getMarginBottom(), getWidth() / 4f ,
getBarLength(), mTickCount, mTickHeightDP, mBarWeight, mBarColor, mTickMarkStep);
invalidate();
}
/**
* Returns if either index is outside the range of the tickCount.
*
* @param leftThumbIndex Integer specifying the left thumb index.
* @param rightThumbIndex Integer specifying the right thumb index.
* @return boolean If the index is out of range.
*/
private boolean indexOutOfRange(int leftThumbIndex, int rightThumbIndex) {
return (leftThumbIndex < 0 || leftThumbIndex >= mTickCount
|| rightThumbIndex < 0
|| rightThumbIndex >= mTickCount);
}
/**
* Sets a listener to receive notifications of changes to the RangeBar. This
* will overwrite any existing set listeners.
*
* @param listener the RangeBar notification listener; null to remove any
* existing listener
*/
public void setOnRangeBarChangeListener(VerticalRangeBar.OnRangeBarChangeListener listener) {
mListener = listener;
}
/**
* Sets the number of ticks in the RangeBar.
*
* @param tickCount Integer specifying the number of ticks.
*/
public void setTickCount(int tickCount) {
if (isValidTickCount(tickCount)) {
mTickCount = tickCount;
// Prevents resetting the indices when creating new activity, but
// allows it on the first setting.
if (mFirstSetTickCount) {
mLeftIndex = 0;
mRightIndex = mTickCount - 1;
if (mListener != null) {
mListener.onIndexChangeListener(this, mLeftIndex, mRightIndex);
}
}
if (indexOutOfRange(mLeftIndex, mRightIndex))
{
mLeftIndex = 0;
mRightIndex = mTickCount - 1;
if (mListener != null)
mListener.onIndexChangeListener(this, mLeftIndex, mRightIndex);
}
createBar();
createThumbs();
}
else {
Log.e(TAG, "tickCount less than 2; invalid tickCount.");
throw new IllegalArgumentException("tickCount less than 2; invalid tickCount.");
}
}
/**
* Sets the height of the ticks in the range bar.
*
* @param tickHeight Float specifying the height of each tick mark in dp.
*/
public void setTickHeight(float tickHeight) {
mTickHeightDP = tickHeight;
createBar();
}
/**
* sets tick mark steps in Vertical Range bar.
*
* @param tickMarkStep int for specifying tickMark steps between two ticks.
*/
public void setTickMarkStep(int tickMarkStep){
mTickMarkStep = tickMarkStep;
createBar();
}
/**
* Get marginLeft in each of the public attribute methods.
*
* @return float marginLeft
*/
private float getMarginBottom() {
return ((mRightThumb != null) ? mRightThumb.getHalfWidth() : 0);
}
/**
* Get barLength in each of the public attribute methods.
*
* @return float barLength
*/
private float getBarLength() {
return (getHeight() - 2 * getMarginBottom());
}
/**
* If is invalid tickCount, rejects. TickCount must be greater than 1
*
* @param tickCount Integer
* @return boolean: whether tickCount > 1
*/
private boolean isValidTickCount(int tickCount) {
return (tickCount > 1);
}
// Inner Classes ///////////////////////////////////////////////////////////
/**
* A callback that notifies clients when the RangeBar has changed. The
* listener will only be called when either thumb's index has changed - not
* for every movement of the thumb.
*/
public static interface OnRangeBarChangeListener {
public void onIndexChangeListener(VerticalRangeBar rangeBar, int leftThumbIndex, int rightThumbIndex);
}
}
|
package io.spine.server.event;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.Message;
import io.grpc.stub.StreamObserver;
import io.spine.annotation.Internal;
import io.spine.core.Ack;
import io.spine.core.Event;
import io.spine.core.EventClass;
import io.spine.core.EventContext;
import io.spine.core.EventEnvelope;
import io.spine.grpc.LoggingObserver;
import io.spine.grpc.LoggingObserver.Level;
import io.spine.server.bus.BusFilter;
import io.spine.server.bus.DeadMessageTap;
import io.spine.server.bus.EnvelopeValidator;
import io.spine.server.bus.MessageUnhandled;
import io.spine.server.outbus.CommandOutputBus;
import io.spine.server.outbus.OutputDispatcherRegistry;
import io.spine.server.storage.StorageFactory;
import io.spine.validate.MessageValidator;
import javax.annotation.Nullable;
import java.util.Deque;
import java.util.Set;
import java.util.concurrent.Executor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.of;
/**
* Dispatches incoming events to subscribers, and provides ways for registering those subscribers.
*
* <h2>Receiving Events</h2>
* <p>To receive event messages a subscriber object should:
* <ol>
* <li>Expose a {@code public} method that accepts an event message as the first parameter
* and an {@link EventContext EventContext} as the second
* (optional) parameter.
* <li>Mark the method with the {@link io.spine.core.Subscribe @Subscribe} annotation.
* <li>{@linkplain #register(io.spine.server.bus.MessageDispatcher)} Register} with an
* instance of {@code EventBus} directly, or rely on message delivery
* from an {@link EventDispatcher}. An example of such a dispatcher is
* {@link io.spine.server.projection.ProjectionRepository ProjectionRepository}
* </ol>
*
* <p><strong>Note:</strong> A subscriber method cannot accept just {@link Message} as
* the first parameter. It must be an <strong>exact type</strong> of the event message
* that needs to be handled.
*
* <h2>Posting Events</h2>
* <p>Events are posted to an EventBus using {@link #post(Message, StreamObserver)} method.
* Normally this is done by an
* {@linkplain io.spine.server.aggregate.AggregateRepository AggregateRepository} in the process
* of handling a command,
* or by a {@linkplain io.spine.server.procman.ProcessManager ProcessManager}.
*
* <p>The passed {@link Event} is stored in the {@link EventStore} associated with
* the {@code EventBus} <strong>before</strong> it is passed to subscribers.
*
* <p>The delivery of the events to the subscribers and dispatchers is performed by
* the {@link DispatcherEventDelivery} strategy associated with
* this instance of the {@code EventBus}.
*
* <p>If there is no subscribers or dispatchers for the posted event, the fact is
* logged as warning, with no further processing.
*
* @author Mikhail Melnik
* @author Alexander Yevsyuov
* @author Alex Tymchenko
* @see io.spine.server.projection.Projection Projection
* @see io.spine.core.Subscribe @Subscribe
*/
public class EventBus
extends CommandOutputBus<Event, EventEnvelope, EventClass, EventDispatcher<?>> {
/*
* NOTE: Even though, the EventBus has a private constructor and
* is not supposed to be derived, we do not make this class final
* in order to be able to spy() on it from Mockito (which cannot
* spy on final or anonymous classes).
*/
/** The {@code EventStore} to which put events before they get handled. */
private final EventStore eventStore;
/** The validator for messages of posted events. */
private final MessageValidator eventMessageValidator;
/** The handler for dead events. */
private final DeadMessageTap<EventEnvelope> deadMessageHandler;
/** Filters applied when an event is posted. */
private final Deque<BusFilter<EventEnvelope>> filterChain;
/** The observer of post operations. */
private final StreamObserver<Ack> streamObserver;
/** The validator for events posted to the bus. */
@Nullable
private EventValidator eventValidator;
/** The enricher for posted events or {@code null} if the enrichment is not supported. */
@Nullable
private final EventEnricher enricher;
/** Creates new instance by the passed builder. */
private EventBus(Builder builder) {
super(checkNotNull(builder.dispatcherEventDelivery));
this.eventStore = builder.eventStore;
this.enricher = builder.enricher;
this.eventMessageValidator = builder.eventValidator;
this.filterChain = builder.getFilters();
this.streamObserver = LoggingObserver.forClass(getClass(), builder.logLevelForPost);
this.deadMessageHandler = new DeadEventTap();
}
/** Creates a builder for new {@code EventBus}. */
public static Builder newBuilder() {
return new Builder();
}
@VisibleForTesting
Set<? extends EventDispatcher<?>> getDispatchers(EventClass eventClass) {
return registry().getDispatchers(eventClass);
}
@VisibleForTesting
boolean hasDispatchers(EventClass eventClass) {
return registry().hasDispatchersFor(eventClass);
}
@Override
protected DeadMessageTap<EventEnvelope> getDeadMessageHandler() {
return deadMessageHandler;
}
@Override
protected EnvelopeValidator<EventEnvelope> getValidator() {
if (eventValidator == null) {
eventValidator = new EventValidator(eventMessageValidator);
}
return eventValidator;
}
@Override
protected OutputDispatcherRegistry<EventClass, EventDispatcher<?>> createRegistry() {
return new EventDispatcherRegistry();
}
@SuppressWarnings("ReturnOfCollectionOrArrayField") // OK for this method.
@Override
protected Deque<BusFilter<EventEnvelope>> createFilterChain() {
return filterChain;
}
@Override
protected EventEnvelope toEnvelope(Event message) {
return EventEnvelope.of(message);
}
@VisibleForTesting
MessageValidator getMessageValidator() {
return eventMessageValidator;
}
/** Returns {@link EventStore} associated with the bus. */
public EventStore getEventStore() {
return eventStore;
}
/**
* Posts the event for handling.
*
* <p>Performs the same action as the
* {@linkplain CommandOutputBus#post(Message, StreamObserver)} parent method}, but does not
* require any response observer.
*
* @param event the event to be handled
* @see CommandOutputBus#post(Message, StreamObserver)
*/
public final void post(Event event) {
post(event, streamObserver);
}
/**
* Posts the events for handling.
*
* <p>Performs the same action as the
* {@linkplain CommandOutputBus#post(Iterable, StreamObserver)} parent method}, but does not
* require any response observer.
*
* <p>This method should be used if the callee does not care about the events acknowledgement.
*
* @param events the events to be handled
* @see CommandOutputBus#post(Message, StreamObserver)
*/
public final void post(Iterable<Event> events) {
post(events, streamObserver);
}
@Override
protected EventEnvelope enrich(EventEnvelope event) {
if (enricher == null || !enricher.canBeEnriched(event)) {
return event;
}
final EventEnvelope enriched = enricher.enrich(event);
return enriched;
}
@Override
protected void store(Iterable<Event> events) {
eventStore.appendAll(events);
}
@Override
public void close() throws Exception {
super.close();
eventStore.close();
}
/**
* {@inheritDoc}
*
* <p>Overrides for return type covariance.
*/
@Override
protected EventDispatcherRegistry registry() {
return (EventDispatcherRegistry) super.registry();
}
/**
* {@inheritDoc}
*
* <p>Overrides for return type covariance.
*/
@Override
protected DispatcherEventDelivery delivery() {
return (DispatcherEventDelivery) super.delivery();
}
/** The {@code Builder} for {@code EventBus}. */
public static class Builder extends AbstractBuilder<EventEnvelope, Event, Builder> {
private static final String MSG_EVENT_STORE_CONFIGURED = "EventStore already configured.";
/**
* A {@code StorageFactory} for configuring the {@code EventStore} instance
* for this {@code EventBus}.
*
* <p>If the {@code EventStore} is passed to this {@code Builder} explicitly
* via {@link #setEventStore(EventStore)}, the {@code storageFactory} field
* value is not used.
*
* <p>Either a {@code StorageFactory} or an {@code EventStore} are mandatory
* to create an instance of {@code EventBus}.
*/
@Nullable
private StorageFactory storageFactory;
@Nullable
private EventStore eventStore;
/**
* Optional {@code Executor} for returning event stream from the {@code EventStore}.
*
* <p>Used only if the {@code EventStore} is NOT set explicitly.
*
* <p>If not set, a default value will be set by the builder.
*/
@Nullable
private Executor eventStoreStreamExecutor;
/**
* Optional {@code DispatcherEventDelivery} for calling the dispatchers.
*
* <p>If not set, a default value will be set by the builder.
*/
@Nullable
private DispatcherEventDelivery dispatcherEventDelivery;
/**
* Optional validator for events.
*
* <p>If not set, a default value will be set by the builder.
*/
@Nullable
private MessageValidator eventValidator;
/**
* Optional enricher for events.
*
* <p>If not set, the enrichments will NOT be supported
* in the {@code EventBus} instance built.
*/
@Nullable
private EventEnricher enricher;
/** Logging level for posted events. */
private LoggingObserver.Level logLevelForPost = Level.TRACE;
/** Prevents direct instantiation. */
private Builder() {
super();
}
/**
* Specifies an {@code StorageFactory} to configure this {@code EventBus}.
*
* <p>This {@code StorageFactory} instance will be used to create
* an instance of {@code EventStore} for this {@code EventBus},
* <em>if</em> {@code EventStore} was not explicitly set in the builder.
*
* <p>Either a {@code StorageFactory} or an {@code EventStore} are mandatory
* to create an {@code EventBus}.
*
* @see #setEventStore(EventStore)
*/
public Builder setStorageFactory(StorageFactory storageFactory) {
checkState(eventStore == null, MSG_EVENT_STORE_CONFIGURED);
this.storageFactory = checkNotNull(storageFactory);
return this;
}
public Optional<StorageFactory> getStorageFactory() {
return Optional.fromNullable(storageFactory);
}
/**
* Specifies {@code EventStore} to be used when creating new {@code EventBus}.
*
* <p>This method can be called if neither {@link #setEventStoreStreamExecutor(Executor)}
* nor {@link #setStorageFactory(StorageFactory)} were called before.
*
* <p>Either a {@code StorageFactory} or an {@code EventStore} must be set
* to create an {@code EventBus}.
*
* @see #setEventStoreStreamExecutor(Executor)
* @see #setStorageFactory(StorageFactory)
*/
public Builder setEventStore(EventStore eventStore) {
checkState(storageFactory == null, "storageFactory already set.");
checkState(eventStoreStreamExecutor == null, "eventStoreStreamExecutor already set.");
this.eventStore = checkNotNull(eventStore);
return this;
}
public Optional<EventStore> getEventStore() {
return Optional.fromNullable(eventStore);
}
/**
* Specifies an {@code Executor} for returning event stream from {@code EventStore}.
*
* <p>This {@code Executor} instance will be used for creating
* new {@code EventStore} instance when building {@code EventBus}, <em>if</em>
* {@code EventStore} was not explicitly set in the builder.
*
* <p>If an {@code Executor} is not set in the builder,
* {@link MoreExecutors#directExecutor()} will be used.
*
* @see #setEventStore(EventStore)
*/
public Builder setEventStoreStreamExecutor(Executor eventStoreStreamExecutor) {
checkState(eventStore == null, MSG_EVENT_STORE_CONFIGURED);
this.eventStoreStreamExecutor = eventStoreStreamExecutor;
return this;
}
public Optional<Executor> getEventStoreStreamExecutor() {
return Optional.fromNullable(eventStoreStreamExecutor);
}
/**
* Sets a {@code DispatcherEventDelivery} to be used for the event delivery
* to the dispatchers in the {@code EventBus} we build.
*
* <p>If the {@code DispatcherEventDelivery} is not set,
* {@link DispatcherEventDelivery#directDelivery()} will be used.
*/
public Builder setDispatcherEventDelivery(DispatcherEventDelivery delivery) {
this.dispatcherEventDelivery = checkNotNull(delivery);
return this;
}
public Optional<DispatcherEventDelivery> getDispatcherEventDelivery() {
return Optional.fromNullable(dispatcherEventDelivery);
}
public Builder setEventValidator(MessageValidator eventValidator) {
this.eventValidator = checkNotNull(eventValidator);
return this;
}
public Optional<MessageValidator> getEventValidator() {
return Optional.fromNullable(eventValidator);
}
/**
* Sets a custom {@link EventEnricher} for events posted to
* the {@code EventBus} which is being built.
*
* <p>If the {@code EventEnricher} is not set, the enrichments
* will <strong>NOT</strong> be supported for the {@code EventBus} instance built.
*
* @param enricher the {@code EventEnricher} for events or {@code null} if enrichment is
* not supported
*/
public Builder setEnricher(EventEnricher enricher) {
this.enricher = enricher;
return this;
}
public Optional<EventEnricher> getEnricher() {
return Optional.fromNullable(enricher);
}
/**
* Sets logging level for post operations.
*
* <p>If not set directly, {@link io.spine.grpc.LoggingObserver.Level#TRACE Level.TRACE}
* will be used.
*/
public Builder setLogLevelForPost(Level level) {
this.logLevelForPost = level;
return this;
}
/**
* Obtains the logging level for {@linkplain EventBus#post(Event) post} operations.
*/
public Level getLogLevelForPost() {
return this.logLevelForPost;
}
/**
* Builds an instance of {@link EventBus}.
*
* <p>This method is supposed to be called internally when building an enclosing
* {@code BoundedContext}.
*/
@Override
@Internal
public EventBus build() {
final String message = "Either storageFactory or eventStore must be " +
"set to build the EventBus instance";
checkState(storageFactory != null || eventStore != null, message);
if (eventStoreStreamExecutor == null) {
eventStoreStreamExecutor = MoreExecutors.directExecutor();
}
checkNotNull(eventStoreStreamExecutor);
if (eventStore == null) {
eventStore = EventStore.newBuilder()
.setStreamExecutor(eventStoreStreamExecutor)
.setStorageFactory(storageFactory)
.setLogger(EventStore.log())
.build();
}
if (dispatcherEventDelivery == null) {
dispatcherEventDelivery = DispatcherEventDelivery.directDelivery();
}
if (eventValidator == null) {
eventValidator = MessageValidator.newInstance();
}
final EventBus result = new EventBus(this);
return result;
}
@Override
protected Builder self() {
return this;
}
}
/**
* Handles a dead event by saving it to the {@link EventStore} and producing an
* {@link UnsupportedEventException}.
*
* <p>We must store dead events, as they are still emitted by some entity and therefore are
* a part of the history for the current bounded context.
*/
private class DeadEventTap implements DeadMessageTap<EventEnvelope> {
@Override
public UnsupportedEventException capture(EventEnvelope envelope) {
final Event event = envelope.getOuterObject();
store(of(event));
final Message message = envelope.getMessage();
final UnsupportedEventException exception = new UnsupportedEventException(message);
return exception;
}
}
}
|
package bob.sun.mpod.view;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import bob.sun.mpod.controller.OnButtonListener;
import bob.sun.mpod.controller.OnTickListener;
import bob.sun.mpod.utils.VibrateUtil;
public class WheelView extends View {
private Point center;
private int radiusOut,radiusIn;
private Paint paintOut, paintIn;
private OnTickListener onTickListener;
private float startDeg = Float.NaN;
private OnButtonListener onButtonListener;
public WheelView(Context context, AttributeSet attrs) {
super(context, attrs);
center = new Point();
paintIn = new Paint();
paintOut = new Paint();
paintOut.setColor(Color.GRAY);
paintIn.setColor(Color.WHITE);
paintOut.setAntiAlias(true);
paintIn.setAntiAlias(true);
paintOut.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// paintIn.setShadowLayer(10.0f, 0.0f, -2.0f, 0xFF000000);
}
@Override
protected void onMeasure(int measureWidthSpec,int measureHeightSpec){
super.onMeasure(measureWidthSpec,measureHeightSpec);
int measuredWidth = measureWidth(measureWidthSpec);
int measuredHeight = measureHeight(measureHeightSpec);
this.setMeasuredDimension(measuredWidth,measuredHeight);
radiusOut = (measuredHeight - 20)/ 2;
radiusIn = radiusOut/3;
center.x = measuredWidth/2;
center.y = measuredHeight/2;
}
@Override
public void onDraw(Canvas canvas){
canvas.drawCircle(center.x,center.y,radiusOut,paintOut);
canvas.drawCircle(center.x,center.y,radiusIn,paintIn);
}
private float xyToDegrees(float x, float y) {
float distanceFromCenter = PointF.length((x - 0.5f), (y - 0.5f));
if (distanceFromCenter < 0.15f
|| distanceFromCenter > 0.5f) { // ignore center and out of bounds events
return Float.NaN;
} else {
return (float) Math.toDegrees(Math.atan2(x - 0.5f, y - 0.5f));
}
}
private int measureWidth(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
int result = 0;
if (specMode == MeasureSpec.AT_MOST) {
result = getWidth();
} else if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
}
return result;
}
private int measureHeight(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
int result = 0;
if (specMode == MeasureSpec.AT_MOST) {
result = getWidth();
} else if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
}
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event){
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
float x = event.getX() / (center.x * 2);
float y = event.getY() / (center.y * 2);
startDeg = xyToDegrees(x, y);
// Log.d("deg = ", "" + startDeg);
// if (Float.isNaN(startDeg)) {
// return false;
return true;
case MotionEvent.ACTION_MOVE:
if (!Float.isNaN(startDeg)) {
float currentDeg = xyToDegrees((event.getX() - (getWidth() - getHeight())/2) / ((float) getHeight()),
event.getY() / getHeight());
if (!Float.isNaN(currentDeg)) {
float degPerTick = 72f;
float deltaDeg = startDeg - currentDeg;
if(Math.abs(deltaDeg) < 72f){
return true;
}
int ticks = (int) (Math.signum(deltaDeg)
* Math.floor(Math.abs(deltaDeg) / degPerTick));
if(ticks == 1){
startDeg = currentDeg;
if(onTickListener !=null)
onTickListener.onNextTick();
VibrateUtil.getStaticInstance(null).TickVibrate();
}
if(ticks == -1){
startDeg = currentDeg;
if(onTickListener !=null)
onTickListener.onPreviousTick();
VibrateUtil.getStaticInstance(null).TickVibrate();
}
}
startDeg = currentDeg;
return true;
} else {
return false;
}
case MotionEvent.ACTION_UP:
if ((Math.pow(event.getX() - getWidth() / 2f,2) + Math.pow(event.getY() - getHeight() / 2f,2) <= radiusIn*radiusIn )){
if(onButtonListener !=null)
onButtonListener.onSelect();
return true;
}
//TODO
return true;
default:
return super.onTouchEvent(event);
}
}
public void setOnTickListener(OnTickListener listener){
this.onTickListener = listener;
}
public void setOnButtonListener(OnButtonListener listener){
this.onButtonListener = listener;
}
}
|
package com.app.loader;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.app.loader.app.AppActivity;
import com.app.loader.sms.SmsActivity;
import com.app.loader.sms2.SmsActivity2;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById( R.id.sms).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity( new Intent( MainActivity.this , SmsActivity.class ));
}
});
findViewById( R.id.app).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity( new Intent( MainActivity.this , AppActivity.class ));
}
});
findViewById( R.id.sms2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity( new Intent( MainActivity.this , SmsActivity2.class ));
}
});
}
}
|
package com.marverenic.music;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.Equalizer;
import android.net.Uri;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import com.crashlytics.android.Crashlytics;
import com.marverenic.music.activity.NowPlayingActivity;
import com.marverenic.music.instances.Library;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.ManagedMediaPlayer;
import com.marverenic.music.utils.Prefs;
import com.marverenic.music.utils.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
public class Player implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
AudioManager.OnAudioFocusChangeListener {
// Sent to refresh views that use up-to-date player information
public static final String UPDATE_BROADCAST = "marverenic.jockey.player.REFRESH";
private static final String TAG = "Player";
private static final String QUEUE_FILE = ".queue";
public static final String PREFERENCE_SHUFFLE = "prefShuffle";
public static final String PREFERENCE_REPEAT = "prefRepeat";
// Instance variables
private ManagedMediaPlayer mediaPlayer;
private Equalizer equalizer;
private Context context;
private MediaSessionCompat mediaSession;
private HeadsetListener headphoneListener;
// Queue information
private List<Song> queue;
private List<Song> queueShuffled = new ArrayList<>();
private int queuePosition;
private int queuePositionShuffled;
// MediaFocus variables
// If we currently have audio focus
private boolean active = false;
// If we should play music when focus is returned
private boolean shouldResumeOnFocusGained = false;
// Shufle & Repeat options
private boolean shuffle; // Shuffle status
public static final short REPEAT_NONE = 0;
public static final short REPEAT_ALL = 1;
public static final short REPEAT_ONE = 2;
private short repeat; // Repeat status
private Bitmap art; // The art for the current song
/**
* A {@link Properties} object used as a hashtable for saving play and skip counts.
* See {@link Player#logPlayCount(long, boolean)}
*
* Keys are stored as strings in the form "song_id"
* Values are stored as strings in the form "play,skip,lastPlayDateAsUtcTimeStamp"
*/
private Properties playCountHashtable;
/**
* Create a new Player Object, which manages a {@link MediaPlayer}
* @param context A {@link Context} that will be held for the lifetime of the Player
*/
public Player(Context context) {
this.context = context;
// Initialize the media player
mediaPlayer = new ManagedMediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
// Initialize the queue
queue = new ArrayList<>();
queuePosition = 0;
// Load preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
shuffle = prefs.getBoolean(PREFERENCE_SHUFFLE, false);
repeat = (short) prefs.getInt(PREFERENCE_REPEAT, REPEAT_NONE);
initMediaSession();
if (Util.hasEqualizer()) {
initEqualizer();
}
// Attach a HeadsetListener to respond to headphone events
headphoneListener = new HeadsetListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_BUTTON);
filter.addAction(Intent.ACTION_HEADSET_PLUG);
context.registerReceiver(headphoneListener, filter);
}
/**
* Reload the last queue saved by the Player
*/
public void reload() {
try {
File save = new File(context.getExternalFilesDir(null), QUEUE_FILE);
Scanner scanner = new Scanner(save);
final int currentPosition = scanner.nextInt();
if (shuffle) {
queuePositionShuffled = scanner.nextInt();
} else {
queuePosition = scanner.nextInt();
}
int queueLength = scanner.nextInt();
int[] queueIDs = new int[queueLength];
for (int i = 0; i < queueLength; i++) {
queueIDs[i] = scanner.nextInt();
}
queue = Library.buildSongListFromIds(queueIDs, context);
int[] shuffleQueueIDs;
if (scanner.hasNextInt()) {
shuffleQueueIDs = new int[queueLength];
for (int i = 0; i < queueLength; i++) {
shuffleQueueIDs[i] = scanner.nextInt();
}
queueShuffled = Library.buildSongListFromIds(shuffleQueueIDs, context);
} else if (shuffle) {
queuePosition = queuePositionShuffled;
shuffleQueue();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.seekTo(currentPosition);
updateNowPlaying();
mp.setOnPreparedListener(Player.this);
}
});
art = Util.fetchFullArt(getNowPlaying());
mediaPlayer.setDataSource(getNowPlaying().getLocation());
mediaPlayer.prepareAsync();
} catch (Exception e) {
queuePosition = 0;
queuePositionShuffled = 0;
queue.clear();
queueShuffled.clear();
}
}
/**
* Reload all equalizer settings from SharedPreferences
*/
private void initEqualizer() {
SharedPreferences prefs = Prefs.getPrefs(context);
String eqSettings = prefs.getString(Prefs.EQ_SETTINGS, null);
boolean enabled = Prefs.getPrefs(context).getBoolean(Prefs.EQ_ENABLED, false);
equalizer = new Equalizer(0, mediaPlayer.getAudioSessionId());
if (eqSettings != null) {
try {
equalizer.setProperties(new Equalizer.Settings(eqSettings));
} catch (IllegalArgumentException | UnsupportedOperationException e) {
Crashlytics.logException(new RuntimeException(
"Failed to load equalizer settings: " + eqSettings, e));
}
}
equalizer.setEnabled(enabled);
// If the built in equalizer is off, bind to the system equalizer if one is available
if (!enabled) {
final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
context.sendBroadcast(intent);
}
}
/**
* Writes a player state to disk. Contains information about the queue (both unshuffled
* and shuffled), current queuePosition within this list, and the current queuePosition
* of the song
* @throws IOException
*/
public void saveState(@NonNull final String nextCommand) throws IOException {
// Anticipate the outcome of a command so that if we're killed right after it executes,
// we can restore to the proper state
int reloadSeekPosition;
int reloadQueuePosition = (shuffle) ? queuePositionShuffled : queuePosition;
switch (nextCommand) {
case PlayerService.ACTION_NEXT:
if (reloadQueuePosition + 1 < queue.size()) {
reloadSeekPosition = 0;
reloadQueuePosition++;
} else {
reloadSeekPosition = mediaPlayer.getDuration();
}
break;
case PlayerService.ACTION_PREV:
if (mediaPlayer.getDuration() < 5000 && reloadQueuePosition - 1 > 0) {
reloadQueuePosition
}
reloadSeekPosition = 0;
break;
default:
reloadSeekPosition = mediaPlayer.getCurrentPosition();
break;
}
final String currentPosition = Integer.toString(reloadSeekPosition);
final String queuePosition = Integer.toString(reloadQueuePosition);
final String queueLength = Integer.toString(queue.size());
String queue = "";
for (Song s : this.queue) {
queue += " " + s.getSongId();
}
String queueShuffled = "";
for (Song s : this.queueShuffled) {
queueShuffled += " " + s.getSongId();
}
String output = currentPosition + " " + queuePosition + " "
+ queueLength + queue + queueShuffled;
File save = new File(context.getExternalFilesDir(null), QUEUE_FILE);
FileOutputStream stream = new FileOutputStream(save);
stream.write(output.getBytes());
stream.close();
}
/**
* Release the player. Call when finished with an instance
*/
public void finish() {
((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
context.unregisterReceiver(headphoneListener);
// Unbind from the system audio effects
final Intent intent = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
context.sendBroadcast(intent);
if (equalizer != null) {
equalizer.release();
}
active = false;
mediaPlayer.stop();
mediaPlayer.release();
mediaSession.release();
mediaPlayer = null;
context = null;
}
/**
* Initiate a MediaSession to allow the Android system to interact with the player
*/
private void initMediaSession() {
mediaSession = new MediaSessionCompat(context, TAG, null, null);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
play();
updateUi();
}
@Override
public void onSkipToQueueItem(long id) {
changeSong((int) id);
updateUi();
}
@Override
public void onPause() {
pause();
updateUi();
}
@Override
public void onSkipToNext() {
skip();
updateUi();
}
@Override
public void onSkipToPrevious() {
previous();
updateUi();
}
@Override
public void onStop() {
stop();
updateUi();
}
@Override
public void onSeekTo(long pos) {
seek((int) pos);
updateUi();
}
});
mediaSession.setSessionActivity(
PendingIntent.getActivity(
context, 0,
new Intent(context, NowPlayingActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_CANCEL_CURRENT));
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
| MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder()
.setActions(PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f);
mediaSession.setPlaybackState(state.build());
mediaSession.setActive(true);
}
@Override
public void onAudioFocusChange(int focusChange) {
shouldResumeOnFocusGained = isPlaying() || shouldResumeOnFocusGained;
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS:
stop();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mediaPlayer.setVolume(0.5f, 0.5f);
break;
case AudioManager.AUDIOFOCUS_GAIN:
mediaPlayer.setVolume(1f, 1f);
if (shouldResumeOnFocusGained) play();
shouldResumeOnFocusGained = false;
break;
default:
break;
}
updateNowPlaying();
updateUi();
}
@Override
public void onCompletion(MediaPlayer mp) {
logPlayCount(getNowPlaying().getSongId(), false);
if (repeat == REPEAT_ONE) {
mediaPlayer.seekTo(0);
play();
} else if (hasNextInQueue(1)) {
skip();
}
updateUi();
}
@Override
public void onPrepared(MediaPlayer mp) {
if (!isPreparing()) {
mediaPlayer.start();
updateUi();
updateNowPlaying();
}
}
private boolean hasNextInQueue(int by) {
if (shuffle) {
return queuePositionShuffled + by < queueShuffled.size();
} else {
return queuePosition + by < queue.size();
}
}
private void setQueuePosition(int position) {
if (shuffle) {
queuePositionShuffled = position;
} else {
queuePosition = position;
}
}
private void incrementQueuePosition(int by) {
if (shuffle) {
queuePositionShuffled += by;
} else {
queuePosition += by;
}
}
/**
* Change the queue and shuffle it if necessary
* @param newQueue A {@link List} of {@link Song}s to become the new queue
* @param newPosition The queuePosition in the list to start playback from
*/
public void setQueue(final List<Song> newQueue, final int newPosition) {
queue = newQueue;
queuePosition = newPosition;
if (shuffle) shuffleQueue();
updateNowPlaying();
}
/**
* Replace the contents of the queue without affecting playback
* @param newQueue A {@link List} of {@link Song}s to become the new queue
* @param newPosition The queuePosition in the list to start playback from
*/
public void editQueue(final List<Song> newQueue, final int newPosition) {
if (shuffle) {
queueShuffled = newQueue;
queuePositionShuffled = newPosition;
} else {
queue = newQueue;
queuePosition = newPosition;
}
updateNowPlaying();
}
/**
* Begin playback of a new song. Call this method after changing the queue or now playing track
*/
public void begin() {
if (getNowPlaying() != null && getFocus()) {
mediaPlayer.stop();
mediaPlayer.reset();
art = Util.fetchFullArt(getNowPlaying());
try {
File source = new File(getNowPlaying().getLocation());
mediaPlayer.setDataSource(context, Uri.fromFile(source));
mediaPlayer.prepareAsync();
} catch (IOException e) {
Crashlytics.logException(
new IOException("Failed to play song " + getNowPlaying().getLocation(), e));
}
}
}
/**
* Update the main thread and Android System about this player instance. This method also calls
* {@link PlayerService#notifyNowPlaying()}.
*/
public void updateNowPlaying() {
PlayerService.getInstance().notifyNowPlaying();
updateMediaSession();
}
/**
* Update the MediaSession to keep the Android system up to date with player information
*/
public void updateMediaSession() {
if (getNowPlaying() != null) {
MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder();
Song nowPlaying = getNowPlaying();
metadataBuilder
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM,
nowPlaying.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,
nowPlaying.getArtistName())
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, getDuration())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, art);
mediaSession.setMetadata(metadataBuilder.build());
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions(
PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
switch (mediaPlayer.getState()) {
case STARTED:
state.setState(PlaybackStateCompat.STATE_PLAYING, getCurrentPosition(), 1f);
break;
case PAUSED:
state.setState(PlaybackStateCompat.STATE_PAUSED, getCurrentPosition(), 1f);
break;
case STOPPED:
state.setState(PlaybackStateCompat.STATE_STOPPED, getCurrentPosition(), 1f);
break;
default:
state.setState(PlaybackStateCompat.STATE_NONE, getCurrentPosition(), 1f);
}
mediaSession.setPlaybackState(state.build());
mediaSession.setActive(active);
}
}
/**
* Called to notify the UI thread to refresh any player data when the player changes states
* on its own (Like when a song finishes)
*/
public void updateUi() {
context.sendBroadcast(new Intent(UPDATE_BROADCAST), null);
}
/**
* Get the song at the current queuePosition in the queue or shuffled queue
* @return The now playing {@link Song} (null if nothing is playing)
*/
public Song getNowPlaying() {
if (shuffle) {
if (queueShuffled.size() == 0 || queuePositionShuffled >= queueShuffled.size()
|| queuePositionShuffled < 0) {
return null;
}
return queueShuffled.get(queuePositionShuffled);
}
if (queue.size() == 0 || queuePosition >= queue.size() || queuePosition < 0) {
return null;
}
return queue.get(queuePosition);
}
// MEDIA CONTROL METHODS
/**
* Toggle between playing and pausing music
*/
public void togglePlay() {
if (isPlaying()) {
pause();
} else {
play();
}
}
/**
* Resume playback. Starts playback over if at the end of the last song in the queue
*/
public void play() {
if (!isPlaying() && getFocus()) {
if (shuffle) {
if (queuePositionShuffled + 1 == queueShuffled.size() && mediaPlayer.isComplete()) {
queuePositionShuffled = 0;
begin();
} else {
mediaPlayer.start();
updateNowPlaying();
}
} else {
if (queuePosition + 1 == queue.size() && mediaPlayer.isComplete()) {
queuePosition = 0;
begin();
} else {
mediaPlayer.start();
updateNowPlaying();
}
}
}
}
/**
* Pauses playback. The same as calling {@link MediaPlayer#pause()}
* and {@link Player#updateNowPlaying()}
*/
public void pause() {
if (isPlaying()) {
mediaPlayer.pause();
updateNowPlaying();
}
shouldResumeOnFocusGained = false;
}
/**
* Pauses playback and releases audio focus from the system
*/
public void stop() {
if (isPlaying()) {
pause();
}
((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
active = false;
updateMediaSession();
}
/**
* Gain Audio focus from the system if we don't already have it
* @return whether we have gained focus (or already had it)
*/
private boolean getFocus() {
if (!active) {
AudioManager audioManager =
(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int response = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
active = response == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
return active;
}
/**
* Skip to the previous track if less than 5 seconds in, otherwise restart this song from
* the beginning
*/
public void previous() {
if (!isPreparing()) {
if (mediaPlayer.getCurrentPosition() > 5000 || !hasNextInQueue(-1)) {
mediaPlayer.seekTo(0);
updateNowPlaying();
} else {
incrementQueuePosition(-1);
begin();
}
}
}
/**
* Skip to the next track in the queue
*/
public void skip() {
if (!isPreparing()) {
if (!mediaPlayer.isComplete() && getNowPlaying() != null) {
if (mediaPlayer.getCurrentPosition() > 24000
|| mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) {
logPlayCount(getNowPlaying().getSongId(), false);
} else if (getCurrentPosition() < 20000) {
logPlayCount(getNowPlaying().getSongId(), true);
}
}
if (hasNextInQueue(1)) {
incrementQueuePosition(1);
begin();
} else if (repeat == REPEAT_ALL) {
setQueuePosition(0);
begin();
} else {
mediaPlayer.complete();
updateNowPlaying();
}
}
}
/**
* Seek to a different queuePosition in the current track
* @param position The queuePosition to seek to (in milliseconds)
*/
public void seek(int position) {
if (position <= mediaPlayer.getDuration() && getNowPlaying() != null) {
mediaPlayer.seekTo(position);
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(
isPlaying()
? PlaybackStateCompat.STATE_PLAYING
: PlaybackStateCompat.STATE_PAUSED,
(long) mediaPlayer.getCurrentPosition(),
isPlaying() ? 1f : 0f)
.build());
}
}
/**
* Change the current song to a different song in the queue
* @param newPosition The index of the song to start playing
*/
public void changeSong(int newPosition) {
if (!mediaPlayer.isComplete()) {
if (mediaPlayer.getCurrentPosition() > 24000
|| mediaPlayer.getCurrentPosition() > mediaPlayer.getDuration() / 2) {
logPlayCount(getNowPlaying().getSongId(), false);
} else if (getCurrentPosition() < 20000) {
logPlayCount(getNowPlaying().getSongId(), true);
}
}
if (shuffle) {
if (newPosition < queueShuffled.size() && newPosition != queuePositionShuffled) {
queuePositionShuffled = newPosition;
begin();
}
} else {
if (newPosition < queue.size() && queuePosition != newPosition) {
queuePosition = newPosition;
begin();
}
}
}
// QUEUE METHODS
/**
* Add a song to the queue so it plays after the current track. If shuffle is enabled, then the
* song will also be added to the end of the unshuffled queue.
* @param song the {@link Song} to add
*/
public void queueNext(final Song song) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.add(queuePositionShuffled + 1, song);
queue.add(song);
} else {
queue.add(queuePosition + 1, song);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.add(song);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add a song to the end of the queue. If shuffle is enabled, then the song will also be added
* to the end of the unshuffled queue.
* @param song the {@link Song} to add
*/
public void queueLast(final Song song) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.add(queueShuffled.size(), song);
}
queue.add(queue.size(), song);
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.add(song);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add songs to the queue so they play after the current track. If shuffle is enabled, then the
* songs will also be added to the end of the unshuffled queue.
* @param songs a {@link List} of {@link Song}s to add
*/
public void queueNext(final List<Song> songs) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.addAll(queuePositionShuffled + 1, songs);
queue.addAll(songs);
} else {
queue.addAll(queuePosition + 1, songs);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.addAll(songs);
setQueue(newQueue, 0);
begin();
}
}
/**
* Add songs to the end of the queue. If shuffle is enabled, then the songs will also be added
* to the end of the unshuffled queue.
* @param songs an {@link List} of {@link Song}s to add
*/
public void queueLast(final List<Song> songs) {
if (queue.size() != 0) {
if (shuffle) {
queueShuffled.addAll(queueShuffled.size(), songs);
queue.addAll(queue.size(), songs);
} else {
queue.addAll(queue.size(), songs);
}
} else {
List<Song> newQueue = new ArrayList<>();
newQueue.addAll(songs);
setQueue(newQueue, 0);
begin();
}
}
// SHUFFLE & REPEAT METHODS
/**
* Shuffle the queue and put it into {@link Player#queueShuffled}. The current song will always
* be placed first in the list
*/
private void shuffleQueue() {
queueShuffled.clear();
if (queue.size() > 0) {
queuePositionShuffled = 0;
queueShuffled.add(queue.get(queuePosition));
List<Song> randomHolder = new ArrayList<>();
for (int i = 0; i < queuePosition; i++) {
randomHolder.add(queue.get(i));
}
for (int i = queuePosition + 1; i < queue.size(); i++) {
randomHolder.add(queue.get(i));
}
Collections.shuffle(randomHolder, new Random(System.nanoTime()));
queueShuffled.addAll(randomHolder);
}
}
public void setPrefs(boolean shuffleSetting, short repeatSetting) {
// Because SharedPreferences doesn't work with multiple processes (thanks Google...)
// we actually have to be told what the new settings are in order to avoid the service
// and UI doing the opposite of what they should be doing and to prevent the universe
// from exploding. It's fine to initialize the SharedPreferences by reading them like we
// do in the constructor since they haven't been modified, but if something gets written
// in one process the SharedPreferences in the other process won't be updated.
// I really wish someone had told me this earlier.
if (shuffle != shuffleSetting) {
shuffle = shuffleSetting;
if (shuffle) {
shuffleQueue();
} else if (queueShuffled.size() > 0) {
queuePosition = queue.indexOf(queueShuffled.get(queuePositionShuffled));
queueShuffled = new ArrayList<>();
}
}
repeat = repeatSetting;
updateNowPlaying();
}
// PLAY & SKIP COUNT LOGGING
/**
* Initializes {@link Player#playCountHashtable}
* @throws IOException
*/
private void openPlayCountFile() throws IOException {
File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME);
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
InputStream is = new FileInputStream(file);
try {
playCountHashtable = new Properties();
playCountHashtable.load(is);
} finally {
is.close();
}
}
/**
* Writes {@link Player#playCountHashtable} to disk
* @throws IOException
*/
private void savePlayCountFile() throws IOException {
OutputStream os = new FileOutputStream(context.getExternalFilesDir(null) + "/"
+ Library.PLAY_COUNT_FILENAME);
try {
playCountHashtable.store(os, Library.PLAY_COUNT_FILE_COMMENT);
} finally {
os.close();
}
}
/**
* Record a play or skip for a certain song
* @param songId the ID of the song written in the {@link android.provider.MediaStore}
* @param skip Whether the song was skipped (true if skipped, false if played)
*/
public void logPlayCount(long songId, boolean skip) {
try {
if (playCountHashtable == null) {
openPlayCountFile();
}
final String originalValue = playCountHashtable.getProperty(Long.toString(songId));
int playCount = 0;
int skipCount = 0;
int playDate = 0;
if (originalValue != null && !originalValue.equals("")) {
final String[] originalValues = originalValue.split(",");
playCount = Integer.parseInt(originalValues[0]);
skipCount = Integer.parseInt(originalValues[1]);
// Preserve backwards compatibility with play count files written with older
// versions of Jockey that didn't save this data
if (originalValues.length > 2) {
playDate = Integer.parseInt(originalValues[2]);
}
}
if (skip) {
skipCount++;
} else {
playDate = (int) (System.currentTimeMillis() / 1000);
playCount++;
}
playCountHashtable.setProperty(
Long.toString(songId),
playCount + "," + skipCount + "," + playDate);
savePlayCountFile();
} catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
// ACCESSOR METHODS
public Bitmap getArt() {
return art;
}
public boolean isPlaying() {
return mediaPlayer.getState() == ManagedMediaPlayer.Status.STARTED;
}
public boolean isPreparing() {
return mediaPlayer.getState() == ManagedMediaPlayer.Status.PREPARING;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public List<Song> getQueue() {
if (shuffle) {
return queueShuffled;
}
return queue;
}
public int getQueuePosition() {
if (shuffle) {
return queuePositionShuffled;
}
return queuePosition;
}
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
/**
* Receives headphone connect and disconnect intents so that music may be paused when headphones
* are disconnected
*/
public static class HeadsetListener extends BroadcastReceiver {
Player instance;
public HeadsetListener(Player instance) {
this.instance = instance;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)
&& intent.getIntExtra("state", -1) == 0 && instance.isPlaying()) {
instance.pause();
instance.updateUi();
}
}
}
}
|
package gof.scut.common.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.util.Hashtable;
import gof.scut.cwh.models.adapter.PhoneListAdapter;
import gof.scut.wechatcontacts.R;
public class Utils {
// listView
public static void setListViewHeightBasedOnChildren(ListView listView) {
PhoneListAdapter listAdapter = (PhoneListAdapter)listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i,null, listView);
listItem.measure(0, 0); //View
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight;
listView.setLayoutParams(params);
}
public static boolean checkPhone(Context mContext,String phoneNumber) {
String telRegex = "[1]\\d{10}";//1100-911
String shortTelRegex = "^[0-9]{1,6}$";
if (TextUtils.isEmpty(phoneNumber))
return false;
if(! (phoneNumber.matches(telRegex) || phoneNumber.matches(shortTelRegex)) ){
Toast.makeText(mContext, R.string.error_phone_format, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/**
* create QRImage.
* @param imageView
* @param url
*/
public static void createQRImage(ImageView imageView,String url) {
int QR_WIDTH = 500;
int QR_HEIGHT = 500;
try {
//URL
if (url == null || "".equals(url) || url.length() < 1) {
return;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
//for
for (int y = 0; y < QR_HEIGHT; y++) {
for (int x = 0; x < QR_WIDTH; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * QR_WIDTH + x] = 0xff000000;
}else{
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
//ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
//ImageView
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
}
|
package xyz.gsora.toot;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class UserTimeline extends AppCompatActivity {
private static final String TAG = UserTimeline.class.getSimpleName();
RecyclerView statusList;
StatusesListAdapter adpt;
LinearLayoutManager llm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_timeline);
setTitle("Timeline");
Mocker m = new Mocker(this);
statusList = (RecyclerView) findViewById(R.id.statuses_list);
llm = new LinearLayoutManager(getApplicationContext());
CoolDivider dividerItemDecoration = new CoolDivider(statusList.getContext(),
llm.getOrientation(),
72,
R.id.avatar);
statusList.setLayoutManager(llm);
statusList.addItemDecoration(dividerItemDecoration);
adpt = new StatusesListAdapter(m.getMockStatuses(), this.getApplicationContext());
statusList.setAdapter(adpt);
}
}
|
package gov.nih.nci.security.ri.util;
import gov.nih.nci.security.ri.struts.Constants;
import gov.nih.nci.security.ri.valueObject.Employee;
import org.apache.log4j.Logger;
/**
* Utility methods for authorization.
*
* @author Brian Husted
*
*/
/**
* @author Brian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SecurityUtils implements Constants {
static final Logger log = Logger.getLogger(SecurityUtils.class.getName());
/**
* Returns the object id key for the protection element
* that represents the employee in the authorization database.
*
* @param empl
* @return the object id for this employee
*/
public static String getEmployeeObjectId(Employee empl) {
return "gov.nih.nci.security.ri.valueObject.Employee_"
+ empl.getEmployeeId();
}
/**
* Returns the object id of the protection element that represents
* the Action that is being requested for invocation.
* @param clazz
* @return
*/
public static String getObjectIdForSecureMethodAccess(Class clazz) {
return clazz.getName();
}
public static String getObjectIdForEmployeeProjecAccess(){
return "MODIFY_EMPLOYEE_PROJECT_ACTION";
}
/**
* Determines the employees User Group.
*
* @param empl
* @return
*/
public static String getEmployeeGroup(Employee empl) {
//If they are not a manager then assign to Employee Group
if (empl.getManagerStatus().equals(NO)) {
log.debug( "Employee status");
return Groups.EMPLOEE;
}
log.debug( "The BusinessUnit is: " + empl.getBusinessUnit() );
//Determine the type of Manager//////////////////////////
if (BUSINESS_DIVISION.equals(empl.getBusinessUnit())) {
return Groups.BUSINESS_MANAGER;
}
if (TECHNOLOGY_DIVISION.equals(empl.getBusinessUnit())) {
return Groups.TECHNICAL_MANAGER;
}
if (HR_DIVISION.equals(empl.getBusinessUnit())) {
return Groups.HR_MANAGER;
}
//DEFAULT TO EMPLOYEE
return Groups.EMPLOEE;
}
}
|
package com.exedio.cope.pattern;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import com.exedio.cope.AbstractLibTest;
import com.exedio.cope.DataField;
import com.exedio.cope.DateField;
import com.exedio.cope.Feature;
import com.exedio.cope.Model;
public final class MediaTest extends AbstractLibTest
{
static final Model MODEL = new Model(MediaItem.TYPE);
public MediaTest()
{
super(MODEL);
}
// TODO test various combinations of internal, external implicit, and external explicit source
protected MediaItem item;
@Override
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(item = new MediaItem("test media item"));
}
public void testData() throws IOException
{
assertEquals(0, data0.length);
assertEquals(4, data4.length);
assertEquals(6, data6.length);
assertEquals(8, data8.length);
assertEquals(20, data20.length);
assertEquals(21, data21.length);
assertEqualsUnmodifiable(Arrays.asList(new Feature[]{
item.TYPE.getThis(),
item.name,
item.file,
item.file.getBody(),
item.file.getContentType(),
item.file.getLastModified(),
item.image,
item.image.getBody(),
item.image.getContentType(),
item.image.getLastModified(),
item.photo,
item.photo.getBody(),
item.photo.getLastModified(),
item.foto,
item.nameServer,
}), item.TYPE.getFeatures());
// photo
assertEquals(true, item.photo.checkContentType("image/jpeg"));
assertEquals(false, item.photo.checkContentType("imaxge/jpeg"));
assertEquals(false, item.photo.checkContentType("image/jpxeg"));
assertEquals("image/jpeg", item.photo.getContentTypeDescription());
assertEquals(2000, item.photo.getMaximumLength());
final DataField photoBody = item.photo.getBody();
assertSame(item.TYPE, photoBody.getType());
assertSame("photoBody", photoBody.getName());
assertEquals(false, photoBody.isFinal());
assertEquals(false, photoBody.isMandatory());
assertEquals(2000, photoBody.getMaximumLength());
assertEqualsUnmodifiable(list(item.photo), photoBody.getPatterns());
assertSame(item.photo, Media.get(photoBody));
assertEquals(null, item.photo.getContentType());
final DateField photoLastModified = item.photo.getLastModified();
assertSame(item.TYPE, photoLastModified.getType());
assertEquals("photoLastModified", photoLastModified.getName());
assertEqualsUnmodifiable(list(item.photo), photoLastModified.getPatterns());
assertEquals(false, photoLastModified.isFinal());
assertEquals(false, photoLastModified.isMandatory());
assertEquals(null, photoLastModified.getImplicitUniqueConstraint());
assertSame(photoLastModified, item.photo.getIsNull());
assertPhotoNull();
item.setPhoto(stream(data4), "image/jpeg");
assertStreamClosed();
assertPhoto(data4);
item.setPhoto(stream(data6), "image/jpeg");
assertStreamClosed();
assertPhoto(data6);
try
{
item.setPhoto(stream(data4), "illegalContentType");
fail();
}
catch(IllegalContentTypeException e)
{
assertStreamClosed();
assertSame(item.photo, e.getFeature());
assertEquals(item, e.getItem());
assertEquals("illegalContentType", e.getContentType());
assertEquals("illegal content type 'illegalContentType' on " + item + " for MediaItem.photo, allowed is 'image/jpeg\' only.", e.getMessage());
assertPhoto(data6);
}
try
{
item.setPhoto(stream(data4), "image/png");
fail();
}
catch(IllegalContentTypeException e)
{
assertStreamClosed();
assertSame(item.photo, e.getFeature());
assertEquals(item, e.getItem());
assertEquals("image/png", e.getContentType());
assertEquals("illegal content type 'image/png' on " + item + " for MediaItem.photo, allowed is 'image/jpeg\' only.", e.getMessage());
assertPhoto(data6);
}
item.setPhoto((InputStream)null, null);
assertPhotoNull();
// foto
assertEquals(item.TYPE, item.foto.getType());
assertEquals("foto", item.foto.getName());
assertSame(item.photo, item.foto.getTarget());
try
{
new MediaRedirect(null);
fail();
}
catch(NullPointerException e)
{
assertEquals("target must not be null", e.getMessage());
}
assertEquals(null, item.getFotoContentType());
assertEquals(null, item.getFotoURL());
item.setPhoto(data4, "image/jpeg");
assertPhoto(data4);
assertEquals("image/jpeg", item.getFotoContentType());
assertEquals("media/MediaItem/foto/" + item.getCopeID() + ".jpg", item.getFotoURL());
item.setPhoto((InputStream)null, null);
assertPhotoNull();
assertEquals(null, item.getFotoContentType());
assertEquals(null, item.getFotoURL());
// nameServer
assertEquals(item.TYPE, item.nameServer.getType());
assertEquals("nameServer", item.nameServer.getName());
assertSame(item.name, item.nameServer.getSource());
assertEquals("text/plain", item.getNameServerContentType());
assertEquals("media/MediaItem/nameServer/" + item.getCopeID() + ".txt", item.getNameServerURL());
assertEquals(0, item.photo.noSuchItem.get());
assertEquals(0, item.photo.isNull.get());
assertEquals(0, item.photo.notModified.get());
assertEquals(0, item.photo.delivered.get());
item.photo.noSuchItem.increment();
assertEquals(1, item.photo.noSuchItem.get());
assertEquals(0, item.photo.isNull.get());
assertEquals(0, item.photo.notModified.get());
assertEquals(0, item.photo.delivered.get());
item.photo.noSuchItem.increment();
item.photo.isNull.increment();
item.photo.notModified.increment();
item.photo.delivered.increment();
assertEquals(2, item.photo.noSuchItem.get());
assertEquals(1, item.photo.isNull.get());
assertEquals(1, item.photo.notModified.get());
assertEquals(1, item.photo.delivered.get());
}
private void assertPhotoNull()
{
assertTrue(item.photo.isNull(item));
assertTrue(item.isPhotoNull());
assertEquals(null, item.getPhotoBody());
assertEquals(-1, item.getPhotoLength());
assertEquals(null, item.getPhotoContentType());
assertEquals(null, item.getPhotoURL());
}
private void assertPhoto(final byte[] expectedData)
{
assertTrue(!item.isPhotoNull());
assertData(expectedData, item.getPhotoBody());
assertEquals(expectedData.length, item.getPhotoLength());
assertEquals("image/jpeg", item.getPhotoContentType());
assertEquals("media/MediaItem/photo/" + item.getCopeID() + ".jpg", item.getPhotoURL());
}
}
|
package grakn.core.rocks;
import grakn.core.common.exception.ErrorMessage;
import grakn.core.common.exception.GraknException;
import grakn.core.common.iterator.ResourceIterator;
import grakn.core.concurrent.common.ConcurrentSet;
import grakn.core.concurrent.lock.ManagedReadWriteLock;
import grakn.core.graph.common.KeyGenerator;
import grakn.core.graph.common.Storage;
import org.rocksdb.AbstractImmutableNativeReference;
import org.rocksdb.OptimisticTransactionDB;
import org.rocksdb.OptimisticTransactionOptions;
import org.rocksdb.ReadOptions;
import org.rocksdb.RocksDBException;
import org.rocksdb.Snapshot;
import org.rocksdb.Transaction;
import org.rocksdb.WriteOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import static grakn.core.common.collection.Bytes.bytesHavePrefix;
import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_OPERATION;
import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE;
import static grakn.core.common.exception.ErrorMessage.Transaction.TRANSACTION_DATA_READ_VIOLATION;
import static grakn.core.common.exception.ErrorMessage.Transaction.TRANSACTION_SCHEMA_READ_VIOLATION;
public abstract class RocksStorage implements Storage {
private static final Logger LOG = LoggerFactory.getLogger(RocksStorage.class);
private static final byte[] EMPTY_ARRAY = new byte[]{};
protected final ConcurrentSet<RocksIterator<?>> iterators;
protected final Transaction storageTransaction;
protected final ReadOptions readOptions;
protected final boolean isReadOnly;
private final ConcurrentLinkedQueue<org.rocksdb.RocksIterator> recycled;
private final OptimisticTransactionOptions transactionOptions;
private final WriteOptions writeOptions;
private final AtomicBoolean isOpen;
private final Snapshot snapshot;
private RocksStorage(OptimisticTransactionDB rocksDB, boolean isReadOnly) {
this.isReadOnly = isReadOnly;
iterators = new ConcurrentSet<>();
recycled = new ConcurrentLinkedQueue<>();
writeOptions = new WriteOptions();
transactionOptions = new OptimisticTransactionOptions().setSetSnapshot(true);
storageTransaction = rocksDB.beginTransaction(writeOptions, transactionOptions);
snapshot = storageTransaction.getSnapshot();
readOptions = new ReadOptions().setSnapshot(snapshot);
isOpen = new AtomicBoolean(true);
}
@Override
public boolean isOpen() {
return isOpen.get();
}
@Override
public byte[] getLastKey(byte[] prefix) {
throw exception(ILLEGAL_OPERATION);
}
@Override
public void delete(byte[] key) {
throw exception(ILLEGAL_OPERATION);
}
@Override
public void put(byte[] key) {
put(key, EMPTY_ARRAY);
}
@Override
public void put(byte[] key, byte[] value) {
throw exception(ILLEGAL_OPERATION);
}
@Override
public void putUntracked(byte[] key) {
putUntracked(key, EMPTY_ARRAY);
}
@Override
public void putUntracked(byte[] key, byte[] value) {
throw exception(ILLEGAL_OPERATION);
}
@Override
public void mergeUntracked(byte[] key, byte[] value) {
throw exception(ILLEGAL_OPERATION);
}
org.rocksdb.RocksIterator getInternalRocksIterator() {
if (isReadOnly) {
org.rocksdb.RocksIterator iterator = recycled.poll();
if (iterator != null) return iterator;
}
return storageTransaction.getIterator(readOptions);
}
void recycle(org.rocksdb.RocksIterator rocksIterator) {
recycled.add(rocksIterator);
}
void remove(RocksIterator<?> iterator) {
iterators.remove(iterator);
}
@Override
public GraknException exception(ErrorMessage error) {
GraknException e = GraknException.of(error);
LOG.error(e.getMessage(), e);
return e;
}
@Override
public GraknException exception(Exception exception) {
GraknException e;
if (exception instanceof GraknException) e = (GraknException) exception;
else e = GraknException.of(exception);
LOG.error(e.getMessage(), e);
return e;
}
@Override
public void close() {
if (isOpen.compareAndSet(true, false)) {
iterators.parallelStream().forEach(RocksIterator::close);
recycled.forEach(AbstractImmutableNativeReference::close);
snapshot.close();
storageTransaction.close();
transactionOptions.close();
readOptions.close();
writeOptions.close();
}
}
static class Cache extends RocksStorage {
public Cache(OptimisticTransactionDB rocksDB) {
super(rocksDB, true);
}
@Override
public byte[] get(byte[] key) {
assert isOpen();
try {
return storageTransaction.get(readOptions, key);
} catch (RocksDBException e) {
throw exception(e);
}
}
@Override
public <G> ResourceIterator<G> iterate(byte[] key, BiFunction<byte[], byte[], G> constructor) {
assert isOpen();
RocksIterator<G> iterator = new RocksIterator<>(this, key, constructor);
iterators.add(iterator);
return iterator.onFinalise(iterator::close);
}
}
static abstract class TransactionBounded extends RocksStorage {
protected final ManagedReadWriteLock readWriteLock;
protected final RocksTransaction transaction;
TransactionBounded(OptimisticTransactionDB rocksDB, RocksTransaction transaction) {
super(rocksDB, transaction.type().isRead());
this.transaction = transaction;
readWriteLock = new ManagedReadWriteLock();
}
@Override
public byte[] get(byte[] key) {
assert isOpen();
try {
if (!isReadOnly) readWriteLock.lockRead();
return storageTransaction.get(readOptions, key);
} catch (RocksDBException | InterruptedException e) {
throw exception(e);
} finally {
if (!isReadOnly) readWriteLock.unlockRead();
}
}
@Override
public byte[] getLastKey(byte[] prefix) {
assert isOpen();
byte[] upperBound = Arrays.copyOf(prefix, prefix.length);
upperBound[upperBound.length - 1] = (byte) (upperBound[upperBound.length - 1] + 1);
assert upperBound[upperBound.length - 1] != Byte.MIN_VALUE;
try (org.rocksdb.RocksIterator iterator = getInternalRocksIterator()) {
iterator.seekForPrev(upperBound);
if (bytesHavePrefix(iterator.key(), prefix)) return iterator.key();
else return null;
}
}
@Override
public void delete(byte[] key) {
assert isOpen() && transaction.isOpen();
if (isReadOnly) {
if (transaction.isSchema()) throw exception(TRANSACTION_SCHEMA_READ_VIOLATION);
else if (transaction.isData()) throw exception(TRANSACTION_DATA_READ_VIOLATION);
else throw exception(ILLEGAL_STATE);
}
try {
readWriteLock.lockWrite();
storageTransaction.delete(key);
} catch (RocksDBException | InterruptedException e) {
throw exception(e);
} finally {
readWriteLock.unlockWrite();
}
}
@Override
public <G> ResourceIterator<G> iterate(byte[] key, BiFunction<byte[], byte[], G> constructor) {
assert isOpen();
RocksIterator<G> iterator = new RocksIterator<>(this, key, constructor);
iterators.add(iterator);
return iterator;
}
@Override
public GraknException exception(ErrorMessage errorMessage) {
transaction.close();
return super.exception(errorMessage);
}
@Override
public GraknException exception(Exception exception) {
transaction.close();
return super.exception(exception);
}
public void commit() throws RocksDBException {
// We disable RocksDB indexing of uncommitted writes, as we're only about to write and never again reading
// TODO: We should benchmark this
storageTransaction.disableIndexing();
storageTransaction.commit();
}
public void rollback() throws RocksDBException {
storageTransaction.rollback();
}
}
public static class Schema extends TransactionBounded implements Storage.Schema {
private final KeyGenerator.Schema schemaKeyGenerator;
public Schema(RocksDatabase database, RocksTransaction transaction) {
super(database.rocksSchema, transaction);
this.schemaKeyGenerator = database.schemaKeyGenerator();
}
@Override
public KeyGenerator.Schema schemaKeyGenerator() {
return schemaKeyGenerator;
}
@Override
public void put(byte[] key, byte[] value) {
assert isOpen() && !isReadOnly;
try {
if (transaction.isOpen()) readWriteLock.lockWrite();
storageTransaction.put(key, value);
} catch (RocksDBException | InterruptedException e) {
throw exception(e);
} finally {
if (transaction.isOpen()) readWriteLock.unlockWrite();
}
}
@Override
public void putUntracked(byte[] key, byte[] value) {
assert isOpen() && !isReadOnly;
try {
if (transaction.isOpen()) readWriteLock.lockWrite();
storageTransaction.putUntracked(key, value);
} catch (RocksDBException | InterruptedException e) {
throw exception(e);
} finally {
if (transaction.isOpen()) readWriteLock.unlockWrite();
}
}
}
public static class Data extends TransactionBounded implements Storage.Data {
private final KeyGenerator.Data dataKeyGenerator;
public Data(RocksDatabase database, RocksTransaction transaction) {
super(database.rocksData, transaction);
this.dataKeyGenerator = database.dataKeyGenerator();
}
@Override
public KeyGenerator.Data dataKeyGenerator() {
return dataKeyGenerator;
}
@Override
public void put(byte[] key, byte[] value) {
assert isOpen() && !isReadOnly;
try {
storageTransaction.put(key, value);
} catch (RocksDBException e) {
throw exception(e);
}
}
@Override
public void putUntracked(byte[] key, byte[] value) {
assert isOpen() && !isReadOnly;
try {
storageTransaction.putUntracked(key, value);
} catch (RocksDBException e) {
throw exception(e);
}
}
@Override
public void mergeUntracked(byte[] key, byte[] value) {
assert isOpen() && !isReadOnly;
try {
storageTransaction.mergeUntracked(key, value);
} catch (RocksDBException e) {
throw exception(e);
}
}
}
}
|
package beast.app.beauti;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import beast.app.draw.ListInputEditor;
import beast.app.draw.SmallButton;
import beast.app.util.FileDrop;
import beast.core.BEASTInterface;
import beast.core.Input;
import beast.core.MCMC;
import beast.core.State;
import beast.core.StateNode;
import beast.core.util.CompoundDistribution;
import beast.core.util.Log;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.FilteredAlignment;
import beast.evolution.alignment.Taxon;
import beast.evolution.branchratemodel.BranchRateModel;
import beast.evolution.likelihood.GenericTreeLikelihood;
import beast.evolution.sitemodel.SiteModel;
import beast.evolution.sitemodel.SiteModelInterface;
import beast.evolution.tree.TreeInterface;
// TODO: add useAmbiguities flag
// TODO: add warning if useAmbiguities=false and nr of patterns=1 (happens when all data is ambiguous)
public class AlignmentListInputEditor extends ListInputEditor {
private static final long serialVersionUID = 1L;
final static int NAME_COLUMN = 0;
final static int FILE_COLUMN = 1;
final static int TAXA_COLUMN = 2;
final static int SITES_COLUMN = 3;
final static int TYPE_COLUMN = 4;
final static int SITEMODEL_COLUMN = 5;
final static int CLOCKMODEL_COLUMN = 6;
final static int TREE_COLUMN = 7;
final static int USE_AMBIGUITIES_COLUMN = 8;
final static int NR_OF_COLUMNS = 9;
final static int STRUT_SIZE = 5;
/**
* alignments that form a partition. These can be FilteredAlignments *
*/
List<Alignment> alignments;
int partitionCount;
GenericTreeLikelihood[] likelihoods;
Object[][] tableData;
JTable table;
JTextField nameEditor;
List<JButton> linkButtons;
List<JButton> unlinkButtons;
JButton splitButton;
/**
* The button for deleting an alignment in the alignment list.
*/
JButton delButton;
protected SmallButton replaceButton;
private JScrollPane scrollPane;
public AlignmentListInputEditor(BeautiDoc doc) {
super(doc);
}
@Override
public Class<?> type() {
return List.class;
}
@Override
public Class<?> baseType() {
return Alignment.class;
}
@Override
public Class<?>[] types() {
Class<?>[] types = new Class[2];
types[0] = List.class;
types[1] = Alignment.class;
return types;
}
@Override
@SuppressWarnings("unchecked")
public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) {
this.itemNr = itemNr;
if (input.get() instanceof List) {
alignments = (List<Alignment>) input.get();
} else {
// we just have a single Alignment
alignments = new ArrayList<>();
alignments.add((Alignment) input.get());
}
linkButtons = new ArrayList<>();
unlinkButtons = new ArrayList<>();
partitionCount = alignments.size();
// override BoxLayout in superclass
setLayout(new BorderLayout());
add(createLinkButtons(), BorderLayout.NORTH);
add(createListBox(), BorderLayout.CENTER);
//Box box = Box.createVerticalBox();
//box.add(Box.createVerticalStrut(STRUT_SIZE));
//box.add(createLinkButtons());
//box.add(Box.createVerticalStrut(STRUT_SIZE));
//box.add(createListBox());
//box.add(Box.createVerticalStrut(STRUT_SIZE));
//box.add(Box.createVerticalGlue());
//add(box, BorderLayout.CENTER);
Color focusColor = UIManager.getColor("Focus.color");
Border focusBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, focusColor);
new FileDrop(null, scrollPane, focusBorder, new FileDrop.Listener() {
@Override
public void filesDropped(java.io.File[] files) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
addItem(files);
}
});
} // end filesDropped
}); // end FileDrop.Listener
// this should place the add/remove/split buttons at the bottom of the window.
add(createAddRemoveSplitButtons(), BorderLayout.SOUTH);
updateStatus();
}
/**
* Creates the link/unlink button component
* @return a box containing three link/unlink button pairs.
*/
private JComponent createLinkButtons() {
Box box = Box.createHorizontalBox();
addLinkUnlinkPair(box, "Site Models");
box.add(Box.createHorizontalStrut(STRUT_SIZE));
addLinkUnlinkPair(box, "Clock Models");
box.add(Box.createHorizontalStrut(STRUT_SIZE));
addLinkUnlinkPair(box, "Trees");
box.add(Box.createHorizontalGlue());
return box;
}
private JComponent createAddRemoveSplitButtons() {
Box buttonBox = Box.createHorizontalBox();
addButton = new SmallButton("+", true, SmallButton.ButtonType.square);
addButton.setName("+");
addButton.setToolTipText("Add item to the list");
addButton.addActionListener(e -> addItem());
buttonBox.add(Box.createHorizontalStrut(STRUT_SIZE));
buttonBox.add(addButton);
buttonBox.add(Box.createHorizontalStrut(STRUT_SIZE));
delButton = new SmallButton("-", true, SmallButton.ButtonType.square);
delButton.setName("-");
delButton.setToolTipText("Delete selected items from the list");
delButton.addActionListener(e -> {
if (doc.hasLinkedAtLeastOnce) {
JOptionPane.showMessageDialog(null, "Cannot delete partition while parameters are linked");
return;
}
delItem();
});
buttonBox.add(delButton);
buttonBox.add(Box.createHorizontalStrut(STRUT_SIZE));
replaceButton = new SmallButton("r", true, SmallButton.ButtonType.square);
replaceButton.setName("r");
replaceButton.setToolTipText("Replace alignment by one loaded from file");
replaceButton.addActionListener(e -> replaceItem());
buttonBox.add(Box.createHorizontalStrut(STRUT_SIZE));
buttonBox.add(replaceButton);
buttonBox.add(Box.createHorizontalStrut(STRUT_SIZE));
splitButton = new JButton("Split");
splitButton.setName("Split");
splitButton.setToolTipText("Split alignment into partitions, for example, codon positions");
splitButton.addActionListener(e -> splitItem());
buttonBox.add(splitButton);
buttonBox.add(Box.createHorizontalGlue());
return buttonBox;
}
/**
* This method just adds the two buttons (with add()) and does not add any glue or struts before or after.
* @param box
* @param label
*/
private void addLinkUnlinkPair(Box box, String label) {
//JLabel label = new JLabel(label+":");
//box.add(label);
JButton linkSModelButton = new JButton("Link " + label);
linkSModelButton.setName("Link " + label);
linkSModelButton.addActionListener(e -> {
JButton button = (JButton) e.getSource();
link(columnLabelToNr(button.getText()));
table.repaint();
});
box.add(linkSModelButton);
linkSModelButton.setEnabled(!getDoc().hasLinkedAtLeastOnce);
JButton unlinkSModelButton = new JButton("Unlink " + label);
unlinkSModelButton.setName("Unlink " + label);
unlinkSModelButton.addActionListener(e -> {
JButton button = (JButton) e.getSource();
unlink(columnLabelToNr(button.getText()));
table.repaint();
});
box.add(unlinkSModelButton);
unlinkSModelButton.setEnabled(!getDoc().hasLinkedAtLeastOnce);
linkButtons.add(linkSModelButton);
unlinkButtons.add(unlinkSModelButton);
}
private int columnLabelToNr(String column) {
int columnNr;
if (column.contains("Tree")) {
columnNr = TREE_COLUMN;
} else if (column.contains("Clock")) {
columnNr = CLOCKMODEL_COLUMN;
} else {
columnNr = SITEMODEL_COLUMN;
}
return columnNr;
}
private void link(int columnNr) {
int[] selected = getTableRowSelection();
// do the actual linking
for (int i = 1; i < selected.length; i++) {
int rowNr = selected[i];
Object old = tableData[rowNr][columnNr];
tableData[rowNr][columnNr] = tableData[selected[0]][columnNr];
try {
updateModel(columnNr, rowNr);
} catch (Exception ex) {
Log.warning.println(ex.getMessage());
// unlink if we could not link
tableData[rowNr][columnNr] = old;
try {
updateModel(columnNr, rowNr);
} catch (Exception ex2) {
// ignore
}
}
}
}
private void unlink(int columnNr) {
int[] selected = getTableRowSelection();
for (int i = 1; i < selected.length; i++) {
int rowNr = selected[i];
tableData[rowNr][columnNr] = getDoc().partitionNames.get(rowNr).partition;
try {
updateModel(columnNr, rowNr);
} catch (Exception ex) {
Log.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
int[] getTableRowSelection() {
return table.getSelectedRows();
}
/** set partition of type columnNr to partition model nr rowNr **/
void updateModel(int columnNr, int rowNr) {
Log.warning.println("updateModel: " + rowNr + " " + columnNr + " " + table.getSelectedRow() + " "
+ table.getSelectedColumn());
for (int i = 0; i < partitionCount; i++) {
Log.warning.println(i + " " + tableData[i][0] + " " + tableData[i][SITEMODEL_COLUMN] + " "
+ tableData[i][CLOCKMODEL_COLUMN] + " " + tableData[i][TREE_COLUMN]);
}
getDoc();
String partition = (String) tableData[rowNr][columnNr];
// check if partition needs renaming
String oldName = null;
boolean isRenaming = false;
try {
switch (columnNr) {
case SITEMODEL_COLUMN:
if (!doc.pluginmap.containsKey("SiteModel.s:" + partition)) {
String id = ((BEASTInterface)likelihoods[rowNr].siteModelInput.get()).getID();
oldName = BeautiDoc.parsePartition(id);
doc.renamePartition(BeautiDoc.SITEMODEL_PARTITION, oldName, partition);
isRenaming = true;
}
break;
case CLOCKMODEL_COLUMN: {
String id = likelihoods[rowNr].branchRateModelInput.get().getID();
String clockModelName = id.substring(0, id.indexOf('.')) + ".c:" + partition;
if (!doc.pluginmap.containsKey(clockModelName)) {
oldName = BeautiDoc.parsePartition(id);
doc.renamePartition(BeautiDoc.CLOCKMODEL_PARTITION, oldName, partition);
isRenaming = true;
}
}
break;
case TREE_COLUMN:
if (!doc.pluginmap.containsKey("Tree.t:" + partition)) {
String id = likelihoods[rowNr].treeInput.get().getID();
oldName = BeautiDoc.parsePartition(id);
doc.renamePartition(BeautiDoc.TREEMODEL_PARTITION, oldName, partition);
isRenaming = true;
}
break;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Cannot rename item: " + e.getMessage());
tableData[rowNr][columnNr] = oldName;
return;
}
if (isRenaming) {
doc.determinePartitions();
initTableData();
setUpComboBoxes();
table.repaint();
return;
}
int partitionID = BeautiDoc.ALIGNMENT_PARTITION;
switch (columnNr) {
case SITEMODEL_COLUMN:
partitionID = BeautiDoc.SITEMODEL_PARTITION;
break;
case CLOCKMODEL_COLUMN:
partitionID = BeautiDoc.CLOCKMODEL_PARTITION;
break;
case TREE_COLUMN:
partitionID = BeautiDoc.TREEMODEL_PARTITION;
break;
}
int partitionNr = doc.getPartitionNr(partition, partitionID);
GenericTreeLikelihood treeLikelihood = null;
if (partitionNr >= 0) {
// we ar linking
treeLikelihood = likelihoods[partitionNr];
}
// (TreeLikelihood) doc.pluginmap.get("treeLikelihood." +
// tableData[rowNr][NAME_COLUMN]);
boolean needsRePartition = false;
PartitionContext oldContext = new PartitionContext(this.likelihoods[rowNr]);
switch (columnNr) {
case SITEMODEL_COLUMN: {
SiteModelInterface siteModel = null;
if (treeLikelihood != null) { // getDoc().getPartitionNr(partition,
// BeautiDoc.SITEMODEL_PARTITION) !=
// rowNr) {
siteModel = treeLikelihood.siteModelInput.get();
} else {
siteModel = (SiteModel) doc.pluginmap.get("SiteModel.s:" + partition);
if (siteModel != likelihoods[rowNr].siteModelInput.get()) {
PartitionContext context = getPartitionContext(rowNr);
try {
siteModel = (SiteModel.Base) BeautiDoc.deepCopyPlugin((BEASTInterface) likelihoods[rowNr].siteModelInput.get(),
likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(this, "Could not clone site model: " + e.getMessage());
return;
}
}
}
SiteModelInterface target = this.likelihoods[rowNr].siteModelInput.get();
if (target instanceof SiteModel.Base && siteModel instanceof SiteModel.Base) {
if (!((SiteModel.Base)target).substModelInput.canSetValue(((SiteModel.Base)siteModel).substModelInput.get(), (SiteModel.Base) target)) {
throw new IllegalArgumentException("Cannot link site model: substitution models are incompatible");
}
} else {
throw new IllegalArgumentException("Don't know how to link this site model");
}
needsRePartition = (this.likelihoods[rowNr].siteModelInput.get() != siteModel);
this.likelihoods[rowNr].siteModelInput.setValue(siteModel, this.likelihoods[rowNr]);
partition = ((BEASTInterface)likelihoods[rowNr].siteModelInput.get()).getID();
partition = BeautiDoc.parsePartition(partition);
getDoc().setCurrentPartition(BeautiDoc.SITEMODEL_PARTITION, rowNr, partition);
}
break;
case CLOCKMODEL_COLUMN: {
BranchRateModel clockModel = null;
if (treeLikelihood != null) { // getDoc().getPartitionNr(partition,
// BeautiDoc.CLOCKMODEL_PARTITION)
// != rowNr) {
clockModel = treeLikelihood.branchRateModelInput.get();
} else {
clockModel = getDoc().getClockModel(partition);
if (clockModel != likelihoods[rowNr].branchRateModelInput.get()) {
PartitionContext context = getPartitionContext(rowNr);
try {
clockModel = (BranchRateModel) BeautiDoc.deepCopyPlugin(likelihoods[rowNr].branchRateModelInput.get(),
likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(this, "Could not clone clock model: " + e.getMessage());
return;
}
}
}
// make sure that *if* the clock model has a tree as input, it is
// the same as
// for the likelihood
TreeInterface tree = null;
for (Input<?> input : ((BEASTInterface) clockModel).listInputs()) {
if (input.getName().equals("tree")) {
tree = (TreeInterface) input.get();
}
}
if (tree != null && tree != this.likelihoods[rowNr].treeInput.get()) {
JOptionPane.showMessageDialog(this, "Cannot link clock model with different trees");
throw new IllegalArgumentException("Cannot link clock model with different trees");
}
needsRePartition = (this.likelihoods[rowNr].branchRateModelInput.get() != clockModel);
this.likelihoods[rowNr].branchRateModelInput.setValue(clockModel, this.likelihoods[rowNr]);
partition = likelihoods[rowNr].branchRateModelInput.get().getID();
partition = BeautiDoc.parsePartition(partition);
getDoc().setCurrentPartition(BeautiDoc.CLOCKMODEL_PARTITION, rowNr, partition);
}
break;
case TREE_COLUMN: {
TreeInterface tree = null;
if (treeLikelihood != null) { // getDoc().getPartitionNr(partition,
// BeautiDoc.TREEMODEL_PARTITION) !=
// rowNr) {
tree = treeLikelihood.treeInput.get();
} else {
tree = (TreeInterface) doc.pluginmap.get("Tree.t:" + partition);
if (tree != likelihoods[rowNr].treeInput.get()) {
PartitionContext context = getPartitionContext(rowNr);
try {
tree = (TreeInterface) BeautiDoc.deepCopyPlugin((BEASTInterface) likelihoods[rowNr].treeInput.get(), likelihoods[rowNr],
(MCMC) doc.mcmc.get(), oldContext, context, doc, null);
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(this, "Could not clone tree model: " + e.getMessage());
return;
}
State state = ((MCMC) doc.mcmc.get()).startStateInput.get();
List<StateNode> stateNodes = new ArrayList<>();
stateNodes.addAll(state.stateNodeInput.get());
for (StateNode s : stateNodes) {
if (s.getID().endsWith(".t:" + oldContext.tree) && !(s instanceof TreeInterface)) {
try {
@SuppressWarnings("unused")
StateNode copy = (StateNode) BeautiDoc.deepCopyPlugin(s, likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(this, "Could not clone tree model: " + e.getMessage());
return;
}
}
}
}
}
// sanity check: make sure taxon sets are compatible
Taxon.assertSameTaxa(tree.getID(), tree.getTaxonset().getTaxaNames(),
likelihoods[rowNr].dataInput.get().getID(), likelihoods[rowNr].dataInput.get().getTaxaNames());
needsRePartition = (this.likelihoods[rowNr].treeInput.get() != tree);
Log.warning.println("needsRePartition = " + needsRePartition);
if (needsRePartition) {
TreeInterface oldTree = this.likelihoods[rowNr].treeInput.get();
List<TreeInterface> tModels = new ArrayList<>();
for (GenericTreeLikelihood likelihood : likelihoods) {
if (likelihood.treeInput.get() == oldTree) {
tModels.add(likelihood.treeInput.get());
}
}
if (tModels.size() == 1) {
// remove old tree from model
((BEASTInterface)oldTree).setInputValue("estimate", false);
// use toArray to prevent ConcurrentModificationException
for (Object beastObject : BEASTInterface.getOutputs(oldTree).toArray()) { //.toArray(new BEASTInterface[0])) {
for (Input<?> input : ((BEASTInterface)beastObject).listInputs()) {
try {
if (input.get() == oldTree) {
if (input.getRule() != Input.Validate.REQUIRED) {
input.setValue(tree/*null*/, (BEASTInterface) beastObject);
//} else {
//input.setValue(tree, (BEASTInterface) beastObject);
}
} else if (input.get() instanceof List) {
@SuppressWarnings("unchecked")
List<TreeInterface> list = (List<TreeInterface>) input.get();
if (list.contains(oldTree)) { // && input.getRule() != Validate.REQUIRED) {
list.remove(oldTree);
if (!list.contains(tree)) {
list.add(tree);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
likelihoods[rowNr].treeInput.setValue(tree, likelihoods[rowNr]);
// TreeDistribution d = getDoc().getTreePrior(partition);
// CompoundDistribution prior = (CompoundDistribution)
// doc.pluginmap.get("prior");
// if (!getDoc().posteriorPredecessors.contains(d)) {
// prior.pDistributions.setValue(d, prior);
partition = likelihoods[rowNr].treeInput.get().getID();
partition = BeautiDoc.parsePartition(partition);
getDoc().setCurrentPartition(BeautiDoc.TREEMODEL_PARTITION, rowNr, partition);
}
}
tableData[rowNr][columnNr] = partition;
if (needsRePartition) {
List<BeautiSubTemplate> templates = new ArrayList<>();
templates.add(doc.beautiConfig.partitionTemplate.get());
templates.addAll(doc.beautiConfig.subTemplates);
// keep applying rules till model does not change
doc.setUpActivePlugins();
int n;
do {
n = doc.posteriorPredecessors.size();
doc.applyBeautiRules(templates, false, oldContext);
doc.setUpActivePlugins();
} while (n != doc.posteriorPredecessors.size());
doc.determinePartitions();
}
if (treeLikelihood == null) {
initTableData();
setUpComboBoxes();
}
updateStatus();
}
private PartitionContext getPartitionContext(int rowNr) {
PartitionContext context = new PartitionContext(
tableData[rowNr][NAME_COLUMN].toString(),
tableData[rowNr][SITEMODEL_COLUMN].toString(),
tableData[rowNr][CLOCKMODEL_COLUMN].toString(),
tableData[rowNr][TREE_COLUMN].toString());
return context;
}
@Override
protected void addInputLabel() {
}
void initTableData() {
this.likelihoods = new GenericTreeLikelihood[partitionCount];
if (tableData == null) {
tableData = new Object[partitionCount][NR_OF_COLUMNS];
}
CompoundDistribution likelihoods = (CompoundDistribution) doc.pluginmap.get("likelihood");
for (int i = 0; i < partitionCount; i++) {
Alignment data = alignments.get(i);
// partition name
tableData[i][NAME_COLUMN] = data;
// alignment name
if (data instanceof FilteredAlignment) {
tableData[i][FILE_COLUMN] = ((FilteredAlignment) data).alignmentInput.get();
} else {
tableData[i][FILE_COLUMN] = data;
}
// # taxa
tableData[i][TAXA_COLUMN] = data.getTaxonCount();
// # sites
tableData[i][SITES_COLUMN] = data.getSiteCount();
// Data type
tableData[i][TYPE_COLUMN] = data.getDataType();
// site model
GenericTreeLikelihood likelihood = (GenericTreeLikelihood) likelihoods.pDistributions.get().get(i);
assert (likelihood != null);
this.likelihoods[i] = likelihood;
tableData[i][SITEMODEL_COLUMN] = getPartition(likelihood.siteModelInput);
// clock model
tableData[i][CLOCKMODEL_COLUMN] = getPartition(likelihood.branchRateModelInput);
// tree
tableData[i][TREE_COLUMN] = getPartition(likelihood.treeInput);
// useAmbiguities
tableData[i][USE_AMBIGUITIES_COLUMN] = null;
try {
if (hasUseAmbiguitiesInput(i)) {
tableData[i][USE_AMBIGUITIES_COLUMN] = likelihood.getInputValue("useAmbiguities");
}
} catch (Exception e) {
// ignore
}
}
}
private boolean hasUseAmbiguitiesInput(int i) {
try {
for (Input<?> input : likelihoods[i].listInputs()) {
if (input.getName().equals("useAmbiguities")) {
return true;
}
}
} catch (Exception e) {
// ignore
}
return false;
}
private String getPartition(Input<?> input) {
BEASTInterface beastObject = (BEASTInterface) input.get();
String id = beastObject.getID();
String partition = BeautiDoc.parsePartition(id);
return partition;
}
protected Component createListBox() {
String[] columnData = new String[] { "Name", "File", "Taxa", "Sites", "Data Type", "Site Model", "Clock Model",
"Tree", "Ambiguities" };
initTableData();
// set up table.
// special features: background shading of rows
// custom editor allowing only Date column to be edited.
table = new JTable(tableData, columnData) {
private static final long serialVersionUID = 1L;
// method that induces table row shading
@Override
public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
// even index, selected or not selected
if (isCellSelected(Index_row, Index_col)) {
comp.setBackground(Color.gray);
} else if (Index_row % 2 == 0 && !isCellSelected(Index_row, Index_col)) {
comp.setBackground(new Color(237, 243, 255));
} else {
comp.setBackground(Color.white);
}
JComponent jcomp = (JComponent) comp;
switch (Index_col) {
case NAME_COLUMN:
case CLOCKMODEL_COLUMN:
case TREE_COLUMN:
case SITEMODEL_COLUMN:
jcomp.setToolTipText("Set " + table.getColumnName(Index_col).toLowerCase() + " for this partition");
break;
case FILE_COLUMN:
case TAXA_COLUMN:
case SITES_COLUMN:
case TYPE_COLUMN:
jcomp.setToolTipText("Report " + table.getColumnName(Index_col).toLowerCase() + " for this partition");
break;
case USE_AMBIGUITIES_COLUMN:
jcomp.setToolTipText("<html>Flag whether to use ambiguities.<br>" +
"If not set, the treelikelihood will treat ambiguities in the<br>" +
"data as unknowns<br>" +
"If set, the treelikelihood will use ambiguities as equally<br>" +
"likely values for the tips.<br>" +
"This will make the computation twice as slow.</html>");
break;
default:
jcomp.setToolTipText(null);
}
updateStatus();
return comp;
}
};
int size = table.getFont().getSize();
table.setRowHeight(25 * size/13);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.setName("alignmenttable");
setUpComboBoxes();
TableColumn col = table.getColumnModel().getColumn(NAME_COLUMN);
nameEditor = new JTextField();
nameEditor.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
processPartitionName();
}
@Override
public void insertUpdate(DocumentEvent e) {
processPartitionName();
}
@Override
public void changedUpdate(DocumentEvent e) {
processPartitionName();
}
});
col.setCellEditor(new DefaultCellEditor(nameEditor));
// // set up editor that makes sure only doubles are accepted as entry
// // and only the Date column is editable.
table.setDefaultEditor(Object.class, new TableCellEditor() {
JTextField m_textField = new JTextField();
int m_iRow, m_iCol;
@Override
public boolean stopCellEditing() {
//Log.warning.println("stopCellEditing()");
table.removeEditor();
String text = m_textField.getText();
try {
Double.parseDouble(text);
} catch (Exception e) {
return false;
}
tableData[m_iRow][m_iCol] = text;
return true;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
//Log.warning.println("isCellEditable()");
return table.getSelectedColumn() == 0;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowNr,
int colNr) {
return null;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
});
// show alignment viewer when double clicking a row
table.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
try {
int alignmemt = table.rowAtPoint(e.getPoint());
Alignment alignment = alignments.get(alignmemt);
int best = 0;
BeautiAlignmentProvider provider = null;
for (BeautiAlignmentProvider provider2 : doc.beautiConfig.alignmentProvider) {
int match = provider2.matches(alignment);
if (match > best) {
best = match;
provider = provider2;
}
}
provider.editAlignment(alignment, doc);
} catch (Exception e1) {
e1.printStackTrace();
}
updateStatus();
} else if (e.getButton() == e.BUTTON3) {
int alignmemt = table.rowAtPoint(e.getPoint());
Alignment alignment = alignments.get(alignmemt);
int result = JOptionPane.showConfirmDialog(null, "Do you want to replace alignment " + alignment.getID());
if (result == JOptionPane.YES_OPTION) {
replaceItem(alignment);
}
}
}
});
scrollPane = new JScrollPane(table);
int rowsToDisplay = 3;
Dimension d = table.getPreferredSize();
scrollPane.setPreferredSize(
new Dimension(d.width,table.getRowHeight()*rowsToDisplay+table.getTableHeader().getHeight()));
return scrollPane;
} // createListBox
void setUpComboBoxes() {
// set up comboboxes
@SuppressWarnings("unchecked")
Set<String>[] partitionNames = new HashSet[3];
for (int i = 0; i < 3; i++) {
partitionNames[i] = new HashSet<>();
}
for (int i = 0; i < partitionCount; i++) {
partitionNames[0].add(((BEASTInterface) likelihoods[i].siteModelInput.get()).getID());
partitionNames[1].add(likelihoods[i].branchRateModelInput.get().getID());
partitionNames[2].add(likelihoods[i].treeInput.get().getID());
}
String[][] partitionNameStrings = new String[3][];
for (int i = 0; i < 3; i++) {
partitionNameStrings[i] = partitionNames[i].toArray(new String[0]);
}
for (int j = 0; j < 3; j++) {
for (int i = 0; i < partitionNameStrings[j].length; i++) {
partitionNameStrings[j][i] = BeautiDoc.parsePartition(partitionNameStrings[j][i]);
}
}
TableColumn col = table.getColumnModel().getColumn(SITEMODEL_COLUMN);
JComboBox<String> siteModelComboBox = new JComboBox<>(partitionNameStrings[0]);
siteModelComboBox.setEditable(true);
siteModelComboBox.addActionListener(new ComboActionListener(SITEMODEL_COLUMN));
col.setCellEditor(new DefaultCellEditor(siteModelComboBox));
// If the cell should appear like a combobox in its
// non-editing state, also set the combobox renderer
col.setCellRenderer(new MyComboBoxRenderer(partitionNameStrings[0]));
col = table.getColumnModel().getColumn(CLOCKMODEL_COLUMN);
JComboBox<String> clockModelComboBox = new JComboBox<>(partitionNameStrings[1]);
clockModelComboBox.setEditable(true);
clockModelComboBox.addActionListener(new ComboActionListener(CLOCKMODEL_COLUMN));
col.setCellEditor(new DefaultCellEditor(clockModelComboBox));
col.setCellRenderer(new MyComboBoxRenderer(partitionNameStrings[1]));
col = table.getColumnModel().getColumn(TREE_COLUMN);
JComboBox<String> treeComboBox = new JComboBox<>(partitionNameStrings[2]);
treeComboBox.setEditable(true);
treeComboBox.addActionListener(new ComboActionListener(TREE_COLUMN));
col.setCellEditor(new DefaultCellEditor(treeComboBox));
col.setCellRenderer(new MyComboBoxRenderer(partitionNameStrings[2]));
col = table.getColumnModel().getColumn(TAXA_COLUMN);
col.setPreferredWidth(30);
col = table.getColumnModel().getColumn(SITES_COLUMN);
col.setPreferredWidth(30);
col = table.getColumnModel().getColumn(USE_AMBIGUITIES_COLUMN);
JCheckBox checkBox = new JCheckBox();
checkBox.addActionListener(e -> {
if (table.getSelectedRow() >= 0 && table.getSelectedColumn() >= 0) {
Log.warning.println(" " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
try {
int row = table.getSelectedRow();
if (hasUseAmbiguitiesInput(row)) {
likelihoods[row].setInputValue("useAmbiguities", checkBox.isSelected());
tableData[row][USE_AMBIGUITIES_COLUMN] = checkBox.isSelected();
} else {
if (checkBox.isSelected()) {
checkBox.setSelected(false);
}
}
} catch (Exception ex) {
// TODO: handle exception
}
});
col.setCellEditor(new DefaultCellEditor(checkBox));
col.setCellRenderer(new MyCheckBoxRenderer());
col.setPreferredWidth(20);
col.setMaxWidth(20);
}
void processPartitionName() {
Log.warning.println("processPartitionName");
Log.warning.println(table.getSelectedColumn() + " " + table.getSelectedRow());
String oldName = tableData[table.getSelectedRow()][table.getSelectedColumn()].toString();
String newName = nameEditor.getText();
if (!oldName.equals(newName) && newName.indexOf(".") >= 0) {
// prevent full stops to be used in IDs
newName = newName.replaceAll("\\.", "");
table.setValueAt(newName, table.getSelectedRow(), table.getSelectedColumn());
table.repaint();
}
if (!oldName.equals(newName)) {
try {
int partitionID = -2;
switch (table.getSelectedColumn()) {
case NAME_COLUMN:
partitionID = BeautiDoc.ALIGNMENT_PARTITION;
break;
case SITEMODEL_COLUMN:
partitionID = BeautiDoc.SITEMODEL_PARTITION;
break;
case CLOCKMODEL_COLUMN:
partitionID = BeautiDoc.CLOCKMODEL_PARTITION;
break;
case TREE_COLUMN:
partitionID = BeautiDoc.TREEMODEL_PARTITION;
break;
default:
throw new IllegalArgumentException("Cannot rename item in column");
}
getDoc().renamePartition(partitionID, oldName, newName);
table.setValueAt(newName, table.getSelectedRow(), table.getSelectedColumn());
setUpComboBoxes();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Renaming failed: " + e.getMessage());
}
}
// debugging code:
//for (int i = 0; i < partitionCount; i++) {
// Log.warning.println(i + " " + tableData[i][0]);
}
class ComboActionListener implements ActionListener {
int m_nColumn;
public ComboActionListener(int columnNr) {
m_nColumn = columnNr;
}
@Override
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
Log.warning.println("actionPerformed ");
Log.warning.println(table.getSelectedRow() + " " + table.getSelectedColumn());
if (table.getSelectedRow() >= 0 && table.getSelectedColumn() >= 0) {
Log.warning.println(" " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
for (int i = 0; i < partitionCount; i++) {
try {
updateModel(m_nColumn, i);
} catch (Exception ex) {
Log.warning.println(ex.getMessage());
}
}
}
}
public class MyComboBoxRenderer extends JComboBox<String> implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyComboBoxRenderer(String[] items) {
super(items);
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (isSelected) {
// setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
// Select the current value
setSelectedItem(value);
return this;
}
}
public class MyCheckBoxRenderer extends JCheckBox implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyCheckBoxRenderer() {
super();
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (hasUseAmbiguitiesInput(row)) {
if (isSelected) {
// setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setEnabled(true);
setSelected((Boolean) value);
} else {
setEnabled(false);
}
return this;
}
}
@Override
protected void addSingleItem(BEASTInterface beastObject) {
initTableData();
repaint();
}
@Override
protected void addItem() {
addItem(null);
} // addItem
private void addItem(File[] fileArray) {
List<BEASTInterface> beastObjects = doc.beautiConfig.selectAlignments(doc, this, fileArray);
// Component c = this;
if (beastObjects != null) {
refreshPanel();
}
}
void delItem() {
int[] selected = getTableRowSelection();
if (selected.length == 0) {
JOptionPane.showMessageDialog(this, "Select partitions to delete, before hitting the delete button");
}
// do the actual deleting
for (int i = selected.length - 1; i >= 0; i
int rowNr = selected[i];
// before deleting, unlink site model, clock model and tree
// check whether any of the models are linked
BranchRateModel.Base clockModel = likelihoods[rowNr].branchRateModelInput.get();
SiteModelInterface siteModel = likelihoods[rowNr].siteModelInput.get();
TreeInterface tree = likelihoods[rowNr].treeInput.get();
List<GenericTreeLikelihood> cModels = new ArrayList<>();
List<GenericTreeLikelihood> models = new ArrayList<>();
List<GenericTreeLikelihood> tModels = new ArrayList<>();
for (GenericTreeLikelihood likelihood : likelihoods) {
if (likelihood != likelihoods[rowNr]) {
if (likelihood.branchRateModelInput.get() == clockModel) {
cModels.add(likelihood);
}
if (likelihood.siteModelInput.get() == siteModel) {
models.add(likelihood);
}
if (likelihood.treeInput.get() == tree) {
tModels.add(likelihood);
}
}
}
try {
if (cModels.size() > 0) {
// clock model is linked, so we need to unlink
if (doc.getPartitionNr(clockModel) != rowNr) {
tableData[rowNr][CLOCKMODEL_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
} else {
int freePartition = doc.getPartitionNr(cModels.get(0));
tableData[rowNr][CLOCKMODEL_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
}
updateModel(CLOCKMODEL_COLUMN, rowNr);
}
if (models.size() > 0) {
// site model is linked, so we need to unlink
if (doc.getPartitionNr((BEASTInterface) siteModel) != rowNr) {
tableData[rowNr][SITEMODEL_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
} else {
int freePartition = doc.getPartitionNr(models.get(0));
tableData[rowNr][SITEMODEL_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
}
updateModel(SITEMODEL_COLUMN, rowNr);
}
if (tModels.size() > 0) {
// tree is linked, so we need to unlink
if (doc.getPartitionNr((BEASTInterface) tree) != rowNr) {
tableData[rowNr][TREE_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
} else {
int freePartition = doc.getPartitionNr(tModels.get(0));
tableData[rowNr][TREE_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
}
updateModel(TREE_COLUMN, rowNr);
}
getDoc().delAlignmentWithSubnet(alignments.get(rowNr));
alignments.remove(rowNr);
// remove deleted likelihood from likelihoods array
GenericTreeLikelihood[] tmp = new GenericTreeLikelihood[likelihoods.length - 1];
int k = 0;
for (int j = 0; j < likelihoods.length; j++) {
if (j != rowNr) {
tmp[k] = likelihoods[j];
k++;
}
}
likelihoods = tmp;
partitionCount
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Deletion failed: " + e.getMessage());
e.printStackTrace();
}
}
refreshPanel();
} // delItem
void replaceItem() {
int [] selected = getTableRowSelection();
if (selected.length != 1) {
// don't know how to replace multiple alignments at the same time
// should never get here (button is disabled)
return;
}
Alignment alignment = alignments.get(selected[0]);
replaceItem(alignment);
}
private void replaceItem(Alignment alignment) {
BeautiAlignmentProvider provider = new BeautiAlignmentProvider();
List<BEASTInterface> list = provider.getAlignments(doc);
List<Alignment> alignments = new ArrayList<>();
for (BEASTInterface o : list) {
if (o instanceof Alignment) {
alignments.add((Alignment) o);
}
}
Alignment replacement = null;
if (alignments.size() > 1) {
JComboBox<Alignment> jcb = new JComboBox<Alignment>(alignments.toArray(new Alignment[]{}));
JOptionPane.showMessageDialog( null, jcb, "Select a replacement alignment", JOptionPane.QUESTION_MESSAGE);
replacement = (Alignment) jcb.getSelectedItem();
} else if (alignments.size() == 1) {
replacement = alignments.get(0);
}
if (replacement != null) {
if (!replacement.getDataType().getClass().getName().equals(alignment.getDataType().getClass().getName())) {
JOptionPane.showMessageDialog(null, "Data types do not match, so alignment cannot be replaced: " +
replacement.getID() + " " + replacement.getDataType().getClass().getName() + " != " +
alignment.getID() + " " + alignment.getDataType().getClass().getName());
return;
}
// replace alignment
Set<BEASTInterface> outputs = new LinkedHashSet<>();
outputs.addAll(alignment.getOutputs());
for (BEASTInterface o : outputs) {
for (Input<?> input : o.listInputs()) {
if (input.get() == alignment) {
input.setValue(replacement, o);
replacement.getOutputs().add(o);
} else if (input.get() instanceof List) {
@SuppressWarnings("rawtypes")
List inputlist = (List) input.get();
int i = inputlist.indexOf(alignment);
if (i >= 0) {
inputlist.set(i, replacement);
replacement.getOutputs().add(o);
}
}
}
}
int i = doc.alignments.indexOf(alignment);
doc.alignments.set(i, replacement);
refreshPanel();
}
} // replaceItem
void splitItem() {
int[] selected = getTableRowSelection();
if (selected.length == 0) {
JOptionPane.showMessageDialog(this, "Select partitions to split, before hitting the split button");
return;
}
String[] options = { "{1,2} + 3", "{1,2} + 3 frame 2", "{1,2} + 3 frame 3", "1 + 2 + 3", "1 + 2 + 3 frame 2", "1 + 2 + 3 frame 3"};
String option = (String)JOptionPane.showInputDialog(null, "Split selected alignments into partitions", "Option",
JOptionPane.WARNING_MESSAGE, null, options, "1 + 2 + 3");
if (option == null) {
return;
}
String[] filters = null;
String[] ids = null;
if (option.equals(options[0])) {
filters = new String[] { "1::3,2::3", "3::3" };
ids = new String[] { "_1,2", "_3" };
} else if (option.equals(options[1])) {
filters = new String[] { "1::3,3::3", "2::3" };
ids = new String[] { "_1,2", "_3" };
} else if (option.equals(options[2])) {
filters = new String[] { "2::3,3::3", "1::3" };
ids = new String[] { "_1,2", "_3" };
} else if (option.equals(options[3])) {
filters = new String[] { "1::3", "2::3", "3::3" };
ids = new String[] { "_1", "_2", "_3" };
} else if (option.equals(options[4])) {
filters = new String[] { "2::3", "3::3", "1::3" };
ids = new String[] { "_1", "_2", "_3" };
} else if (option.equals(options[5])) {
filters = new String[] { "3::3", "1::3", "2::3" };
ids = new String[] { "_1", "_2", "_3" };
} else {
return;
}
for (int i = selected.length - 1; i >= 0; i
int rowNr = selected[i];
Alignment alignment = alignments.remove(rowNr);
getDoc().delAlignmentWithSubnet(alignment);
try {
for (int j = 0; j < filters.length; j++) {
FilteredAlignment f = new FilteredAlignment();
f.initByName("data", alignment, "filter", filters[j], "dataType", alignment.dataTypeInput.get());
f.setID(alignment.getID() + ids[j]);
getDoc().addAlignmentWithSubnet(f, getDoc().beautiConfig.partitionTemplate.get());
}
} catch (Exception e) {
e.printStackTrace();
}
}
refreshPanel();
} // splitItem
/** enable/disable buttons, etc **/
void updateStatus() {
boolean status = (alignments.size() > 1);
if (alignments.size() >= 2 && getTableRowSelection().length == 0) {
status = false;
}
for (JButton button : linkButtons) {
button.setEnabled(status);
}
for (JButton button : unlinkButtons) {
button.setEnabled(status);
}
status = (getTableRowSelection().length > 0);
splitButton.setEnabled(status);
delButton.setEnabled(status);
replaceButton.setEnabled(getTableRowSelection().length == 1);
}
} // class AlignmentListInputEditor
|
package radlab.rain.workload.rubis;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.logging.Logger;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import radlab.rain.Generator;
import radlab.rain.IScoreboard;
import radlab.rain.LoadProfile;
import radlab.rain.Operation;
import radlab.rain.TraceRecord;
import radlab.rain.util.HttpTransport;
import radlab.rain.workload.rubis.model.RubisUser;
/**
* Base class for RUBiS operations.
*
* @author Marco Guazzone (marco.guazzone@gmail.com)
*/
public abstract class RubisOperation extends Operation
{
public RubisOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
}
@Override
public void prepare(Generator generator)
{
this._generator = generator;
LoadProfile currentLoadProfile = generator.getLatestLoadProfile();
if (currentLoadProfile != null)
{
this.setGeneratedDuringProfile(currentLoadProfile);
}
// final String lastResponse = this.getSessionState().getLastResponse();
// if (lastResponse != null && lastResponse.indexOf("Sorry") != -1)
// // FIXME: Nothing matched the request, we have to go back to the previous operation
//// this.getLogger().warning("Operation completed with warnings. Last response is: " + lastResponse);
//// //this.setFailed(true);
// this.getGenerator().forceNextOperation(RubisGenerator.BACK_SPECIAL_OP);
}
@Override
public void postExecute()
{
this.getSessionState().setLastOperation(this._operationIndex);
final String lastResponse = this.getSessionState().getLastResponse();
if (this.isFailed())
{
this.getLogger().severe("Operation '" + this.getOperationName() + "' failed to execute. Last request is: '" + this.getLastRequest() + "'. Last response is: " + lastResponse);
this.getSessionState().setLastResponse(null);
}
else if (lastResponse != null)
{
// Look for any image to download
try
{
this.loadImages(this.parseImagesInHtml(lastResponse));
}
catch (Throwable t)
{
this.getLogger().warning("Unable to load images");
this.setFailed(true);
}
// Check for possible errors
if (lastResponse.indexOf("ERROR") != -1)
{
// A logic error happened on the server-side
this.getLogger().severe("Operation '" + this.getOperationName() + "' completed with server-side. Last request is: '" + this.getLastRequest() + "'. Last response is: " + lastResponse);
this.getSessionState().setLastResponse(null);
this.setFailed(true);
}
else if (lastResponse.indexOf("Sorry") != -1)
{
this.getGenerator().forceNextOperation(RubisGenerator.BACK_SPECIAL_OP);
this.setFailed(false);
}
}
}
@Override
public void cleanup()
{
// Empty
}
public RubisGenerator getGenerator()
{
return (RubisGenerator) this._generator;
}
public HttpTransport getHttpTransport()
{
return this.getGenerator().getHttpTransport();
}
public Random getRandomGenerator()
{
return this.getGenerator().getRandomGenerator();
}
public Logger getLogger()
{
return this.getGenerator().getLogger();
}
public RubisSessionState getSessionState()
{
return this.getGenerator().getSessionState();
}
public RubisUtility getUtility()
{
return this.getGenerator().getUtility();
}
public RubisConfiguration getConfiguration()
{
return this.getGenerator().getConfiguration();
}
/**
* Get the last request issued by this operation.
*
* @return The last request issued by this operation.
*/
protected String getLastRequest()
{
final TraceRecord trace = this.getTrace();
if (trace == null || trace._lstRequests == null || trace._lstRequests.isEmpty())
{
return null;
}
return trace._lstRequests.get(trace._lstRequests.size()-1);
}
/**
* Parses an HTML document for image URLs specified by IMG tags.
*
* @param buffer The HTTP response; expected to be an HTML document.
* @return An unordered set of image URLs.
*/
protected Set<String> parseImagesInHtml(String html)
{
String regex = null;
regex = "<img\\s+.*?src=\"([^\"]+?)\"";
this.getLogger().finest("Parsing images from buffer: " + html);
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Set<String> urlSet = new LinkedHashSet<String>();
Matcher match = pattern.matcher(html);
while (match.find())
{
String url = match.group(1);
this.getLogger().finest("Adding " + url);
urlSet.add(url);
}
return urlSet;
}
/**
* Load the image files specified by the image URLs.
*
* @param imageURLs The set of image URLs.
* @return The number of images loaded.
*
* @throws Throwable
*/
protected long loadImages(Set<String> imageUrls) throws Throwable
{
long imagesLoaded = 0;
if (imageUrls != null)
{
for (String imageUrl : imageUrls)
{
URI uri = new URI(this.getGenerator().getBaseURL());
String url = uri.resolve(imageUrl).toString();
this.getLogger().finer("Loading image: " + url);
this.getHttpTransport().fetchUrl(url);
++imagesLoaded;
}
}
return imagesLoaded;
}
}
|
// DBTCP.java
package ed.db;
import java.io.*;
import java.nio.*;
import ed.js.*;
public class DBTCP extends DBMessageLayer {
DBTCP( String root , String ip, int port){
super( root );
_portPool = DBPortPool.get( ip, port);
_host = ip;
}
public void requestStart(){
_threadPort.get().requestStart();
}
public void requestDone(){
_threadPort.get().requestDone();
}
protected void say( int op , ByteBuffer buf ){
MyPort mp = _threadPort.get();
DBPort port = mp.get( true );
try {
port.say( new DBMessage( op , buf ) );
mp.done( port );
}
catch ( IOException ioe ){
mp.error();
throw new JSException( "can't say something" , ioe );
}
}
protected int call( int op , ByteBuffer out , ByteBuffer in ){
MyPort mp = _threadPort.get();
DBPort port = mp.get( false );
try {
DBMessage a = new DBMessage( op , out );
DBMessage b = port.call( a , in );
mp.done( port );
return b.dataLen();
}
catch ( IOException ioe ){
mp.error();
throw new JSException( "can't call something" , ioe );
}
}
public String getConnectPoint(){
return _host;
}
class MyPort {
DBPort get( boolean keep ){
if ( _port != null )
return _port;
DBPort p = _portPool.get();
if ( keep && _inRequest )
_port = p;
return p;
}
void done( DBPort p ){
if ( p != _port )
_portPool.done( p );
}
void error(){
_port = null;
_portPool.gotError();
}
void requestStart(){
_inRequest = true;
if ( _port != null ){
_port = null;
System.err.println( "ERROR. somehow _port was not null at requestStart" );
}
}
void requestDone(){
if ( _port != null )
_portPool.done( _port );
_port = null;
_inRequest = false;
}
DBPort _port;
boolean _inRequest;
}
private final String _host;
private final DBPortPool _portPool;
private final ThreadLocal<MyPort> _threadPort = new ThreadLocal<MyPort>(){
protected MyPort initialValue(){
return new MyPort();
}
};
}
|
public class Hello2 {
public void hello() {
System.out.println("Hello");
}
}
|
package sergeysav.neuralnetwork.chess;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.stream.StreamSupport;
import sergeysav.neuralnetwork.NeuralNetwork;
import sergeysav.neuralnetwork.chess.ChessTrainer.TrainingResult;
/*
*
* Inputs 0-5 are type of piece at (0,0), Inputs (6-11) are type of piece at (1,0)
*
*/
public class ChessAIMain {
private static double trainingRatio = 0.75;
private static BufferedWriter fileWriter;
public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException {
Runtime.getRuntime().addShutdownHook(new Thread(()->{
if (fileWriter != null) {
try {
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}));
try {
fileWriter = new BufferedWriter(new FileWriter(new File("log.log")));
} catch (IOException e) {
e.printStackTrace();
}
print("Initializing games");
File gamesDirectory = new File("games");
List<File> trainingFiles = new ArrayList<File>();
List<File> testingFiles = new ArrayList<File>();
for (File pgnFile : gamesDirectory.listFiles()) {
if (!pgnFile.isDirectory() && !pgnFile.isHidden() && pgnFile.getName().endsWith(".pgn")) {
if (Math.random() <= trainingRatio) {
trainingFiles.add(pgnFile);
} else {
testingFiles.add(pgnFile);
}
}
}
print("Creating Neural Network");
//Create a new neural network
NeuralNetwork network = new NeuralNetwork(true, 384, 259, 259, 134); //384 inputs, 2 layers of 259 neurons, 134 outputs (128 tiles + 6 upgrade types)
print("Creating Network Trainer");
ChessTrainer trainer = new ChessTrainer(0.2, ()->{
//Generate a stream of double arrays for the training data
Collections.shuffle(trainingFiles);
return trainingFiles.stream().flatMap((f)->{
//Convert each file to a stream of transcripts
List<Transcript> trans = new LinkedList<Transcript>();
readTranscripts(f, trans);
return trans.stream();
}).flatMap((t)->StreamSupport.stream(t.spliterator(), false)).parallel();
}, ()->{
//Generate a stream of double arrays for the testing data
Collections.shuffle(testingFiles);
return testingFiles.stream().flatMap((f)->{
//Convert each file to a stream of transcripts
List<Transcript> trans = new LinkedList<Transcript>();
readTranscripts(f, trans);
return trans.stream();
}).flatMap((t)->StreamSupport.stream(t.spliterator(), false)).parallel();
}, network, 1e-2);
ChessStore store = new ChessStore();
store.network = network;
store.trainer = trainer;
store.epoch = 0;
print("Saving Backup 0");
store.save();
print("Calculating if next epoch needed\n");
while (trainer.isNextEpochNeeded()) {
print("Epoch " + (store.epoch+1) + " starting");
trainer.performEpoch();
print("Epoch completed");
store.epoch++;
print("Saving Backup " + store.epoch);
store.save();
print("Calculating if next epoch needed\n");
}
//I don't ever expect this code to be reached
print("Training Completed");
TrainingResult result = trainer.getResult();
print("Took " + result.epochs + " epochs");
}
private static void readTranscripts(File file, List<Transcript> transcripts) {
int transcript = 0;
try (Scanner scan = new Scanner(file)) {
Transcript t = null;
String moveList = null;
while(scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("[Event \"")) {
if (t != null) {
transcript++;
try {
if (moveList != null) {
populateTranscript(t, moveList);
moveList = null;
transcripts.add(t);
}
} catch (Exception e) {
System.err.println("Error reading " + file.getName() + "#" + transcript);
e.printStackTrace();
}
}
t = new Transcript();
}
if (line.startsWith("1.")) {
moveList = "";
}
if (moveList != null) moveList += line + " ";
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void populateTranscript(Transcript t, String moveList) {
String old;
do {
old = moveList;
moveList = moveList.replaceAll("(?:\\([^\\(\\)]*\\))", ""); //Remove areas enclosed in parenthesis
moveList = moveList.replaceAll("(?:\\{[^\\{\\}]*\\})", ""); //Remove areas enclosed in braces
} while (!old.equals(moveList));
moveList = moveList.replaceAll("(?:\\d+\\.\\.\\.)", ""); //Remove all elipses
//if (moveList.contains("+")) checks++;
//if (moveList.contains("#")) checkmates++;
String[] moved = moveList.split("\\d*[\\\\.]\\s*");
ChessBoard board = new ChessBoard();
LinkedList<String> moves = t.getMoves();
for (int i = 1; i<moved.length; i++) {
if (i == moved.length - 1) {
String[] parts = moved[i].split("\\s+");
if (parts.length > 2) {
String movew = board.getMoveConverted(parts[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
String moveb = board.getMoveConverted(parts[1], false);
moves.add(moveb);
board.applyConvertedMove(moveb);
t.setOutcome(parts[2]);
} else {
String movew = board.getMoveConverted(parts[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
t.setOutcome(parts[1]);
}
} else {
String[] steps = moved[i].split("\\s+");
String movew = board.getMoveConverted(steps[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
String moveb = board.getMoveConverted(steps[1], false);
moves.add(moveb);
board.applyConvertedMove(moveb);
}
}
//games++;
//ChessAIMain.moves += moves.size();
}
public static void print(String arg) {
String str = "[" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS")) + "] " + arg;
try {
fileWriter.write(str+"\n");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(str);
}
}
|
package sergeysav.neuralnetwork.chess;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class ChessAIMain {
private static int games = 0;
private static int checks = 0;
private static int checkmates = 0;
public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException {
File gamesDirectory = new File("games");
List<Transcript> transcripts = new LinkedList<Transcript>();
for (File pgnFile : gamesDirectory.listFiles()) {
if (!pgnFile.isDirectory() && !pgnFile.isHidden() && pgnFile.getName().endsWith(".pgn")) {
readTranscripts(pgnFile, transcripts);
}
}
System.out.println(games);
System.out.println(checks);
System.out.println(checkmates);
/*
//Create a new neural network
NeuralNetwork network = new NeuralNetwork(true, 384, 512, 512, 512, 512, 128); //384 inputs, 4 layers of 512 neurons, 128 outputs
//Training data for the network
double[][] trainingData = null;
//Testing data for the network
double[][] testingData = null;
//Teach the XOR function to the neural network
Trainer trainer = new Trainer(0.2, trainingData, testingData, network);
//Train the network
TrainingResult result = trainer.train(1e-2, 100000);
//Print the error
System.out.println(result);*/
}
private static void readTranscripts(File file, List<Transcript> transcripts) {
int transcript = 0;
try (Scanner scan = new Scanner(file)) {
Transcript t = null;
String moveList = null;
while(scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("[Event \"")) {
if (t != null) {
transcript++;
try {
if (moveList != null) {
populateTranscript(t, moveList);
moveList = null;
transcripts.add(t);
}
} catch (Exception e) {
System.err.println("Error reading " + file.getName() + "#" + transcript);
e.printStackTrace();
}
}
t = new Transcript();
}
if (line.startsWith("1.")) {
moveList = "";
}
if (moveList != null) moveList += line + " ";
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void populateTranscript(Transcript t, String moveList) {
String old;
do {
old = moveList;
moveList = moveList.replaceAll("(?:\\([^\\(\\)]*\\))", ""); //Remove areas enclosed in parenthesis
moveList = moveList.replaceAll("(?:\\{[^\\{\\}]*\\})", ""); //Remove areas enclosed in braces
} while (!old.equals(moveList));
moveList = moveList.replaceAll("(?:\\d+\\.\\.\\.)", ""); //Remove all elipses
if (moveList.contains("+")) checks++;
if (moveList.contains("#")) checkmates++;
String[] moved = moveList.split("\\d*[\\\\.]\\s*");
ChessBoard board = new ChessBoard();
LinkedList<String> moves = t.getMoves();
for (int i = 1; i<moved.length; i++) {
if (i == moved.length - 1) {
String[] parts = moved[i].split("\\s+");
if (parts.length > 2) {
String movew = board.getMoveConverted(parts[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
String moveb = board.getMoveConverted(parts[1], false);
moves.add(moveb);
board.applyConvertedMove(moveb);
t.setOutcome(parts[2]);
} else {
String movew = board.getMoveConverted(parts[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
t.setOutcome(parts[1]);
}
} else {
String[] steps = moved[i].split("\\s+");
String movew = board.getMoveConverted(steps[0], true);
moves.add(movew);
board.applyConvertedMove(movew);
String moveb = board.getMoveConverted(steps[1], false);
moves.add(moveb);
board.applyConvertedMove(moveb);
}
}
games++;
//System.out.println(games + " " + moves);
}
}
|
package com.example.octoissues;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.octoissues.EditOwnerRepoDialog.EditRepoDialogListener;
public class IssuesListActivity extends FragmentActivity implements EditRepoDialogListener, OnItemSelectedListener{
ListView issuesView, commentsView;
Dialog commentsDialog;
//TODO: 1. Take owner and repo as input, or on finding owner
// auto populate with repos
// 2. Send body of comment to comments dialog view to display
// body with comments (would need custom layout, include listview
// in linearlayout or relativelayout)
private static final String OWNER = "paypal";
private static final String REPO = "PayPal-Android-SDK";
private Spinner sprRepoName;
TextView repoNameView;
GithubClient client = new GithubClient();
//Remove?
private void showEditDialog() {
FragmentManager fm = getSupportFragmentManager();
EditOwnerRepoDialog editNameDialog = new EditOwnerRepoDialog();
editNameDialog.show(fm, "fragment_edit_name");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.issues_view);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("repo_name_pref", "");
//showEditDialog();
//Set repository name in view
repoNameView = (TextView) findViewById(R.id.repoName);
repoNameView.setText("Repo Issues");
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sdk_repos, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sprRepoName = (Spinner) findViewById(R.id.spr_repo_name);
sprRepoName.setAdapter(adapter);
sprRepoName.setOnItemSelectedListener(this);
//Associate the listview with id issues_list in the context of this Activity
issuesView = (ListView) findViewById(R.id.issues_list);
if (isNetworkAvailable()) {
//Get issues for repo named rails, owner named rails
GithubIssuesTask githubIssuesTask = new GithubIssuesTask();
githubIssuesTask.execute(OWNER, REPO);
issuesView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View viewCLicked, int position,
long id) {
if (isNetworkAvailable()) {
commentsDialog = new Dialog(IssuesListActivity.this);
commentsDialog.setCancelable(true);
commentsDialog.setContentView(R.layout.comments_view);
commentsDialog.setTitle("Comments");
//Associate the listview with id comments in the context of commentsDialog
commentsView = (ListView) commentsDialog.findViewById(R.id.comments_list);
//Suppressing type cast warning here since it is known that type will be HashMap<String, String>
@SuppressWarnings("unchecked")
Map<String, String> itemMap = (HashMap<String, String>) issuesView.getItemAtPosition(position);
TextView issueBody = (TextView) commentsDialog.findViewById(R.id.issueBody);
issueBody.setText(itemMap.get("body"));
//Get Github issue number, pass to client to get comments for that issue
int issueNumber = Integer.parseInt(itemMap.get("issue_number"));
GithubCommentsTask githubCommentsTask = new GithubCommentsTask();
githubCommentsTask.execute(OWNER, REPO, Integer.toString(issueNumber));
}
}
});
}
}
/*
* Task that make Github API request for issues in the background and post result to
* UI thread when available.
* -- share code/be expose via interfaces with GithubCommentsTask
*/
private class GithubIssuesTask extends AsyncTask<String, String, List<Map<String, String>>> {
final ProgressDialog dialog = new ProgressDialog(IssuesListActivity.this);
@Override
protected void onPreExecute() {
//Display feedback to user while background process in running
dialog.setMessage("Fetching SDK Issues...");
dialog.show();
}
@Override
protected List<Map<String, String>> doInBackground(String... params) {
List<Map<String, String>> issues = null;
try {
String owner = params[0];
String repo = params[1];
//Get issues sorted by last updated
String[] SDK_REPOS = getResources().getStringArray(R.array.sdk_repos);
for(String sdk : SDK_REPOS) {
if (issues == null) {
issues = client.getIssues(owner, sdk, "updated");
}
else {
issues.addAll(client.getIssues(owner, sdk, "updated"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return issues;
}
@Override
protected void onPostExecute(List<Map<String, String>> issues) {
if (issues != null) {
//Map fieldnames to listview item elements
String[] from = { "header", "snippet" };
int[] to = { android.R.id.text1, android.R.id.text2 };
// Initialize adapter with result as the dataset, using
// android.R.layout.simple_list_item_2 for simplicity but custom
// layout could be used for better flexibility
SimpleAdapter adapter = new SimpleAdapter(IssuesListActivity.this, issues,
android.R.layout.simple_list_item_2, from, to);
// Associate the adapter with the view, could update dataset later
// by invoking notifyDataSetChanged
issuesView.setAdapter(adapter);
dialog.dismiss();
} else {
displayErrorDialog("Error getting Github Issues");
}
}
}
/*
* Task that make Github API request for comments in the background and post result to
* UI thread when available.
* -- catching responses, requesting comments for a few issues above and below the current
* item would improve response time
*/
private class GithubCommentsTask extends AsyncTask<String, String, List<Map<String, String>>> {
@Override
protected void onPreExecute() {
IssuesListActivity.this.setProgressBarIndeterminateVisibility(true);
}
@Override
protected List<Map<String, String>> doInBackground(String... params) {
List<Map<String, String>> comments = null;
try {
String owner = params[0];
String repo = params[1];
String issueNumber = params[2];
comments = client.getComments(owner, repo, issueNumber);
} catch (JSONException e) {
e.printStackTrace();
}
return comments;
}
@Override
protected void onPostExecute(List<Map<String, String>> comments) {
if (comments != null) {
String[] from = { "header", "body" };
int[] to = { android.R.id.text1, android.R.id.text2 };
//Use simple list item for comments, issues and errors for now
SimpleAdapter adapter = new SimpleAdapter(IssuesListActivity.this, comments,
android.R.layout.simple_list_item_2, from, to);
IssuesListActivity.this.setProgressBarIndeterminateVisibility(false);
commentsView.setAdapter(adapter);
commentsDialog.show();
} else {
displayErrorDialog("Error getting Github Comments");
}
}
}
/*
* Display error message in a Dialog
*/
private void displayErrorDialog(String message){
Dialog dialog = new Dialog(IssuesListActivity.this);
dialog.setTitle(message);
dialog.show();
}
/*
* Return true if network is available, otherwise display
* Dialog with Error message and return false
*/
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (!(activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting())) {
Dialog dialog = new Dialog(IssuesListActivity.this);
dialog.setTitle("No Internet Connection");
dialog.setCancelable(true);
dialog.show();
return false;
}
return true;
}
@Override
public void onFinishEditDialog(String owner, String repo) {
Toast.makeText(this, "Hi, " + owner + " " + repo, Toast.LENGTH_SHORT).show();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(this, "Hi, " + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
package ru.ncedu.tlt.controllers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import ru.ncedu.tlt.entity.EntityFile;
import ru.ncedu.tlt.hash.HashGenerator;
import ru.ncedu.tlt.properties.PropertiesCB;
/**
*
* @author victori
*/
@Stateless
@LocalBean
public class EntityFileController {
@EJB
HashGenerator hashGenerator;
PreparedStatement preparedStatement;
Connection connection;
public EntityFile createEntityFile(String fileName, Integer ownerId) throws SQLException {
EntityFile entityFile = new EntityFile();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
int indexOfFileExt = fileName.lastIndexOf('.');
entityFile.setName(fileName.substring(0, indexOfFileExt));
entityFile.setExt(fileName.substring(indexOfFileExt, fileName.length()));
entityFile.setDate(timestamp);
String prehash = entityFile.getName()
+ entityFile.getExt()
+ timestamp.toString();
String hash = hashGenerator.getHash(prehash);
entityFile.setHash(hash);
preparedStatement = null;
String sqlQuery = "INSERT INTO CB_FILE "
+ "(FILENAME, FILEEXT, FILEDATE, FILEHASH, FILEUSERID) VALUES "
+ "(?,?,?,?,?)";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, entityFile.getName());
preparedStatement.setString(2, entityFile.getExt());
preparedStatement.setString(3, timestamp.toString());
preparedStatement.setString(4, entityFile.getHash());
preparedStatement.setInt(5, ownerId);
preparedStatement.executeUpdate();
//ERROR! createEntityFile: Column 'FILEID' cannot accept a NULL value.
System.out.println("retriving new id for file");
try (ResultSet keys = preparedStatement.getGeneratedKeys()) {
keys.next();
entityFile.setId(keys.getInt(1));
}
System.out.println("Record is inserted into CB_FILE table!");
insertIntoUserFiles(ownerId, entityFile.getId());
} catch (SQLException e) {
System.out.println("ERROR! createEntityFile: " + e.getMessage());
return null;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return entityFile;
}
public Boolean insertIntoUserFiles(Integer idUser, Integer idFile) throws SQLException {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = null;
String sqlQuery = "INSERT INTO CB_USERFILE "
+ "(UF_USERID, UF_FILEID) VALUES"
+ "(?, ?)";
try {
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setInt(1, idUser);
preparedStatement.setInt(2, idFile);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into CB_USERFILE table!");
} catch (SQLException e) {
System.out.println("ERROR! insertIntoUserFiles : " + e.getMessage());
return false;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return true;
}
public Boolean deleteFileToTrash(Integer idUser, Integer idFile) throws SQLException {
preparedStatement = null;
String sqlQuery = "UPDATE CB_USERFILE"
+ "SET UF_DEL = SYSDATE"
+ "WHERE UF_FILEID = ? AND UF_USERID = ?";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setInt(1, idFile);
preparedStatement.setInt(2, idUser);
preparedStatement.executeUpdate();
System.out.println("File with id=" + idFile + "and user id=" + idUser + " has been deleted");
cleanDependenciesAfterDeleteToTrash(idUser, idFile);
} catch (SQLException e) {
System.out.println("ERROR! deleteFileToTrash : " + e.getMessage());
return false;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return true;
}
public Boolean cleanDependenciesAfterDeleteToTrash(Integer idUser, Integer idFile) throws SQLException {
preparedStatement = null;
String sqlQuery = "DELETE FROM CB_USERFILE"
+ "WHERE UF_FILEID = ?"
+ "AND UF_USERID IS NOT ?";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setInt(1, idFile);
preparedStatement.setInt(2, idUser);
preparedStatement.executeUpdate();
System.out.println("Deleting dependencies successfully");
} catch (SQLException e) {
System.out.println("ERROR! cleanDependenciesAfterDeleteToTrash : " + e.getMessage());
return false;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return true;
}
public ArrayList<EntityFile> getMyFilesList(String userID) throws SQLException {
ArrayList<EntityFile> entityFileList = new ArrayList();
preparedStatement = null;
String sqlQuery = "SELECT * FROM CB_FILE"
+ "JOIN CB_USERFILE ON CB_FILE.FILEID = CB_USERFILE.UF_FILEID"
+ "WHERE (CB_USERFILE.UF_USERID = ?) AND (CB_USERFILE.UF_DEL IS NULL)"
+ "AND (CB_FILE.FILEUSERID = CB_USERFILE.UF_USERID)" +
"ORDER BY CB_FILE.FILENAME";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, userID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
EntityFile entityFile = new EntityFile();
entityFile.setId(rs.getInt("FILEID"));
entityFile.setName(rs.getString("FILENAME"));
entityFile.setExt(rs.getString("FILEEXT"));
entityFile.setDate((Timestamp) rs.getObject("FILEDATE"));
entityFile.setHash(rs.getString("FILEHASH"));
entityFile.setOwner(rs.getInt("FILEUSERID"));
entityFileList.add(entityFile);
}
} catch (Exception e) {
System.out.println("ERROR! getFilesList: " + e.getMessage());
return null;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return entityFileList;
}
public ArrayList<EntityFile> getMyDeletedFilesList(String userID) throws SQLException {
ArrayList<EntityFile> entityFileList = new ArrayList();
preparedStatement = null;
String sqlQuery = "SELECT * FROM CB_FILE"
+ "JOIN CB_USERFILE ON CB_FILE.FILEID = CB_USERFILE.UF_FILEID"
+ "WHERE (CB_USERFILE.UF_USERID = ?) AND (CB_USERFILE.UF_DEL IS NOT NULL)"
+ "AND (CB_FILE.FILEUSERID = CB_USERFILE.UF_USERID)"
+ "ORDER BY CB_FILE.FILENAME";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, userID);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
EntityFile entityFile = new EntityFile();
entityFile.setId(rs.getInt("FILEID"));
entityFile.setName(rs.getString("FILENAME"));
entityFile.setExt(rs.getString("FILEEXT"));
entityFile.setDate((Timestamp) rs.getObject("FILEDATE"));
entityFile.setHash(rs.getString("FILEHASH"));
entityFile.setOwner(rs.getInt("FILEUSERID"));
entityFileList.add(entityFile);
}
} catch (Exception e) {
System.out.println("ERROR! getFilesList: " + e.getMessage());
return null;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return entityFileList;
}
public ArrayList<EntityFile> getAllFiles() throws SQLException {
ArrayList<EntityFile> entityFileList = new ArrayList();
preparedStatement = null;
String sqlQuery = "SELECT * FROM CB_FILE";
try {
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = connection.prepareStatement(sqlQuery);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
EntityFile entityFile = new EntityFile();
entityFile.setId(rs.getInt("FILEID"));
entityFile.setName(rs.getString("FILENAME"));
entityFile.setExt(rs.getString("FILEEXT"));
entityFile.setDate((Timestamp) rs.getObject("FILEDATE"));
entityFile.setHash(rs.getString("FILEHASH"));
entityFile.setOwner(rs.getInt("FILEUSERID"));
entityFileList.add(entityFile);
}
} catch (Exception e) {
System.out.println("ERROR! getAllFiles: " + e.getMessage());
return null;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(EntityFileController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return entityFileList;
}
public EntityFile getFileData(Integer fileId) throws SQLException {
EntityFile entityFile = new EntityFile();
connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL);
preparedStatement = null;
String sqlQuery = "SELECT * FROM CB_FILE WHERE FILEID = ?";
try {
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setInt(1, fileId);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
entityFile.setId(rs.getInt("FILEID"));
entityFile.setName(rs.getString("FILENAME"));
entityFile.setExt(rs.getString("FILEEXT"));
entityFile.setDate((Timestamp) rs.getObject("FILEDATE"));
entityFile.setHash(rs.getString("FILEHASH"));
entityFile.setOwner(rs.getInt("FILEUSERID"));
}
} catch (Exception e) {
System.out.println("ERROR! getFileData: " + e.getMessage());
return null;
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
return entityFile;
}
}
|
package com.github.noxan.aves.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
public class SocketServer implements Server {
private String host;
private int port;
private ServerSocket server;
public SocketServer() {
this.host = "0.0.0.0";
this.port = 1666;
}
public SocketServer(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void start() {
try {
server = new ServerSocket();
server.bind(new InetSocketAddress(host, port));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
}
|
package com.carporange.cloudmusic.fragment;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.RadioGroup;
import com.carporange.cloudmusic.R;
import com.carporange.cloudmusic.adapter.CarpFragmentPagerAdapter;
import com.carporange.cloudmusic.ui.base.BaseFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class MainFragment extends BaseFragment {
private Activity mActivity;
@BindView(R.id.viewPager_main)
ViewPager mViewPager;
@BindView(R.id.radioGroup)
RadioGroup mRadioGroup;
public MainFragment() {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
@Override
public int getLayoutId() {
return R.layout.fragment_main;
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
protected void initViews() {
List<Fragment> list = new ArrayList<>();
list.add(new DiscoverFragment());
list.add(new MusicFragment());
list.add(new FriendsFragment());
//FragmentFragmentgetChildFragmentManager(),
FragmentPagerAdapter fpa = new CarpFragmentPagerAdapter(list, getChildFragmentManager());
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(fpa);
mRadioGroup.check(R.id.rb_discover);
}
@Override
protected void onVisible() {
}
@Override
public void setListeners() {
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
mRadioGroup.check(R.id.rb_discover);
break;
case 1:
mRadioGroup.check(R.id.rb_music);
break;
case 2:
mRadioGroup.check(R.id.rb_friends);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_discover:
mViewPager.setCurrentItem(0);
break;
case R.id.rb_music:
mViewPager.setCurrentItem(1);
break;
case R.id.rb_friends:
mViewPager.setCurrentItem(2);
break;
}
}
});
}
}
|
package com.intellij.codeInsight.highlighting;
import com.intellij.lang.BracePair;
import com.intellij.lang.Language;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.HighlighterIterator;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.JavaDocTokenType;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.TokenType;
import com.intellij.psi.jsp.JspTokenType;
import com.intellij.psi.jsp.el.ELTokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.java.IJavaDocElementType;
import com.intellij.psi.tree.java.IJavaElementType;
import com.intellij.psi.tree.jsp.IJspElementType;
import com.intellij.psi.tree.xml.IXmlLeafElementType;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.containers.BidirectionalMap;
import com.intellij.xml.util.HtmlUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
public class BraceMatchingUtil {
private static final int UNDEFINED_TOKEN_GROUP = -1;
private static final int JAVA_TOKEN_GROUP = 0;
private static final int XML_TAG_TOKEN_GROUP = 1;
private static final int XML_VALUE_DELIMITER_GROUP = 2;
private static final int JSP_TOKEN_GROUP = 3;
private static final int PAIRED_TOKEN_GROUP = 4;
private static final int DOC_TOKEN_GROUP = 5;
public static boolean isAfterClassLikeIdentifier(final int offset, final Editor editor) {
HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
iterator.retreat();
final IElementType tokenType = iterator.getTokenType();
if (tokenType == JavaTokenType.IDENTIFIER && iterator.getEnd() == offset) {
final CharSequence chars = editor.getDocument().getCharsSequence();
final char startChar = chars.charAt(iterator.getStart());
if (!Character.isUpperCase(startChar)) return false;
final CharSequence word = chars.subSequence(iterator.getStart(), iterator.getEnd());
if (word.length() == 1) return true;
for (int i = 1; i < word.length(); i++) {
if (Character.isLowerCase(word.charAt(i))) return true;
}
}
return false;
}
public static boolean isTokenInvalidInsideReference(final IElementType tokenType) {
return tokenType == JavaTokenType.SEMICOLON ||
tokenType == JavaTokenType.LBRACE ||
tokenType == JavaTokenType.RBRACE;
}
public interface BraceMatcher {
int getTokenGroup(IElementType tokenType);
boolean isLBraceToken(HighlighterIterator iterator,CharSequence fileText, FileType fileType);
boolean isRBraceToken(HighlighterIterator iterator,CharSequence fileText, FileType fileType);
boolean isPairBraces(IElementType tokenType,IElementType tokenType2);
boolean isStructuralBrace(HighlighterIterator iterator,CharSequence text, FileType fileType);
IElementType getTokenType(char ch, HighlighterIterator iterator);
}
private static class PairedBraceMatcherAdapter implements BraceMatcher {
private PairedBraceMatcher myMatcher;
private Language myLanguage;
public PairedBraceMatcherAdapter(final PairedBraceMatcher matcher, Language language) {
myMatcher = matcher;
myLanguage = language;
}
public int getTokenGroup(IElementType tokenType) {
return PAIRED_TOKEN_GROUP;
}
public boolean isLBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
final IElementType tokenType = getToken(iterator);
final BracePair[] pairs = myMatcher.getPairs();
for (BracePair pair : pairs) {
if (tokenType == pair.getLeftBraceType()) return true;
}
return false;
}
public boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
final IElementType tokenType = getToken(iterator);
final BracePair[] pairs = myMatcher.getPairs();
for (BracePair pair : pairs) {
if (tokenType == pair.getRightBraceType()) return true;
}
return false;
}
public boolean isPairBraces(IElementType tokenType, IElementType tokenType2) {
final BracePair[] pairs = myMatcher.getPairs();
for (BracePair pair : pairs) {
if (tokenType == pair.getLeftBraceType() && tokenType2 == pair.getRightBraceType() ||
tokenType == pair.getRightBraceType() && tokenType2 == pair.getLeftBraceType()) {
return true;
}
}
return false;
}
public boolean isStructuralBrace(HighlighterIterator iterator, CharSequence text, FileType fileType) {
final IElementType tokenType = getToken(iterator);
final BracePair[] pairs = myMatcher.getPairs();
for (BracePair pair : pairs) {
if (tokenType == pair.getRightBraceType() || tokenType == pair.getLeftBraceType()) return pair.isStructural();
}
return false;
}
public IElementType getTokenType(char ch, HighlighterIterator iterator) {
if (iterator.atEnd()) return null;
final IElementType tokenType = getToken(iterator);
if (tokenType.getLanguage() != myLanguage) return null;
final BracePair[] pairs = myMatcher.getPairs();
for (final BracePair pair : pairs) {
if (ch == pair.getRightBraceChar()) return pair.getRightBraceType();
if (ch == pair.getLeftBraceChar()) return pair.getLeftBraceType();
}
return null;
}
}
private static class DefaultBraceMatcher implements BraceMatcher {
private static final BidirectionalMap<IElementType, IElementType> PAIRING_TOKENS = new BidirectionalMap<IElementType, IElementType>();
static {
PAIRING_TOKENS.put(JavaTokenType.LPARENTH, JavaTokenType.RPARENTH);
PAIRING_TOKENS.put(JavaTokenType.LBRACE, JavaTokenType.RBRACE);
PAIRING_TOKENS.put(JavaTokenType.LBRACKET, JavaTokenType.RBRACKET);
PAIRING_TOKENS.put(XmlTokenType.XML_TAG_END, XmlTokenType.XML_START_TAG_START);
PAIRING_TOKENS.put(XmlTokenType.XML_EMPTY_ELEMENT_END, XmlTokenType.XML_START_TAG_START);
PAIRING_TOKENS.put(XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER, XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER);
PAIRING_TOKENS.put(JspTokenType.JSP_SCRIPTLET_START, JspTokenType.JSP_SCRIPTLET_END);
PAIRING_TOKENS.put(JspTokenType.JSP_EXPRESSION_START, JspTokenType.JSP_EXPRESSION_END);
PAIRING_TOKENS.put(JspTokenType.JSP_DECLARATION_START, JspTokenType.JSP_DECLARATION_END);
PAIRING_TOKENS.put(JspTokenType.JSP_DIRECTIVE_START, JspTokenType.JSP_DIRECTIVE_END);
PAIRING_TOKENS.put(JavaDocTokenType.DOC_INLINE_TAG_START, JavaDocTokenType.DOC_INLINE_TAG_END);
PAIRING_TOKENS.put(ELTokenType.JSP_EL_RBRACKET, ELTokenType.JSP_EL_LBRACKET);
PAIRING_TOKENS.put(ELTokenType.JSP_EL_RPARENTH, ELTokenType.JSP_EL_LPARENTH);
}
public int getTokenGroup(IElementType tokenType) {
if (tokenType instanceof IJavaElementType) {
return JAVA_TOKEN_GROUP;
}
else if (tokenType instanceof IXmlLeafElementType) {
return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER
? XML_VALUE_DELIMITER_GROUP
: XML_TAG_TOKEN_GROUP;
}
else if (tokenType instanceof IJspElementType) {
return JSP_TOKEN_GROUP;
}
else if (tokenType instanceof IJavaDocElementType) {
return DOC_TOKEN_GROUP;
}
else{
return UNDEFINED_TOKEN_GROUP;
}
}
public boolean isLBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
return isLBraceToken(getToken(iterator));
}
private boolean isLBraceToken(final IElementType tokenType) {
PairedBraceMatcher matcher = tokenType.getLanguage().getPairedBraceMatcher();
if (matcher != null) {
BracePair[] pairs = matcher.getPairs();
for (BracePair pair : pairs) {
if (pair.getLeftBraceType() == tokenType) return true;
}
}
return tokenType == JavaTokenType.LPARENTH ||
tokenType == JavaTokenType.LBRACE ||
tokenType == JavaTokenType.LBRACKET ||
tokenType == XmlTokenType.XML_START_TAG_START ||
tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER ||
tokenType == JspTokenType.JSP_SCRIPTLET_START ||
tokenType == JspTokenType.JSP_EXPRESSION_START ||
tokenType == JspTokenType.JSP_DECLARATION_START ||
tokenType == JspTokenType.JSP_DIRECTIVE_START ||
tokenType == ELTokenType.JSP_EL_LBRACKET ||
tokenType == ELTokenType.JSP_EL_LPARENTH ||
tokenType == JavaDocTokenType.DOC_INLINE_TAG_START;
}
public boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
final IElementType tokenType = getToken(iterator);
PairedBraceMatcher matcher = tokenType.getLanguage().getPairedBraceMatcher();
if (matcher != null) {
BracePair[] pairs = matcher.getPairs();
for (BracePair pair : pairs) {
if (pair.getRightBraceType() == tokenType) return true;
}
}
if (tokenType == JavaTokenType.RPARENTH ||
tokenType == JavaTokenType.RBRACE ||
tokenType == JavaTokenType.RBRACKET ||
tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END ||
tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER ||
tokenType == JspTokenType.JSP_SCRIPTLET_END ||
tokenType == JspTokenType.JSP_EXPRESSION_END ||
tokenType == JspTokenType.JSP_DECLARATION_END ||
tokenType == JspTokenType.JSP_DIRECTIVE_END ||
tokenType == ELTokenType.JSP_EL_RBRACKET ||
tokenType == ELTokenType.JSP_EL_RPARENTH ||
tokenType == JavaDocTokenType.DOC_INLINE_TAG_END) {
return true;
}
else if (tokenType == XmlTokenType.XML_TAG_END) {
final boolean result = findEndTagStart(iterator);
if (fileType == StdFileTypes.HTML || fileType == StdFileTypes.JSP) {
final String tagName = getTagName(fileText, iterator);
if (tagName != null && HtmlUtil.isSingleHtmlTag(tagName)) {
return !result;
}
}
return result;
}
else {
return false;
}
}
public boolean isPairBraces(IElementType tokenType1, IElementType tokenType2) {
if (tokenType2.equals(PAIRING_TOKENS.get(tokenType1))) return true;
List<IElementType> keys = PAIRING_TOKENS.getKeysByValue(tokenType1);
return keys != null && keys.contains(tokenType2);
}
public boolean isStructuralBrace(HighlighterIterator iterator,CharSequence text, FileType fileType) {
IElementType tokenType = getToken(iterator);
PairedBraceMatcher matcher = tokenType.getLanguage().getPairedBraceMatcher();
if (matcher != null) {
BracePair[] pairs = matcher.getPairs();
for (BracePair pair : pairs) {
if ((pair.getLeftBraceType() == tokenType || pair.getRightBraceType() == tokenType) &&
pair.isStructural()) return true;
}
}
if (fileType == StdFileTypes.JAVA) {
return tokenType == JavaTokenType.RBRACE || tokenType == JavaTokenType.LBRACE;
}
else if (fileType == StdFileTypes.HTML || fileType == StdFileTypes.XML) {
return tokenType == XmlTokenType.XML_START_TAG_START ||
tokenType == XmlTokenType.XML_TAG_END ||
tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END ||
( tokenType == XmlTokenType.XML_TAG_END &&
( fileType == StdFileTypes.HTML ||
fileType == StdFileTypes.JSP
) &&
isEndOfSingleHtmlTag(text, iterator)
);
}
else if (fileType == StdFileTypes.JSP || fileType == StdFileTypes.JSPX) {
return isJspJspxStructuralBrace(tokenType);
}
else{
return false;
}
}
private boolean isJspJspxStructuralBrace(final IElementType tokenType) {
return tokenType == JavaTokenType.LBRACE ||
tokenType == JavaTokenType.RBRACE ||
tokenType == XmlTokenType.XML_START_TAG_START ||
tokenType == XmlTokenType.XML_TAG_END ||
tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END;
}
public IElementType getTokenType(char ch, HighlighterIterator iterator) {
IElementType tokenType = (!iterator.atEnd())?getToken(iterator) :null;
if(tokenType == TokenType.WHITE_SPACE) {
iterator.retreat();
if (!iterator.atEnd()) {
tokenType = getToken(iterator);
iterator.advance();
}
}
if(tokenType instanceof IJavaElementType) {
if (ch == '}') return JavaTokenType.RBRACE;
if (ch == '{') return JavaTokenType.LBRACE;
if (ch == ']') return JavaTokenType.RBRACKET;
if (ch == '[') return JavaTokenType.LBRACKET;
if (ch == ')') return JavaTokenType.RPARENTH;
if (ch == '(') return JavaTokenType.LPARENTH;
} else if(tokenType instanceof IJspElementType) {
if (ch == ']') return ELTokenType.JSP_EL_RBRACKET;
if (ch == '[') return ELTokenType.JSP_EL_LBRACKET;
if (ch == ')') return ELTokenType.JSP_EL_RPARENTH;
if (ch == '(') return ELTokenType.JSP_EL_LPARENTH;
}
return null; //TODO: add more here!
}
}
public static class HtmlBraceMatcher extends DefaultBraceMatcher {
private static BraceMatcher ourStyleBraceMatcher;
private static BraceMatcher ourScriptBraceMatcher;
public static void setStyleBraceMatcher(BraceMatcher braceMatcher) {
ourStyleBraceMatcher = braceMatcher;
}
public static void setScriptBraceMatcher(BraceMatcher _scriptBraceMatcher) {
ourScriptBraceMatcher = _scriptBraceMatcher;
}
public int getTokenGroup(IElementType tokenType) {
int tokenGroup = super.getTokenGroup(tokenType);
if(tokenGroup == UNDEFINED_TOKEN_GROUP && ourStyleBraceMatcher != null) {
tokenGroup = ourStyleBraceMatcher.getTokenGroup(tokenType);
}
if(tokenGroup == UNDEFINED_TOKEN_GROUP && ourScriptBraceMatcher != null) {
tokenGroup = ourScriptBraceMatcher.getTokenGroup(tokenType);
}
return tokenGroup;
}
public boolean isLBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
boolean islbrace = super.isLBraceToken(iterator, fileText, fileType);
if (!islbrace && ourStyleBraceMatcher!=null) {
islbrace = ourStyleBraceMatcher.isLBraceToken(iterator, fileText, fileType);
}
if (!islbrace && ourScriptBraceMatcher!=null) {
islbrace = ourScriptBraceMatcher.isLBraceToken(iterator, fileText, fileType);
}
return islbrace;
}
public boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
boolean rBraceToken = super.isRBraceToken(iterator, fileText, fileType);
if (!rBraceToken && ourStyleBraceMatcher!=null) {
rBraceToken = ourStyleBraceMatcher.isRBraceToken(iterator, fileText, fileType);
}
if (!rBraceToken && ourScriptBraceMatcher!=null) {
rBraceToken = ourScriptBraceMatcher.isRBraceToken(iterator, fileText, fileType);
}
return rBraceToken;
}
public boolean isPairBraces(IElementType tokenType1, IElementType tokenType2) {
boolean pairBraces = super.isPairBraces(tokenType1, tokenType2);
if (!pairBraces && ourStyleBraceMatcher!=null) {
pairBraces = ourStyleBraceMatcher.isPairBraces(tokenType1, tokenType2);
}
if (!pairBraces && ourScriptBraceMatcher!=null) {
pairBraces = ourScriptBraceMatcher.isPairBraces(tokenType1, tokenType2);
}
return pairBraces;
}
public boolean isStructuralBrace(HighlighterIterator iterator, CharSequence text, FileType fileType) {
boolean structuralBrace = super.isStructuralBrace(iterator, text, fileType);
if (!structuralBrace && ourStyleBraceMatcher!=null) {
structuralBrace = ourStyleBraceMatcher.isStructuralBrace(iterator, text, fileType);
}
if (!structuralBrace && ourScriptBraceMatcher!=null) {
structuralBrace = ourScriptBraceMatcher.isStructuralBrace(iterator, text, fileType);
}
return structuralBrace;
}
public IElementType getTokenType(char ch, HighlighterIterator iterator) {
IElementType pairedParenType = null;
if (ourScriptBraceMatcher!=null) {
pairedParenType = ourScriptBraceMatcher.getTokenType(ch, iterator);
}
if (pairedParenType == null && ourStyleBraceMatcher!=null) {
pairedParenType = ourStyleBraceMatcher.getTokenType(ch, iterator);
}
if (pairedParenType == null) {
pairedParenType = super.getTokenType(ch,iterator);
}
return pairedParenType;
}
}
private static final HashMap<FileType,BraceMatcher> BRACE_MATCHERS = new HashMap<FileType, BraceMatcher>();
static {
final BraceMatcher defaultBraceMatcher = new DefaultBraceMatcher();
registerBraceMatcher(StdFileTypes.JAVA,defaultBraceMatcher);
registerBraceMatcher(StdFileTypes.XML,defaultBraceMatcher);
HtmlBraceMatcher braceMatcher = new HtmlBraceMatcher();
registerBraceMatcher(StdFileTypes.HTML,braceMatcher);
registerBraceMatcher(StdFileTypes.XHTML,braceMatcher);
registerBraceMatcher(StdFileTypes.JSP, braceMatcher);
registerBraceMatcher(StdFileTypes.JSPX, braceMatcher);
}
public static void registerBraceMatcher(FileType fileType,BraceMatcher braceMatcher) {
BRACE_MATCHERS.put(fileType, braceMatcher);
}
private static final Stack<IElementType> ourBraceStack = new Stack<IElementType>();
private static final Stack<String> ourTagNameStack = new Stack<String>();
public static synchronized boolean matchBrace(CharSequence fileText, FileType fileType, HighlighterIterator iterator, boolean forward) {
IElementType brace1Token = getToken(iterator);
int group = getTokenGroup(brace1Token, fileType);
String brace1TagName = getTagName(fileText, iterator);
boolean isStrict = isStrictTagMatching(fileType, group);
boolean isCaseSensitive = areTagsCaseSensitive(fileType, group);
ourBraceStack.clear();
ourTagNameStack.clear();
ourBraceStack.push(brace1Token);
if (isStrict){
ourTagNameStack.push(brace1TagName);
}
boolean matched = false;
while(true){
if (!forward){
iterator.retreat();
}
else{
iterator.advance();
}
if (iterator.atEnd()) {
break;
}
IElementType tokenType = getToken(iterator);
if (getTokenGroup(tokenType, fileType) == group) {
String tagName = getTagName(fileText, iterator);
if (!isStrict && !Comparing.equal(brace1TagName, tagName, isCaseSensitive)) continue;
if (forward ? isLBraceToken(iterator, fileText, fileType) : isRBraceToken(iterator, fileText, fileType)){
ourBraceStack.push(tokenType);
if (isStrict){
ourTagNameStack.push(tagName);
}
}
else if (forward ? isRBraceToken(iterator, fileText,fileType) : isLBraceToken(iterator, fileText, fileType)){
IElementType topTokenType = ourBraceStack.pop();
String topTagName = null;
if (isStrict){
topTagName = ourTagNameStack.pop();
}
if (!isPairBraces(topTokenType, tokenType, fileType)
|| isStrict && !Comparing.equal(topTagName, tagName, isCaseSensitive)
){
matched = false;
break;
}
if (ourBraceStack.size() == 0){
matched = true;
break;
}
}
}
}
return matched;
}
public static boolean findStructuralLeftBrace(FileType fileType, HighlighterIterator iterator, CharSequence fileText) {
ourBraceStack.clear();
ourTagNameStack.clear();
while (!iterator.atEnd()) {
if (isStructuralBraceToken(fileType, iterator,fileText)) {
if (isRBraceToken(iterator, fileText, fileType)) {
ourBraceStack.push(getToken(iterator));
ourTagNameStack.push(getTagName(fileText, iterator));
}
if (isLBraceToken(iterator, fileText, fileType)) {
if (ourBraceStack.size() == 0) return true;
final int group = getTokenGroup(getToken(iterator), fileType);
final IElementType topTokenType = ourBraceStack.pop();
final IElementType tokenType = getToken(iterator);
boolean isStrict = isStrictTagMatching(fileType, group);
boolean isCaseSensitive = areTagsCaseSensitive(fileType, group);
String topTagName = null;
String tagName = null;
if (isStrict){
topTagName = ourTagNameStack.pop();
tagName = getTagName(fileText, iterator);
}
if (!isPairBraces(topTokenType, tokenType, fileType)
|| isStrict && !Comparing.equal(topTagName, tagName, isCaseSensitive)) {
return false;
}
}
}
iterator.retreat();
}
return false;
}
public static boolean isStructuralBraceToken(FileType fileType, HighlighterIterator iterator,CharSequence text) {
BraceMatcher matcher = getBraceMatcher(fileType);
if (matcher!=null) return matcher.isStructuralBrace(iterator, text, fileType);
return false;
}
private static boolean isEndOfSingleHtmlTag(CharSequence text,HighlighterIterator iterator) {
String tagName = getTagName(text,iterator);
if (tagName!=null) return HtmlUtil.isSingleHtmlTag(tagName);
return false;
}
public static boolean isLBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType){
final BraceMatcher braceMatcher = getBraceMatcher(fileType);
if (braceMatcher!=null) return braceMatcher.isLBraceToken(iterator, fileText, fileType);
return false;
}
public static boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType){
final BraceMatcher braceMatcher = getBraceMatcher(fileType);
if (braceMatcher!=null) return braceMatcher.isRBraceToken(iterator, fileText, fileType);
return false;
}
public static boolean isPairBraces(IElementType tokenType1, IElementType tokenType2, FileType fileType){
BraceMatcher matcher = getBraceMatcher(fileType);
if (matcher!=null) return matcher.isPairBraces(tokenType1, tokenType2);
return false;
}
private static int getTokenGroup(IElementType tokenType, FileType fileType){
BraceMatcher matcher = getBraceMatcher(fileType);
if (matcher!=null) return matcher.getTokenGroup(tokenType);
return UNDEFINED_TOKEN_GROUP;
}
private static boolean isStrictTagMatching(FileType fileType, int tokenGroup) {
switch(tokenGroup){
case XML_TAG_TOKEN_GROUP:
// Other xml languages may have nonbalanced tag names
return fileType == StdFileTypes.XML ||
fileType == StdFileTypes.XHTML ||
fileType == StdFileTypes.JSPX;
case JSP_TOKEN_GROUP:
return true;
default:
return false;
}
}
private static boolean areTagsCaseSensitive(FileType fileType, int tokenGroup) {
switch(tokenGroup){
case XML_TAG_TOKEN_GROUP:
return fileType == StdFileTypes.XML;
case JSP_TOKEN_GROUP:
return true;
default:
return false;
}
}
private static String getTagName(CharSequence fileText, HighlighterIterator iterator) {
final IElementType tokenType = getToken(iterator);
String name = null;
if (tokenType == XmlTokenType.XML_START_TAG_START) {
{
boolean wasWhiteSpace = false;
iterator.advance();
IElementType tokenType1 = (!iterator.atEnd() ? getToken(iterator) :null);
if (tokenType1 == JavaTokenType.WHITE_SPACE || tokenType1 == JspTokenType.JSP_WHITE_SPACE) {
wasWhiteSpace = true;
iterator.advance();
tokenType1 = (!iterator.atEnd() ? getToken(iterator) :null);
}
if (tokenType1 == XmlTokenType.XML_TAG_NAME ||
tokenType1 == XmlTokenType.XML_NAME
) {
name = fileText.subSequence(iterator.getStart(), iterator.getEnd()).toString();
}
if (wasWhiteSpace) iterator.retreat();
iterator.retreat();
}
}
else if (tokenType == XmlTokenType.XML_TAG_END || tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END) {
{
int balance = 0;
int count = 0;
IElementType tokenType1 = getToken(iterator);
while (balance >=0) {
iterator.retreat();
count++;
if (iterator.atEnd()) break;
tokenType1 = getToken(iterator);
if(tokenType1 == XmlTokenType.XML_TAG_END || tokenType1 == XmlTokenType.XML_EMPTY_ELEMENT_END) balance++;
else if(tokenType1 == XmlTokenType.XML_TAG_NAME)
balance
}
if(tokenType1 == XmlTokenType.XML_TAG_NAME) name = fileText.subSequence(iterator.getStart(), iterator.getEnd()).toString();
while (count-- > 0) iterator.advance();
}
}
return name;
}
private static IElementType getToken(final HighlighterIterator iterator) {
return iterator.getTokenType();
}
private static boolean findEndTagStart(HighlighterIterator iterator) {
IElementType tokenType = getToken(iterator);
int balance = 0;
int count = 0;
while(balance >= 0){
iterator.retreat();
count++;
if (iterator.atEnd()) break;
tokenType = getToken(iterator);
if (tokenType == XmlTokenType.XML_TAG_END || tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END){
balance++;
}
else if (tokenType == XmlTokenType.XML_END_TAG_START || tokenType == XmlTokenType.XML_START_TAG_START){
balance
}
}
while(count-- > 0) iterator.advance();
return tokenType == XmlTokenType.XML_END_TAG_START;
}
// TODO: better name for this method
public static int findLeftmostLParen(HighlighterIterator iterator, IElementType lparenTokenType, CharSequence fileText, FileType fileType){
int lastLbraceOffset = -1;
Stack<IElementType> braceStack = new Stack<IElementType>();
for( ; !iterator.atEnd(); iterator.retreat()){
final IElementType tokenType = getToken(iterator);
if (isLBraceToken(iterator, fileText, fileType)){
if (braceStack.size() > 0){
IElementType topToken = braceStack.pop();
if (!isPairBraces(tokenType, topToken, fileType)) {
break; // unmatched braces
}
}
else{
if (tokenType == lparenTokenType){
lastLbraceOffset = iterator.getStart();
}
else{
break;
}
}
}
else if (isRBraceToken(iterator, fileText, fileType )){
braceStack.push(getToken(iterator));
}
}
return lastLbraceOffset;
}
// TODO: better name for this method
public static int findRightmostRParen(HighlighterIterator iterator, IElementType rparenTokenType, CharSequence fileText, FileType fileType) {
int lastRbraceOffset = -1;
Stack<IElementType> braceStack = new Stack<IElementType>();
for(; !iterator.atEnd(); iterator.advance()){
final IElementType tokenType = getToken(iterator);
if (isRBraceToken(iterator, fileText, fileType)){
if (braceStack.size() > 0){
IElementType topToken = braceStack.pop();
if (!isPairBraces(tokenType, topToken, fileType)) {
break; // unmatched braces
}
}
else{
if (tokenType == rparenTokenType){
lastRbraceOffset = iterator.getStart();
}
else{
break;
}
}
}
else if (isLBraceToken(iterator, fileText, fileType)){
braceStack.push(getToken(iterator));
}
}
return lastRbraceOffset;
}
public static BraceMatcher getBraceMatcher(FileType fileType) {
BraceMatcher braceMatcher = BRACE_MATCHERS.get(fileType);
if (braceMatcher==null) {
if (fileType instanceof LanguageFileType) {
final Language language = ((LanguageFileType)fileType).getLanguage();
final PairedBraceMatcher matcher = language.getPairedBraceMatcher();
if (matcher != null) {
braceMatcher = new PairedBraceMatcherAdapter(matcher,language);
}
}
if (braceMatcher == null) braceMatcher = getBraceMatcher(StdFileTypes.JAVA);
BRACE_MATCHERS.put(fileType, braceMatcher);
}
return braceMatcher;
}
}
|
package com.example.e4.rcp.todo.parts;
import javax.annotation.PostConstruct;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class PlaygroundPart {
private Text text;
private Browser browser;
@PostConstruct
public void createControls(Composite parent) {
parent.setLayout(new GridLayout(2, false));
text = new Text(parent, SWT.BORDER);
text.setMessage("Enter City");
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Button button = new Button(parent, SWT.PUSH);
button.setText("Search");
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// Commented out for LINUX
// String city = text.getText();
// if (city.isEmpty()) {
// return;
// try {
// + URLEncoder.encode(city, "UTF-8")
// + "/&output=embed");
// } catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
}
});
Label label = new Label(parent, SWT.NONE);
label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
false));
label.setText("BROWSER CODE COMMENT out in PlaygroundPart.java to avoid problems with Linux. If you not using Linux please remove the comments in this class.");
// Commented out for LINUX
// browser = new Browser(parent, SWT.NONE);
// browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
}
@Focus
public void onFocus() {
text.setFocus();
}
}
|
package com.jme.scene.state.lwjgl;
import java.nio.FloatBuffer;
import java.util.Stack;
import org.lwjgl.opengl.GL11;
import com.jme.light.DirectionalLight;
import com.jme.light.Light;
import com.jme.light.PointLight;
import com.jme.light.SpotLight;
import com.jme.scene.Spatial;
import com.jme.scene.state.LightState;
import com.jme.scene.state.RenderState;
import com.jme.util.geom.BufferUtils;
/**
* <code>LWJGLLightState</code> subclasses the Light class using the LWJGL API
* to access OpenGL for light processing.
*
* @author Mark Powell
* @version $Id: LWJGLLightState.java,v 1.13 2005-09-21 18:52:13 irrisor Exp $
*/
public class LWJGLLightState extends LightState {
private static final long serialVersionUID = 1L;
//buffer for light colors.
private transient FloatBuffer buffer;
private float[] ambient = { 0.0f, 0.0f, 0.0f, 1.0f };
private float[] color;
private float[] posParam = new float[4];
private float[] spotDir = new float[4];
private float[] defaultDirection = new float[4];
/**
* Constructor instantiates a new <code>LWJGLLightState</code>.
*
*/
public LWJGLLightState() {
super();
buffer = BufferUtils.createColorBuffer(4);
color = new float[4];
color[3] = 1.0f;
}
/**
* <code>set</code> iterates over the light queue and processes each
* individual light.
*
* @see com.jme.scene.state.RenderState#apply()
*/
public void apply() {
int quantity = getQuantity();
ambient[0] = 1;
ambient[1] = 1;
ambient[2] = 1;
ambient[3] = 1;
color[0] = 0;
color[1] = 0;
color[2] = 0;
color[3] = 1;
if (quantity > 0 && isEnabled()) {
GL11.glEnable(GL11.GL_LIGHTING);
if (twoSidedOn) {
GL11.glLightModeli(GL11.GL_LIGHT_MODEL_TWO_SIDE, GL11.GL_TRUE);
}
for (int i = 0; i < quantity; i++) {
int index = GL11.GL_LIGHT0 + i;
Light light = get(i);
if (light.getType() == Light.LT_AMBIENT) {
ambient[0] = light.getAmbient().r;
ambient[1] = light.getAmbient().g;
ambient[2] = light.getAmbient().b;
}
if (light.isEnabled()) {
GL11.glEnable(index);
color[0] = light.getAmbient().r;
color[1] = light.getAmbient().g;
color[2] = light.getAmbient().b;
buffer.clear();
buffer.put(color);
buffer.flip();
GL11.glLight(index, GL11.GL_AMBIENT, buffer);
color[0] = light.getDiffuse().r;
color[1] = light.getDiffuse().g;
color[2] = light.getDiffuse().b;
buffer.clear();
buffer.put(color);
buffer.flip();
GL11.glLight(index, GL11.GL_DIFFUSE, buffer);
color[0] = light.getSpecular().r;
color[1] = light.getSpecular().g;
color[2] = light.getSpecular().b;
buffer.clear();
buffer.put(color);
buffer.flip();
GL11.glLight(index, GL11.GL_SPECULAR, buffer);
if (light.isAttenuate()) {
GL11.glLightf(index, GL11.GL_CONSTANT_ATTENUATION,
light.getConstant());
GL11.glLightf(index, GL11.GL_LINEAR_ATTENUATION, light
.getLinear());
GL11.glLightf(index, GL11.GL_QUADRATIC_ATTENUATION,
light.getQuadratic());
} else {
GL11
.glLightf(index, GL11.GL_CONSTANT_ATTENUATION,
1.0f);
GL11.glLightf(index, GL11.GL_LINEAR_ATTENUATION, 0.0f);
GL11.glLightf(index, GL11.GL_QUADRATIC_ATTENUATION,
0.0f);
}
switch (light.getType()) {
case Light.LT_DIRECTIONAL: {
DirectionalLight pkDL = (DirectionalLight) light;
posParam[0] = -pkDL.getDirection().x;
posParam[1] = -pkDL.getDirection().y;
posParam[2] = -pkDL.getDirection().z;
posParam[3] = 0.0f;
buffer.clear();
buffer.put(posParam);
buffer.flip();
GL11.glLight(index, GL11.GL_POSITION, buffer);
break;
}
case Light.LT_POINT:
case Light.LT_SPOT: {
PointLight pointLight = (PointLight) light;
posParam[0] = pointLight.getLocation().x;
posParam[1] = pointLight.getLocation().y;
posParam[2] = pointLight.getLocation().z;
posParam[3] = 1.0f;
buffer.clear();
buffer.put(posParam);
buffer.flip();
GL11.glLight(index, GL11.GL_POSITION, buffer);
break;
}
}
if (light.getType() == Light.LT_SPOT) {
SpotLight spot = (SpotLight) light;
GL11.glLightf(index, GL11.GL_SPOT_CUTOFF, spot
.getAngle());
buffer.clear();
spotDir[0] = spot.getDirection().x;
spotDir[1] = spot.getDirection().y;
spotDir[2] = spot.getDirection().z;
buffer.put(spotDir);
buffer.flip();
GL11.glLight(index, GL11.GL_SPOT_DIRECTION, buffer);
GL11.glLightf(index, GL11.GL_SPOT_EXPONENT, spot
.getExponent());
} else {
defaultDirection[0] = 0.0f;
defaultDirection[1] = 0.0f;
defaultDirection[2] = -1.0f;
GL11.glLightf(index, GL11.GL_SPOT_CUTOFF, 180.0f);
buffer.clear();
buffer.put(defaultDirection);
buffer.flip();
GL11.glLight(index, GL11.GL_SPOT_DIRECTION, buffer);
GL11.glLightf(index, GL11.GL_SPOT_EXPONENT, 0.0f);
}
} else {
GL11.glDisable(index);
}
}
buffer.clear();
buffer.put(ambient);
buffer.flip();
GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, buffer);
for (int i = quantity; i < MAX_LIGHTS_ALLOWED; i++)
GL11.glDisable((GL11.GL_LIGHT0 + i));
} else {
GL11.glDisable(GL11.GL_LIGHTING);
}
}
public RenderState extract(Stack stack, Spatial spat) {
int mode = spat.getLightCombineMode();
if (mode == REPLACE || (mode != OFF && stack.size() == 1) )
return (LWJGLLightState) stack.peek();
// accumulate the lights in the stack into a single LightState object
LWJGLLightState newLState = new LWJGLLightState();
Object states[] = stack.toArray();
boolean foundEnabled = false;
switch (mode) {
case COMBINE_CLOSEST:
case COMBINE_RECENT_ENABLED:
for (int iIndex = states.length - 1; iIndex >= 0; iIndex
LWJGLLightState pkLState = (LWJGLLightState) states[iIndex];
if (!pkLState.isEnabled()) {
if (mode == COMBINE_RECENT_ENABLED)
break;
else
continue;
} else
foundEnabled = true;
if (pkLState.twoSidedOn)
newLState.setTwoSidedLighting(true);
for (int i = 0, maxL = pkLState.getQuantity(); i < maxL; i++) {
Light pkLight = pkLState.get(i);
if (pkLight != null) {
newLState.attach(pkLight);
}
}
}
break;
case COMBINE_FIRST:
for (int iIndex = 0, max = states.length; iIndex < max; iIndex++) {
LWJGLLightState pkLState = (LWJGLLightState) states[iIndex];
if (!pkLState.isEnabled())
continue;
else
foundEnabled = true;
if (pkLState.twoSidedOn)
newLState.setTwoSidedLighting(true);
for (int i = 0, maxL = pkLState.getQuantity(); i < maxL; i++) {
Light pkLight = pkLState.get(i);
if (pkLight != null) {
newLState.attach(pkLight);
}
}
}
break;
case OFF:
break;
}
newLState.setEnabled(foundEnabled);
return newLState;
}
}
|
package com.wakatime.eclipse.plugin;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Dependencies {
private static String pythonLocation = null;
public Dependencies() {
}
public boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
File cli = new File(WakaTime.getWakaTimeCLI());
File dir = cli.getParentFile().getParentFile();
return dir.getAbsolutePath();
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
ArrayList<String> paths = new ArrayList<String>();
paths.add(null);
paths.add("/");
paths.add("/usr/local/bin/");
paths.add("/usr/bin/");
if (System.getProperty("os.name").contains("Windows")) {
File resourcesLocation = new File(Dependencies.getResourcesLocation());
paths.add(combinePaths(resourcesLocation.getAbsolutePath(), "python"));
paths.add("/python39");
paths.add("/Python39");
paths.add("/python38");
paths.add("/Python38");
paths.add("/python37");
paths.add("/Python37");
paths.add("/python36");
paths.add("/Python36");
paths.add("/python35");
paths.add("/Python35");
paths.add("/python34");
paths.add("/Python34");
paths.add("/python33");
paths.add("/Python33");
paths.add("/python27");
paths.add("/Python27");
paths.add("/python26");
paths.add("/Python26");
}
for (String path : paths) {
try {
String[] cmds = {combinePaths(path, "pythonw"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "pythonw");
break;
} catch (Exception e) {
try {
String[] cmds = {combinePaths(path, "python"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "python");
break;
} catch (Exception e2) { }
}
}
if (Dependencies.pythonLocation != null) {
WakaTime.log("Found python binary: " + Dependencies.pythonLocation);
} else {
WakaTime.log("Could not find python binary.");
}
return Dependencies.pythonLocation;
}
public void installPython() {
if (System.getProperty("os.name").contains("Windows")) {
String pyVer = "3.5.0";
String arch = "win32";
if (is64bit()) arch = "amd64";
String url = "https:
File cli = new File(WakaTime.getWakaTimeCLI());
File dir = cli.getParentFile().getParentFile();
String outFile = combinePaths(dir.getAbsolutePath(), "python.zip");
if (downloadFile(url, outFile)) {
File targetDir = new File(combinePaths(dir.getAbsolutePath(), "python"));
// extract python
try {
unzip(outFile, targetDir);
} catch (IOException e) {
WakaTime.error("Error", e);
}
File zipFile = new File(outFile);
zipFile.delete();
}
}
}
public boolean isCLIInstalled() {
File cli = new File(WakaTime.getWakaTimeCLI());
return cli.exists();
}
public void installCLI() {
File cli = new File(WakaTime.getWakaTimeCLI());
String url = "https://codeload.github.com/wakatime/wakatime/zip/master";
String zipFile = combinePaths(cli.getParentFile().getParentFile().getParentFile().getAbsolutePath(), "wakatime.zip");
File outputDir = cli.getParentFile().getParentFile().getParentFile();
// download wakatime-master.zip file
if (downloadFile(url, zipFile)) {
// Delete old wakatime-master directory if it exists
File dir = cli.getParentFile().getParentFile();
if (dir.exists()) {
deleteDirectory(dir);
}
// unzip wakatime.zip file
try {
WakaTime.log("Extracting wakatime.zip ...");
this.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
WakaTime.log("Finished installing WakaTime dependencies.");
} catch (FileNotFoundException e) {
WakaTime.error("Error", e);
} catch (IOException e) {
WakaTime.error("Error", e);
}
}
}
public boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
WakaTime.log("Downloading " + url + " to " + outFile.toString());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
try {
// download file
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
// save file contents
DataOutputStream os = new DataOutputStream(new FileOutputStream(outFile));
entity.writeTo(os);
os.close();
return true;
} catch (ClientProtocolException e) {
WakaTime.error("Error", e);
} catch (FileNotFoundException e) {
WakaTime.error("Error", e);
} catch (IOException e) {
WakaTime.error("Error", e);
}
return false;
}
private void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
// WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath());
newFile.mkdirs();
} else {
// WakaTime.log("Extracting File: "+newFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
path.delete();
}
public static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
if (path == null)
return null;
return path.toString();
}
public static boolean is64bit() {
boolean is64bit = false;
if (System.getProperty("os.name").contains("Windows")) {
is64bit = (System.getenv("ProgramFiles(x86)") != null);
} else {
is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
}
return is64bit;
}
}
|
package com.jme3.ai.recast.structures;
/**
* A dynamic heightfield representing obstructed space.
*
* @author Tihomir Radosavljevic
*/
public class Heightfield extends BoundedField {
/**
* The height of the heightfield. (Along the z-axis in cell units.)
*/
private int height;
/**
* Heightfield of spans (width*height).
*/
private Span spans;
/**
* The width of the heightfield. (Along the x-axis in cell units.)
*/
private int width;
public Heightfield() {
structure = rcAllocHeightField();
spans = new Span(this);
}
private native Object rcAllocHeightField();
public int getHeight() {
getNativeHeight();
return height;
}
private native void getNativeHeight();
public void setHeight(int height) {
this.height = height;
setHeight();
}
private native void setHeight();
public Span getSpans() {
getNativeSpan();
return spans;
}
private native void getNativeSpan();
public int getWidth() {
getNativeWidth();
return width;
}
public native void getNativeWidth();
public void setWidth(int width) {
this.width = width;
setWidth();
}
private native void setWidth();
@Override
protected void finalize() throws Throwable {
super.finalize();
rcFreeHeightField();
}
private native void rcFreeHeightField();
/**
* Represents a span in a heightfield.
*/
public class Span {
/**
* The area id assigned to the span.
*/
private int area;
/**
* The next span higher up in column.
*/
private Span next;
/**
* The upper limit of the span.
*/
private int max;
/**
* The lower limit of the span.
*/
private int min;
private Heightfield heightfield;
private Span(Heightfield heightfield) {
this.heightfield = heightfield;
}
public int getArea() {
getNativeArea();
return area;
}
private native void getNativeArea();
public void setArea(int area) {
this.area = area;
setArea();
}
private native void setArea();
public Span getNext() {
getNativeNext();
return next;
}
private native Span getNativeNext();
public int getMax() {
getNativeMax();
return max;
}
private native void getNativeMax();
public void setMax(int max) {
this.max = max;
setMax();
}
private native void setMax();
public int getMin() {
getNativeMin();
return min;
}
private native void getNativeMin();
public void setMin(int min) {
this.min = min;
setMin();
}
private native void setMin();
@Override
public String toString() {
return "Span{" + "area=" + area + ", max=" + max + ", min=" + min + '}';
}
}
/**
* Represents a set of heightfield layers.
*
* @author Tihomir Radosavljevic
*/
public class HeightfieldLayerSet {
private Object structure;
/**
* The layers in the set.
*/
private HeightfieldLayer[] layers;
public HeightfieldLayerSet() {
structure = rcAllocHeightfieldLayerset();
}
private native Object rcAllocHeightfieldLayerset();
public HeightfieldLayer[] getLayers() {
getNativeLayers();
return layers;
}
private native void getNativeLayers();
public void setLayers(HeightfieldLayer[] layers) {
this.layers = layers;
setLayers();
}
private native void setLayers();
@Override
protected void finalize() throws Throwable {
super.finalize();
rcFreeHeightfieldLayerSet();
}
private native void rcFreeHeightfieldLayerSet();
}
/**
* Represents a heightfield layer within a layer set.
*
* @author Tihomir Radosavljevic
*/
public class HeightfieldLayer extends BoundedField {
/**
* Area ids. [Size: Same as heights].
*/
private char[] areas;
/**
* Packed neighbor connection information. [Size: Same as heights].
*/
private char[] connections;
/**
* The height of the heightfield. (Along the z-axis in cell units.)
*/
private int heightOfHeightfield;
/**
* The heightfield.
*
* [Size: (width - borderSize*2) * (h - borderSize*2)].
*/
private char[] heights;
/**
* The maximum height bounds of usable data. (Along the y-axis.)
*/
private int maxHeight;
/**
* The minimum height bounds of usable data. (Along the y-axis.)
*/
private int minHeight;
/**
* The maximum x-bounds of usable data.
*/
private int maxX;
/**
* The maximum y-bounds of usable data. (Along the z-axis.)
*/
private int maxY;
/**
* The minimum x-bounds of usable data.
*/
private int minX;
/**
* The minimum y-bounds of usable data. (Along the z-axis.)
*/
private int minY;
/**
* The width of the heightfield. (Along the x-axis in cell units.)
*/
private int width;
private HeightfieldLayerSet heightfieldLayerSet;
private HeightfieldLayer(HeightfieldLayerSet heightfieldLayerSet) {
this.heightfieldLayerSet = heightfieldLayerSet;
}
public char[] getAreas() {
getNativeAreas();
return areas;
}
private native void getNativeAreas();
public char[] getConnections() {
getNativeConnections();
return connections;
}
private native void getNativeConnections();
public int getHeightOfHeightfield() {
getNativeHeight();
return heightOfHeightfield;
}
private native void getNativeHeightOfHeightfield();
public char[] getHeights() {
getNativeHeights();
return heights;
}
private native void getNativeHeights();
public int getMaxHeight() {
getNativeMaxHeight();
return maxHeight;
}
private native void getNativeMaxHeight();
public int getMinHeight() {
getNativeMinHeight();
return minHeight;
}
private native void getNativeMinHeight();
public int getMaxX() {
getNativeMaxX();
return maxX;
}
private native void getNativeMaxX();
public int getMaxY() {
return maxY;
}
private native void getNativeMaxY();
public int getMinX() {
getNativeMinX();
return minX;
}
private native void getNativeMinX();
public int getMinY() {
getNativeMinY();
return minY;
}
private native void getNativeMinY();
public int getWidth() {
getNativeWidth();
return width;
}
private native void getNativeWidth();
}
}
|
package com.namelessmc.NamelessAPI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.google.gson.JsonObject;
import com.namelessmc.NamelessAPI.Notification.NotificationType;
import com.namelessmc.NamelessAPI.Request.Action;
public final class NamelessPlayer {
private String userName;
private String displayName;
private UUID uuid;
private int groupID;
private int reputation;
private Date registeredDate;
private boolean exists;
private boolean validated;
private boolean banned;
private String groupName;
private URL baseUrl;
/**
* Creates a new NamelessPlayer object. This constructor should not be called in the main server thread.
* @param uuid
* @param baseUrl Base API URL: <i>http(s)://yoursite.com/api/v2/API_KEY<i>
* @throws NamelessException
*/
NamelessPlayer(UUID uuid, URL baseUrl) throws NamelessException {
this.uuid = uuid;
this.baseUrl = baseUrl;
final Request request = new Request(baseUrl, Action.USER_INFO, new ParameterBuilder().add("uuid", uuid).build());
init(request);
}
private void init(Request request) throws NamelessException {
request.connect();
if (request.hasError()) throw new ApiError(request.getError());
final JsonObject response = request.getResponse();
exists = response.get("exists").getAsBoolean();
if (!exists) {
return;
}
// Convert UNIX timestamp to date
Date registered = new Date(Long.parseLong(response.get("registered").toString().replaceAll("^\"|\"$", "")) * 1000);
userName = response.get("username").getAsString();
displayName = response.get("displayname").getAsString();
//uuid = UUID.fromString(addDashesToUUID(response.get("uuid").getAsString()));
groupName = response.get("group_name").getAsString();
groupID = response.get("group_id").getAsInt();
registeredDate = registered;
validated = response.get("validated").getAsBoolean();
//reputation = response.get("reputation").getAsInt();
reputation = 0; // temp until reputation is added to API
banned = response.get("banned").getAsBoolean();
}
/**
* @return The Minecraft username associated with the provided UUID. This is not always the name displayed on the website.
* @see #getDisplayName()
*/
public String getUsername() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return userName;
}
/**
* @return The name this player uses on the website. This is not always the same as their Minecraft username.
* @see #getUsername()
*/
public String getDisplayName() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return displayName;
}
/**
* @return Minecraft UUID of this player.
* @see #getUsername()
*/
public UUID getUniqueId() {
return uuid;
}
/**
* @return A numerical group id.
*/
public int getGroupID() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return groupID;
}
/**
* @return The user's primary group name
*/
public String getGroupName() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return groupName;
}
/**
* @return The user's site reputation.
*/
public int getReputation() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return reputation;
}
/**
* @return The date the user registered on the website.
*/
public Date getRegisteredDate() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return registeredDate;
}
/**
* @return Whether an account associated with the UUID exists.
* @see #getUniqueId()
*/
public boolean exists() {
return exists;
}
/**
* @return Whether this account has been validated. An account is validated when a password is set.
*/
public boolean isValidated() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return validated;
}
/**
* @return Whether this account is banned from the website.
*/
public boolean isBanned() {
if (!exists) {
throw new UnsupportedOperationException("This player does not exist.");
}
return banned;
}
/**
* @param code
* @return True if the user could be validated successfully, false if the provided code is wrong
* @throws NamelessException
* @throws
*/
public boolean validate(String code) throws NamelessException {
final String[] params = new ParameterBuilder()
.add("uuid", uuid)
.add("code", code).build();
final Request request = new Request(baseUrl, Action.VALIDATE_USER, params);
request.connect();
if (request.hasError()) {
if (request.getError() == ApiError.INVALID_VALIDATE_CODE) {
return false;
} else {
throw new ApiError(request.getError());
}
} else {
return true;
}
}
public List<Notification> getNotifications() throws NamelessException {
final Request request = new Request(baseUrl, Action.GET_NOTIFICATIONS, new ParameterBuilder().add("uuid", uuid).build());
request.connect();
if (request.hasError()) throw new ApiError(request.getError());
final List<Notification> notifications = new ArrayList<>();
final JsonObject object = request.getResponse();
object.getAsJsonArray().forEach((element) -> {
final String message = element.getAsJsonObject().get("message").getAsString();
final String url = element.getAsJsonObject().get("url").getAsString();
final NotificationType type = NotificationType.fromString(element.getAsJsonObject().get("type").getAsString());
notifications.add(new Notification(message, url, type));
});
return notifications;
}
/**
* Sets the players group
* @param groupId Numerical ID associated with a group
* @throws NamelessException
*/
public void setGroup(int groupId) throws NamelessException {
final String[] parameters = new ParameterBuilder().add("uuid", uuid).add("group_id", groupId).build();
final Request request = new Request(baseUrl, Action.SET_GROUP, parameters);
request.connect();
if (request.hasError()) throw new ApiError(request.getError());
}
/**
* Registers a new account. The player will be sent an email to set a password.
* @param minecraftName In-game name for this player
* @param email Email address
* @return Email verification disabled: A link which the user needs to click to complete registration
* <br>Email verification enabled: An empty string (the user needs to check their email to complete registration)
* @throws NamelessException
*/
public String register(String minecraftName, String email) throws NamelessException {
final String[] parameters = new ParameterBuilder().add("username", minecraftName).add("uuid", uuid).add("email", email).build();
final Request request = new Request(baseUrl, Action.REGISTER, parameters);
request.connect();
if (request.hasError()) throw new ApiError(request.getError());
final JsonObject response = request.getResponse();
if (response.has("link")) {
return response.get("link").getAsString();
} else {
return "";
}
}
/**
* Reports a player
* @param reportedUuid UUID of the reported player
* @param reportedUsername In-game name of the reported player
* @param reason Reason why this player has been reported
* @throws NamelessException
*/
public void createReport(UUID reportedUuid, String reportedUsername, String reason) throws NamelessException {
final String[] parameters = new ParameterBuilder()
.add("reporter_uuid", uuid)
.add("reported_uuid", reportedUuid)
.add("reported_username", reportedUsername)
.add("reason", reason)
.build();
Request request = new Request(baseUrl, Action.CREATE_REPORT, parameters);
request.connect();
if (request.hasError()) throw new ApiError(request.getError());
}
}
|
package com.ralitski.util.input;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import com.ralitski.util.input.event.ControllerAxisEvent;
import com.ralitski.util.input.event.ControllerAxisEvent.ControllerAxisType;
import com.ralitski.util.input.event.ControllerButtonEvent;
import com.ralitski.util.input.event.ControllerEvent;
public abstract class ControllerMonitor {
public void update() {
while(Controllers.next()) {
handleInput();
}
}
private void handleInput() {
int index = Controllers.getEventControlIndex();
Controller src = Controllers.getEventSource();
long nano = Controllers.getEventNanoseconds();
if(Controllers.isEventButton()) {
boolean state = Controllers.getEventButtonState();
handleEvent(new ControllerButtonEvent(src, index, nano, state));
} else if(Controllers.isEventXAxis()) {
float x = Controllers.getEventXAxisValue();
handleEvent(new ControllerAxisEvent(src, index, nano, x, ControllerAxisType.AXIS_X));
} else if(Controllers.isEventYAxis()) {
float y = Controllers.getEventYAxisValue();
handleEvent(new ControllerAxisEvent(src, index, nano, y, ControllerAxisType.AXIS_Y));
} else if(Controllers.isEventPovX()) {
float x = Controllers.getEventXAxisValue();
handleEvent(new ControllerAxisEvent(src, index, nano, x, ControllerAxisType.POV_X));
} else if(Controllers.isEventPovY()) {
float y = Controllers.getEventYAxisValue();
handleEvent(new ControllerAxisEvent(src, index, nano, y, ControllerAxisType.POV_Y));
}
}
public abstract void handleEvent(ControllerEvent event);
}
|
package ctripwireless.testclient.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shelper.iffixture.HTTPFacade;
import ctripwireless.testclient.enums.ActionFileName;
import ctripwireless.testclient.enums.CheckPointResult;
import ctripwireless.testclient.enums.CheckPointType;
import ctripwireless.testclient.enums.HistoryFolderName;
import ctripwireless.testclient.enums.LoopParameterNameInForm;
import ctripwireless.testclient.enums.PreConfigType;
import ctripwireless.testclient.enums.SeperatorDefinition;
import ctripwireless.testclient.enums.TestStatus;
import ctripwireless.testclient.factory.JsonObjectMapperFactory;
import ctripwireless.testclient.httpmodel.CheckPointItem;
import ctripwireless.testclient.httpmodel.Json;
import ctripwireless.testclient.httpmodel.PreConfigItem;
import ctripwireless.testclient.httpmodel.ServerItem;
import ctripwireless.testclient.httpmodel.ServiceBoundDataItem;
import ctripwireless.testclient.httpmodel.SqlEntity;
import ctripwireless.testclient.httpmodel.TestResultItem;
import ctripwireless.testclient.model.CheckPointContianer;
import ctripwireless.testclient.model.HttpTarget;
import ctripwireless.testclient.model.InvokeRequest;
import ctripwireless.testclient.model.InvokeResponse;
import ctripwireless.testclient.model.KeyValue;
import ctripwireless.testclient.model.Parameter;
import ctripwireless.testclient.model.PreConfigContainer;
import ctripwireless.testclient.model.SocketTarget;
import ctripwireless.testclient.model.SqlQueryReturn;
import ctripwireless.testclient.utils.Auto;
import ctripwireless.testclient.utils.FileNameUtils;
import ctripwireless.testclient.utils.JdbcUtils;
import ctripwireless.testclient.utils.MyFileUtils;
import ctripwireless.testclient.utils.SocketOperationUtils;
import ctripwireless.testclient.utils.TemplateUtils;
@Service("testExecuteService")
public class TestExecuteService {
private static final Logger logger = Logger.getLogger(TestExecuteService.class);
@Autowired
OutputParameterService outputParameterService;
@Autowired
SocketOperationUtils socketOperationUtils;
public Json executeTest(Map<String, Object> request) {
Json j=new Json();
String path = request.get("__HiddenView_path").toString();
Map<String, Object> datamap=getParametersFromPreConfigFile(path,request);
request.putAll(datamap);
request=getRequestParameterMap(request);
TestResultItem testresult = getTestResultItem(path,request);
if(!testresult.getResult().equals(TestStatus.exception)){
getCheckpointsAndResultFromFile(path, request, testresult.getResponseInfo(),testresult);
j.setSuccess(true);
}else{
j.setMsg("\n" + testresult.getComment());
j.setSuccess(false);
}
j.setObj(testresult);
return j;
}
public void setupAction(String testPath){
executeSqlAction(testPath,ActionFileName.setup);
executeServiceAction(testPath,ActionFileName.setup);
}
public void teardownAction(String testPath,Map requestParas,String response){
executeSqlAction(testPath,ActionFileName.teardown,requestParas,response);
executeServiceAction(testPath,ActionFileName.teardown);
}
private void executeServiceAction(String testPath, String actionType){
try {
File f=new File(testPath+"/"+actionType+"2");
if(f.exists()){
String serviceCalled=FileUtils.readFileToString(f);
Map request = getRequestParameterMap(serviceCalled);
executeServiceRequest(serviceCalled,request);
}
} catch (IOException e) {
logger.error(e.getClass()+e.getMessage());
}
}
private int executeSqlAction(String testPath, String actionType){
File f=new File(testPath+"/"+actionType);
if(f.exists()){
try {
String sqlactionstr = FileUtils.readFileToString(f, "UTF-8");
if(sqlactionstr.contains("[[") && sqlactionstr.contains("]]"))
sqlactionstr=processEnv(loadEnv(testPath),sqlactionstr);
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
SqlEntity e = mapper.readValue(sqlactionstr, SqlEntity.class);
String source=e.getSource();
String server=e.getServer();
String port=e.getPort();
String username=e.getUsername();
String password=e.getPassword();
String database=e.getDatabase();
String sql=e.getSql();
return new JdbcUtils(source, server, port, username, password, database).executeSqlAction(sql);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return 0;
}
private int executeSqlAction(String testPath, String actionType,Map reqParas,String response){
File f=new File(testPath+"/"+actionType);
if(f.exists()){
try {
String sqlactionstr = FileUtils.readFileToString(f, "UTF-8");
if(sqlactionstr.contains("[[") && sqlactionstr.contains("]]"))
sqlactionstr=processEnv(loadEnv(testPath),sqlactionstr);
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
SqlEntity e = mapper.readValue(sqlactionstr, SqlEntity.class);
String source=e.getSource();
String server=e.getServer();
String port=e.getPort();
String username=e.getUsername();
String password=e.getPassword();
String database=e.getDatabase();
String sql=e.getSql();
//resolve string if contains parameter
sql = TemplateUtils.getString(sql, reqParas);
if(actionType.equalsIgnoreCase(ActionFileName.teardown)){
sql=processOutputParameter(testPath, response, sql);
}
return new JdbcUtils(source, server, port, username, password, database).executeSqlAction(sql);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return 0;
}
public Set<CheckPointItem> getCheckpointsAndResultFromFile(String foldername,Map parameters, String responseinfo, TestResultItem testresult){
try{
File checkpoint=new File(FileNameUtils.getCheckPointsFilePath(foldername));
if(checkpoint.exists()){
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String ckstr = FileUtils.readFileToString(checkpoint, "UTF-8");
CheckPointContianer c;
if(ckstr.indexOf("[[")>0 && ckstr.indexOf("]]")>ckstr.indexOf("[[")){
ckstr=processEnv(loadEnv(foldername),ckstr);
c = mapper.readValue(ckstr, CheckPointContianer.class);
}else
c = mapper.readValue(checkpoint, CheckPointContianer.class);
testresult.setResult(TestStatus.pass);
if(c.getCheckPoint().entrySet().size()==0){
testresult.setResult(TestStatus.invalid);
return testresult.getCheckPoint();
}
//String responsebody=responseinfo.substring(responseinfo.indexOf("[body]:")+1);
for(Entry<String,CheckPointItem> entry:c.getCheckPoint().entrySet()){
CheckPointItem item = new CheckPointItem();
item=entry.getValue();
String checktype=item.getType();
//resolve string if contains parameter
String checkInfo = TemplateUtils.getString(item.getCheckInfo(),parameters);
item.setCheckInfo(checkInfo);
if(checktype.equals(CheckPointType.CheckSql)){
checkInfo=this.processOutputParameter(foldername, responseinfo, checkInfo);
addCheckPointItemsForDBVerification(testresult,checkInfo,responseinfo);
}else if(checktype.equals(CheckPointType.CheckJsExp)){
String[] arr=checkInfo.split(SeperatorDefinition.checkInfoSeperator);
String objtext=responseinfo.replaceAll("\\n","").replaceAll("\\r","");
objtext=StringUtils.substringAfter(objtext, arr[0]);
if(!arr[1].isEmpty()){
objtext=StringUtils.substringBefore(objtext, arr[1]);
}
addCheckPointItemsForJsExpVerification(testresult,arr[2].split("`"),objtext.trim());
}else{
boolean r=false;
if(checktype.equals(CheckPointType.CheckContain)){
r = responseinfo.contains(checkInfo);
}else if(checktype.equals(CheckPointType.CheckPattern)){
try{
r = responseinfo.replaceAll("\\n","").replaceAll("\\r","").matches(checkInfo);
}catch(Exception e){
r=false;
item.setCheckInfo(checkInfo+"\n"+""+e.getMessage());
}
}
if(r){
item.setResult(CheckPointResult.pass);
}else{
item.setResult(CheckPointResult.fail);
if(testresult.getResult().equalsIgnoreCase(CheckPointResult.pass))
testresult.setResult(TestStatus.fail);
}
testresult.getCheckPoint().add(item);
}
}
}
else
testresult.setResult(TestStatus.invalid);
}catch(Exception e){
logger.error("test execute error",e);
}
return testresult.getCheckPoint();
}
private void addCheckPointItemsForDBVerification(TestResultItem testresult, String setting, String response){
String[] arr=setting.split(SeperatorDefinition.checkInfoSeperator);
if(arr.length==8){
String source=arr[0];
String server=arr[1];
String port=arr[2];
String username=arr[3];
String password=arr[4];
String db=arr[5];
String sql=arr[6];
String data=arr[7];
SqlQueryReturn sqr= new JdbcUtils(source,server,port,username,password,db).getReturnedColumnsAndRows(sql);
for(String item : data.split(SeperatorDefinition.verifiedDataRow)){
String[] a=item.split(SeperatorDefinition.verifiedDataItem);
String column=a[0];
String rowIndex=a[1];
String comparedType=a[2];
String expectedValue=a[3].trim();
String actualValue=new JdbcUtils(source,server,port,username,password,db).getValueByColumnAndRowIndex(sqr,column,rowIndex);
actualValue=actualValue.trim();
boolean res=false;
if(comparedType.equalsIgnoreCase("equal")){
res=expectedValue.equalsIgnoreCase(actualValue);
}else if(comparedType.equalsIgnoreCase("contain")){
res=expectedValue.contains(actualValue);
}else if(comparedType.equalsIgnoreCase("pattern")){
res=actualValue.matches(expectedValue);
}else if(comparedType.equalsIgnoreCase("equalFromResponse")){
String[] str = expectedValue.split(SeperatorDefinition.shrinkResponseSeperator);
expectedValue=getParaValueFromResponse(response,str[0],str[1],Integer.parseInt(str[2]));
res=expectedValue.equalsIgnoreCase(actualValue);
}
CheckPointItem cp=new CheckPointItem();
cp.setName("Verify Column: "+column+" in DB: "+db);
cp.setType("sql "+comparedType);
cp.setCheckInfo("Expected: "+expectedValue+"; Actual: "+actualValue);
cp.setResult(res ? CheckPointResult.pass : CheckPointResult.fail);
testresult.getCheckPoint().add(cp);
if(testresult.getResult().equalsIgnoreCase(CheckPointResult.pass)){
if(!res)
testresult.setResult(CheckPointResult.fail);
}
}
}
}
//modejs
private void addCheckPointItemsForJsExpVerification(TestResultItem testresult, String[] exps, String objtext){
String objDef="";
String res="";
if(!objtext.isEmpty()){
if(objtext.indexOf("{")>-1 & objtext.indexOf("{")<objtext.indexOf("}")){
objDef="var obj=JSON.parse('"+objtext.replace(" ", "").replace("'", "\"")+"');";
}
//xmldom npm
else if(objtext.indexOf("<")>-1 & objtext.indexOf("<")<objtext.indexOf(">")){
objDef="var DOMParser = require('xmldom').DOMParser1;var obj=new DOMParser().parseFromString('"+objtext.replace("'", "\"")+"','text/xml');";
}
for(int i=0;i<exps.length;i++){
objDef+="console.info("+exps[i]+");";
}
String filename=new Date().getTime()+".js";
File f=new File(filename);
try{
f.createNewFile();
FileUtils.writeStringToFile(f, objDef);
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("cmd /k node "+f.getAbsolutePath());
InputStream err = p.getErrorStream();
InputStream is = p.getInputStream();
p.getOutputStream().close();
res = IOUtils.toString(err,"gbk");
res += IOUtils.toString(is,"gbk");
res = StringUtils.substringBetween(res, "", "\n\r");
int exitVal = p.waitFor();
}catch(Exception e){
res=e.getMessage();
}finally{
if(f.exists())
f.delete();
}
}
String[] result=res.split("\n");
for(int i=0;i<exps.length;i++){
CheckPointItem cp=new CheckPointItem();
cp.setName("Verify content by js expression "+(i+1));
cp.setType("js expression");
cp.setCheckInfo(exps[i]);
boolean r=Boolean.parseBoolean(result.length==exps.length ? result[i] : "false");
cp.setResult(r ? CheckPointResult.pass : CheckPointResult.fail);
testresult.getCheckPoint().add(cp);
if(testresult.getResult().equalsIgnoreCase(CheckPointResult.pass)){
if(!r)
testresult.setResult(CheckPointResult.fail);
}
}
}
private String getParameterValueAfterRequest(String extraInfo){
String val="";
String[] parainfo=extraInfo.split(SeperatorDefinition.paraForReferencedService);
String path=parainfo[0];
String lb=parainfo[1];
String rb=parainfo[2];
return getParaValueAfterRequest(path,lb,rb,1);
}
private String getParaValueAfterRequest(String path,String lb,String rb,int times){
Map paras = getRequestParameterMap(path);
String res = getTestResultItem(path,paras).getResponseInfo();
int startpos = res.indexOf(lb);
if(startpos>0){
while(times
if(startpos>0)
res = res.substring(startpos+lb.length());
startpos = res.indexOf(lb);
}
int endpos = res.indexOf(rb);
if(endpos>0){
res = res.substring(0, endpos);
}else
res="";
}else
res="";
return res;
}
private String getParaValueFromResponse(String response,String lb,String rb,int times){
int startpos = response.indexOf(lb);
if(startpos>0){
while(times
if(startpos>0)
response = response.substring(startpos+lb.length());
startpos = response.indexOf(lb);
}
int endpos = response.indexOf(rb);
if(endpos>0){
response = response.substring(0, endpos);
}else
response="";
}else
response="";
return response;
}
//for back-end test execution usage
public Map<String,Object> getRequestParameterMap(String path){
Map<String,Object> request=new HashMap<String,Object>();
try {
request.put("auto", new Auto());
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String targetjson="";
Map<String, Parameter> paras = new HashMap<String, Parameter>();
if(path.endsWith("-leaf")){
targetjson=FileNameUtils.getHttpTarget(path);
HttpTarget target = mapper.readValue(new File(targetjson), HttpTarget.class);
paras=target.getParameters();
}else if(path.endsWith("-t")){
targetjson=FileNameUtils.getSocketTestAbsPath(path);
SocketTarget target = mapper.readValue(new File(targetjson), SocketTarget.class);
paras=target.getParameters();
}
for(Parameter p : paras.values()){
String val=p.getDefaultValue();
//if defaultvalue is returned function of Auto class.
val = TemplateUtils.getString(val, request);
if(p.getType().equalsIgnoreCase("loop")){
p.setName(LoopParameterNameInForm.name);
}
else if(p.getType().equalsIgnoreCase("service")){
val=getParameterValueAfterRequest(p.getExtraInfo());
}
request.put(p.getName(), val);
}
Map<String, Object> datamap=getParametersFromPreConfigFile(path,request);
request.putAll(datamap);
}catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getClass().toString()+": "+e.getMessage());
}
return request;
}
//for submit form usage
private Map<String,Object> getRequestParameterMap(Map<String, Object> request){
try{
for(Entry<String, Object> e : request.entrySet()){
String val=e.getValue().toString();
if(val!=null && !val.isEmpty()){
if(val.contains(SeperatorDefinition.paraForReferencedService)){
val=getParameterValueAfterRequest(val);
request.put(e.getKey(), val);
break;
}
}
}
}catch(Exception e){
logger.error(e.getClass().toString()+": "+e.getMessage());
}
return request;
}
private Map<String,Object> getParametersFromPreConfigFile(String testPath,Map<String,Object> request){
Map<String,Object> para=new HashMap<String,Object>();
try {
File f=new File(FileNameUtils.getPreConfigFilePath(testPath));
if(f.exists()){
String preconfigstr = FileUtils.readFileToString(f, "UTF-8");
if(preconfigstr.contains("[[") && preconfigstr.contains("]]"))
preconfigstr=processEnv(loadEnv(testPath),preconfigstr);
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
PreConfigContainer c = mapper.readValue(preconfigstr, PreConfigContainer.class);
for(Entry<String,PreConfigItem> entry:c.getPreConfig().entrySet()){
String type=entry.getValue().getType();
String setting=entry.getValue().getSetting();
if(type.equalsIgnoreCase(PreConfigType.service)){
String[] arr=setting.split(SeperatorDefinition.paraForReferencedService);
String path=arr[0];
String[] configs=arr[1].split(SeperatorDefinition.queryBoundRow);
for(String item : configs){
String[] info=item.split(SeperatorDefinition.queryBoundItem);
String lb=info[1];
String rb=info[2];
int times=Integer.parseInt(info[3]);
String value=getParaValueAfterRequest(path,lb,rb,times);
para.put(info[0], value);
}
}else if(type.equalsIgnoreCase(PreConfigType.query)){
String[] arr=setting.split(SeperatorDefinition.paraForReferencedService);
String datasource=arr[0];
String server=arr[1];
String port=arr[2];
String username=arr[3];
String password=arr[4];
String db=arr[5];
String sql=arr[6];
if(sql.contains("${")){
try {
sql = TemplateUtils.getString(sql, request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Map<String,String> evnmap=loadEnv(testPath);
// if(server.startsWith("[["))
// server=processVariableInEnv(evnmap,server);
// if(port.startsWith("[["))
// port=processVariableInEnv(evnmap,port);
// if(username.startsWith("[["))
// username=processVariableInEnv(evnmap,username);
// if(password.startsWith("[["))
// password=processVariableInEnv(evnmap,password);
// if(db.startsWith("[["))
// db=processVariableInEnv(evnmap,db);
String[] configs=arr[7].split(SeperatorDefinition.queryBoundRow);
SqlQueryReturn sqr= new JdbcUtils(datasource,server,port,username,password,db).getReturnedColumnsAndRows(sql);
for(String item : configs){
String[] info=item.split(SeperatorDefinition.queryBoundItem);
String columnLabel=info[1];
String rowIndex=info[2];
String value=new JdbcUtils(datasource,server,port,username,password,db).getValueByColumnAndRowIndex(sqr,columnLabel,rowIndex);
para.put(info[0], value);
}
}
}
}
}catch (IOException e) {
logger.error(e.getClass()+e.getMessage());
}
return para;
}
public void generateHistoryFile(String foldername, TestResultItem testresult) {
try{
String folder = foldername + "/"+HistoryFolderName.folderName;
String filename = FileNameUtils.getResultFile(testresult.getTime(), testresult.getDuration(),testresult.getResult());
File dir=new File(folder);
if(!dir.exists()){
dir.mkdirs();
}
File file=new File(dir,filename);
if(!file.exists()){
file.createNewFile();
}
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
mapper.writeValue(file, testresult);
} catch (JsonGenerationException e) {
logger.error("", e);
} catch (JsonMappingException e) {
logger.error("", e);
} catch (IOException e) {
logger.error("", e);
}
}
private int executeHttpServiceRequest(String path, Map request){
int reponsestatus=0;
try{
Map<String,String> evnmap=loadEnv(path);
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String httptargetjson=FileNameUtils.getHttpTarget(path);
HttpTarget target = mapper.readValue(new File(httptargetjson), HttpTarget.class);
String url=processEnv(evnmap,target.getPath());
url=TemplateUtils.getString(url, request);
HTTPFacade hf=new HTTPFacade();
hf.setRequesttimeout(600*1000);
hf.setUrl(url);
String body=processEnv(evnmap,target.getRequestBody());
body=TemplateUtils.getString(body, request);
Set<KeyValue> headset=target.getHeads();
for(KeyValue kv:headset){
hf.addHeaderValue(kv.getKey(), kv.getValue());
}
if(body==null || body.trim().equals("")){
hf.get();
}else{
for(Object e : request.entrySet()){
Object v=((Entry<String,String>)e).getValue();
if(v instanceof String){
String k=((Entry<String,String>)e).getKey();
hf.addParamValue(k, v.toString());
}
}
hf.addRequestBody(body);
hf.postWithQueryStrInUrl();
}
reponsestatus= hf.getStatus();
}catch(Exception e){
logger.error(e.getClass()+e.getMessage());
}
return reponsestatus;
}
private void executeSocketServiceRequest(String path, Map request){
try{
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String socketconfig=FileNameUtils.getSocketTestAbsPath(path);
SocketTarget target = mapper.readValue(new File(socketconfig), SocketTarget.class);
String head=retrieveString(target.getHead(),path,request);
String body=retrieveString(target.getBody(),path,request);
String name=target.getServer().getName();
String ip=retrieveString(target.getServer().getIp(),path,request);
String port=retrieveString(target.getServer().getPort(),path,request);
String protocol=target.getServer().getProtocol();
String code=target.getCode();
int dataversion=target.getDatagramVersion();
boolean indented=target.isIndented();
InvokeRequest req = new InvokeRequest();
ServerItem si=new ServerItem();
si.setName(name);
si.setIp(ip);
si.setPort(port);
si.setProtocol(protocol);
req.setServer(si);
req.setCode(code);
req.setHead(head);
req.setBody(body);
req.setDatagramVersion(dataversion);
req.setIndented(indented);
socketOperationUtils.invokeService(req);
}catch(Exception e){
logger.error(e.getClass()+e.getMessage());
}
}
private void executeServiceRequest(String path, Map request){
if(path.endsWith("-leaf")){
executeHttpServiceRequest(path,request);
}else if(path.endsWith("-t")){
executeSocketServiceRequest(path,request);
}
}
public TestResultItem getTestResultItem(String folderName, Map request){
TestResultItem testresult=new TestResultItem();
if(folderName.endsWith("-leaf")){
testresult=getHttpTestResultItem(folderName,request);
}else if(folderName.endsWith("-t")){
testresult=getSocketTestResultItem(folderName,request);
}
return testresult;
}
private TestResultItem getHttpTestResultItem(String path, Map request){
TestResultItem testresult=new TestResultItem();
try{
String requestinfo="";
String resopnseinfo="";
Set<String> callbackset=new HashSet<String>();
Map<String,String> evnmap=loadEnv(path);
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String httptargetjson=FileNameUtils.getHttpTarget(path);
HttpTarget target = mapper.readValue(new File(httptargetjson), HttpTarget.class);
String url=retrieveString(target.getPath(),path, request).trim();
boolean ishttps=url.startsWith("https") ? true : false;
HTTPFacade hf=new HTTPFacade(ishttps);
hf.setRequesttimeout(600*1000);
hf.setUrl(url);
String body=retrieveString(target.getRequestBody(),path, request);
requestinfo="[url]:\n"+url+"\n[request headers]:\n";
Set<KeyValue> headset=target.getHeads();
for(KeyValue kv:headset){
String k=retrieveString(kv.getKey(),path, request);
String v=retrieveString(kv.getValue(),path, request);
hf.addHeaderValue(k, v);
requestinfo+=k + ":"+v+"\n";
}
requestinfo+="[request body]:\n"+body;
long start = System.currentTimeMillis();
if(body==null || body.trim().equals("")){
hf.get();
}else{
for(Object e : request.entrySet()){
Object v=((Entry<String,String>)e).getValue();
if(v instanceof String){
String k=((Entry<String,String>)e).getKey();
hf.addParamValue(k, v.toString());
}
}
hf.addRequestBody(body);
hf.postWithQueryStrInUrl();
}
long end = System.currentTimeMillis();
long duration = end - start;
testresult.setDuration(String.valueOf(duration));
String responsebody=hf.getResponseBody();
int responsestatus=hf.getStatus();
String responseheader="";
if(!responsebody.isEmpty()){
responseheader=hf.getResponseheaders();
}
logger.info("REQUEST finish with status:"+responsestatus+"\nresponse body:"+responsebody+"\n reponse heads:"+responseheader);
resopnseinfo="[status]:\n" + responsestatus + "\n" ;
resopnseinfo+="[response headers]:\n" + responseheader + "\n" ;
resopnseinfo+="[body]:\n" + responsebody;
if(responsestatus==200){
if(request.get("testcallback")!=null && request.get("testcallback").equals("callPayRedirction")){
callbackset.add(callBack(request,responsebody));
}else if(request.get("testcallback")!=null && request.get("testcallback").equals("callPayRedirction4CreateTicketOrder")){
callbackset.add(callBack4CreateTicketOrder(request,responsebody));
}
}
if(responsestatus!=0){
requestinfo=requestinfo.replaceAll("<", "<").replaceAll(">", ">").replaceAll("'", "'").replaceAll(""","\"").replaceAll("&", "&");
resopnseinfo=resopnseinfo.replaceAll("<", "<").replaceAll(">", ">").replaceAll("'", "'").replaceAll(""","\"").replaceAll("&", "&");
testresult.setRequestInfo(requestinfo);
testresult.setResponseInfo(resopnseinfo);
testresult.setCallback(callbackset);
}else{
testresult.setResult(TestStatus.exception);
testresult.setComment("communication failure! response status:"+responsestatus);
}
}catch(Exception e){
testresult.setResult(TestStatus.exception);
testresult.setComment(e.getClass().toString()+": "+e.getMessage());
}
return testresult;
}
private String retrieveString(String content,String folderName, Map request){
try {
Map<String,String> evnmap=loadEnv(folderName);
content=processEnv(evnmap,content);
content=TemplateUtils.getString(content, request);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
private TestResultItem getSocketTestResultItem(String path, Map request){
TestResultItem testresult=new TestResultItem();
try{
String requestinfo="";
String resopnseinfo="";
Set<String> callbackset=new HashSet<String>();
ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper();
String socketconfig=FileNameUtils.getSocketTestAbsPath(path);
SocketTarget target = mapper.readValue(new File(socketconfig), SocketTarget.class);
String head=retrieveString(target.getHead(),path,request);
String body=retrieveString(target.getBody(),path,request);
String name=target.getServer().getName();
String ip=retrieveString(target.getServer().getIp(),path,request);
String port=retrieveString(target.getServer().getPort(),path,request);
String protocol=target.getServer().getProtocol();
String code=target.getCode();
String service=target.getServiceDescription();
int dataversion=target.getDatagramVersion();
boolean indented=target.isIndented();
requestinfo="[Server]:\n"+name+" "+ip+":"+port+" "+protocol+"\n";
requestinfo+="[Service]:\n"+service+"\n";
requestinfo+="[Request Head]:\n"+head+"\n";
requestinfo+="[Request Body]:\n"+body+"\n";
InvokeRequest req = new InvokeRequest();
ServerItem si=new ServerItem();
si.setName(name);
si.setIp(ip);
si.setPort(port);
si.setProtocol(protocol);
req.setServer(si);
req.setCode(code);
req.setHead(head);
req.setBody(body);
req.setDatagramVersion(dataversion);
req.setIndented(indented);
InvokeResponse response=socketOperationUtils.invokeService(req);
testresult.setDuration(response.getTimespan());
String responsebody=response.getBody();
logger.info("REQUEST finish with response body:"+responsebody+"\n");
resopnseinfo="[Response Body]:\n" + responsebody;
String error=response.getError();
if(error==null || error.trim().isEmpty()){
testresult.setRequestInfo(requestinfo);
testresult.setResponseInfo(resopnseinfo);
testresult.setCallback(callbackset);
}else{
testresult.setResult(TestStatus.exception);
testresult.setComment("Error: "+error);
}
}catch(Exception e){
testresult.setResult(TestStatus.exception);
testresult.setComment(e.getClass().toString()+": "+e.getMessage());
}
return testresult;
}
public String callBack(Map<String,String> map,String response){
String orderamount=map.get("OrderAmount");
String callbackhost =map.get("callbackhost");
String paymentdomain =map.get("paymentdomain");
String paymenttitle =map.get("paymenttitle");
String auth=StringUtils.substringBetween(response, "\"auth\":\"", "\"");
String onum=StringUtils.substringBetween(response, "\"odnum\":\"", "\"");
return "Ext.getCmp('Base').PayAction(\""+auth+"\",\""+onum+"\",\""+paymenttitle+"\","+orderamount+",\""+callbackhost+"\",\""+paymentdomain+"\",2001)";
}
public String callBack4CreateTicketOrder(Map<String,String> map,String response){
String orderamount=map.get("OrderAmount");
String callbackhost =map.get("callbackhost");
String paymentdomain =map.get("paymentdomain");
String paymenttitle =map.get("paymenttitle");
String auth=StringUtils.substringBetween(response, "\"auth\":\"", "\"");
String onum=StringUtils.substringBetween(response, "\"oid\":", ",");
return "Ext.getCmp('Base').PayAction(\""+auth+"\",\""+onum+"\",\""+paymenttitle+"\","+orderamount+",\""+callbackhost+"\",\""+paymentdomain+"\",7)";
}
public Map<String,String> loadEnv(String foldername){
Map<String,String> m=new HashMap<String,String>();
File f=new File(FileNameUtils.getEnvFilePath(foldername));
while(true){
if(f.exists()){
try {
String fs=FileUtils.readFileToString(f);
if(!fs.isEmpty()){
String[] fa=fs.split("\n");
for(String s:fa){
String[] kv=s.split("=");
if(kv.length==2){
if(!m.containsKey(kv[0])){
m.put(kv[0], kv[1]);
}
}else
if(kv.length==1){
if(!m.containsKey(kv[0])){
m.put(kv[0], "");
}
}else if(kv.length>2){
if(!m.containsKey(kv[0])){
m.put(kv[0],StringUtils.substringAfter(s, kv[0]+"="));
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String parentFileName=f.getParentFile().getName();
if(!parentFileName.endsWith("-leaf") && !parentFileName.endsWith("-t") && !parentFileName.endsWith("-dir")){
break;
}else
f=new File(FileNameUtils.getEnvFilePath(f.getParentFile().getParent()));
}
return m;
}
public String processEnv(Map<String,String> m,String content){
String result=content;
if(content.contains("[[") && content.contains("]]")){
for(Entry<String, String> e:m.entrySet()){
result=result.replace("[["+e.getKey()+"]]", e.getValue());
}
}
return result;
}
public String processVariableInEnv(Map<String,String> m,String variable){
variable=variable.replace("[[", "").replace("]]", "");
return m.get(variable);
}
private List<ServiceBoundDataItem> loadOutputParameter(String testPath){
return outputParameterService.getOutputParameterDataItems(testPath).getRows();
}
public String processOutputParameter(String testPath,String responseInfo,String content){
int pos1=content.indexOf("{{");
int pos2=content.indexOf("}}");
while(pos1>=0 && pos1<pos2){
List<ServiceBoundDataItem> parameters = loadOutputParameter(testPath);
String name=content.substring(pos1+2, pos2);
String value="";
for(ServiceBoundDataItem p : parameters){
if(name.equalsIgnoreCase(p.getName())){
String lb=p.getLb();
String rb=p.getRb();
String times=p.getTimes();
value=getParaValueFromResponse(responseInfo,lb,rb,Integer.parseInt(times));
break;
}
}
content=content.replace("{{"+name+"}}", value);
pos1=content.indexOf("{{");
pos2=content.indexOf("}}");
}
return content;
}
public String processOutputParameter(String testPath,String content){
int pos1=content.indexOf("{{");
int pos2=content.indexOf("}}");
String responseinfo="";
if(pos2>pos1 && pos1>0){
Map request = getRequestParameterMap(testPath);
TestResultItem item = getTestResultItem(testPath,request);
if(!item.getResult().equals(TestStatus.exception)){
responseinfo=item.getResponseInfo();
}
}
while(pos1>=0 && pos1<pos2){
List<ServiceBoundDataItem> parameters = loadOutputParameter(testPath);
String name=content.substring(pos1+2, pos2);
String value="";
for(ServiceBoundDataItem p : parameters){
if(name.equalsIgnoreCase(p.getName())){
String lb=p.getLb();
String rb=p.getRb();
String times=p.getTimes();
if(!responseinfo.isEmpty())
value=getParaValueFromResponse(responseinfo,lb,rb,Integer.parseInt(times));
break;
}
}
content=content.replace("{{"+name+"}}", value);
pos1=content.indexOf("{{");
pos2=content.indexOf("}}");
}
return content;
}
public static void main(String args[]){
String key="";
StringUtils.substringAfter("qqwww123","q");
String exp="JSON.parse(\"{\\\\\"id\\\\\":1}\").id==1";
String filename=new Date().getTime()+".js";
File f=new File(filename);
try{
f.createNewFile();
FileUtils.writeStringToFile(f, "console.log(eval(\""+exp.replace("\"", "\\\"")+"\"))");
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("cmd /k node "+f.getAbsolutePath());
InputStream is = p.getInputStream();
OutputStream os = p.getOutputStream();
os.close();
key = IOUtils.toString(is,"gbk");
key=StringUtils.substringBetween(key, "", "\n\r");
}catch(Exception e){
key=e.getMessage();
}finally{
if(f.exists())
f.delete();
}
System.out.println(key);
}
}
|
package com.thelinuxkid.cordova.mixpanel;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.LOG;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.text.TextUtils;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
public class Mixpanel extends CordovaPlugin {
private static String NO = "";
public static MixpanelAPI mixpanel;
public static MixpanelAPI.People people;
@Override
public boolean execute(
String action,
JSONArray args,
final CallbackContext cbCtx) throws JSONException {
try {
if (action.equals("init")) {
String tk = args.optString(0, NO);
if (TextUtils.isEmpty(tk)) {
this.error(cbCtx, "init token not provided");
return false;
}
Context ctx = cordova.getActivity();
if (mixpanel == null) {
mixpanel = MixpanelAPI.getInstance(ctx, tk);
people = mixpanel.getPeople();
}
cbCtx.success();
return true;
} else if (mixpanel == null) {
this.error(cbCtx, "mixpanel is not initialized");
return false;
}
if (action.equals("alias")) {
String alias = args.optString(0, NO);
if (TextUtils.isEmpty(alias)) {
this.error(cbCtx, "alias id not provided");
return false;
}
String original = args.optString(1, NO);
if (TextUtils.isEmpty(original)) {
this.error(cbCtx, "alias original id provided");
return false;
}
mixpanel.alias(alias, original);
cbCtx.success();
return true;
}
if (action.equals("identify")) {
String id = args.optString(0, NO);
if (TextUtils.isEmpty(id)) {
this.error(
cbCtx,
"identify distinct id not provided");
return false;
}
mixpanel.identify(id);
cbCtx.success();
return true;
}
if (action.equals("time_event")) {
String event = args.optString(0, NO);
if (TextUtils.isEmpty(event)) {
this.error(
cbCtx,
"timeEvent event name not provided");
return false;
}
mixpanel.timeEvent(event);
cbCtx.success();
return true;
}
if (action.equals("track")) {
String event = args.optString(0, NO);
if (TextUtils.isEmpty(event)) {
this.error(
cbCtx,
"track event name not provided");
return false;
}
JSONObject props = args.optJSONObject(1) ;
if (props == null) {
// It's OK for an event not to have properties.
props = new JSONObject();
}
mixpanel.track(event, props);
cbCtx.success();
return true;
}
if (action.equals("flush")) {
Runnable runnable = new Runnable() {
@Override
public void run() {
mixpanel.flush();
cbCtx.success();
}
};
cordova.getThreadPool().execute(runnable);
return true;
}
if (action.equals("super_properties")) {
JSONObject props = mixpanel.getSuperProperties();
cbCtx.success(props);
return true;
}
if (action.equals("distinct_id")) {
String id = mixpanel.getDistinctId();
cbCtx.success(id);
return true;
}
if (action.equals("register")) {
JSONObject props = args.optJSONObject(0);
if (props == null) {
this.error(
cbCtx,
"register properties not provided");
return false;
}
mixpanel.registerSuperProperties(props);
cbCtx.success();
return true;
}
if (action.equals("unregister")) {
String prop = args.optString(0, NO);
if (TextUtils.isEmpty(prop)) {
this.error(
cbCtx,
"unregister property not provided");
return false;
}
mixpanel.unregisterSuperProperty(prop);
cbCtx.success();
return true;
}
if (action.equals("register_once")) {
JSONObject props = args.optJSONObject(0);
if (props == null) {
this.error(
cbCtx,
"register once properties not provided");
return false;
}
mixpanel.registerSuperPropertiesOnce(props);
cbCtx.success();
return true;
}
if (action.equals("clear")) {
mixpanel.clearSuperProperties();
cbCtx.success();
return true;
}
if (action.equals("reset")) {
mixpanel.reset();
cbCtx.success();
return true;
}
} catch (final Exception e) {
cbCtx.error(e.getMessage());
}
return false;
}
@Override
public void onDestroy() {
mixpanel.flush();
super.onDestroy();
}
@Override
public void onPause(boolean multitasking) {
// TODO
}
@Override
public void onResume(boolean multitasking) {
// TODO
}
@Override
public void onReset() {
// TODO
}
private void error(CallbackContext cbCtx, String message) {
LOG.e("Mixpanel", message);
cbCtx.error(message);
}
}
|
package com.cloud.vm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.manager.Commands;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.CapacityManager;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.ManagementServerException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.ha.HighAvailabilityManager.WorkType;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.ItWorkVO.Step;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value = VirtualMachineManager.class)
public class VirtualMachineManagerImpl implements VirtualMachineManager, Listener {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
String _name;
@Inject
protected StorageManager _storageMgr;
@Inject
protected NetworkManager _networkMgr;
@Inject
protected AgentManager _agentMgr;
@Inject
protected VMInstanceDao _vmDao;
@Inject
protected ServiceOfferingDao _offeringDao;
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected UserDao _userDao;
@Inject
protected AccountDao _accountDao;
@Inject
protected DomainDao _domainDao;
@Inject
protected ClusterManager _clusterMgr;
@Inject
protected ItWorkDao _workDao;
@Inject
protected UserVmDao _userVmDao;
@Inject
protected DomainRouterDao _routerDao;
@Inject
protected ConsoleProxyDao _consoleDao;
@Inject
protected SecondaryStorageVmDao _secondaryDao;
@Inject
protected NicDao _nicsDao;
@Inject
protected AccountManager _accountMgr;
@Inject
protected HostDao _hostDao;
@Inject
protected AlertManager _alertMgr;
@Inject
protected GuestOSCategoryDao _guestOsCategoryDao;
@Inject
protected GuestOSDao _guestOsDao;
@Inject
protected VolumeDao _volsDao;
@Inject
protected ConsoleProxyManager _consoleProxyMgr;
@Inject
protected ConfigurationManager _configMgr;
@Inject
protected CapacityManager _capacityMgr;
@Inject
protected HighAvailabilityManager _haMgr;
@Inject
protected HostPodDao _podDao;
@Inject
protected DataCenterDao _dcDao;
@Inject
protected StoragePoolDao _storagePoolDao;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject(adapter = DeploymentPlanner.class)
protected Adapters<DeploymentPlanner> _planners;
@Inject(adapter = HostAllocator.class)
protected Adapters<HostAllocator> _hostAllocators;
Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>();
protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
ScheduledExecutorService _executor = null;
protected int _operationTimeout;
protected int _retry;
protected long _nodeId;
protected long _cleanupWait;
protected long _cleanupInterval;
protected long _cancelWait;
protected long _opWaitInterval;
protected int _lockStateRetry;
@Override
public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) {
synchronized (_vmGurus) {
_vmGurus.put(type, guru);
}
}
@Override
@DB
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering,
List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan,
HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating entries for VM: " + vm);
}
VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params);
vm.setDataCenterId(plan.getDataCenterId());
if (plan.getPodId() != null) {
vm.setPodId(plan.getPodId());
}
assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
@SuppressWarnings("unchecked")
VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>) _vmGurus.get(vm.getType());
Transaction txn = Transaction.currentTxn();
txn.start();
vm = guru.persist(vm);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating nics for " + vm);
}
try {
_networkMgr.allocate(vmProfile, networks);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
}
if (dataDiskOfferings == null) {
dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocaing disks for " + vm);
}
if (template.getFormat() == ImageFormat.ISO) {
_storageMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner);
} else if (template.getFormat() == ImageFormat.BAREMETAL) {
// Do nothing
} else {
_storageMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner);
}
for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) {
_storageMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner);
}
txn.commit();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocation completed for VM: " + vm);
}
return vm;
}
@Override
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering,
List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1);
if (dataDiskOffering != null) {
diskOfferings.add(dataDiskOffering);
}
return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner);
}
@Override
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan,
HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner);
}
@SuppressWarnings("unchecked")
private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) {
return (VirtualMachineGuru<T>) _vmGurus.get(vm.getType());
}
@SuppressWarnings("unchecked")
private <T extends VMInstanceVO> VirtualMachineGuru<T> getBareMetalVmGuru(T vm) {
return (VirtualMachineGuru<T>) _vmGurus.get(VirtualMachine.Type.UserBareMetal);
}
@Override
public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException {
try {
if (advanceExpunge(vm, caller, account)) {
// Mark vms as removed
remove(vm, caller, account);
return true;
} else {
s_logger.info("Did not expunge " + vm);
return false;
}
} catch (OperationTimedoutException e) {
throw new CloudRuntimeException("Operation timed out", e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation ", e);
}
}
@Override
public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (vm == null || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return true;
}
if (!this.advanceStop(vm, false, caller, account)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to stop the VM so we can't expunge it.");
}
}
try {
if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
} catch (NoTransitionException e) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
_networkMgr.cleanupNics(profile);
// Clean up volumes based on the vm's instance id
_storageMgr.cleanupVolumes(vm.getId());
VirtualMachineGuru<T> guru = getVmGuru(vm);
guru.finalizeExpunge(vm);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunged " + vm);
}
return true;
}
@Override
public boolean start() {
_executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
Map<String, String> params = configDao.getConfiguration(xmlParams);
_retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10);
ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao);
VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao);
_cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600);
_cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600);
_cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000;
_opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000;
_lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5);
_operationTimeout = NumbersUtil.parseInt(params.get(Config.Wait.key()), 1800) * 2;
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
_nodeId = _clusterMgr.getManagementNodeId();
_agentMgr.registerForHostEvents(this, true, true, true);
return true;
}
@Override
public String getName() {
return _name;
}
protected VirtualMachineManagerImpl() {
setStateMachine();
}
@Override
public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
return start(vm, params, caller, account, null);
}
@Override
public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ResourceUnavailableException {
try {
return advanceStart(vm, params, caller, account, planToDeploy);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e);
}
}
protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException {
while (true) {
ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
if (vo == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state);
}
return true;
}
if (vo.getStep() == Step.Done) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Work for " + vm + " is " + vo.getStep());
}
return true;
}
if (vo.getSecondsTaskIsInactive() > _cancelWait) {
s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
return false;
}
try {
Thread.sleep(_opWaitInterval);
} catch (InterruptedException e) {
s_logger.info("Waiting for " + vm + " but is interrupted");
throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
}
s_logger.debug("Waiting some more to make sure there's no activity on " + vm);
}
}
@DB
protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account)
throws ConcurrentOperationException {
long vmId = vm.getId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
int retry = _lockStateRetry;
while (retry
Transaction txn = Transaction.currentTxn();
Ternary<T, ReservationContext, ItWorkVO> result = null;
txn.start();
try {
Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
work = _workDao.persist(work);
ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
}
result = new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work);
txn.commit();
return result;
}
} catch (NoTransitionException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
}
} finally {
if (result == null) {
txn.rollback();
}
}
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance == null) {
throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry);
}
State state = instance.getState();
if (state == State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already started: " + vm);
}
return null;
}
if (state.isTransitional()) {
if (!checkWorkItems(vm, state)) {
throw new ConcurrentOperationException("There are concurrent operations on " + vm);
} else {
continue;
}
}
if (state != State.Stopped) {
s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
return null;
}
}
throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
@DB
protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException {
Transaction txn = Transaction.currentTxn();
txn.start();
if (!stateTransitTo(vm, event, hostId)) {
return false;
}
_workDao.updateStep(work, step);
txn.commit();
return true;
}
@Override
public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
return advanceStart(vm, params, caller, account, null);
}
@Override
public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
long vmId = vm.getId();
VirtualMachineGuru<T> vmGuru;
if (vm.getHypervisorType() == HypervisorType.BareMetal) {
vmGuru = getBareMetalVmGuru(vm);
} else {
vmGuru = getVmGuru(vm);
}
vm = vmGuru.findById(vm.getId());
Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account);
if (start == null) {
return vmGuru.findById(vmId);
}
vm = start.first();
ReservationContext ctx = start.second();
ItWorkVO work = start.third();
T startedVm = null;
ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId());
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null);
if(planToDeploy != null){
if (s_logger.isDebugEnabled()) {
s_logger.debug("advanceStart: DeploymentPlan is provided, using that plan to deploy");
}
plan = (DataCenterDeployment)planToDeploy;
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
boolean canRetry = true;
try {
Journal journal = start.second().getJournal();
ExcludeList avoids = new ExcludeList();
if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) {
List<DomainRouterVO> routers = _routerDao.findBy(vm.getAccountId(), vm.getDataCenterIdToDeployIn());
for (DomainRouterVO router : routers) {
if (router.hostId != null) {
avoids.addHost(router.hostId);
s_logger.info("Router: try to avoid host " + router.hostId);
}
}
}
int retry = _retry;
while (retry-- != 0) { // It's != so that it can match -1.
// edit plan if this vm's ROOT volume is in READY state already
// edit plan if this vm's ROOT volume is in READY state already
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO vol : vols) {
// make sure if the templateId is unchanged. If it is changed, let planner
// reassign pool for the volume even if it ready.
Long volTemplateId = vol.getTemplateId();
if (volTemplateId != null && volTemplateId.longValue() != template.getId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool");
}
continue;
}
StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId());
if (!pool.isInMaintenance()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Root volume is ready, need to place VM in volume's cluster");
}
long rootVolDcId = pool.getDataCenterId();
Long rootVolPodId = pool.getPodId();
Long rootVolClusterId = pool.getClusterId();
if(planToDeploy != null){
Long clusterIdSpecified = planToDeploy.getClusterId();
if(clusterIdSpecified != null && rootVolClusterId != null){
if(rootVolClusterId.longValue() != clusterIdSpecified.longValue()){
//cannot satisfy the plan passed in to the planner
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: "+rootVolClusterId + ", cluster specified: "+clusterIdSpecified);
}
throw new ResourceUnavailableException("Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm, Cluster.class, clusterIdSpecified);
}
}
plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId());
}else{
plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId());
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId);
}
}
}
}
VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, account, params);
DeployDestination dest = null;
for (DeploymentPlanner planner : _planners) {
if (planner.canHandle(vmProfile, plan, avoids)) {
dest = planner.plan(vmProfile, plan, avoids);
} else {
continue;
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
break;
}
}
if (dest == null) {
//see if we can allocate the router without limitation
if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) {
avoids = new ExcludeList();
s_logger.info("Router: cancel avoids ");
for (DeploymentPlanner planner : _planners) {
if (planner.canHandle(vmProfile, plan, avoids)) {
dest = planner.plan(vmProfile, plan, avoids);
} else {
continue;
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
break;
}
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId());
}
}
long destHostId = dest.getHost().getId();
try {
if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException(e1.getMessage());
}
try {
_networkMgr.prepare(vmProfile, dest, ctx);
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
_storageMgr.prepare(vmProfile, dest);
}
vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(new StartCommand(vmTO));
vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
vm.setPodId(dest.getPod().getId());
work = _workDao.findById(work.getId());
if (work == null || work.getStep() != Step.Prepare) {
throw new ConcurrentOperationException("Work steps have been changed: " + work);
}
_workDao.updateStep(work, Step.Starting);
_agentMgr.send(destHostId, cmds);
_workDao.updateStep(work, Step.Started);
Answer startAnswer = cmds.getAnswer(StartAnswer.class);
if (startAnswer != null && startAnswer.getResult()) {
if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) {
if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
throw new ConcurrentOperationException("Unable to transition to a new state.");
}
startedVm = vm;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Start completed for VM " + vm);
}
return startedVm;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.info("The guru did not like the answers so stopping " + vm);
}
StopCommand cmd = new StopCommand(vm.getInstanceName());
StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd);
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
canRetry = false;
_haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop);
throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation");
}
}
}
s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to send the start command to host " + dest.getHost());
if (e.isActive()) {
_haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop);
}
canRetry = false;
throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
} catch (ResourceUnavailableException e) {
s_logger.info("Unable to contact resource.", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
throw e;
}
}
} catch (InsufficientCapacityException e) {
s_logger.info("Insufficient capacity ", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
}
}
} catch (Exception e) {
s_logger.error("Failed to start instance " + vm, e);
throw new AgentUnavailableException("Unable to start instance", destHostId, e);
} finally {
if (startedVm == null && canRetry) {
_workDao.updateStep(work, Step.Release);
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false, caller, account);
}
}
}
} finally {
if (startedVm == null) {
if (canRetry) {
try {
changeState(vm, Event.OperationFailed, null, work, Step.Done);
} catch (NoTransitionException e) {
throw new ConcurrentOperationException(e.getMessage());
}
}
}
}
return startedVm;
}
@Override
public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException {
try {
return advanceStop(vm, false, user, account);
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e);
}
}
protected <T extends VMInstanceVO> boolean sendStop(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, boolean force) {
VMInstanceVO vm = profile.getVirtualMachine();
StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null);
try {
Answer answer = _agentMgr.send(vm.getHostId(), stop);
if (!answer.getResult()) {
s_logger.debug("Unable to stop VM due to " + answer.getDetails());
return false;
}
guru.finalizeStop(profile, (StopAnswer)answer);
} catch (AgentUnavailableException e) {
if (!force) {
return false;
}
} catch (OperationTimedoutException e) {
if (!force) {
return false;
}
}
return true;
}
protected <T extends VMInstanceVO> boolean cleanup(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, ItWorkVO work, Event event, boolean force, User user, Account account) {
T vm = profile.getVirtualMachine();
State state = vm.getState();
s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
if (state == State.Starting) {
Step step = work.getStep();
if (step == Step.Starting && !force) {
s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
return false;
}
if (step == Step.Started || step == Step.Starting) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
return false;
}
}
}
if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) {
s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
return true;
}
} else if (state == State.Stopping) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Migrating) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
if (vm.getLastHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Running) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
return false;
}
}
_networkMgr.release(profile, force);
_storageMgr.release(profile);
s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state");
return true;
}
@Override
public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
State state = vm.getState();
if (state == State.Stopped) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already stopped: " + vm);
}
return true;
}
if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopped called on " + vm + " but the state is " + state);
}
return true;
}
Long hostId = vm.getHostId();
if (hostId == null) {
try {
stateTransitTo(vm, Event.AgentReportStopped, null, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
return true;
}
VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
try {
if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
throw new ConcurrentOperationException("VM is being operated on.");
}
} catch (NoTransitionException e1) {
if (!forced) {
throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
}
s_logger.debug("Unable to transition the state but we're moving on because it's forced stop");
}
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
if ((vm.getState() == State.Starting || vm.getState() == State.Stopping || vm.getState() == State.Migrating) && forced) {
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.StopRequested, forced, user, account)) {
try {
return stateTransitTo(vm, Event.AgentReportStopped, null);
} catch (NoTransitionException e) {
s_logger.warn("Unable to cleanup " + vm);
return false;
}
}
} else {
try {
return stateTransitTo(vm, Event.AgentReportStopped, null);
} catch (NoTransitionException e) {
s_logger.warn("Unable to cleanup " + vm);
return false;
}
}
}
if (vm.getHostId() != null) {
String routerPrivateIp = null;
if (vm.getType() == VirtualMachine.Type.DomainRouter) {
routerPrivateIp = vm.getPrivateIpAddress();
}
StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null, routerPrivateIp);
boolean stopped = false;
StopAnswer answer = null;
try {
answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop);
stopped = answer.getResult();
if (!stopped) {
throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
}
vmGuru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
} catch (OperationTimedoutException e) {
} finally {
if (!stopped) {
if (!forced) {
s_logger.warn("Unable to stop vm " + vm);
try {
stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unable to transition the state " + vm);
}
return false;
} else {
s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
vmGuru.finalizeStop(profile, answer);
}
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held.");
}
try {
_networkMgr.release(profile, forced);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
try {
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
_storageMgr.release(profile);
s_logger.debug("Successfully released storage resources for the vm " + vm);
}
} catch (Exception e) {
s_logger.warn("Unable to release storage resources.", e);
}
try {
return stateTransitTo(vm, Event.OperationSucceeded, null, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
return false;
}
}
private void setStateMachine() {
_stateMachine = VirtualMachine.State.getStateMachine();
}
protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException {
vm.setReservationId(reservationId);
return _stateMachine.transitTo(vm, e, hostId, _vmDao);
}
@Override
public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
State oldState = vm.getState();
if (oldState == State.Starting) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(hostId);
}
} else if (oldState == State.Stopping) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(vm.getHostId());
}
}
return _stateMachine.transitTo(vm, e, hostId, _vmDao);
}
@Override
public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) {
// expunge the corresponding nics
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
_networkMgr.expungeNics(profile);
s_logger.trace("Nics of the vm " + vm + " are expunged successfully");
return _vmDao.remove(vm.getId());
}
@Override
public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return true;
}
if (!advanceStop(vm, false, user, caller)) {
s_logger.debug("Unable to stop " + vm);
return false;
}
try {
if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
} catch (NoTransitionException e) {
s_logger.debug(e.getMessage());
return false;
}
return true;
}
protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException {
CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName()));
if (!answer.getResult() || answer.getState() == State.Stopped) {
return false;
}
return true;
}
@Override
public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
VirtualMachineMigrationException {
s_logger.info("Migrating " + vm + " to " + dest);
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
long vmId = vm.getId();
vm = vmGuru.findById(vmId);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vm);
}
throw new ManagementServerException("Unable to find a virtual machine with id " + vmId);
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm);
}
short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
_networkMgr.prepareNicForMigration(profile, dest);
_storageMgr.prepareForMigration(profile, dest);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
try {
MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
s_logger.error("Unable to migrate due to " + ma.getDetails());
return null;
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
return null;
}
} catch (OperationTimedoutException e) {
}
migrated = true;
return vm;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone "
+ dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
protected void cancelWorkItems(long nodeId) {
GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem");
try {
if (scanLock.lock(3)) {
try {
List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId);
for (ItWorkVO work : works) {
s_logger.info("Handling unfinished work item: " + work);
try {
VMInstanceVO vm = _vmDao.findById(work.getInstanceId());
if (vm != null) {
if (work.getType() == State.Starting) {
_haMgr.scheduleRestart(vm, true);
} else if (work.getType() == State.Stopping) {
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop);
} else if (work.getType() == State.Migrating) {
_haMgr.scheduleMigration(vm);
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
} catch (Exception e) {
s_logger.error("Error while handling " + work, e);
}
}
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
@Override
public boolean migrateAway(VirtualMachine.Type vmType, long vmId, long srcHostId) throws InsufficientServerCapacityException, VirtualMachineMigrationException {
VirtualMachineGuru<? extends VMInstanceVO> vmGuru = _vmGurus.get(vmType);
VMInstanceVO vm = vmGuru.findById(vmId);
if (vm == null) {
s_logger.debug("Unable to find a VM for " + vmId);
return true;
}
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
Long hostId = vm.getHostId();
if (hostId == null) {
s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm);
return true;
}
Host host = _hostDao.findById(hostId);
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null);
ExcludeList excludes = new ExcludeList();
excludes.addHost(hostId);
DeployDestination dest = null;
while (true) {
for (DeploymentPlanner planner : _planners) {
dest = planner.plan(profile, plan, excludes);
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Planner " + planner + " found " + dest + " for migrating to.");
}
break;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Planner " + planner + " was unable to find anything.");
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
VMInstanceVO vmInstance = null;
try {
vmInstance = migrate(vm, srcHostId, dest);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
} catch (ManagementServerException e) {
s_logger.debug("Unable to migrate VM: " + e.getMessage());
} catch (VirtualMachineMigrationException e) {
s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage());
if (vm.getState() == State.Starting) {
s_logger.debug("VM seems to be still Starting, we should retry migration later");
throw e;
} else {
s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString());
}
}
if (vmInstance != null) {
return true;
}
try {
boolean result = advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
return result;
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
}
return false;
}
}
protected class CleanupTask implements Runnable {
@Override
public void run() {
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(_cleanupWait);
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
}
}
@Override
public boolean isVirtualMachineUpgradable(UserVm vm, ServiceOffering offering) {
Enumeration<HostAllocator> en = _hostAllocators.enumeration();
boolean isMachineUpgradable = true;
while (isMachineUpgradable && en.hasMoreElements()) {
final HostAllocator allocator = en.nextElement();
isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering);
}
return isMachineUpgradable;
}
@Override
public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
try {
return advanceReboot(vm, params, caller, account);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e);
}
}
@Override
public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
T rebootedVm = null;
DataCenter dc = _configMgr.getZone(vm.getDataCenterIdToDeployIn());
Host host = _hostDao.findById(vm.getHostId());
Cluster cluster = null;
if (host != null) {
cluster = _configMgr.getCluster(host.getClusterId());
}
HostPodVO pod = _configMgr.getPod(host.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, cluster, host);
try {
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(new RebootCommand(vm.getInstanceName()));
_agentMgr.send(host.getId(), cmds);
Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
if (rebootAnswer != null && rebootAnswer.getResult()) {
rebootedVm = vm;
return rebootedVm;
}
s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
}
return rebootedVm;
}
@Override
public VMInstanceVO findById(VirtualMachine.Type type, long vmId) {
VirtualMachineGuru<? extends VMInstanceVO> guru = _vmGurus.get(type);
return guru.findById(vmId);
}
public Command cleanup(String vmName) {
return new StopCommand(vmName);
}
public Commands deltaSync(long hostId, Map<String, State> newStates) {
Map<Long, AgentVmInfo> states = convertToInfos(newStates);
Commands commands = new Commands(OnError.Continue);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hostId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
commands.addCommand(command);
}
}
return commands;
}
protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, State> states) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values();
for (Map.Entry<String, State> entry : states.entrySet()) {
for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) {
String name = entry.getKey();
VMInstanceVO vm = vmGuru.findByName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue()));
break;
}
Long id = vmGuru.convertToId(name);
if (id != null) {
map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null, entry.getValue()));
break;
}
}
}
return map;
}
/**
* compareState does as its name suggests and compares the states between management server and agent. It returns whether
* something should be cleaned up
*
*/
protected Command compareState(long hostId, VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean trackExternalChange) {
State agentState = info.state;
final String agentName = info.name;
final State serverState = vm.getState();
final String serverName = vm.getInstanceName();
Command command = null;
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM " + serverName + ": server state = " + serverState + " and agent state = " + agentState);
}
if (agentState == State.Error) {
agentState = State.Stopped;
short alertType = AlertManager.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
}
HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn());
DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterIdToDeployIn());
HostVO hostVO = _hostDao.findById(vm.getHostId());
String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host " + hostDesc + " due to storage failure",
"Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure.");
}
if(trackExternalChange) {
if(vm.getHostId() == null || hostId != vm.getHostId()) {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
}
// if (serverState == State.Migrating) {
// s_logger.debug("Skipping vm in migrating state: " + vm);
// return null;
if (agentState == serverState) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Both states are " + agentState + " for " + vm);
}
assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed.";
if (agentState == State.Running) {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, hostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// FIXME: What if someone comes in and sets it to stopping? Then what?
return null;
}
s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways.");
return cleanup(agentName);
}
if (agentState == State.Shutdowned) {
if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
try {
advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (AgentUnavailableException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (OperationTimedoutException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (ConcurrentOperationException e) {
assert (false) : "How do we hit this with forced on?";
return null;
}
} else {
s_logger.debug("Sending cleanup to a shutdowned vm: " + agentName);
command = cleanup(agentName);
}
} else if (agentState == State.Stopped) {
// This state means the VM on the agent was detected previously
// and now is gone. This is slightly different than if the VM
// was never completed but we still send down a Stop Command
// to ensure there's cleanup.
if (serverState == State.Running) {
// Our records showed that it should be running so let's restart it.
_haMgr.scheduleRestart(vm, false);
} else if (serverState == State.Stopping) {
_haMgr.scheduleStop(vm, hostId, WorkType.ForceStop);
s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm);
} else if (serverState == State.Starting) {
s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName());
_haMgr.scheduleRestart(vm, false);
}
command = cleanup(agentName);
} else if (agentState == State.Running) {
if (serverState == State.Starting) {
if (fullSync) {
try {
ensureVmRunningContext(hostId, vm, Event.AgentReportRunning);
} catch (OperationTimedoutException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
} else if (serverState == State.Stopping) {
s_logger.debug("Scheduling a stop command for " + vm);
_haMgr.scheduleStop(vm, hostId, WorkType.Stop);
} else {
s_logger.debug("VM state is in stopped so stopping it on the agent");
command = cleanup(agentName);
}
}
return command;
}
private void ensureVmRunningContext(long hostId, VMInstanceVO vm, Event cause) throws OperationTimedoutException, ResourceUnavailableException, NoTransitionException {
VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vm);
s_logger.debug("VM state is starting on full sync so updating it to running");
vm = findById(vm.getType(), vm.getId());
try {
stateTransitTo(vm, cause, hostId);
} catch (NoTransitionException e1) {
s_logger.warn(e1.getMessage());
}
s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running");
vm = vmGuru.findById(vm.getId()); // this should ensure vm has the most up to date info
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
List<NicVO> nics = _nicsDao.listByVmId(profile.getId());
for (NicVO nic : nics) {
Network network = _networkMgr.getNetwork(nic.getNetworkId());
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null);
profile.addNic(nicProfile);
}
Commands cmds = new Commands(OnError.Stop);
s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm);
if (vmGuru.finalizeCommandsOnStart(cmds, profile)) {
if (cmds.size() != 0) {
_agentMgr.send(vm.getHostId(), cmds);
}
if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) {
stateTransitTo(vm, cause, vm.getHostId());
} else {
s_logger.error("Unable to finish finialization for running vm: " + vm);
}
} else {
s_logger.error("Unable to finalize commands on start for vm: " + vm);
}
}
public Commands fullSync(final long hostId, final Map<String, State> newStates) {
Commands commands = new Commands(OnError.Continue);
final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId);
s_logger.debug("Found " + vms.size() + " VMs for host " + hostId);
Map<Long, AgentVmInfo> infos = convertToInfos(newStates);
for (VMInstanceVO vm : vms) {
AgentVmInfo info = infos.remove(vm.getId());
VMInstanceVO castedVm = null;
if (info == null) {
info = new AgentVmInfo(vm.getInstanceName(), getVmGuru(vm), vm, State.Stopped);
castedVm = info.guru.findById(vm.getId());
} else {
castedVm = info.vm;
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(castedVm.getHypervisorType());
Command command = compareState(hostId, castedVm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
commands.addCommand(command);
}
}
for (final AgentVmInfo left : infos.values()) {
for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : _vmGurus.values()) {
VMInstanceVO vm = vmGuru.findByName(left.name);
if (vm == null) {
s_logger.warn("Stopping a VM that we have no record of: " + left.name);
commands.addCommand(cleanup(left.name));
} else {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
if(hvGuru.trackVmHostChange()) {
Command command = compareState(hostId, vm, left, true, true);
if (command != null) {
commands.addCommand(command);
}
} else {
s_logger.warn("Stopping a VM that we have no record of: " + left.name);
commands.addCommand(cleanup(left.name));
}
}
}
}
return commands;
}
@Override
public boolean isRecurring() {
return false;
}
@Override
public boolean processAnswers(long agentId, long seq, Answer[] answers) {
for (final Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Cleanup failed due to " + answer.getDetails());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleanup succeeded. Details " + answer.getDetails());
}
}
}
return true;
}
@Override
public boolean processTimeout(long agentId, long seq) {
return true;
}
@Override
public int getTimeout() {
return -1;
}
@Override
public boolean processCommands(long agentId, long seq, Command[] cmds) {
boolean processed = false;
for (Command cmd : cmds) {
if (cmd instanceof PingRoutingCommand) {
PingRoutingCommand ping = (PingRoutingCommand) cmd;
if (ping.getNewStates().size() > 0) {
Commands commands = deltaSync(agentId, ping.getNewStates());
if (commands.size() > 0) {
try {
_agentMgr.send(agentId, commands, this);
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is now unavailable", e);
}
}
}
processed = true;
}
}
return processed;
}
@Override
public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
return null;
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return true;
}
@Override
public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
if (!(cmd instanceof StartupRoutingCommand)) {
return;
}
if (forRebalance) {
s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process");
return;
}
long agentId = agent.getId();
StartupRoutingCommand startup = (StartupRoutingCommand) cmd;
Commands commands = fullSync(agentId, startup.getVmStates());
if (commands.size() > 0) {
s_logger.debug("Sending clean commands to the agent");
try {
boolean error = false;
Answer[] answers = _agentMgr.send(agentId, commands);
for (Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
error = true;
}
}
if (error) {
throw new ConnectionException(true, "Unable to stop VMs");
}
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
} catch (final OperationTimedoutException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
}
}
}
protected class TransitionTask implements Runnable {
@Override
public void run() {
GlobalLock lock = GlobalLock.getInternLock("TransitionChecking");
if (lock == null) {
s_logger.debug("Couldn't get the global lock");
return;
}
if (!lock.lock(30)) {
s_logger.debug("Couldn't lock the db");
return;
}
try {
lock.addRef();
List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
_haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop);
} else if (state == State.Starting) {
_haMgr.scheduleRestart(instance, true);
}
}
} catch (Exception e) {
s_logger.warn("Caught the following exception on transition checking", e);
} finally {
StackMaid.current().exitCleanup();
lock.unlock();
}
}
}
protected class AgentVmInfo {
public String name;
public State state;
public VMInstanceVO vm;
public VirtualMachineGuru<VMInstanceVO> guru;
@SuppressWarnings("unchecked")
public AgentVmInfo(String name, VirtualMachineGuru<? extends VMInstanceVO> guru, VMInstanceVO vm, State state) {
this.name = name;
this.state = state;
this.vm = vm;
this.guru = (VirtualMachineGuru<VMInstanceVO>) guru;
}
}
}
|
package com.cloud.vm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.manager.Commands;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.CapacityManager;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.ManagementServerException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.ha.HighAvailabilityManager.WorkType;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.ItWorkVO.Step;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value = VirtualMachineManager.class)
public class VirtualMachineManagerImpl implements VirtualMachineManager, Listener {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
String _name;
@Inject
protected StorageManager _storageMgr;
@Inject
protected NetworkManager _networkMgr;
@Inject
protected AgentManager _agentMgr;
@Inject
protected VMInstanceDao _vmDao;
@Inject
protected ServiceOfferingDao _offeringDao;
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected UserDao _userDao;
@Inject
protected AccountDao _accountDao;
@Inject
protected DomainDao _domainDao;
@Inject
protected ClusterManager _clusterMgr;
@Inject
protected ItWorkDao _workDao;
@Inject
protected UserVmDao _userVmDao;
@Inject
protected DomainRouterDao _routerDao;
@Inject
protected ConsoleProxyDao _consoleDao;
@Inject
protected SecondaryStorageVmDao _secondaryDao;
@Inject
protected UsageEventDao _usageEventDao;
@Inject
protected NicDao _nicsDao;
@Inject
protected AccountManager _accountMgr;
@Inject
protected HostDao _hostDao;
@Inject
protected AlertManager _alertMgr;
@Inject
protected GuestOSCategoryDao _guestOsCategoryDao;
@Inject
protected GuestOSDao _guestOsDao;
@Inject
protected VolumeDao _volsDao;
@Inject
protected ConsoleProxyManager _consoleProxyMgr;
@Inject
protected ConfigurationManager _configMgr;
@Inject
protected CapacityManager _capacityMgr;
@Inject
protected HighAvailabilityManager _haMgr;
@Inject
protected HostPodDao _podDao;
@Inject
protected DataCenterDao _dcDao;
@Inject
protected StoragePoolDao _storagePoolDao;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject(adapter = DeploymentPlanner.class)
protected Adapters<DeploymentPlanner> _planners;
@Inject(adapter = HostAllocator.class)
protected Adapters<HostAllocator> _hostAllocators;
Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>();
protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
ScheduledExecutorService _executor = null;
protected int _operationTimeout;
protected int _retry;
protected long _nodeId;
protected long _cleanupWait;
protected long _cleanupInterval;
protected long _cancelWait;
protected long _opWaitInterval;
protected int _lockStateRetry;
@Override
public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) {
synchronized (_vmGurus) {
_vmGurus.put(type, guru);
}
}
@Override
@DB
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering,
List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan,
HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating entries for VM: " + vm);
}
VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params);
vm.setDataCenterId(plan.getDataCenterId());
if (plan.getPodId() != null) {
vm.setPodId(plan.getPodId());
}
assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
@SuppressWarnings("unchecked")
VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>) _vmGurus.get(vm.getType());
Transaction txn = Transaction.currentTxn();
txn.start();
vm = guru.persist(vm);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating nics for " + vm);
}
try {
_networkMgr.allocate(vmProfile, networks);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
}
if (dataDiskOfferings == null) {
dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocaing disks for " + vm);
}
if (template.getFormat() == ImageFormat.ISO) {
_storageMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner);
} else if (template.getFormat() == ImageFormat.BAREMETAL) {
// Do nothing
} else {
_storageMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner);
}
for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) {
_storageMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner);
}
txn.commit();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocation completed for VM: " + vm);
}
return vm;
}
@Override
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering,
List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1);
if (dataDiskOffering != null) {
diskOfferings.add(dataDiskOffering);
}
return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner);
}
@Override
public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan,
HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner);
}
@SuppressWarnings("unchecked")
private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) {
return (VirtualMachineGuru<T>) _vmGurus.get(vm.getType());
}
@SuppressWarnings("unchecked")
private <T extends VMInstanceVO> VirtualMachineGuru<T> getBareMetalVmGuru(T vm) {
return (VirtualMachineGuru<T>) _vmGurus.get(VirtualMachine.Type.UserBareMetal);
}
@Override
public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException {
try {
if (advanceExpunge(vm, caller, account)) {
// Mark vms as removed
remove(vm, caller, account);
return true;
} else {
s_logger.info("Did not expunge " + vm);
return false;
}
} catch (OperationTimedoutException e) {
throw new CloudRuntimeException("Operation timed out", e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation ", e);
}
}
@Override
public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (vm == null || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return true;
}
if (!this.advanceStop(vm, false, caller, account)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to stop the VM so we can't expunge it.");
}
}
try {
if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
} catch (NoTransitionException e) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
_networkMgr.cleanupNics(profile);
// Clean up volumes based on the vm's instance id
_storageMgr.cleanupVolumes(vm.getId());
VirtualMachineGuru<T> guru = getVmGuru(vm);
guru.finalizeExpunge(vm);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunged " + vm);
}
return true;
}
@Override
public boolean start() {
_executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
Map<String, String> params = configDao.getConfiguration(xmlParams);
_retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10);
ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao);
VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao);
_cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600);
_cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600);
_cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000;
_opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000;
_lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5);
_operationTimeout = NumbersUtil.parseInt(params.get(Config.Wait.key()), 1800) * 2;
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
_nodeId = _clusterMgr.getManagementNodeId();
_agentMgr.registerForHostEvents(this, true, true, true);
return true;
}
@Override
public String getName() {
return _name;
}
protected VirtualMachineManagerImpl() {
setStateMachine();
}
@Override
public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
return start(vm, params, caller, account, null);
}
@Override
public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ResourceUnavailableException {
try {
return advanceStart(vm, params, caller, account, planToDeploy);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e);
}
}
protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException {
while (true) {
ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
if (vo == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state);
}
return true;
}
if (vo.getStep() == Step.Done) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Work for " + vm + " is " + vo.getStep());
}
return true;
}
if (vo.getSecondsTaskIsInactive() > _cancelWait) {
s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
return false;
}
try {
Thread.sleep(_opWaitInterval);
} catch (InterruptedException e) {
s_logger.info("Waiting for " + vm + " but is interrupted");
throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
}
s_logger.debug("Waiting some more to make sure there's no activity on " + vm);
}
}
protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account)
throws ConcurrentOperationException {
long vmId = vm.getId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
int retry = _lockStateRetry;
while (retry
Transaction txn = Transaction.currentTxn();
Ternary<T, ReservationContext, ItWorkVO> result = null;
txn.start();
try {
Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
work = _workDao.persist(work);
ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
}
result = new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work);
txn.commit();
return result;
}
} catch (NoTransitionException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
}
} finally {
if (result == null) {
txn.rollback();
}
}
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance == null) {
throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry);
}
State state = instance.getState();
if (state == State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already started: " + vm);
}
return null;
}
if (state.isTransitional()) {
if (!checkWorkItems(vm, state)) {
throw new ConcurrentOperationException("There are concurrent operations on " + vm);
} else {
continue;
}
}
if (state != State.Stopped) {
s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
return null;
}
}
throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
@DB
protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException {
Transaction txn = Transaction.currentTxn();
txn.start();
if (!stateTransitTo(vm, event, hostId)) {
return false;
}
_workDao.updateStep(work, step);
txn.commit();
return true;
}
@Override
public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
return advanceStart(vm, params, caller, account, null);
}
@Override
public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
long vmId = vm.getId();
VirtualMachineGuru<T> vmGuru;
if (vm.getHypervisorType() == HypervisorType.BareMetal) {
vmGuru = getBareMetalVmGuru(vm);
} else {
vmGuru = getVmGuru(vm);
}
vm = vmGuru.findById(vm.getId());
Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account);
if (start == null) {
return vmGuru.findById(vmId);
}
vm = start.first();
ReservationContext ctx = start.second();
ItWorkVO work = start.third();
T startedVm = null;
ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId());
VMTemplateVO template = _templateDao.findById(vm.getTemplateId());
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null);
if(planToDeploy != null){
if (s_logger.isDebugEnabled()) {
s_logger.debug("advanceStart: DeploymentPlan is provided, using that plan to deploy");
}
plan = (DataCenterDeployment)planToDeploy;
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
boolean canRetry = true;
try {
Journal journal = start.second().getJournal();
ExcludeList avoids = new ExcludeList();
if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) {
List<DomainRouterVO> routers = _routerDao.findBy(vm.getAccountId(), vm.getDataCenterIdToDeployIn());
for (DomainRouterVO router : routers) {
if (router.hostId != null) {
avoids.addHost(router.hostId);
s_logger.info("Router: try to avoid host " + router.hostId);
}
}
}
int retry = _retry;
while (retry-- != 0) { // It's != so that it can match -1.
// edit plan if this vm's ROOT volume is in READY state already
// edit plan if this vm's ROOT volume is in READY state already
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO vol : vols) {
// make sure if the templateId is unchanged. If it is changed, let planner
// reassign pool for the volume even if it ready.
Long volTemplateId = vol.getTemplateId();
if (volTemplateId != null && volTemplateId.longValue() != template.getId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool");
}
continue;
}
StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId());
if (!pool.isInMaintenance()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Root volume is ready, need to place VM in volume's cluster");
}
long rootVolDcId = pool.getDataCenterId();
Long rootVolPodId = pool.getPodId();
Long rootVolClusterId = pool.getClusterId();
if(planToDeploy != null){
Long clusterIdSpecified = planToDeploy.getClusterId();
if(clusterIdSpecified != null && rootVolClusterId != null){
if(rootVolClusterId.longValue() != clusterIdSpecified.longValue()){
//cannot satisfy the plan passed in to the planner
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: "+rootVolClusterId + ", cluster specified: "+clusterIdSpecified);
}
throw new ResourceUnavailableException("Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm, Cluster.class, clusterIdSpecified);
}
}
plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId());
}else{
plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId());
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId);
}
}
}
}
VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, account, params);
DeployDestination dest = null;
for (DeploymentPlanner planner : _planners) {
if (planner.canHandle(vmProfile, plan, avoids)) {
dest = planner.plan(vmProfile, plan, avoids);
} else {
continue;
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
break;
}
}
if (dest == null) {
//see if we can allocate the router without limitation
if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) {
avoids = new ExcludeList();
s_logger.info("Router: cancel avoids ");
for (DeploymentPlanner planner : _planners) {
if (planner.canHandle(vmProfile, plan, avoids)) {
dest = planner.plan(vmProfile, plan, avoids);
} else {
continue;
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
break;
}
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile + " due to lack of VLAN available.", DataCenter.class, plan.getDataCenterId());
}
}
long destHostId = dest.getHost().getId();
try {
if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException(e1.getMessage());
}
try {
_networkMgr.prepare(vmProfile, dest, ctx);
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
_storageMgr.prepare(vmProfile, dest);
}
vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(new StartCommand(vmTO));
vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
vm.setPodId(dest.getPod().getId());
work = _workDao.findById(work.getId());
if (work == null || work.getStep() != Step.Prepare) {
throw new ConcurrentOperationException("Work steps have been changed: " + work);
}
_workDao.updateStep(work, Step.Starting);
_agentMgr.send(destHostId, cmds);
_workDao.updateStep(work, Step.Started);
Answer startAnswer = cmds.getAnswer(StartAnswer.class);
if (startAnswer != null && startAnswer.getResult()) {
if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) {
if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
throw new ConcurrentOperationException("Unable to transition to a new state.");
}
startedVm = vm;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Start completed for VM " + vm);
}
return startedVm;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.info("The guru did not like the answers so stopping " + vm);
}
StopCommand cmd = new StopCommand(vm.getInstanceName());
StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd);
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
canRetry = false;
_haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop);
throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation");
}
}
}
s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to send the start command to host " + dest.getHost());
if (e.isActive()) {
_haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop);
}
canRetry = false;
throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
} catch (ResourceUnavailableException e) {
s_logger.info("Unable to contact resource.", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
throw e;
}
}
} catch (InsufficientCapacityException e) {
s_logger.info("Insufficient capacity ", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
}
}
} catch (Exception e) {
s_logger.error("Failed to start instance " + vm, e);
throw new AgentUnavailableException("Unable to start instance", destHostId, e);
} finally {
if (startedVm == null && canRetry) {
_workDao.updateStep(work, Step.Release);
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false, caller, account);
}
}
}
} finally {
if (startedVm == null) {
// decrement only for user VM's and newly created VM
if (vm.getType().equals(VirtualMachine.Type.User) && (vm.getLastHostId() == null)) {
_accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm);
}
if (canRetry) {
try {
changeState(vm, Event.OperationFailed, null, work, Step.Done);
} catch (NoTransitionException e) {
throw new ConcurrentOperationException(e.getMessage());
}
}
}
}
return startedVm;
}
@Override
public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException {
try {
return advanceStop(vm, false, user, account);
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e);
}
}
protected <T extends VMInstanceVO> boolean sendStop(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, boolean force) {
VMInstanceVO vm = profile.getVirtualMachine();
StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null);
try {
Answer answer = _agentMgr.send(vm.getHostId(), stop);
if (!answer.getResult()) {
s_logger.debug("Unable to stop VM due to " + answer.getDetails());
return false;
}
guru.finalizeStop(profile, (StopAnswer)answer);
} catch (AgentUnavailableException e) {
if (!force) {
return false;
}
} catch (OperationTimedoutException e) {
if (!force) {
return false;
}
}
return true;
}
protected <T extends VMInstanceVO> boolean cleanup(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, ItWorkVO work, Event event, boolean force, User user, Account account) {
T vm = profile.getVirtualMachine();
State state = vm.getState();
s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
if (state == State.Starting) {
Step step = work.getStep();
if (step == Step.Starting && !force) {
s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
return false;
}
if (step == Step.Started || step == Step.Starting) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
return false;
}
}
}
if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) {
s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
return true;
}
} else if (state == State.Stopping) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Migrating) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
if (vm.getLastHostId() != null) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Running) {
if (!sendStop(guru, profile, force)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
return false;
}
}
_networkMgr.release(profile, force);
_storageMgr.release(profile);
s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state");
return true;
}
@Override
public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
State state = vm.getState();
if (state == State.Stopped) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already stopped: " + vm);
}
return true;
}
if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopped called on " + vm + " but the state is " + state);
}
return true;
}
Long hostId = vm.getHostId();
if (hostId == null) {
try {
stateTransitTo(vm, Event.AgentReportStopped, null, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
return true;
}
VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
try {
if (!stateTransitTo(vm, forced ? Event.AgentReportStopped : Event.StopRequested, vm.getHostId(), null)) {
throw new ConcurrentOperationException("VM is being operated on.");
}
} catch (NoTransitionException e1) {
throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
}
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
if ((vm.getState() == State.Starting || vm.getState() == State.Stopping || vm.getState() == State.Migrating) && forced) {
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.StopRequested, forced, user, account)) {
try {
return stateTransitTo(vm, Event.AgentReportStopped, null);
} catch (NoTransitionException e) {
s_logger.warn("Unable to cleanup " + vm);
return false;
}
}
}
}
if (vm.getHostId() != null) {
String routerPrivateIp = null;
if (vm.getType() == VirtualMachine.Type.DomainRouter) {
routerPrivateIp = vm.getPrivateIpAddress();
}
StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null, routerPrivateIp);
boolean stopped = false;
StopAnswer answer = null;
try {
answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop);
stopped = answer.getResult();
if (!stopped) {
throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
}
vmGuru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
} catch (OperationTimedoutException e) {
} finally {
if (!stopped) {
if (!forced) {
s_logger.warn("Unable to stop vm " + vm);
try {
stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unable to transition the state " + vm);
}
return false;
} else {
s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
vmGuru.finalizeStop(profile, answer);
}
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held.");
}
try {
_networkMgr.release(profile, forced);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
try {
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
_storageMgr.release(profile);
s_logger.debug("Successfully released storage resources for the vm " + vm);
}
} catch (Exception e) {
s_logger.warn("Unable to release storage resources.", e);
}
vm.setReservationId(null);
try {
return stateTransitTo(vm, Event.OperationSucceeded, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
return false;
}
}
private void setStateMachine() {
_stateMachine = VirtualMachine.State.getStateMachine();
}
protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException {
vm.setReservationId(reservationId);
return _stateMachine.transitTo(vm, e, hostId, _vmDao);
}
@Override
public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
State oldState = vm.getState();
if (oldState == State.Starting) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(hostId);
}
} else if (oldState == State.Stopping) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(vm.getHostId());
}
}
return _stateMachine.transitTo(vm, e, hostId, _vmDao);
}
@Override
public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) {
// expunge the corresponding nics
VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm);
_networkMgr.expungeNics(profile);
s_logger.trace("Nics of the vm " + vm + " are expunged successfully");
return _vmDao.remove(vm.getId());
}
@Override
public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return true;
}
if (!advanceStop(vm, false, user, caller)) {
s_logger.debug("Unable to stop " + vm);
return false;
}
try {
if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
return false;
}
} catch (NoTransitionException e) {
s_logger.debug(e.getMessage());
return false;
}
return true;
}
protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException {
CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName()));
if (!answer.getResult() || answer.getState() == State.Stopped) {
return false;
}
return true;
}
@Override
public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
VirtualMachineMigrationException {
s_logger.info("Migrating " + vm + " to " + dest);
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
long vmId = vm.getId();
vm = vmGuru.findById(vmId);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vm);
}
throw new ManagementServerException("Unable to find a virtual machine with id " + vmId);
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm);
}
short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
_networkMgr.prepareNicForMigration(profile, dest);
_storageMgr.prepareForMigration(profile, dest);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
try {
MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
s_logger.error("Unable to migrate due to " + ma.getDetails());
return null;
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
return null;
}
} catch (OperationTimedoutException e) {
}
migrated = true;
return vm;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone "
+ dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
protected void cancelWorkItems(long nodeId) {
GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem");
try {
if (scanLock.lock(3)) {
try {
List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId);
for (ItWorkVO work : works) {
s_logger.info("Handling unfinished work item: " + work);
try {
VMInstanceVO vm = _vmDao.findById(work.getInstanceId());
if (vm != null) {
if (work.getType() == State.Starting) {
_haMgr.scheduleRestart(vm, true);
} else if (work.getType() == State.Stopping) {
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop);
} else if (work.getType() == State.Migrating) {
_haMgr.scheduleMigration(vm);
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
} catch (Exception e) {
s_logger.error("Error while handling " + work, e);
}
}
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
@Override
public boolean migrateAway(VirtualMachine.Type vmType, long vmId, long srcHostId) throws InsufficientServerCapacityException, VirtualMachineMigrationException {
VirtualMachineGuru<? extends VMInstanceVO> vmGuru = _vmGurus.get(vmType);
VMInstanceVO vm = vmGuru.findById(vmId);
if (vm == null) {
s_logger.debug("Unable to find a VM for " + vmId);
return true;
}
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
Long hostId = vm.getHostId();
if (hostId == null) {
s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm);
return true;
}
Host host = _hostDao.findById(hostId);
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null);
ExcludeList excludes = new ExcludeList();
excludes.addHost(hostId);
DeployDestination dest = null;
while (true) {
for (DeploymentPlanner planner : _planners) {
dest = planner.plan(profile, plan, excludes);
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Planner " + planner + " found " + dest + " for migrating to.");
}
break;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Planner " + planner + " was unable to find anything.");
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
VMInstanceVO vmInstance = null;
try {
vmInstance = migrate(vm, srcHostId, dest);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
} catch (ManagementServerException e) {
s_logger.debug("Unable to migrate VM: " + e.getMessage());
} catch (VirtualMachineMigrationException e) {
s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage());
if (vm.getState() == State.Starting) {
s_logger.debug("VM seems to be still Starting, we should retry migration later");
throw e;
} else {
s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString());
}
}
if (vmInstance != null) {
return true;
}
try {
boolean result = advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
return result;
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
}
return false;
}
}
protected class CleanupTask implements Runnable {
@Override
public void run() {
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(_cleanupWait);
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
}
}
@Override
public boolean isVirtualMachineUpgradable(UserVm vm, ServiceOffering offering) {
Enumeration<HostAllocator> en = _hostAllocators.enumeration();
boolean isMachineUpgradable = true;
while (isMachineUpgradable && en.hasMoreElements()) {
final HostAllocator allocator = en.nextElement();
isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering);
}
return isMachineUpgradable;
}
@Override
public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
try {
return advanceReboot(vm, params, caller, account);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e);
}
}
@Override
public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
T rebootedVm = null;
DataCenter dc = _configMgr.getZone(vm.getDataCenterIdToDeployIn());
Host host = _hostDao.findById(vm.getHostId());
Cluster cluster = null;
if (host != null) {
cluster = _configMgr.getCluster(host.getClusterId());
}
HostPodVO pod = _configMgr.getPod(host.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, cluster, host);
try {
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(new RebootCommand(vm.getInstanceName()));
_agentMgr.send(host.getId(), cmds);
Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
if (rebootAnswer != null && rebootAnswer.getResult()) {
rebootedVm = vm;
return rebootedVm;
}
s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
}
return rebootedVm;
}
@Override
public VMInstanceVO findById(VirtualMachine.Type type, long vmId) {
VirtualMachineGuru<? extends VMInstanceVO> guru = _vmGurus.get(type);
return guru.findById(vmId);
}
public Command cleanup(String vmName) {
return new StopCommand(vmName);
}
public Commands deltaSync(long hostId, Map<String, State> newStates) {
Map<Long, AgentVmInfo> states = convertToInfos(newStates);
Commands commands = new Commands(OnError.Continue);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hostId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
commands.addCommand(command);
}
}
return commands;
}
protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, State> states) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values();
for (Map.Entry<String, State> entry : states.entrySet()) {
for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) {
String name = entry.getKey();
VMInstanceVO vm = vmGuru.findByName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue()));
break;
}
Long id = vmGuru.convertToId(name);
if (id != null) {
map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null, entry.getValue()));
break;
}
}
}
return map;
}
/**
* compareState does as its name suggests and compares the states between management server and agent. It returns whether
* something should be cleaned up
*
*/
protected Command compareState(long hostId, VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean nativeHA) {
State agentState = info.state;
final String agentName = info.name;
final State serverState = vm.getState();
final String serverName = vm.getInstanceName();
VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vm);
Command command = null;
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM " + serverName + ": server state = " + serverState + " and agent state = " + agentState);
}
if (agentState == State.Error) {
agentState = State.Stopped;
short alertType = AlertManager.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
}
HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn());
DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterIdToDeployIn());
HostVO hostVO = _hostDao.findById(vm.getHostId());
String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host " + hostDesc + " due to storage failure",
"Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure.");
}
// if (serverState == State.Migrating) {
// s_logger.debug("Skipping vm in migrating state: " + vm);
// return null;
if (agentState == serverState) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Both states are " + agentState + " for " + vm);
}
assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed.";
if (agentState == State.Running) {
try {
if(nativeHA) {
stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, hostId);
} else {
stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
}
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// FIXME: What if someone comes in and sets it to stopping? Then what?
return null;
}
s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways.");
return cleanup(agentName);
}
if (agentState == State.Shutdowned) {
if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
try {
advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (AgentUnavailableException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (OperationTimedoutException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (ConcurrentOperationException e) {
assert (false) : "How do we hit this with forced on?";
return null;
}
} else {
s_logger.debug("Sending cleanup to a shutdowned vm: " + agentName);
command = cleanup(agentName);
}
} else if (agentState == State.Stopped) {
// This state means the VM on the agent was detected previously
// and now is gone. This is slightly different than if the VM
// was never completed but we still send down a Stop Command
// to ensure there's cleanup.
if (serverState == State.Running) {
// Our records showed that it should be running so let's restart it.
_haMgr.scheduleRestart(vm, false);
} else if (serverState == State.Stopping) {
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.ForceStop);
s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm);
} else if (serverState == State.Starting) {
s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName());
_haMgr.scheduleRestart(vm, false);
}
command = cleanup(agentName);
} else if (agentState == State.Running) {
if (serverState == State.Starting) {
if (fullSync) {
s_logger.debug("VM state is starting on full sync so updating it to running");
vm = findById(vm.getType(), vm.getId());
try {
stateTransitTo(vm, Event.AgentReportRunning, vm.getHostId());
} catch (NoTransitionException e1) {
s_logger.warn(e1.getMessage());
}
s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running");
vm = vmGuru.findById(vm.getId());
VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
List<NicVO> nics = _nicsDao.listByVmId(profile.getId());
for (NicVO nic : nics) {
Network network = _networkMgr.getNetwork(nic.getNetworkId());
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null);
profile.addNic(nicProfile);
}
Commands cmds = new Commands(OnError.Stop);
s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm);
if (vmGuru.finalizeCommandsOnStart(cmds, profile)) {
if (cmds.size() != 0) {
try {
_agentMgr.send(vm.getHostId(), cmds);
} catch (OperationTimedoutException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
}
}
if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) {
try {
stateTransitTo(vm, Event.AgentReportRunning, vm.getHostId());
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
} else {
s_logger.error("Exception during update for running vm: " + vm);
return null;
}
} else {
s_logger.error("Unable to finalize commands on start for vm: " + vm);
return null;
}
}
} else if (serverState == State.Stopping) {
s_logger.debug("Scheduling a stop command for " + vm);
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.Stop);
} else {
s_logger.debug("VM state is in stopped so stopping it on the agent");
command = cleanup(agentName);
}
}
return command;
}
public Commands fullSync(final long hostId, final Map<String, State> newStates) {
Commands commands = new Commands(OnError.Continue);
final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId);
s_logger.debug("Found " + vms.size() + " VMs for host " + hostId);
Map<Long, AgentVmInfo> infos = convertToInfos(newStates);
for (VMInstanceVO vm : vms) {
AgentVmInfo info = infos.remove(vm.getId());
VMInstanceVO castedVm = null;
if (info == null) {
info = new AgentVmInfo(vm.getInstanceName(), getVmGuru(vm), vm, State.Stopped);
castedVm = info.guru.findById(vm.getId());
} else {
castedVm = info.vm;
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(castedVm.getHypervisorType());
Command command = compareState(hostId, castedVm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
commands.addCommand(command);
}
}
for (final AgentVmInfo left : infos.values()) {
for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : _vmGurus.values()) {
VMInstanceVO vm = vmGuru.findByName(left.name);
if (vm == null) {
s_logger.warn("Stopping a VM that we have no record of: " + left.name);
commands.addCommand(cleanup(left.name));
} else {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
if(hvGuru.trackVmHostChange()) {
Command command = compareState(hostId, vm, left, true, true);
if (command != null) {
commands.addCommand(command);
}
} else {
s_logger.warn("Stopping a VM that we have no record of: " + left.name);
commands.addCommand(cleanup(left.name));
}
}
}
}
return commands;
}
@Override
public boolean isRecurring() {
return false;
}
@Override
public boolean processAnswers(long agentId, long seq, Answer[] answers) {
for (final Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Cleanup failed due to " + answer.getDetails());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleanup succeeded. Details " + answer.getDetails());
}
}
}
return true;
}
@Override
public boolean processTimeout(long agentId, long seq) {
return true;
}
@Override
public int getTimeout() {
return -1;
}
@Override
public boolean processCommands(long agentId, long seq, Command[] cmds) {
boolean processed = false;
for (Command cmd : cmds) {
if (cmd instanceof PingRoutingCommand) {
PingRoutingCommand ping = (PingRoutingCommand) cmd;
if (ping.getNewStates().size() > 0) {
Commands commands = deltaSync(agentId, ping.getNewStates());
if (commands.size() > 0) {
try {
_agentMgr.send(agentId, commands, this);
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is now unavailable", e);
}
}
}
processed = true;
}
}
return processed;
}
@Override
public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
return null;
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return true;
}
@Override
public void processConnect(HostVO agent, StartupCommand cmd) throws ConnectionException {
if (!(cmd instanceof StartupRoutingCommand)) {
return;
}
long agentId = agent.getId();
StartupRoutingCommand startup = (StartupRoutingCommand) cmd;
Commands commands = fullSync(agentId, startup.getVmStates());
if (commands.size() > 0) {
s_logger.debug("Sending clean commands to the agent");
try {
boolean error = false;
Answer[] answers = _agentMgr.send(agentId, commands);
for (Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
error = true;
}
}
if (error) {
throw new ConnectionException(true, "Unable to stop VMs");
}
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
} catch (final OperationTimedoutException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
}
}
}
protected class TransitionTask implements Runnable {
@Override
public void run() {
GlobalLock lock = GlobalLock.getInternLock("TransitionChecking");
if (lock == null) {
s_logger.debug("Couldn't get the global lock");
return;
}
if (!lock.lock(30)) {
s_logger.debug("Couldn't lock the db");
return;
}
try {
lock.addRef();
List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
_haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop);
} else if (state == State.Starting) {
_haMgr.scheduleRestart(instance, true);
}
}
} catch (Exception e) {
s_logger.warn("Caught the following exception on transition checking", e);
} finally {
StackMaid.current().exitCleanup();
lock.unlock();
}
}
}
protected class AgentVmInfo {
public String name;
public State state;
public VMInstanceVO vm;
public VirtualMachineGuru<VMInstanceVO> guru;
@SuppressWarnings("unchecked")
public AgentVmInfo(String name, VirtualMachineGuru<? extends VMInstanceVO> guru, VMInstanceVO vm, State state) {
this.name = name;
this.state = state;
this.vm = vm;
this.guru = (VirtualMachineGuru<VMInstanceVO>) guru;
}
}
}
|
package org.jscep.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertStoreParameters;
import java.security.cert.Certificate;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.pkcs.CertificationRequest;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.util.encoders.Base64;
import org.jscep.asn1.IssuerAndSubject;
import org.jscep.message.CertRep;
import org.jscep.message.PkcsPkiEnvelopeDecoder;
import org.jscep.message.PkcsPkiEnvelopeEncoder;
import org.jscep.message.PkiMessage;
import org.jscep.message.PkiMessageDecoder;
import org.jscep.message.PkiMessageEncoder;
import org.jscep.request.Operation;
import org.jscep.response.Capability;
import org.jscep.transaction.FailInfo;
import org.jscep.transaction.MessageType;
import org.jscep.transaction.Nonce;
import org.jscep.transaction.OperationFailureException;
import org.jscep.transaction.TransactionId;
import org.jscep.util.LoggingUtil;
/**
* This class provides a base Servlet which can be extended using the abstract
* methods to implement a SCEP CA (or RA).
*/
public abstract class ScepServlet extends HttpServlet {
private final static String GET = "GET";
private final static String POST = "POST";
private final static String MSG_PARAM = "message";
private final static String OP_PARAM = "operation";
private static Logger LOGGER = LoggingUtil.getLogger(ScepServlet.class);
/**
* Serialization ID
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
LOGGER.entering(getClass().getName(), "service");
byte[] body = getMessageBytes(req);
final Operation op;
try {
op = getOperation(req);
if (op == null) {
// The operation parameter must be set.
res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
Writer writer = res.getWriter();
writer.write("Missing \"operation\" parameter.");
writer.flush();
return;
}
} catch (IllegalArgumentException e) {
// The operation was not recognised.
res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
Writer writer = res.getWriter();
writer.write("Invalid \"operation\" parameter.");
writer.flush();
return;
}
LOGGER.fine("Incoming Operation: " + op);
final String reqMethod = req.getMethod();
if (op == Operation.PKIOperation) {
if (reqMethod.equals(POST) == false && reqMethod.equals(GET) == false) {
// PKIOperation must be sent using GET or POST
res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
res.addHeader("Allow", GET + ", " + POST);
return;
}
} else {
if (reqMethod.equals(GET) == false) {
// Operations other than PKIOperation must be sent using GET
res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
res.addHeader("Allow", GET);
return;
}
}
LOGGER.fine("Method " + reqMethod + " Allowed for Operation: " + op);
if (op == Operation.GetCACaps) {
try {
doGetCaCaps(req, res);
} catch (Exception e) {
throw new ServletException(e);
}
} else if (op == Operation.GetCACert) {
try {
doGetCaCert(req, res);
} catch (Exception e) {
throw new ServletException(e);
}
} else if (op == Operation.GetNextCACert) {
try {
doGetNextCaCert(req, res);
} catch (Exception e) {
throw new ServletException(e);
}
} else if (op == Operation.PKIOperation) {
// PKIOperation
res.setHeader("Content-Type", "application/x-pki-message");
CMSSignedData sd;
try {
sd = new CMSSignedData(body);
} catch (CMSException e) {
throw new ServletException(e);
}
CertStore reqStore;
try {
reqStore = sd.getCertificatesAndCRLs("Collection", (String) null);
} catch (GeneralSecurityException e) {
throw new ServletException(e);
} catch (CMSException e) {
throw new ServletException(e);
}
Collection<? extends Certificate> reqCerts;
try {
reqCerts = reqStore.getCertificates(null);
} catch (CertStoreException e) {
throw new ServletException(e);
}
X509Certificate reqCert = (X509Certificate) reqCerts.iterator().next();
PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getPrivate());
PkiMessageDecoder decoder = new PkiMessageDecoder(envDecoder);
PkiMessage<? extends ASN1Encodable> msg = decoder.decode(sd);
MessageType msgType = msg.getMessageType();
ASN1Encodable msgData = msg.getMessageData();
Nonce senderNonce = Nonce.nextNonce();
TransactionId transId = msg.getTransactionId();
Nonce recipientNonce = msg.getSenderNonce();
CertRep certRep;
if (msgType == MessageType.GetCert) {
final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
final X509Name principal = iasn.getName();
final BigInteger serial = iasn.getSerialNumber().getValue();
try {
List<X509Certificate> issued = doGetCert(principal, serial);
if (issued.size() == 0) {
certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
} else {
CertStoreParameters params = new CollectionCertStoreParameters(issued);
CertStore store = CertStore.getInstance("Collection", params);
SignedData messageData = getMessageData(store);
certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
}
} catch (OperationFailureException e) {
certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
} catch (Exception e) {
throw new ServletException(e);
}
} else if (msgType == MessageType.GetCertInitial) {
final IssuerAndSubject ias = (IssuerAndSubject) msgData;
final X509Name issuer = ias.getIssuer();
final X509Name subject = ias.getSubject();
try {
List<X509Certificate> issued = doGetCertInitial(issuer, subject);
if (issued.size() == 0) {
certRep = new CertRep(transId, senderNonce, recipientNonce);
} else {
CertStoreParameters params = new CollectionCertStoreParameters(issued);
CertStore store = CertStore.getInstance("Collection", params);
SignedData messageData = getMessageData(store);
certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
}
} catch (OperationFailureException e) {
certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
} catch (Exception e) {
throw new ServletException(e);
}
} else if (msgType == MessageType.GetCRL) {
final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
final X509Name issuer = iasn.getName();
final BigInteger serialNumber = iasn.getSerialNumber().getValue();
try {
X509CRL crl = doGetCrl(issuer, serialNumber);
CertStoreParameters params = new CollectionCertStoreParameters(Collections.singleton(crl));
CertStore store = CertStore.getInstance("Collection", params);
SignedData messageData = getMessageData(store);
certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
} catch (OperationFailureException e) {
certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
} catch (Exception e) {
throw new ServletException(e);
}
} else if (msgType == MessageType.PKCSReq) {
final CertificationRequest certReq = (CertificationRequest) msgData;
try {
List<X509Certificate> issued = doEnroll(certReq);
if (issued.size() == 0) {
certRep = new CertRep(transId, senderNonce, recipientNonce);
} else {
CertStoreParameters params = new CollectionCertStoreParameters(issued);
CertStore store = CertStore.getInstance("Collection", params);
SignedData messageData = getMessageData(store);
certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
}
} catch (OperationFailureException e) {
certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
} catch (Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException("Unknown Message for Operation");
}
PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert);
PkiMessageEncoder encoder = new PkiMessageEncoder(getPrivate(), getSender(), envEncoder);
CMSSignedData signedData = encoder.encode(certRep);
byte[] resBytes = signedData.getEncoded();
res.getOutputStream().write(resBytes);
res.getOutputStream().close();
} else {
res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
}
LOGGER.exiting(getClass().getName(), "service");
}
private SignedData getMessageData(CertStore store) throws GeneralSecurityException, CMSException, IOException {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addCertificatesAndCRLs(store);
CMSSignedData cmsMessageData = generator.generate(null, (String) null);
ContentInfo cmsContentInfo = ContentInfo.getInstance(ASN1Object.fromByteArray(cmsMessageData.getEncoded()));
return SignedData.getInstance(cmsContentInfo.getContent());
}
private void doGetNextCaCert(HttpServletRequest req, HttpServletResponse res) throws Exception {
res.setHeader("Content-Type", "application/x-x509-next-ca-cert");
List<X509Certificate> certs = getNextCaCertificate(req.getParameter(MSG_PARAM));
if (certs.size() == 0) {
res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "GetNextCACert Not Supported");
} else {
CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addCertificatesAndCRLs(store);
generator.addSigner(getPrivate(), getSender(), PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
CMSSignedData degenerateSd = generator.generate(null, (String) null);
byte[] bytes = degenerateSd.getEncoded();
res.getOutputStream().write(bytes);
res.getOutputStream().close();
}
}
private void doGetCaCert(HttpServletRequest req, HttpServletResponse res) throws Exception {
final List<X509Certificate> certs = doGetCaCertificate(req.getParameter(MSG_PARAM));
final byte[] bytes;
if (certs.size() == 1) {
res.setHeader("Content-Type", "application/x-x509-ca-cert");
bytes = certs.get(0).getEncoded();
} else {
res.setHeader("Content-Type", "application/x-x509-ca-ra-cert");
CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addCertificatesAndCRLs(store);
CMSSignedData degenerateSd = generator.generate(null, (String) null);
bytes = degenerateSd.getEncoded();
}
res.getOutputStream().write(bytes);
res.getOutputStream().close();
}
private Operation getOperation(HttpServletRequest req) {
String op = req.getParameter(OP_PARAM);
if (op == null)
{
return null;
}
return Operation.valueOf(req.getParameter(OP_PARAM));
}
private void doGetCaCaps(HttpServletRequest req, HttpServletResponse res) throws Exception {
res.setHeader("Content-Type", "text/plain");
final Set<Capability> caps = doCapabilities(req.getParameter("message"));
for (Capability cap : caps) {
res.getWriter().write(cap.toString());
res.getWriter().write('\n');
}
res.getWriter().close();
}
/**
* Returns the capabilities of the specified CA.
*
* @param identifier the CA identifier, which may be an empty string.
* @return the capabilities.
*/
abstract protected Set<Capability> doCapabilities(String identifier) throws Exception;
/**
* Returns the certificate chain of the specified CA.
*
* @param identifier the CA identifier, which may be an empty string.
* @return the CA's certificate.
*/
abstract protected List<X509Certificate> doGetCaCertificate(String identifier) throws Exception;
/**
* Return the chain of the next X.509 certificate which will be used by
* the specified CA.
*
* @param identifier the CA identifier, which may be an empty string.
* @return the list of certificates.
*/
abstract protected List<X509Certificate> getNextCaCertificate(String identifier) throws Exception;
/**
* Retrieve the certificate chain identified by the given parameters.
*
* @param issuer the issuer name.
* @param serial the serial number.
* @return the identified certificate, if any.
* @throws OperationFailureException if the operation cannot be completed
*/
abstract protected List<X509Certificate> doGetCert(X509Name issuer, BigInteger serial) throws OperationFailureException, Exception;
/**
* Checks to see if a previously-requested certificate has been issued. If
* the certificate has been issued, this method will return the appropriate
* certificate chain. Otherwise, this method should return null or an empty
* list to indicate that the request is still pending.
*
* @param issuer the issuer name.
* @param subject the subject name.
* @return the identified certificate, if any.
* @throws OperationFailureException if the operation cannot be completed
*/
abstract protected List<X509Certificate> doGetCertInitial(X509Name issuer, X509Name subject) throws OperationFailureException, Exception;
/**
* Retrieve the CRL covering the given certificate identifiers.
*
* @param issuer the certificate issuer.
* @param serial the certificate serial number.
* @return the CRL.
* @throws OperationFailureException if the operation cannot be completed
*/
abstract protected X509CRL doGetCrl(X509Name issuer, BigInteger serial) throws OperationFailureException, Exception;
/**
* Enrols a certificate into the PKI represented by this SCEP interface. If
* the request can be completed immediately, this method returns an appropriate
* certificate chain. If the request is pending, this method should return null
* or any empty list.
*
* @param certificationRequest the PKCS #10 CertificationRequest
* @return the certificate chain, if any
* @throws OperationFailureException if the operation cannot be completed
*/
abstract protected List<X509Certificate> doEnroll(CertificationRequest certificationRequest) throws OperationFailureException, Exception;
/**
* Returns the private key of the entity represented by this SCEP server.
*
* @return the private key.
*/
abstract protected PrivateKey getPrivate();
/**
* Returns the certificate of the entity represented by this SCEP server.
*
* @return the certificate.
*/
abstract protected X509Certificate getSender();
private byte[] getBody(ServletInputStream servletIn) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b;
while ((b = servletIn.read()) != -1) {
baos.write(b);
}
baos.close();
return baos.toByteArray();
}
private byte[] getMessageBytes(HttpServletRequest req) throws IOException {
if (req.getMethod().equals(POST)) {
return getBody(req.getInputStream());
} else {
Operation op = getOperation(req);
if (op == Operation.PKIOperation) {
String msg = req.getParameter(MSG_PARAM);
if (msg.isEmpty()) {
return new byte[0];
}
return Base64.decode(msg);
} else {
return new byte[0];
}
}
}
}
|
package com.tqmall.search.common.result;
import java.util.Collection;
public final class ResultUtils {
private ResultUtils() {
}
private static final ResultBuild<Result> RESULT_BUILD = new ResultBuild<Result>() {
@Override
public Result errorBuild(ErrorCode errorCode) {
return new Result(errorCode);
}
};
private static final ResultBuild<MapResult> MAP_RESULT_BUILD = new ResultBuild<MapResult>() {
@Override
public MapResult errorBuild(ErrorCode errorCode) {
return new MapResult(errorCode);
}
};
private static final ResultBuild<PageResult> PAGE_RESULT_BUILD = new ResultBuild<PageResult>() {
@Override
public PageResult errorBuild(ErrorCode errorCode) {
return new PageResult(errorCode);
}
};
/**
* Result
*/
public static String resultToString(Result result) {
return "Result: succeed = " + result.isSucceed() + ", code = " + result.getCode() + ", message = " + result.getMessage()
+ (result instanceof PageResult ? (", total = " + ((PageResult) result).getTotal()) : "")
+ ", data = " + result.getData().toString();
}
/**
* , {@link Result}
* @param data
* @param <T>
* @return , {@link Result}
*/
public static <T> Result<T> result(T data) {
return new Result<>(data);
}
/**
* {@link Result}
* @param errorCode
* @param <T> ,
* @return {@link Result}
*/
@SuppressWarnings("unchecked")
public static <T> Result<T> result(ErrorCode errorCode) {
return wrapError(errorCode, RESULT_BUILD);
}
/**
* {@link Result}, Message
* @param errorCode
* @param <T> ,
* @return {@link Result}
*/
@SuppressWarnings("unchecked")
public static <T> Result<T> result(ErrorCode errorCode, Object... args) {
return wrapError(errorCode, RESULT_BUILD, args);
}
/**
* @see #result(Object)
* @return PageResult
*/
public static <T> PageResult<T> pageResult(Collection<T> data, long total) {
return new PageResult<>(data, total);
}
/**
* @see #result(ErrorCode)
* @return PageResult
*/
@SuppressWarnings("unchecked")
public static <T> PageResult<T> pageResult(ErrorCode errorCode) {
return wrapError(errorCode, PAGE_RESULT_BUILD);
}
/**
* @see #result(ErrorCode, Object...)
* @return PageResult
*/
@SuppressWarnings("unchecked")
public static <T> PageResult<T> pageResult(ErrorCode errorCode, Object... args) {
return wrapError(errorCode, PAGE_RESULT_BUILD, args);
}
/**
* @see #result(Object)
* @return MapResult
*/
public static MapResult mapResult() {
return new MapResult();
}
/**
* @see #result(Object)
* @return MapResult
*/
public static MapResult mapResult(String key, Object val) {
MapResult mapResult = new MapResult();
mapResult.put(key, val);
return mapResult;
}
/**
* @see #result(ErrorCode)
* @return MapResult
*/
public static MapResult mapResult(ErrorCode errorCode) {
return wrapError(errorCode, MAP_RESULT_BUILD);
}
/**
* @see #result(ErrorCode, Object...)
* @return MapResult
*/
public static MapResult mapResult(ErrorCode errorCode, Object... args) {
return wrapError(errorCode, MAP_RESULT_BUILD, args);
}
/**
*
* @param errorCode errorCode
* @param build Result
* @param <T> Result
* @return Result
*/
public static <T extends Result> T wrapError(ErrorCode errorCode, ResultBuild<T> build) {
return build.errorBuild(errorCode);
}
/**
* error message
* @see #wrapError(ErrorCode, ResultBuild)
*/
public static <T extends Result> T wrapError(final ErrorCode errorCode, ResultBuild<T> build, Object... args) {
if (args.length == 0) {
return build.errorBuild(errorCode);
} else {
final String message = String.format(errorCode.getMessage(), args);
return build.errorBuild(new ErrorCode() {
@Override
public String getCode() {
return errorCode.getCode();
}
@Override
public String getMessage() {
return message;
}
});
}
}
/**
* Result, Result
* @param <T> Result
*/
interface ResultBuild<T extends Result> {
T errorBuild(ErrorCode errorCode);
}
}
|
package org.cf.smalivm;
import gnu.trove.list.TIntList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cf.smalivm.context.ClassState;
import org.cf.smalivm.context.ExecutionContext;
import org.cf.smalivm.context.ExecutionGraph;
import org.cf.smalivm.context.ExecutionNode;
import org.cf.smalivm.context.HeapItem;
import org.cf.smalivm.context.MethodState;
import org.cf.smalivm.exception.MaxAddressVisitsExceeded;
import org.cf.smalivm.exception.MaxCallDepthExceeded;
import org.cf.smalivm.exception.MaxMethodVisitsExceeded;
import org.cf.smalivm.exception.UnhandledVirtualException;
import org.cf.smalivm.type.LocalInstance;
import org.cf.util.ImmutableUtils;
import org.cf.util.Utils;
import org.jf.dexlib2.AccessFlags;
import org.jf.dexlib2.iface.MethodImplementation;
import org.jf.dexlib2.writer.builder.BuilderMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VirtualMachine {
private static String getClassNameFromMethodDescriptor(String methodDescriptor) {
return methodDescriptor.split("->", 2)[0];
}
private static HeapItem getMutableParameterConsensus(TIntList addressList, ExecutionGraph graph,
int parameterRegister) {
ExecutionNode firstNode = graph.getNodePile(addressList.get(0)).get(0);
HeapItem item = firstNode.getContext().getMethodState().peekParameter(parameterRegister);
int[] addresses = addressList.toArray();
for (int address : addresses) {
List<ExecutionNode> nodes = graph.getNodePile(address);
for (ExecutionNode node : nodes) {
HeapItem otherItem = node.getContext().getMethodState().peekParameter(parameterRegister);
if (item.getValue() != otherItem.getValue()) {
if (log.isTraceEnabled()) {
log.trace("No conensus value for r" + parameterRegister + ". Returning unknown.");
}
return HeapItem.newUnknown(item.getType());
}
}
}
return item;
}
private static final Logger log = LoggerFactory.getLogger(VirtualMachine.class.getSimpleName());
private static final int DEFAULT_MAX_ADDRESS_VISITS = 500;
private static final int DEFAULT_MAX_CALL_DEPTH = 20;
private static final int DEFAULT_MAX_METHOD_VISITS = 1_000_000;
// TODO: Refactor these max values into method executor's constructor
private final int maxCallDepth;
private final int maxAddressVisits;
private final int maxMethodVisits;
private final MethodExecutor methodExecutor;
private final SmaliClassManager classManager;
private final Map<BuilderMethod, ExecutionGraph> methodToTemplateExecutionGraph;
private final StaticFieldAccessor staticFieldAccessor;
public VirtualMachine(SmaliClassManager manager) {
this(manager, DEFAULT_MAX_ADDRESS_VISITS, DEFAULT_MAX_CALL_DEPTH, DEFAULT_MAX_METHOD_VISITS);
}
public VirtualMachine(SmaliClassManager manager, int maxAddressVisits, int maxCallDepth, int maxMethodVisits) {
this.classManager = manager;
this.maxAddressVisits = maxAddressVisits;
this.maxMethodVisits = maxMethodVisits;
this.maxCallDepth = maxCallDepth;
methodExecutor = new MethodExecutor(this);
methodToTemplateExecutionGraph = new HashMap<BuilderMethod, ExecutionGraph>();
staticFieldAccessor = new StaticFieldAccessor(this);
}
public ExecutionGraph execute(String methodDescriptor) throws MaxAddressVisitsExceeded, MaxCallDepthExceeded,
MaxMethodVisitsExceeded, UnhandledVirtualException {
if (!classManager.methodHasImplementation(methodDescriptor)) {
return null;
}
ExecutionContext ectx = spawnExecutionContext(methodDescriptor);
return execute(methodDescriptor, ectx);
}
public ExecutionGraph execute(String methodDescriptor, ExecutionContext ectx) throws MaxAddressVisitsExceeded,
MaxCallDepthExceeded, MaxMethodVisitsExceeded, UnhandledVirtualException {
return execute(methodDescriptor, ectx, null, null);
}
public ExecutionGraph execute(String methodDescriptor, ExecutionContext calleeContext,
ExecutionContext callerContext, int[] parameterRegisters) throws MaxAddressVisitsExceeded,
MaxCallDepthExceeded, MaxMethodVisitsExceeded, UnhandledVirtualException {
if (callerContext != null) {
inheritClassStates(callerContext, calleeContext);
}
String className = getClassNameFromMethodDescriptor(methodDescriptor);
calleeContext.staticallyInitializeClassIfNecessary(className);
ExecutionGraph graph = spawnInstructionGraph(methodDescriptor);
ExecutionNode rootNode = new ExecutionNode(graph.getRoot());
rootNode.setContext(calleeContext);
graph.addNode(rootNode);
ExecutionGraph result = methodExecutor.execute(graph);
if ((result != null) && (callerContext != null)) {
collapseMultiverse(methodDescriptor, graph, calleeContext, callerContext, parameterRegisters);
}
return result;
}
public SmaliClassManager getClassManager() {
return classManager;
}
public StaticFieldAccessor getStaticFieldAccessor() {
return staticFieldAccessor;
}
public ExecutionGraph spawnInstructionGraph(String methodDescriptor) {
BuilderMethod method = classManager.getMethod(methodDescriptor);
if (!methodToTemplateExecutionGraph.containsKey(method)) {
updateInstructionGraph(methodDescriptor);
}
ExecutionGraph graph = methodToTemplateExecutionGraph.get(method);
ExecutionGraph spawn = new ExecutionGraph(graph);
return spawn;
}
public int getMaxAddressVisits() {
return maxAddressVisits;
}
public int getMaxCallDepth() {
return maxCallDepth;
}
public int getMaxMethodVisits() {
return maxMethodVisits;
}
public ExecutionContext spawnExecutionContext(String methodDescriptor) {
return spawnExecutionContext(methodDescriptor, null, 0);
}
public ExecutionContext spawnExecutionContext(String methodDescriptor, ExecutionContext callerContext,
int callerAddress) {
if (!classManager.isLocalMethod(methodDescriptor)) {
throw new IllegalArgumentException("Method does not exist: " + methodDescriptor);
}
if (!classManager.methodHasImplementation(methodDescriptor)) {
// Native or abstract methods have no implementation. Shouldn't be executing them.
throw new IllegalArgumentException("No implementation for " + methodDescriptor);
}
BuilderMethod method = classManager.getMethod(methodDescriptor);
MethodImplementation impl = method.getImplementation();
int registerCount = impl.getRegisterCount();
List<String> parameterTypes = classManager.getParameterTypes(methodDescriptor);
int parameterSize = Utils.getRegisterSize(parameterTypes);
int accessFlags = method.getAccessFlags();
boolean isStatic = ((accessFlags & AccessFlags.STATIC.getValue()) != 0);
ExecutionContext spawnedContext = new ExecutionContext(this, methodDescriptor);
String className = getClassNameFromMethodDescriptor(methodDescriptor);
addTemplateClassState(spawnedContext, className);
// Assume all input values are unknown.
// TODO: refactor this to a method, lots of noise
MethodState mState = new MethodState(spawnedContext, registerCount, parameterTypes.size(), parameterSize);
int firstParameter = mState.getParameterStart();
int parameterRegister = firstParameter;
for (String type : parameterTypes) {
HeapItem item;
if (!isStatic && (parameterRegister == firstParameter)) {
item = new HeapItem(new LocalInstance(type), type);
} else {
item = HeapItem.newUnknown(type);
}
mState.assignParameter(parameterRegister, item);
parameterRegister += "J".equals(type) || "D".equals(type) ? 2 : 1;
}
spawnedContext.setMethodState(mState);
if (callerContext != null) {
spawnedContext.registerCaller(callerContext, callerAddress);
}
return spawnedContext;
}
public boolean isLocalClass(String classDescriptor) {
// Prefer to reflect methods, even if local. It's faster and less prone to error than emulating ourselves.
return classManager.isLocalClass(classDescriptor) && !MethodReflector.isSafe(classDescriptor);
}
public void updateInstructionGraph(String methodDescriptor) {
BuilderMethod method = classManager.getMethod(methodDescriptor);
ExecutionGraph graph = new ExecutionGraph(this, method);
methodToTemplateExecutionGraph.put(method, graph);
}
public void addTemplateClassState(ExecutionContext ectx, String className) {
List<String> fieldNameAndTypes = classManager.getFieldNameAndTypes(className);
ClassState cState = new ClassState(ectx, className, fieldNameAndTypes.size());
ectx.setClassState(className, cState, SideEffect.Level.NONE);
for (String fieldNameAndType : fieldNameAndTypes) {
String type = fieldNameAndType.split(":")[1];
cState.pokeField(fieldNameAndType, HeapItem.newUnknown(type));
}
}
/*
* Get consensus for method and class states for all execution paths and merge them into callerContext.
*/
private void collapseMultiverse(String methodDescriptor, ExecutionGraph graph, ExecutionContext calleeContext,
ExecutionContext callerContext, int[] parameterRegisters) {
TIntList terminatingAddresses = graph.getConnectedTerminatingAddresses();
if (parameterRegisters != null) {
MethodState mState = callerContext.getMethodState();
List<String> parameterTypes = classManager.getParameterTypes(methodDescriptor);
int parameterRegister = calleeContext.getMethodState().getParameterStart();
for (int parameterIndex = 0; parameterIndex < parameterTypes.size(); parameterIndex++) {
String type = parameterTypes.get(parameterIndex);
if (ImmutableUtils.isImmutableClass(type)) {
continue;
}
HeapItem item = getMutableParameterConsensus(terminatingAddresses, graph, parameterRegister);
int register = parameterRegisters[parameterIndex];
mState.assignRegister(register, item);
parameterRegister += "J".equals(type) || "D".equals(type) ? 2 : 1;
}
}
for (String currentClassName : classManager.getClassNames()) {
if (!callerContext.isClassInitialized(currentClassName) && !calleeContext
.isClassInitialized(currentClassName)) {
continue;
}
List<String> fieldNameAndTypes = classManager.getFieldNameAndTypes(currentClassName);
ClassState currentClassState;
if (callerContext.isClassInitialized(currentClassName)) {
currentClassState = callerContext.peekClassState(currentClassName);
} else {
currentClassState = new ClassState(callerContext, currentClassName, fieldNameAndTypes.size());
SideEffect.Level level = graph.getHighestClassSideEffectLevel(currentClassName);
callerContext.initializeClass(currentClassName, currentClassState, level);
}
for (String fieldNameAndType : fieldNameAndTypes) {
HeapItem item = graph.getFieldConsensus(terminatingAddresses, currentClassName, fieldNameAndType);
currentClassState.pokeField(fieldNameAndType, item);
}
}
}
private void inheritClassStates(ExecutionContext parent, ExecutionContext child) {
for (String className : classManager.getLoadedClassNames()) {
if (!parent.isClassInitialized(className)) {
continue;
}
ClassState fromClassState = parent.peekClassState(className);
ClassState toClassState = new ClassState(fromClassState, child);
for (String fieldNameAndType : classManager.getFieldNameAndTypes(className)) {
HeapItem item = fromClassState.peekField(fieldNameAndType);
toClassState.pokeField(fieldNameAndType, item);
}
SideEffect.Level level = parent.getClassStateSideEffectLevel(className);
child.initializeClass(className, toClassState, level);
}
}
}
|
package sqlancer.tidb.gen;
import java.util.stream.Collectors;
import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.tidb.TiDBBugs;
import sqlancer.tidb.TiDBProvider.TiDBGlobalState;
import sqlancer.tidb.TiDBSchema.TiDBColumn;
import sqlancer.tidb.TiDBSchema.TiDBDataType;
import sqlancer.tidb.TiDBSchema.TiDBTable;
public final class TiDBAlterTableGenerator {
private TiDBAlterTableGenerator() {
}
private enum Action {
MODIFY_COLUMN, ENABLE_DISABLE_KEYS, DROP_PRIMARY_KEY, ADD_PRIMARY_KEY, CHANGE, DROP_COLUMN, ORDER_BY
}
public static SQLQueryAdapter getQuery(TiDBGlobalState globalState) {
ExpectedErrors errors = new ExpectedErrors();
errors.add(
"Information schema is changed during the execution of the statement(for example, table definition may be updated by other DDL ran in parallel)");
errors.add("Data truncated");
errors.add("Data truncation");
errors.add("without a key length");
errors.add("charset");
errors.add("not supported");
errors.add("SQL syntax");
errors.add("can't drop");
StringBuilder sb = new StringBuilder("ALTER TABLE ");
TiDBTable table = globalState.getSchema().getRandomTable(t -> !t.isView());
TiDBColumn column = table.getRandomColumn();
sb.append(table.getName());
Action a = Randomly.fromOptions(Action.values());
sb.append(" ");
switch (a) {
case MODIFY_COLUMN:
if (TiDBBugs.bug10) {
throw new IgnoreMeException();
}
sb.append("MODIFY ");
sb.append(column.getName());
sb.append(" ");
sb.append(TiDBDataType.getRandom());
errors.add("Unsupported modify column");
break;
case DROP_COLUMN:
sb.append(" DROP ");
if (table.getColumns().size() <= 1) {
throw new IgnoreMeException();
}
sb.append(column.getName());
errors.add("with composite index covered or Primary Key covered now");
errors.add("Unsupported drop integer primary key");
errors.add("has a generated column dependency");
errors.add(
"references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them");
break;
case ENABLE_DISABLE_KEYS:
sb.append(Randomly.fromOptions("ENABLE", "DISABLE"));
sb.append(" KEYS");
break;
case DROP_PRIMARY_KEY:
if (!column.isPrimaryKey()) {
throw new IgnoreMeException();
}
errors.add("Unsupported drop integer primary key");
errors.add("Unsupported drop primary key when alter-primary-key is false");
errors.add("Unsupported drop primary key when the table's pkIsHandle is true");
errors.add("Incorrect table definition; there can be only one auto column and it must be defined as a key");
sb.append(" DROP PRIMARY KEY");
break;
case ADD_PRIMARY_KEY:
sb.append("ADD PRIMARY KEY(");
sb.append(table.getRandomNonEmptyColumnSubset().stream().map(c -> {
StringBuilder colName = new StringBuilder(c.getName());
if (c.getType().getPrimitiveDataType() == TiDBDataType.TEXT
|| c.getType().getPrimitiveDataType() == TiDBDataType.BLOB) {
TiDBTableGenerator.appendSpecifiers(colName, c.getType().getPrimitiveDataType());
}
return colName;
}).collect(Collectors.joining(", ")));
sb.append(")");
errors.add("Unsupported add primary key, alter-primary-key is false");
errors.add("Information schema is changed during the execution of the statement");
errors.add("Multiple primary key defined");
errors.add("Invalid use of NULL value");
errors.add("Duplicate entry");
errors.add("'Defining a virtual generated column as primary key' is not supported for generated columns");
break;
case CHANGE:
if (TiDBBugs.bug10) {
throw new IgnoreMeException();
}
sb.append(" CHANGE ");
sb.append(column.getName());
sb.append(" ");
sb.append(column.getName());
sb.append(" ");
sb.append(column.getType().getPrimitiveDataType());
sb.append(" NOT NULL ");
errors.add("Invalid use of NULL value");
errors.add("Unsupported modify column:");
errors.add("Invalid integer format for value");
break;
case ORDER_BY:
sb.append(" ORDER BY ");
sb.append(table.getRandomNonEmptyColumnSubset().stream()
.map(c -> c.getName() + Randomly.fromOptions("", " ASC", " DESC"))
.collect(Collectors.joining(", ")));
break;
default:
throw new AssertionError(a);
}
return new SQLQueryAdapter(sb.toString(), errors, true);
}
}
|
package org.jasig.portal;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import org.jasig.portal.properties.PropertiesManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.utils.SAX2BufferImpl;
import org.jasig.portal.utils.SetCheckInSemaphore;
import org.jasig.portal.utils.SoftHashMap;
import org.jasig.portal.utils.threading.ThreadPool;
import org.jasig.portal.utils.threading.WorkTracker;
import org.jasig.portal.utils.threading.WorkerTask;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* This class takes care of initiating channel rendering thread,
* monitoring it for timeouts, retreiving cache, and returning
* rendering results and status.
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @version $Revision$
*/
public class ChannelRenderer
implements IChannelRenderer
{
private static final Log log = LogFactory.getLog(ChannelRenderer.class);
public static final boolean CACHE_CHANNELS=PropertiesManager.getPropertyAsBoolean("org.jasig.portal.ChannelRenderer.cache_channels");
public static final int RENDERING_SUCCESSFUL=0;
public static final int RENDERING_FAILED=1;
public static final int RENDERING_TIMED_OUT=2;
public static final String[] renderingStatus={"successful","failed","timed out"};
protected IChannel channel;
protected ChannelRuntimeData rd;
protected Map channelCache;
protected Map cacheTables;
protected boolean rendering;
protected boolean donerendering;
protected Thread workerThread;
protected WorkTracker workTracker;
protected Worker worker;
protected long startTime;
protected long timeOut = java.lang.Long.MAX_VALUE;
protected boolean ccacheable;
protected static ThreadPool tp=null;
protected static Map systemCache=null;
protected SetCheckInSemaphore groupSemaphore;
protected Object groupRenderingKey;
private Object cacheWriteLock;
/**
* Default contstructor
*
* @param chan an <code>IChannel</code> value
* @param runtimeData a <code>ChannelRuntimeData</code> value
* @param threadPool a <code>ThreadPool</code> value
*/
public ChannelRenderer (IChannel chan,ChannelRuntimeData runtimeData, ThreadPool threadPool) {
this.channel=chan;
this.rd=runtimeData;
rendering = false;
ccacheable=false;
cacheWriteLock=new Object();
tp = threadPool;
if(systemCache==null) {
systemCache=ChannelManager.systemCache;
}
this.groupSemaphore=null;
this.groupRenderingKey=null;
}
/**
* Default contstructor
*
* @param chan an <code>IChannel</code> value
* @param runtimeData a <code>ChannelRuntimeData</code> value
* @param threadPool a <code>ThreadPool</code> value
* @param groupSemaphore a <code>SetCheckInSemaphore</code> for the current rendering group
* @param groupRenderingKey an <code>Object</code> to be used for check ins with the group semaphore
*/
public ChannelRenderer (IChannel chan,ChannelRuntimeData runtimeData, ThreadPool threadPool, SetCheckInSemaphore groupSemaphore, Object groupRenderingKey) {
this(chan,runtimeData,threadPool);
this.groupSemaphore=groupSemaphore;
this.groupRenderingKey=groupRenderingKey;
}
/**
* Sets the channel on which ChannelRenderer is to operate.
*
* @param channel an <code>IChannel</code>
*/
public void setChannel(IChannel channel) {
if (log.isDebugEnabled())
log.debug("ChannelRenderer::setChannel() : channel is being reset!");
this.channel=channel;
if(worker!=null) {
worker.setChannel(channel);
}
// clear channel chace
channelCache=null;
cacheWriteLock=new Object();
}
/**
* Obtains a content cache specific for this channel instance.
*
* @return a key->rendering map for this channel
*/
Map getChannelCache() {
if(channelCache==null) {
if((channelCache=(SoftHashMap)cacheTables.get(channel))==null) {
channelCache=new SoftHashMap(1);
cacheTables.put(channel,channelCache);
}
}
return channelCache;
}
/**
* Set the timeout value
* @param value timeout in milliseconds
*/
public void setTimeout (long value) {
timeOut = value;
}
public void setCacheTables(Map cacheTables) {
this.cacheTables=cacheTables;
}
/**
* Informs IChannelRenderer that a character caching scheme
* will be used for the current rendering.
* @param setting a <code>boolean</code> value
*/
public void setCharacterCacheable(boolean setting) {
this.ccacheable=setting;
}
/**
* Start rendering of the channel in a new thread.
* Note that rendered information will be accumulated in a
* buffer until outputRendering() function is called.
* startRendering() is a non-blocking function.
*/
public void startRendering ()
{
// start the rendering thread
worker = new Worker (channel,rd);
workTracker=tp.execute(worker);
rendering = true;
startTime = System.currentTimeMillis ();
}
public void startRendering(SetCheckInSemaphore groupSemaphore, Object groupRenderingKey) {
this.groupSemaphore=groupSemaphore;
this.groupRenderingKey=groupRenderingKey;
this.startRendering();
}
/**
* <p>Cancels the rendering job.
**/
public void cancelRendering()
{
if( null != worker )
{
worker.kill();
}
}
/**
* Output channel rendering through a given ContentHandler.
* Note: call of outputRendering() without prior call to startRendering() is equivalent to
* sequential calling of startRendering() and then outputRendering().
* outputRendering() is a blocking function. It will return only when the channel completes rendering
* or fails to render by exceeding allowed rendering time.
* @param out Document Handler that will receive information rendered by the channel.
* @return error code. 0 - successful rendering; 1 - rendering failed; 2 - rendering timedOut;
*/
public int outputRendering (ContentHandler out) throws Throwable {
int renderingStatus=completeRendering();
if(renderingStatus==RENDERING_SUCCESSFUL) {
SAX2BufferImpl buffer;
if ((buffer=worker.getBuffer())!=null) {
// unplug the buffer :)
try {
buffer.setAllHandlers(out);
buffer.outputBuffer();
return RENDERING_SUCCESSFUL;
} catch (SAXException e) {
// worst case scenario: partial content output :(
log.error( "ChannelRenderer::outputRendering() : following SAX exception occured : "+e);
throw e;
}
} else {
log.error( "ChannelRenderer::outputRendering() : output buffer is null even though rendering was a success?! trying to rendering for ccaching ?");
throw new PortalException("unable to obtain rendering buffer");
}
}
return renderingStatus;
}
/**
* Requests renderer to complete rendering and return status.
* This does exactly the same things as outputRendering except for the
* actual stream output.
*
* @return an <code>int</code> return status value
*/
public int completeRendering() throws Throwable {
if (!rendering) {
this.startRendering ();
}
boolean abandoned=false;
long timeOutTarget = startTime + timeOut;
// separate waits caused by rendering group
if(groupSemaphore!=null) {
while(!worker.isSetRuntimeDataComplete() && System.currentTimeMillis() < timeOutTarget && !workTracker.isJobComplete()) {
long wait=timeOutTarget-System.currentTimeMillis();
if(wait<=0) { wait=1; }
try {
synchronized(groupSemaphore) {
groupSemaphore.wait(wait);
}
} catch (InterruptedException ie) {}
}
if(!worker.isSetRuntimeDataComplete() && !workTracker.isJobComplete()) {
workTracker.killJob();
abandoned=true;
if (log.isDebugEnabled())
log.debug("ChannelRenderer::outputRendering() : killed. " +
"(key="+groupRenderingKey.toString()+")");
} else {
groupSemaphore.waitOn();
}
// reset timer for rendering
timeOutTarget=System.currentTimeMillis()+timeOut;
}
if(!abandoned) {
while(System.currentTimeMillis() < timeOutTarget && !workTracker.isJobComplete()) {
long wait=timeOutTarget-System.currentTimeMillis();
if(wait<=0) { wait=1; }
try {
synchronized(workTracker) {
workTracker.wait(wait);
}
} catch (InterruptedException ie) {}
}
if(!workTracker.isJobComplete()) {
workTracker.killJob();
abandoned=true;
if (log.isDebugEnabled())
log.debug("ChannelRenderer::outputRendering() : killed.");
} else {
abandoned=!workTracker.isJobSuccessful();
}
}
if (!abandoned && worker.done ()) {
if (worker.successful() && (((worker.getBuffer())!=null) || (ccacheable && worker.cbuffer!=null))) {
return RENDERING_SUCCESSFUL;
} else {
// rendering was not successful
Throwable e;
if((e=worker.getThrowable())!=null) throw new InternalPortalException(e);
// should never get there, unless thread.stop() has seriously messed things up for the worker thread.
return RENDERING_FAILED;
}
} else {
Throwable e;
e = workTracker.getException();
if (e != null) {
throw new InternalPortalException(e);
} else {
// Assume rendering has timed out
return RENDERING_TIMED_OUT;
}
}
}
/**
* Returns rendered buffer.
* This method does not perform any status checks, so make sure to call completeRendering() prior to invoking this method.
*
* @return rendered buffer
*/
public SAX2BufferImpl getBuffer() {
if(worker!=null) {
return worker.getBuffer();
} else {
return null;
}
}
/**
* Returns a character output of a channel rendering.
*/
public String getCharacters() {
if(worker!=null) {
return worker.getCharacters();
} else {
if (log.isDebugEnabled())
log.debug("ChannelRenderer::getCharacters() : worker is null already !");
return null;
}
}
/**
* Sets a character cache for the current rendering.
*/
public void setCharacterCache(String chars) {
if(worker!=null) {
worker.setCharacterCache(chars);
}
}
/**
* I am not really sure if this will take care of the runaway rendering threads.
* The alternative is kill them explicitly in ChannelManager.
*/
protected void finalize () throws Throwable {
if(workTracker!=null && !workTracker.isJobComplete())
workTracker.killJob();
super.finalize ();
}
protected class Worker extends WorkerTask{
private boolean successful;
private boolean done;
private boolean setRuntimeDataComplete;
private boolean decremented;
private IChannel channel;
private ChannelRuntimeData rd;
private SAX2BufferImpl buffer;
private String cbuffer;
private Throwable exc=null;
public Worker (IChannel ch, ChannelRuntimeData runtimeData) {
this.channel=ch; this.rd=runtimeData;
successful = false; done = false; setRuntimeDataComplete=false;
buffer=null; cbuffer=null;
}
public void setChannel(IChannel ch) {
this.channel=ch;
}
public boolean isSetRuntimeDataComplete() {
return this.setRuntimeDataComplete;
}
public void run () {
try {
if(rd!=null) {
channel.setRuntimeData(rd);
}
setRuntimeDataComplete=true;
if(groupSemaphore!=null) {
groupSemaphore.checkInAndWaitOn(groupRenderingKey);
}
if(CACHE_CHANNELS) {
// try to obtain rendering from cache
if(channel instanceof ICacheable ) {
ChannelCacheKey key=((ICacheable)channel).generateKey();
if(key!=null) {
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
ChannelCacheEntry entry=(ChannelCacheEntry)systemCache.get(key.getKey());
if(entry!=null) {
// found cached page
// check page validity
if(((ICacheable)channel).isCacheValid(entry.validity) && (entry.buffer!=null)) {
// use it
if(ccacheable && (entry.buffer instanceof String)) {
cbuffer=(String)entry.buffer;
log.debug("ChannelRenderer.Worker::run() : retrieved system-wide cached character content based on a key \""+key.getKey()+"\"");
} else if(entry.buffer instanceof SAX2BufferImpl) {
buffer=(SAX2BufferImpl) entry.buffer;
log.debug("ChannelRenderer.Worker::run() : retrieved system-wide cached content based on a key \""+key.getKey()+"\"");
}
} else {
// remove it
systemCache.remove(key.getKey());
log.debug("ChannelRenderer.Worker::run() : removed system-wide unvalidated cache based on a key \""+key.getKey()+"\"");
}
}
} else {
// by default we assume INSTANCE_KEY_SCOPE
ChannelCacheEntry entry=(ChannelCacheEntry)getChannelCache().get(key.getKey());
if(entry!=null) {
// found cached page
// check page validity
if(((ICacheable)channel).isCacheValid(entry.validity) && (entry.buffer!=null)) {
// use it
if(ccacheable && (entry.buffer instanceof String)) {
cbuffer=(String)entry.buffer;
log.debug("ChannelRenderer.Worker::run() : retrieved instance-cached character content based on a key \""+key.getKey()+"\"");
} else if(entry.buffer instanceof SAX2BufferImpl) {
buffer=(SAX2BufferImpl) entry.buffer;
log.debug("ChannelRenderer.Worker::run() : retrieved instance-cached content based on a key \""+key.getKey()+"\"");
}
} else {
// remove it
getChannelCache().remove(key.getKey());
log.debug("ChannelRenderer.Worker::run() : removed unvalidated instance-cache based on a key \""+key.getKey()+"\"");
}
}
}
}
// future work: here we should synchronize based on a particular cache key.
// Imagine a VERY popular cache entry timing out, then portal will attempt
// to re-render the page in many threads (serving many requests) simultaneously.
// If one was to synchronize on writing cache for a particular key, one thread
// would render and others would wait for it to complete.
// check if need to render
if((ccacheable && cbuffer==null && buffer==null) || ((!ccacheable) && buffer==null)) {
if (ccacheable && channel instanceof ICharacterChannel) {
StringWriter sw = new StringWriter(100);
PrintWriter pw = new PrintWriter(sw);
((ICharacterChannel)channel).renderCharacters(pw);
pw.flush();
cbuffer = sw.toString();
// save cache
if (key != null) {
if (key.getKeyScope() == ChannelCacheKey.SYSTEM_KEY_SCOPE) {
systemCache.put(key.getKey(), new ChannelCacheEntry(cbuffer, key.getKeyValidity()));
log.debug("ChannelRenderer.Worker::run() : recorded system character cache based on a key \"" + key.getKey() + "\"");
} else {
getChannelCache().put(key.getKey(), new ChannelCacheEntry(cbuffer, key.getKeyValidity()));
log.debug("ChannelRenderer.Worker::run() : recorded instance character cache based on a key \"" + key.getKey() + "\"");
}
}
} else {
// need to render again and cache the output
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML(buffer);
// save cache
if(key!=null) {
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
systemCache.put(key.getKey(),new ChannelCacheEntry(buffer,key.getKeyValidity()));
log.debug("ChannelRenderer.Worker::run() : recorded system cache based on a key \""+key.getKey()+"\"");
} else {
getChannelCache().put(key.getKey(),new ChannelCacheEntry(buffer,key.getKeyValidity()));
log.debug("ChannelRenderer.Worker::run() : recorded instance cache based on a key \""+key.getKey()+"\"");
}
}
}
}
} else {
if (ccacheable && channel instanceof ICharacterChannel) {
StringWriter sw = new StringWriter(100);
PrintWriter pw = new PrintWriter(sw);
((ICharacterChannel)channel).renderCharacters(pw);
pw.flush();
cbuffer = sw.toString();
} else {
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML(buffer);
}
}
} else {
// in the case when channel cache is not enabled
buffer = new SAX2BufferImpl ();
buffer.startBuffering();
channel.renderXML (buffer);
}
successful = true;
} catch (Exception e) {
if(groupSemaphore!=null) {
groupSemaphore.checkIn(groupRenderingKey);
}
this.setException(e);
}
done = true;
}
public boolean successful () {
return this.successful;
}
public SAX2BufferImpl getBuffer() {
return this.buffer;
}
/**
* Returns a character output of a channel rendering.
*/
public String getCharacters() {
if(ccacheable) {
return this.cbuffer;
} else {
log.error("ChannelRenderer.Worker::getCharacters() : attempting to obtain character data while character caching is not enabled !");
return null;
}
}
/**
* Sets a character cache for the current rendering.
*/
public void setCharacterCache(String chars) {
cbuffer=chars;
if(CACHE_CHANNELS) {
// try to obtain rendering from cache
if(channel instanceof ICacheable ) {
ChannelCacheKey key=((ICacheable)channel).generateKey();
if(key!=null) {
log.debug("ChannelRenderer::setCharacterCache() : called on a key \""+key.getKey()+"\"");
ChannelCacheEntry entry=null;
if(key.getKeyScope()==ChannelCacheKey.SYSTEM_KEY_SCOPE) {
entry=(ChannelCacheEntry)systemCache.get(key.getKey());
if(entry==null) {
log.debug("ChannelRenderer::setCharacterCache() : setting character cache buffer based on a system key \""+key.getKey()+"\"");
entry=new ChannelCacheEntry(chars,key.getKeyValidity());
} else {
entry.buffer=chars;
}
systemCache.put(key.getKey(),entry);
} else {
// by default we assume INSTANCE_KEY_SCOPE
entry=(ChannelCacheEntry)getChannelCache().get(key.getKey());
if(entry==null) {
log.debug("ChannelRenderer::setCharacterCache() : no existing cache on a key \""+key.getKey()+"\"");
entry=new ChannelCacheEntry(chars,key.getKeyValidity());
} else {
entry.buffer=chars;
}
getChannelCache().put(key.getKey(),entry);
}
} else {
log.debug("ChannelRenderer::setCharacterCache() : channel cache key is null.");
}
}
}
}
public boolean done () {
return this.done;
}
public Throwable getThrowable() {
return this.getException();
}
}
}
|
package boa.test.datagen.java;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.eclipse.jgit.lib.Constants;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import boa.datagen.DefaultProperties;
import boa.datagen.forges.github.RepositoryCloner;
import boa.datagen.scm.AbstractCommit;
import boa.datagen.scm.GitConnector;
import boa.datagen.util.FileIO;
import boa.functions.BoaAstIntrinsics;
import boa.types.Code.CodeRepository;
import boa.types.Code.CodeRepository.RepositoryKind;
import boa.types.Code.Revision;
import boa.types.Diff.ChangedFile;
//FIXME assert, autoboxing, static imports, binary literals, underscore literals, unsafe varargs
@RunWith(Parameterized.class)
public class TestJLSVersion {
@Parameters(name = "{index}: {0}")
public static List<ChangedFile[]> data() throws Exception {
List<ChangedFile[]> data = new ArrayList<ChangedFile[]>();
CodeRepository cr = buildCodeRepository("boalang/test-datagen");
String[][] commits = new String[][] {
{"15c9685cbd36edba1709637bb8f8c217c894bee6", "58"},
};
for (String[] commit : commits) {
ChangedFile[] snapshot = BoaAstIntrinsics.getSnapshot(cr, commit[0], new String[]{"SOURCE_JAVA_"});
assertThat(snapshot.length, Matchers.is(Integer.parseInt(commit[1])));
for (ChangedFile cf : snapshot)
data.add(new ChangedFile[]{cf});
}
return data;
}
private ChangedFile changedFile;
private static Configuration conf = new Configuration();
private static FileSystem fileSystem = null;
private static SequenceFile.Writer projectWriter, astWriter, commitWriter, contentWriter;
private static long astWriterLen = 0, commitWriterLen = 0, contentWriterLen = 0;
public TestJLSVersion(ChangedFile input) {
DefaultProperties.DEBUG = true;
this.changedFile = input;
}
@Test
public void testJLSVersion() throws Exception {
String kind = changedFile.getKind().name();
String version = kind.substring(kind.lastIndexOf('_') + 1);
assertThat(changedFile.getName(), Matchers.containsString("/" + version + "/"));
}
private static CodeRepository buildCodeRepository(String repoName) throws Exception {
fileSystem = FileSystem.get(conf);
System.out.println("Repo: " + repoName);
File gitDir = new File("dataset/repos/" + repoName);
openWriters(gitDir.getAbsolutePath());
FileIO.DirectoryRemover filecheck = new FileIO.DirectoryRemover(gitDir.getAbsolutePath());
filecheck.run();
String url = "https://github.com/" + repoName + ".git";
RepositoryCloner.clone(new String[]{url, gitDir.getAbsolutePath()});
GitConnector conn = new GitConnector(gitDir.getAbsolutePath(), repoName, astWriter, astWriterLen, contentWriter, contentWriterLen);
final CodeRepository.Builder repoBuilder = CodeRepository.newBuilder();
repoBuilder.setKind(RepositoryKind.GIT);
repoBuilder.setUrl(url);
for (final Revision rev : conn.getCommits(true, repoName)) {
final Revision.Builder revBuilder = Revision.newBuilder(rev);
repoBuilder.addRevisions(revBuilder);
}
if (repoBuilder.getRevisionsCount() > 0) {
// System.out.println("Build head snapshot");
repoBuilder.setHead(conn.getHeadCommitOffset());
repoBuilder.addAllHeadSnapshot(conn.buildHeadSnapshot(new String[] { "java" }, repoName));
}
repoBuilder.addAllBranches(conn.getBranchIndices());
repoBuilder.addAllBranchNames(conn.getBranchNames());
repoBuilder.addAllTags(conn.getTagIndices());
repoBuilder.addAllTagNames(conn.getTagNames());
closeWriters();
List<ChangedFile> snapshot1 = new ArrayList<ChangedFile>();
Map<String, AbstractCommit> commits = new HashMap<String, AbstractCommit>();
conn.getSnapshot(conn.getHeadCommitOffset(), snapshot1, commits);
// System.out.println("Finish building head snapshot");
List<String> snapshot2 = conn.getSnapshot(Constants.HEAD);
Set<String> s1 = new HashSet<String>(), s2 = new HashSet<String>(snapshot2);
for (ChangedFile cf : snapshot1)
s1.add(cf.getName());
// System.out.println("Test head snapshot");
assertEquals(s2, s1);
for (int i = conn.getRevisions().size()-1; i >= 0; i
AbstractCommit commit = conn.getRevisions().get(i);
snapshot1 = new ArrayList<ChangedFile>();
conn.getSnapshot(i, snapshot1, new HashMap<String, AbstractCommit>());
snapshot2 = conn.getSnapshot(commit.getId());
s1 = new HashSet<String>();
s2 = new HashSet<String>(snapshot2);
for (ChangedFile cf : snapshot1)
s1.add(cf.getName());
// System.out.println("Test snapshot at " + commit.getId());
assertEquals(s2, s1);
}
CodeRepository cr = repoBuilder.build();
{
ChangedFile[] snapshot = BoaAstIntrinsics.getSnapshot(cr);
String[] fileNames = new String[snapshot.length];
for (int i = 0; i < snapshot.length; i++)
fileNames[i] = snapshot[i].getName();
Arrays.sort(fileNames);
String[] expectedFileNames = conn.getSnapshot(Constants.HEAD).toArray(new String[0]);
Arrays.sort(expectedFileNames);
// System.out.println("Test head snapshot");
assertArrayEquals(expectedFileNames, fileNames);
}
for (Revision rev : cr.getRevisionsList()) {
ChangedFile[] snapshot = BoaAstIntrinsics.getSnapshot(cr, rev.getId());
String[] fileNames = new String[snapshot.length];
for (int i = 0; i < snapshot.length; i++)
fileNames[i] = snapshot[i].getName();
Arrays.sort(fileNames);
String[] expectedFileNames = conn.getSnapshot(rev.getId()).toArray(new String[0]);
Arrays.sort(expectedFileNames);
// System.out.println("Test snapshot at " + rev.getId());
assertArrayEquals(expectedFileNames, fileNames);
}
new Thread(new FileIO.DirectoryRemover(gitDir.getAbsolutePath())).start();
conn.close();
return cr;
}
public static void openWriters(String base) {
long time = System.currentTimeMillis();
String suffix = time + ".seq";
while (true) {
try {
projectWriter = SequenceFile.createWriter(fileSystem, conf, new Path(base + "/project/" + suffix),
Text.class, BytesWritable.class, CompressionType.BLOCK);
astWriter = SequenceFile.createWriter(fileSystem, conf, new Path(base + "/ast/" + suffix),
LongWritable.class, BytesWritable.class, CompressionType.BLOCK);
commitWriter = SequenceFile.createWriter(fileSystem, conf, new Path(base + "/commit/" + suffix),
LongWritable.class, BytesWritable.class, CompressionType.BLOCK);
contentWriter = SequenceFile.createWriter(fileSystem, conf, new Path(base + "/source/" + suffix),
LongWritable.class, BytesWritable.class, CompressionType.BLOCK);
break;
} catch (Throwable t) {
t.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
public static void closeWriters() {
while (true) {
try {
projectWriter.close();
astWriter.close();
commitWriter.close();
contentWriter.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
break;
} catch (Throwable t) {
t.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
public void print(Set<String> s, List<ChangedFile> snapshot, Map<String, AbstractCommit> commits) {
List<String> l = new ArrayList<String>(s);
Collections.sort(l);
for (String f : l)
System.out.println(f + " " + commits.get(f).getId());
System.out.println("==========================================");
}
}
|
package ca.sapon.jici.test;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import ca.sapon.jici.SourceException;
import ca.sapon.jici.SourceMetadata;
import ca.sapon.jici.decoder.Decoder;
import ca.sapon.jici.evaluator.Environment;
import ca.sapon.jici.evaluator.type.LiteralReferenceType;
import ca.sapon.jici.evaluator.type.LiteralType;
import ca.sapon.jici.evaluator.type.ParametrizedType;
import ca.sapon.jici.evaluator.type.ReferenceType;
import ca.sapon.jici.evaluator.type.SingleReferenceType;
import ca.sapon.jici.evaluator.type.TypeArgument;
import ca.sapon.jici.evaluator.type.WildcardType;
import ca.sapon.jici.lexer.Lexer;
import ca.sapon.jici.lexer.Token;
import ca.sapon.jici.parser.Parser;
import ca.sapon.jici.parser.expression.Expression;
import ca.sapon.jici.test.GenericsTest.Outer.Inner;
import ca.sapon.jici.test.GenericsTest.Outer.Normal;
import ca.sapon.jici.test.GenericsTest.Outer.Ref;
import ca.sapon.jici.util.IntegerCounter;
import ca.sapon.jici.util.TypeUtil;
public class GenericsTest {
@Test
public void testWildcards() {
// Subtype assignable to upper-bound
assertAssignSucceeds(
"List<String>",
"List<? extends CharSequence>"
);
assertLUB(
"java.util.List<? extends java.lang.CharSequence>",
"List<String>",
"List<? extends CharSequence>"
);
assertAssignFails(
"List<CharSequence>",
"List<? extends String>"
);
// Super type assignable to lower-bound
assertAssignSucceeds(
"List<CharSequence>",
"List<? super String>"
);
assertLUB(
"java.util.List<? super java.lang.String>",
"List<CharSequence>",
"List<? super String>"
);
assertAssignFails(
"List<String>",
"List<? super CharSequence>"
);
// Unbounded assignable to unbounded
assertAssignSucceeds(
"List<?>",
"List<?>"
);
assertLUB(
"java.util.List<?>",
"List<?>",
"List<?>"
);
// Upper-bounded assignable to higher upper-bounded
assertAssignSucceeds(
"List<? extends String>",
"List<? extends CharSequence>"
);
assertLUB(
"java.util.List<? extends java.lang.CharSequence>",
"List<? extends String>",
"List<? extends CharSequence>"
);
assertAssignFails(
"List<? extends CharSequence>",
"List<? extends String>"
);
// Lower-bounded assignable to lower lower-bounded
assertAssignSucceeds(
"List<? super CharSequence>",
"List<? super String>"
);
assertLUB(
"java.util.List<? super java.lang.String>",
"List<? super CharSequence>",
"List<? super String>"
);
assertAssignFails(
"List<? super String>",
"List<? super CharSequence>"
);
// Similar as a above but with bounded and unbounded
assertAssignSucceeds(
"List<? extends String>",
"List<?>"
);
assertLUB(
"java.util.List<?>",
"List<? extends String>",
"List<?>"
);
assertAssignSucceeds(
"List<? super String>",
"List<?>"
);
assertLUB(
"java.util.List<?>",
"List<? super String>",
"List<?>"
);
assertAssignFails(
"List<?>",
"List<? extends String>"
);
assertAssignFails(
"List<?>",
"List<? super String>"
);
}
@Test
public void testParametrizedConversions() {
final Environment environment = new Environment();
environment.importClass(M.class);
environment.importClass(L.class);
environment.importClass(K.class);
EvaluatorTest.assertSucceeds(
"M<String> m; L<Integer> l = null; m = l;",
environment
);
EvaluatorTest.assertFails(
"M<M<? extends CharSequence>> l1; M<M<? extends String>> l2 = null; l1 = l2;",
environment
);
EvaluatorTest.assertSucceeds(
"M<? extends M<? extends CharSequence>> l3; M<M<? extends String>> l4 = null; l3 = l4;",
environment
);
EvaluatorTest.assertFails(
"M<String> n; K k = null; n = k;",
environment
);
EvaluatorTest.assertSucceeds(
"M i; M<String> j = null; i = j;",
environment
);
EvaluatorTest.assertSucceeds(
"M<String> a; M b = null; a = b;",
environment
);
}
@Test
public void testCasts() {
final Environment environment = new Environment();
environment.importClass(I.class);
environment.importClass(J.class);
environment.importClass(X.class);
environment.importClass(N.class);
environment.importClass(M.class);
EvaluatorTest.assertSucceeds(
"J<String> i1 = null; Object o1 = (I<String>) i1;",
environment
);
EvaluatorTest.assertFails(
"N<Integer> i2 = null; Object o2 = (N<String>) i2;",
environment
);
EvaluatorTest.assertSucceeds(
"J<String> i3 = null; Object o3 = (X) i3;",
environment
);
EvaluatorTest.assertFails(
"J<Integer> i4 = null; Object o4 = (X) i4;",
environment
);
EvaluatorTest.assertSucceeds(
"M<? extends CharSequence> i5 = null; Object o5 = (M<? extends String>) i5;",
environment
);
EvaluatorTest.assertFails(
"M<CharSequence> i6 = null; Object o6 = (M<Number>) i6;",
environment
);
EvaluatorTest.assertFails(
"M<? extends CharSequence> i7 = null; Object o7 = (M<Number>) i7;",
environment
);
EvaluatorTest.assertFails(
"M<CharSequence> i8 = null; Object o8 = (M<? extends Number>) i8;",
environment
);
EvaluatorTest.assertFails(
"M<? extends CharSequence> i9 = null; Object o9 = (M<? extends Number>) i9;",
environment
);
}
@Test
public void testTypeArgumentSubstitution() {
Assert.assertEquals(
Collections.singleton(
ParametrizedType.of(M.class,
Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING)
)
),
ParametrizedType.of(N.class,
Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING))
.getDirectSuperTypes()
);
Assert.assertEquals(
Collections.singleton(
ParametrizedType.of(M.class,
Collections.<TypeArgument>singletonList(ParametrizedType.of(M.class,
Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING)
))
)
),
ParametrizedType.of(Q.class,
Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING))
.getDirectSuperTypes()
);
}
@Test
public void testCaptureConversion() {
ParametrizedType type;
// Y<? extends Serializable, ? extends Comparable>
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Serializable.class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Comparable.class)))
));
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.Y<CAP#2 extends (CAP#1 extends java.lang.Comparable & java.io.Serializable), CAP#1 extends java.lang.Comparable>",
type.capture(new IntegerCounter()).getName()
);
// Y<? extends String, Serializable>
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(String.class))),
LiteralReferenceType.of(Serializable.class)
));
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.Y<CAP#1 extends java.lang.String, java.io.Serializable>",
type.capture(new IntegerCounter()).getName()
);
// Y<? extends Integer, ? extends String>
try {
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Integer.class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(String.class)))
));
type.capture(new IntegerCounter());
Assert.fail("Expected type error");
} catch (UnsupportedOperationException ignored) {
}
// Y<? extends Integer, ? extends Serializable>
try {
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Integer.class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Serializable.class)))
));
type.capture(new IntegerCounter());
Assert.fail("Expected type error");
} catch (UnsupportedOperationException ignored) {
}
// Y<? extends Integer, ? extends TypeArgument>
try {
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Integer.class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(TypeArgument.class)))
));
type.capture(new IntegerCounter());
Assert.fail("Expected type error");
} catch (UnsupportedOperationException ignored) {
}
// Y<? extends Integer[], ? extends Number[]>
try {
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Integer[].class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(Number[].class)))
));
type.capture(new IntegerCounter());
Assert.fail("Expected type error");
} catch (UnsupportedOperationException ignored) {
}
// Y<? extends float[], ? extends int[]>
try {
type = ParametrizedType.of(LiteralReferenceType.of(Y.class), Arrays.<TypeArgument>asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(float[].class))),
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>singleton(LiteralReferenceType.of(int[].class)))
));
type.capture(new IntegerCounter());
Assert.fail("Expected type error");
} catch (UnsupportedOperationException ignored) {
}
// W<?, String>
type = ParametrizedType.of(LiteralReferenceType.of(W.class), Arrays.asList(
WildcardType.of(Collections.<SingleReferenceType>emptySet(), Collections.<SingleReferenceType>emptySet()),
LiteralReferenceType.THE_STRING
));
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.W<CAP#1 extends java.util.List<java.lang.String>, java.lang.String>",
type.capture(new IntegerCounter()).getName()
);
}
@Test
public void testSuperTypes() {
// Parametrized of L
final Set<LiteralReferenceType> superTypes1 = TypeUtil.getSuperTypes(ParametrizedType.of(L.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_CLONEABLE)));
Assert.assertEquals(new HashSet<>(Arrays.asList(
ParametrizedType.of(L.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_CLONEABLE)),
ParametrizedType.of(N.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING)),
ParametrizedType.of(M.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.THE_STRING)),
LiteralReferenceType.THE_OBJECT)
), superTypes1);
// Raw of L
final Set<LiteralReferenceType> superTypes2 = TypeUtil.getSuperTypes(LiteralReferenceType.of(L.class));
Assert.assertEquals(new HashSet<>(Arrays.asList(
LiteralReferenceType.of(L.class),
LiteralReferenceType.of(N.class),
LiteralReferenceType.of(M.class),
LiteralReferenceType.THE_OBJECT)
), superTypes2);
}
@Test
public void testGenericNestedTypes() {
final Environment environment = new Environment();
environment.importClass(Map.class);
environment.importClass(Map.Entry.class);
environment.importClass(Outer.class);
environment.importClass(Outer.Inner.class);
environment.importClass(Outer.Normal.class);
environment.importClass(Outer.Ref.class);
environment.importClass(Z.class);
EvaluatorTest.assertFails(
"Outer<String>.Inner f;",
environment
);
EvaluatorTest.assertFails(
"Outer.Inner<Integer> g;",
environment
);
EvaluatorTest.assertFails(
"Inner<Integer> h;",
environment
);
EvaluatorTest.assertFails(
"Map<String, Integer>.Entry<String, Integer> e;",
environment
);
EvaluatorTest.assertFails(
"Outer<CharSequence>.Ref<Integer> j;",
environment
);
final ParametrizedType type0 = ParametrizedType.of(
ParametrizedType.of(Outer.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.of(CharSequence.class))),
LiteralReferenceType.of(Ref.class),
Collections.<TypeArgument>singletonList(LiteralReferenceType.of(String.class))
);
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.Outer<java.lang.CharSequence>.Ref<java.lang.String>",
type0.capture(new IntegerCounter()).getName()
);
Assert.assertTrue(type0.convertibleTo(ParametrizedType.of(
LiteralReferenceType.of(I.class),
Collections.<TypeArgument>singletonList(LiteralReferenceType.of(CharSequence.class)))
));
final LiteralType type1 = Parser.parseTypeName(Lexer.lex("Outer<String>.Inner<Integer>")).getType(environment);
Assert.assertEquals(ParametrizedType.of(
ParametrizedType.of(Outer.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.of(String.class))),
Inner.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.of(Integer.class))
), type1);
final LiteralType type2 = Parser.parseTypeName(Lexer.lex("Outer.Inner")).getType(environment);
Assert.assertEquals(LiteralReferenceType.of(Inner.class), type2);
final LiteralType type3 = Parser.parseTypeName(Lexer.lex("Map.Entry<String, Integer>")).getType(environment);
Assert.assertEquals(ParametrizedType.of(
Map.Entry.class, Arrays.<TypeArgument>asList(LiteralReferenceType.of(String.class), LiteralReferenceType.of(Integer.class))
), type3);
final LiteralType type4 = Parser.parseTypeName(Lexer.lex("Outer.Normal")).getType(environment);
Assert.assertEquals(LiteralReferenceType.of(Normal.class), type4);
final LiteralType type5 = Parser.parseTypeName(Lexer.lex("Outer<String>.Normal")).getType(environment);
Assert.assertEquals(ParametrizedType.of(
ParametrizedType.of(Outer.class, Collections.<TypeArgument>singletonList(LiteralReferenceType.of(String.class))),
Normal.class, Collections.<TypeArgument>emptyList()
), type5);
final ParametrizedType type6 = (ParametrizedType) Parser.parseTypeName(Lexer.lex("Outer<? extends String>.Inner<? extends Integer>")).getType(environment);
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.Outer<CAP#1 extends java.lang.String>" +
".Inner<CAP#2 extends java.lang.Integer>",
type6.capture(new IntegerCounter()).getName()
);
final ParametrizedType type7 = (ParametrizedType) Parser.parseTypeName(Lexer.lex("Outer<? extends Comparable<?>>.Ref<? extends java.io.Serializable>")).getType(environment);
Assert.assertEquals("ca.sapon.jici.test.GenericsTest.Outer<CAP#1 extends java.lang.Comparable<?>>" +
".Ref<CAP#2 extends (CAP#1 extends java.lang.Comparable<?> & java.io.Serializable)>",
type7.capture(new IntegerCounter()).getName()
);
final ParametrizedType type8 = (ParametrizedType) Parser.parseTypeName(Lexer.lex("Z<?, String, Integer>")).getType(environment);
Assert.assertEquals(
"ca.sapon.jici.test.GenericsTest.Z<CAP#1 extends ca.sapon.jici.test.GenericsTest.Outer<" +
"java.lang.String>.Inner<java.lang.Integer>, java.lang.String, java.lang.Integer>",
type8.capture(new IntegerCounter()).getName()
);
}
@Test
public void testErasure() {
final Environment environment = new Environment();
environment.importClass(Outer.class);
environment.importClass(Outer.Inner.class);
environment.importClass(Outer.Normal.class);
final ReferenceType type1 = ((ReferenceType) Parser.parseTypeName(Lexer.lex("Outer")).getType(environment)).getErasure();
Assert.assertEquals(LiteralReferenceType.of(Outer.class), type1);
final ReferenceType type2 = ((ReferenceType) Parser.parseTypeName(Lexer.lex("Outer<String>")).getType(environment)).getErasure();
Assert.assertEquals(LiteralReferenceType.of(Outer.class), type2);
final ReferenceType type3 = ((ReferenceType) Parser.parseTypeName(Lexer.lex("Outer<String>.Inner<Integer>")).getType(environment)).getErasure();
Assert.assertEquals(LiteralReferenceType.of(Inner.class), type3);
final ReferenceType type4 = ((ReferenceType) Parser.parseTypeName(Lexer.lex("Outer<String>.Normal")).getType(environment)).getErasure();
Assert.assertEquals(LiteralReferenceType.of(Normal.class), type4);
}
@Test
public void testConstructors() {
final Environment environment = new Environment();
environment.importClass(M.class);
environment.importClass(N.class);
environment.importClass(K.class);
environment.importClass(Outer.class);
environment.importClass(Inner.class);
environment.importClass(U.class);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.M<java.lang.String>",
"new M<String>()"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.N<java.lang.Integer>",
"new N<Integer>()"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.M<ca.sapon.jici.test.GenericsTest.N<?>>",
"new M<N<?>>()"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.U<java.lang.String>",
"new U<String>(\"Me too thanks\")"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.U<java.lang.String>",
"new U<String>(\"1\", \"2\", \"3\")"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.U<java.lang.String>",
"new U<String>(new String[1])"
);
assertType(
environment,
"ca.sapon.jici.test.GenericsTest.U<java.lang.String>",
"new U<String>()"
);
EvaluatorTest.assertFails(
"new U<String>(2);",
environment
);
EvaluatorTest.assertFails(
"new M<?>();",
environment
);
EvaluatorTest.assertFails(
"new M<? extends String>();",
environment
);
/*assertType(
environment,
"ca.sapon.jici.test.GenericsTest.Outer<java.lang.Integer>.Inner<java.lang.String>",
"new Outer<Integer>().newStringInner()"
);*/
/*assertType(
environment,
"ca.sapon.jici.test.GenericsTest.Outer<java.lang.Integer>.Inner<java.lang.Float>",
"new Outer<Integer>().<Float>newInner()"
);*/
}
@Test
public void testFields() {
final Environment environment = new Environment();
environment.importClass(M.class);
environment.importClass(N.class);
environment.importClass(K.class);
environment.importClass(Outer.class);
environment.importClass(Inner.class);
assertType(
environment,
"java.lang.Integer",
"new M<String>().m"
);
assertType(
environment,
"java.lang.Double",
"new N<String>().o"
);
assertType(
environment,
"java.lang.Float",
"new K().p"
);
assertType(
environment,
"java.lang.String",
"new M<String>().t"
);
assertType(
environment,
"java.lang.Float",
"new N<Float>().t"
);
assertType(
environment,
"java.lang.Integer",
"new K().t"
);
assertType(
environment,
"CAP#1 extends java.lang.String",
"M.newWildcardM().t"
);
/*assertType(
environment,
"java.lang.String",
"new Outer<Integer>().newStringInner().t"
);*/
/*assertType(
environment,
"java.lang.Integer",
"new Outer<Integer>().<Float>newInner().t"
);*/
}
@Test
public void testMethods() {
final Environment environment = new Environment();
environment.importClass(M.class);
environment.importClass(N.class);
environment.importClass(K.class);
environment.importClass(Outer.class);
environment.importClass(Inner.class);
assertType(
environment,
"java.lang.String",
"new M<String>().getT()"
);
assertType(
environment,
"java.lang.Integer",
"new K().getT()"
);
assertType(
environment,
"java.lang.Short",
"new M<String>().getS()"
);
assertType(
environment,
"CAP#1 extends java.lang.String",
"M.newWildcardM().getT()"
);
/*assertType(
environment,
"java.lang.String",
"new Outer<Integer>().newStringInner().getT()"
);*/
/*assertType(
environment,
"java.lang.Integer",
"new Outer<Integer>().<Float>newInner().getT()"
);*/
EvaluatorTest.assertFails(
"new M<String>().setT();",
environment
);
EvaluatorTest.assertFails(
"new M<String>().setT(new Integer(1));",
environment
);
EvaluatorTest.assertSucceeds(
"new M<String>().setT(\"1\");",
environment
);
EvaluatorTest.assertSucceeds(
"new M<N<String>>().setT(new N());",
environment
);
EvaluatorTest.assertSucceeds(
"new M<String>().setTs(\"1\", \"2\", \"3\");",
environment
);
EvaluatorTest.assertSucceeds(
"new M<String>().setTs(new String[1]);",
environment
);
EvaluatorTest.assertFails(
"new M<String>().setTs(1, 2);",
environment
);
EvaluatorTest.assertSucceeds(
"new M<String>().setTs();",
environment
);
EvaluatorTest.assertSucceeds(
"new M<CharSequence>().setT(\"1\");",
environment
);
EvaluatorTest.assertSucceeds(
"new K().setT(new Integer(1));",
environment
);
EvaluatorTest.assertFails(
"new K().setT(\"1\");",
environment
);
assertType(
environment,
"java.lang.Integer[]",
"new M<Integer>().getTs()"
);
assertType(
environment,
"java.lang.Integer[][]",
"new M<Integer>().getTts()"
);
assertType(
environment,
"CAP#1[] extends java.lang.String[]",
"M.newWildcardM().getTs()"
);
assertType(
environment,
"CAP#1[][] extends java.lang.String[][]",
"M.newWildcardM().getTts()"
);
}
public static class M<T> {
public static Short s = null;
public T t = null;
public Integer m = null;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
@SafeVarargs
public final void setTs(T... t) {
}
public T[] getTs() {
return null;
}
public T[][] getTts() {
return null;
}
public static Short getS() {
return s;
}
public static M<? extends String> newWildcardM() {
return new M<>();
}
}
public static class N<T> extends M<T> {
public Double o = null;
}
public static class L<T> extends N<String> {
}
public static class K extends N<Integer> {
public Float p = null;
}
public class Q<T> extends M<M<T>> {
}
interface I<A> {
}
public static class J<A> implements I<A> {
}
public static final class X implements I<String> {
}
public static class Y<T extends S, S> {
}
public static class W<T extends List<S>, S> {
}
public static class Outer<T> {
public class Inner<S> {
public T t = null;
public T getT() {
return t;
}
}
public class Normal {
}
public class Ref<R extends T> implements I<T> {
}
public <S> Inner<S> newInner() {
return new Inner<>();
}
public Inner<String> newStringInner() {
return new Inner<>();
}
}
public class Z<T extends Outer<S>.Inner<R>, S, R> {
}
public class U<T> {
public T t;
public U(T t) {
this.t = t;
}
@SafeVarargs
public U(T... t) {
this.t = null;
}
}
private static Environment assertSucceeds(String source) {
final Environment environment = new Environment();
return EvaluatorTest.assertSucceeds(source, environment);
}
private static Environment assertFails(String source) {
final Environment environment = new Environment();
return EvaluatorTest.assertFails(source, environment);
}
private static void assertAssignSucceeds(String leftType, String rightType) {
assertSucceeds(generateDeclarationSource(leftType, rightType) + "l2 = l1;");
}
private static void assertAssignFails(String leftType, String rightType) {
assertFails(generateDeclarationSource(leftType, rightType) + "l2 = l1;");
}
private static void assertLUB(String expectedType, String leftType, String rightType) {
final Environment environment = assertSucceeds(generateDeclarationSource(leftType, rightType));
String source = "true ? l1 : l2";
assertType(environment, expectedType, source);
}
private static void assertType(Environment environment, String expectedType, String source) {
final SourceMetadata metadata = new SourceMetadata(source);
try {
source = Decoder.decode(source, metadata);
final List<Token> tokens = Lexer.lex(source);
final Expression expression = Parser.parseExpression(tokens);
Assert.assertEquals(expectedType, expression.getType(environment).toString());
} catch (Exception exception) {
if (exception instanceof SourceException) {
System.out.println(metadata.generateErrorInformation((SourceException) exception));
}
throw new AssertionError(exception);
}
}
private static String generateDeclarationSource(String leftType, String rightType) {
return "import java.util.List;"
+ leftType + " l1 = null;"
+ rightType + " l2;";
}
}
|
package ch.bind.philib.util;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
public class LruListTest {
@Test
public void removeTailOnOverflow() {
TestNode a = new TestNode(), b = new TestNode(), c = new TestNode();
LruList<TestNode> lru = new LruList<TestNode>(2);
assertNull(lru.add(a));
assertNull(lru.add(b));
assertEquals(lru.add(c), a);
}
@Test
public void moveToHead() {
TestNode a = new TestNode(), b = new TestNode(), c = new TestNode();
LruList<TestNode> lru = new LruList<TestNode>(2);
assertNull(lru.add(a));
assertNull(lru.add(b));
lru.moveToHead(a);
assertEquals(lru.add(c), b);
lru.moveToHead(c);
assertEquals(lru.add(b), a);
}
@Test
public void clear() {
TestNode a = new TestNode(), b = new TestNode();
LruList<TestNode> lru = new LruList<TestNode>(2);
assertNull(lru.add(a));
assertNull(lru.add(b));
assertEquals(lru.size(), 2);
lru.clear();
assertEquals(lru.size(), 0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void ctorValidation() {
new LruList<TestNode>(0);
}
@Test
public void removeTail() {
TestNode a = new TestNode(), b = new TestNode(), c = new TestNode();
LruList<TestNode> lru = new LruList<TestNode>(3);
lru.add(a); // lru: a
lru.add(b); // lru: b, a
lru.add(c); // lru: c, b, a
assertEquals(lru.removeTail(), a); // lru: c, b
assertEquals(lru.size(), 2);
lru.moveToHead(b);// lru: b, c
assertEquals(lru.removeTail(), c); // lru: b
assertEquals(lru.size(), 1);
assertEquals(lru.removeTail(), b);
assertEquals(lru.size(), 0);
assertNull(lru.removeTail());
}
@Test
public void fullScenario() {
TestNode a = new TestNode(), b = new TestNode(), c = new TestNode();
LruList<TestNode> lru = new LruList<TestNode>(3);
assertEquals(lru.capacity(), 3);
lru.add(a); // lru: a
assertEquals(lru.size(), 1);
lru.add(b); // lru: b, a
assertEquals(lru.size(), 2);
lru.add(c); // lru: c, b, a
assertEquals(lru.size(), 3);
lru.moveToHead(a); // lru: a, c, b
lru.moveToHead(b); // lru: b, a, c
lru.moveToHead(c); // lru: c, a, b
lru.moveToHead(b); // lru: b, a, c
lru.moveToHead(a); // lru: a, b, c
assertEquals(lru.size(), 3);
// remove from the middle
lru.remove(b); // lru: a, c
assertEquals(lru.size(), 2);
lru.add(b); // lru: b, a, c
assertEquals(lru.size(), 3);
lru.moveToHead(a); // lru: a, b, c
// remove from the tail
lru.remove(c); // lru: a, b
assertEquals(lru.size(), 2);
lru.add(c); // lru: c, a, b
assertEquals(lru.size(), 3);
lru.moveToHead(b); // lru: b, a, c
lru.moveToHead(a); // lru: a, b, c
// remove from head
lru.remove(a); // lru: b, c
assertEquals(lru.size(), 2);
lru.remove(b); // lru: c
assertEquals(lru.size(), 1);
lru.remove(c);
assertEquals(lru.size(), 0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void nonNullAdd() {
LruList<TestNode> lru = new LruList<TestNode>(1);
lru.add(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void nonNullRemove() {
LruList<TestNode> lru = new LruList<TestNode>(1);
lru.remove(null);
}
@Test
public void addAsserts() {
LruList<TestNode> lru = new LruList<TestNode>(8);
TestNode node = new TestNode();
TestNode bad = new TestNode();
node.setLruNext(bad);
try {
lru.add(node);
fail();
} catch (AssertionError e) {
// expected
}
node.setLruNext(null);
node.setLruPrev(bad);
try {
lru.add(node);
fail();
} catch (AssertionError e) {
// expected
}
node.setLruPrev(null);
}
@Test
public void removeAsserts() {
LruList<TestNode> lru = new LruList<TestNode>(8);
TestNode node = new TestNode();
TestNode bad = new TestNode();
node.setLruNext(bad);
try {
lru.remove(node);
fail();
} catch (AssertionError e) {
// expected
}
node.setLruNext(null);
node.setLruPrev(bad);
try {
lru.remove(node);
fail();
} catch (AssertionError e) {
// expected
}
node.setLruPrev(null);
}
private static final class TestNode implements LruNode {
private LruNode next;
private LruNode prev;
@Override
public void setLruNext(LruNode next) {
this.next = next;
}
@Override
public void setLruPrev(LruNode prev) {
this.prev = prev;
}
@Override
public LruNode getLruNext() {
return next;
}
@Override
public LruNode getLruPrev() {
return prev;
}
@Override
public void resetLruNode() {
next = null;
prev = null;
}
}
}
|
package gluu.scim2.client;
import gluu.BaseScimTest;
import gluu.scim2.client.factory.ScimClientFactory;
import org.gluu.oxtrust.model.scim2.Constants;
import org.gluu.oxtrust.model.scim2.ListResponse;
import org.gluu.oxtrust.model.scim2.Name;
import org.gluu.oxtrust.model.scim2.User;
import org.jboss.resteasy.client.core.BaseClientResponse;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
public class TestModeTests extends BaseScimTest {
ScimClient client;
@Parameters({ "domainURL", "OIDCMetadataUrl" })
@BeforeTest
public void init(String domainURL, String OIDCMetadataUrl){
try {
System.out.println("Testing the test mode of SCIM-client with params: " + Arrays.asList(domainURL, OIDCMetadataUrl).toString());
client = ScimClientFactory.getTestClient(domainURL, OIDCMetadataUrl);
}
catch (Exception e){
e.printStackTrace();
}
}
//@Test
public void retrieveAllUsers() throws IOException {
BaseClientResponse<ListResponse> response = client.retrieveAllUsers();
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Could not get a list of all users, status != 200");
}
//@Test
public void retrieveAllGroups() throws IOException {
BaseClientResponse<ListResponse> response = client.retrieveAllGroups();
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Could not get a list of all groups, status != 200");
}
@Test
public void nullMiddleNameUser() throws Exception{
User user = createDummyUser();
String newUsrId=user.getId();
//Retrieve user
BaseClientResponse<User>response = client.retrievePerson(newUsrId, MediaType.APPLICATION_JSON);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
User userRetrieved = response.getEntity();
//... and check it has correct middle name
assertEquals(userRetrieved.getId(), newUsrId);
assertEquals(userRetrieved.getName().getMiddleName(), user.getName().getMiddleName());
//Check if setting to empty string or null is really flushing the middle name attr
userRetrieved.getName().setMiddleName("");
response=client.updateUser(userRetrieved, newUsrId, new String[]{});
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
userRetrieved = response.getEntity();
assertNull(userRetrieved.getName().getMiddleName());
//Check if setting the null attribute to non-empty takes effect
String newMiddleName=UUID.randomUUID().toString();
userRetrieved.getName().setMiddleName(newMiddleName);
response=client.updateUser(userRetrieved, newUsrId, new String[]{});
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
userRetrieved = response.getEntity();
assertEquals(userRetrieved.getName().getMiddleName(), newMiddleName);
deleteDummyUser(newUsrId);
}
@Test
public void PPIDSearch() throws Exception{
//Create a dummy user
User user = createDummyUser();
String newUsrId=user.getId();
//Set it with two random ppids
List<String> ppids=Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString());
user.setPairwiseIdentitifers(ppids);
//Update him
BaseClientResponse<User> response=client.updateUser(user, newUsrId, new String[]{});
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
//Search for one ppid
String filter=String.format("oxPPID eq \"%s\"", ppids.get(0));
BaseClientResponse<ListResponse> list = client.searchUsers(filter, 0, Constants.MAX_COUNT, null, null, null);
assertEquals(Response.Status.OK.getStatusCode(), list.getStatus());
assertEquals(list.getEntity().getTotalResults(),1);
deleteDummyUser(newUsrId);
}
private void deleteDummyUser(String id) throws Exception{
//Delete dummy
BaseClientResponse<User>response=client.deletePerson(id);
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
private User createDummyUser() throws Exception{
User user=new User();
Name name = new Name();
name.setGivenName("Jose");
name.setMiddleName("Graupera");
name.setFamilyName("Capablanca");
user.setName(name);
user.setDisplayName("Dummy");
user.setUserName("j"+ new Date().getTime());
user.setActive(true);
//Create a dummy user for testing
BaseClientResponse<User> response = client.createPerson(user, MediaType.APPLICATION_JSON);
assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), "Fail to add user " + user.getDisplayName());
return response.getEntity();
}
}
|
package info.u_team.u_team_test;
import info.u_team.u_team_core.util.registry.BusRegister;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import info.u_team.u_team_test.init.*;
import net.minecraftforge.fml.common.Mod;
@Mod(TestMod.MODID)
public class TestMod {
public static final String MODID = "uteamtest";
public TestMod() {
JarSignVerifier.checkSigned(MODID);
System.out.println("
register();
}
private void register() {
BusRegister.registerMod(TestBiomes::register);
BusRegister.registerMod(TestContainers::register);
BusRegister.registerMod(TestEffects::register);
}
}
|
package org.threeten.extra;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MONTHS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.tngtech.junit.dataprovider.DataProvider;
import com.tngtech.junit.dataprovider.UseDataProvider;
/**
* Test class.
*/
public class TestInterval {
static Instant NOW1 = ZonedDateTime.of(2014, 12, 1, 1, 0, 0, 0, ZoneOffset.UTC).toInstant();
static Instant NOW2 = NOW1.plusSeconds(60);
static Instant NOW3 = NOW2.plusSeconds(60);
static Instant NOW4 = NOW3.plusSeconds(60);
static Instant NOW11 = NOW1.plusSeconds(11);
static Instant NOW12 = NOW1.plusSeconds(12);
static Instant NOW13 = NOW1.plusSeconds(13);
static Instant NOW14 = NOW1.plusSeconds(14);
static Instant NOW15 = NOW1.plusSeconds(15);
static Instant NOW16 = NOW1.plusSeconds(16);
@Test
public void test_isSerializable() {
assertTrue(Serializable.class.isAssignableFrom(Interval.class));
}
@Test
public void test_serialization() throws Exception {
Interval test = Interval.of(Instant.EPOCH, NOW1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(test);
}
try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
assertEquals(test, ois.readObject());
}
}
@Test
public void test_ALL() {
Interval test = Interval.ALL;
assertEquals(Instant.MIN, test.getStart());
assertEquals(Instant.MAX, test.getEnd());
assertEquals(false, test.isEmpty());
assertEquals(true, test.isUnboundedStart());
assertEquals(true, test.isUnboundedEnd());
}
@Test
public void test_of_Instant_Instant() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(NOW1, test.getStart());
assertEquals(NOW2, test.getEnd());
assertEquals(false, test.isEmpty());
assertEquals(false, test.isUnboundedStart());
assertEquals(false, test.isUnboundedEnd());
}
@Test
public void test_of_Instant_Instant_empty() {
Interval test = Interval.of(NOW1, NOW1);
assertEquals(NOW1, test.getStart());
assertEquals(NOW1, test.getEnd());
assertEquals(true, test.isEmpty());
assertEquals(false, test.isUnboundedStart());
assertEquals(false, test.isUnboundedEnd());
}
@Test
public void test_of_Instant_Instant_badOrder() {
assertThrows(DateTimeException.class, () -> Interval.of(NOW2, NOW1));
}
@Test
public void test_of_Instant_Instant_nullStart() {
assertThrows(NullPointerException.class, () -> Interval.of(null, NOW2));
}
@Test
public void test_of_Instant_Instant_nullEnd() {
assertThrows(NullPointerException.class, () -> Interval.of(NOW1, (Instant) null));
}
@Test
public void test_of_Instant_Duration() {
Interval test = Interval.of(NOW1, Duration.ofSeconds(60));
assertEquals(NOW1, test.getStart());
assertEquals(NOW2, test.getEnd());
}
@Test
public void test_of_Instant_Duration_zero() {
Interval test = Interval.of(NOW1, Duration.ZERO);
assertEquals(NOW1, test.getStart());
assertEquals(NOW1, test.getEnd());
}
@Test
public void test_of_Instant_Duration_negative() {
assertThrows(DateTimeException.class, () -> Interval.of(NOW2, Duration.ofSeconds(-1)));
}
@Test
public void test_of_Instant_Duration_nullInstant() {
assertThrows(NullPointerException.class, () -> Interval.of(null, Duration.ZERO));
}
@Test
public void test_of_Instant_Duration_nullDuration() {
assertThrows(NullPointerException.class, () -> Interval.of(NOW1, (Duration) null));
}
@Test
public void test_startingAt_Instant_createsUnboundedEnd() {
Interval interval = Interval.startingAt(NOW1);
assertEquals(NOW1, interval.getStart());
assertTrue(interval.isUnboundedEnd());
assertFalse(interval.isEmpty());
}
@Test
public void test_startingAt_InstantMAX_createsUnboundedEndEmpty() {
Interval interval = Interval.startingAt(Instant.MAX);
assertEquals(Instant.MAX, interval.getStart());
assertTrue(interval.isUnboundedEnd());
assertTrue(interval.isEmpty());
}
@Test
public void test_startingAt_InstantMIN_isALL() {
Interval interval = Interval.startingAt(Instant.MIN);
assertEquals(Interval.ALL, interval);
}
@Test
public void test_startingAt_null() {
assertThrows(NullPointerException.class, () -> Interval.startingAt(null));
}
@Test
public void test_endingAt_createsUnboundedStart() {
Interval interval = Interval.endingAt(NOW1);
assertEquals(NOW1, interval.getEnd());
assertTrue(interval.isUnboundedStart());
assertFalse(interval.isEmpty());
}
@Test
public void test_sendingAt_InstantMIN_createsUnboundedStartEmpty() {
Interval interval = Interval.endingAt(Instant.MIN);
assertEquals(Instant.MIN, interval.getEnd());
assertTrue(interval.isUnboundedStart());
assertTrue(interval.isEmpty());
}
@Test
public void test_endingAt_InstantMAX_isALL() {
Interval interval = Interval.endingAt(Instant.MAX);
assertEquals(Interval.ALL, interval);
}
@Test
public void test_endingAt_null() {
assertThrows(NullPointerException.class, () -> Interval.endingAt(null));
}
/* Lower and upper bound for Intervals */
private static final Instant MIN_OFFSET_DATE_TIME = OffsetDateTime.MIN.plusDays(1L).toInstant();
private static final Instant MAX_OFFSET_DATE_TIME = OffsetDateTime.MAX.minusDays(1L).toInstant();
@DataProvider
public static Object[][] data_parseValid() {
Instant minPlusOneDay = Instant.MIN.plus(Duration.ofDays(1));
Instant maxMinusOneDay = Instant.MAX.minus(Duration.ofDays(1));
return new Object[][] {
{NOW1 + "/" + NOW2, NOW1, NOW2},
{Duration.ofHours(6) + "/" + NOW2, NOW2.minus(6, HOURS), NOW2},
{"P6MT5H/" + NOW2, NOW2.atZone(ZoneOffset.UTC).minus(6, MONTHS).minus(5, HOURS).toInstant(), NOW2},
{"pt6h/" + NOW2, NOW2.minus(6, HOURS), NOW2},
{"pt6h/" + Instant.MAX, Instant.MAX.minus(6, HOURS), Instant.MAX},
{"pt6h/" + minPlusOneDay, minPlusOneDay.minus(6, HOURS), minPlusOneDay},
{NOW1 + "/" + Duration.ofHours(6), NOW1, NOW1.plus(6, HOURS)},
{NOW1 + "/pt6h", NOW1, NOW1.plus(6, HOURS)},
{Instant.MIN + "/pt6h", Instant.MIN, Instant.MIN.plus(6, HOURS)},
{maxMinusOneDay + "/Pt6h", maxMinusOneDay, maxMinusOneDay.plus(6, HOURS)},
{NOW1 + "/" + NOW1, NOW1, NOW1},
{NOW1.atOffset(ZoneOffset.ofHours(2)) + "/" + NOW2.atOffset(ZoneOffset.ofHours(2)), NOW1, NOW2},
{NOW1.atOffset(ZoneOffset.ofHours(2)) + "/" + NOW2.atOffset(ZoneOffset.ofHours(3)), NOW1, NOW2},
{NOW1.atOffset(ZoneOffset.ofHours(2)) + "/" + NOW2.atOffset(ZoneOffset.ofHours(2)).toLocalDateTime(), NOW1, NOW2},
{MIN_OFFSET_DATE_TIME.toString() + "/" + MAX_OFFSET_DATE_TIME, MIN_OFFSET_DATE_TIME, MAX_OFFSET_DATE_TIME},
{NOW1 + "/" + Instant.MAX, NOW1, Instant.MAX},
{Instant.MIN.toString() + "/" + NOW2, Instant.MIN, NOW2},
{Instant.MIN.toString() + "/" + Instant.MAX, Instant.MIN, Instant.MAX}
};
}
@ParameterizedTest
@UseDataProvider("data_parseValid")
public void test_parse_CharSequence(String input, Instant start, Instant end) {
Interval test = Interval.parse(input);
assertEquals(start, test.getStart());
assertEquals(end, test.getEnd());
}
@Test
public void test_parse_CharSequence_badOrder() {
assertThrows(DateTimeException.class, () -> Interval.parse(NOW2 + "/" + NOW1));
}
@Test
public void test_parse_CharSequence_badFormat() {
assertThrows(DateTimeParseException.class, () -> Interval.parse(NOW2 + "-" + NOW1));
}
@Test
public void test_parse_CharSequence_null() {
assertThrows(NullPointerException.class, () -> Interval.parse(null));
}
@Test
public void test_withStart() {
Interval base = Interval.of(NOW1, NOW3);
Interval test = base.withStart(NOW2);
assertEquals(NOW2, test.getStart());
assertEquals(NOW3, test.getEnd());
}
@Test
public void test_withStart_badOrder() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(DateTimeException.class, () -> base.withStart(NOW3));
}
@Test
public void test_withStart_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.withStart(null));
}
@Test
public void test_withEnd() {
Interval base = Interval.of(NOW1, NOW3);
Interval test = base.withEnd(NOW2);
assertEquals(NOW1, test.getStart());
assertEquals(NOW2, test.getEnd());
}
@Test
public void test_withEnd_badOrder() {
Interval base = Interval.of(NOW2, NOW3);
assertThrows(DateTimeException.class, () -> base.withEnd(NOW1));
}
@Test
public void test_withEnd_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.withEnd(null));
}
@Test
public void test_contains_Instant() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(false, test.contains(NOW1.minusSeconds(1)));
assertEquals(true, test.contains(NOW1));
assertEquals(true, test.contains(NOW1.plusSeconds(1)));
assertEquals(true, test.contains(NOW2.minusSeconds(1)));
assertEquals(false, test.contains(NOW2));
}
@Test
public void test_contains_Instant_baseEmpty() {
Interval test = Interval.of(NOW1, NOW1);
assertEquals(false, test.contains(NOW1.minusSeconds(1)));
assertEquals(false, test.contains(NOW1));
assertEquals(false, test.contains(NOW1.plusSeconds(1)));
}
@Test
public void test_contains_max() {
Interval test = Interval.of(NOW2, Instant.MAX);
assertEquals(false, test.contains(Instant.MIN));
assertEquals(false, test.contains(NOW1));
assertEquals(true, test.contains(NOW2));
assertEquals(true, test.contains(NOW3));
assertEquals(true, test.contains(Instant.MAX));
}
@Test
public void test_contains_Instant_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.contains((Instant) null));
}
@Test
public void test_encloses_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(true, test.encloses(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(true, test.encloses(Interval.of(NOW1, NOW2)));
assertEquals(true, test.encloses(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(false, test.encloses(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(false, test.encloses(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(false, test.encloses(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(false, test.encloses(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_encloses_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
// partly before
assertEquals(false, test.encloses(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(true, test.encloses(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(false, test.encloses(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(false, test.encloses(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_encloses_Interval_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.encloses((Interval) null));
}
@Test
public void test_abuts_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(false, test.abuts(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.abuts(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(false, test.abuts(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(false, test.abuts(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(false, test.abuts(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(false, test.abuts(Interval.of(NOW1, NOW2)));
assertEquals(false, test.abuts(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(false, test.abuts(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(false, test.abuts(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(true, test.abuts(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(false, test.abuts(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_abuts_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(false, test.abuts(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.abuts(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(false, test.abuts(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(true, test.abuts(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(false, test.abuts(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_abuts_Interval_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.abuts((Interval) null));
}
@Test
public void test_isConnected_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(false, test.isConnected(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.isConnected(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(true, test.isConnected(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(true, test.isConnected(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(true, test.isConnected(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(true, test.isConnected(Interval.of(NOW1, NOW2)));
assertEquals(true, test.isConnected(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(true, test.isConnected(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(true, test.isConnected(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(true, test.isConnected(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(false, test.isConnected(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_isConnected_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(false, test.isConnected(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.isConnected(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(true, test.isConnected(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(true, test.isConnected(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(false, test.isConnected(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_isConnected_Interval_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.isConnected((Interval) null));
}
@Test
public void test_overlaps_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(false, test.overlaps(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(false, test.overlaps(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(true, test.overlaps(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(true, test.overlaps(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(true, test.overlaps(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(true, test.overlaps(Interval.of(NOW1, NOW2)));
assertEquals(true, test.overlaps(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(true, test.overlaps(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(true, test.overlaps(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(false, test.overlaps(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(false, test.overlaps(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_overlaps_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(false, test.overlaps(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(false, test.overlaps(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(true, test.overlaps(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(false, test.overlaps(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(false, test.overlaps(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_overlaps_Interval_null() {
Interval base = Interval.of(NOW1, NOW2);
assertThrows(NullPointerException.class, () -> base.overlaps((Interval) null));
}
@DataProvider
public static Object[][] data_intersection() {
return new Object[][] {
// adjacent
{ NOW1, NOW2, NOW2, NOW4, NOW2, NOW2 },
// adjacent empty
{ NOW1, NOW4, NOW4, NOW4, NOW4, NOW4 },
// overlap
{ NOW1, NOW3, NOW2, NOW4, NOW2, NOW3 },
// encloses
{ NOW1, NOW4, NOW2, NOW3, NOW2, NOW3 },
// encloses empty
{ NOW1, NOW4, NOW2, NOW2, NOW2, NOW2 },
};
}
@ParameterizedTest
@UseDataProvider("data_intersection")
public void test_intersection(
Instant start1, Instant end1, Instant start2, Instant end2, Instant expStart, Instant expEnd) {
Interval test1 = Interval.of(start1, end1);
Interval test2 = Interval.of(start2, end2);
Interval expected = Interval.of(expStart, expEnd);
assertTrue(test1.isConnected(test2));
assertEquals(expected, test1.intersection(test2));
}
@ParameterizedTest
@UseDataProvider("data_intersection")
public void test_intersection_reverse(
Instant start1, Instant end1, Instant start2, Instant end2, Instant expStart, Instant expEnd) {
Interval test1 = Interval.of(start1, end1);
Interval test2 = Interval.of(start2, end2);
Interval expected = Interval.of(expStart, expEnd);
assertTrue(test2.isConnected(test1));
assertEquals(expected, test2.intersection(test1));
}
@Test
public void test_intersectionBad() {
Interval test1 = Interval.of(NOW1, NOW2);
Interval test2 = Interval.of(NOW3, NOW4);
assertEquals(false, test1.isConnected(test2));
assertThrows(DateTimeException.class, () -> test1.intersection(test2));
}
@Test
public void test_intersection_same() {
Interval test = Interval.of(NOW2, NOW4);
assertEquals(test, test.intersection(test));
}
@DataProvider
public static Object[][] data_union() {
return new Object[][] {
// adjacent
{ NOW1, NOW2, NOW2, NOW4, NOW1, NOW4 },
// adjacent empty
{ NOW1, NOW4, NOW4, NOW4, NOW1, NOW4 },
// overlap
{ NOW1, NOW3, NOW2, NOW4, NOW1, NOW4 },
// encloses
{ NOW1, NOW4, NOW2, NOW3, NOW1, NOW4 },
// encloses empty
{ NOW1, NOW4, NOW2, NOW2, NOW1, NOW4 },
};
}
@ParameterizedTest
@UseDataProvider("data_union")
public void test_unionAndSpan(
Instant start1, Instant end1, Instant start2, Instant end2, Instant expStart, Instant expEnd) {
Interval test1 = Interval.of(start1, end1);
Interval test2 = Interval.of(start2, end2);
Interval expected = Interval.of(expStart, expEnd);
assertTrue(test1.isConnected(test2));
assertEquals(expected, test1.union(test2));
assertEquals(expected, test1.span(test2));
}
@ParameterizedTest
@UseDataProvider("data_union")
public void test_unionAndSpan_reverse(
Instant start1, Instant end1, Instant start2, Instant end2, Instant expStart, Instant expEnd) {
Interval test1 = Interval.of(start1, end1);
Interval test2 = Interval.of(start2, end2);
Interval expected = Interval.of(expStart, expEnd);
assertTrue(test2.isConnected(test1));
assertEquals(expected, test2.union(test1));
assertEquals(expected, test2.span(test1));
}
@ParameterizedTest
@UseDataProvider("data_union")
public void test_span_enclosesInputs(
Instant start1, Instant end1, Instant start2, Instant end2, Instant expStart, Instant expEnd) {
Interval test1 = Interval.of(start1, end1);
Interval test2 = Interval.of(start2, end2);
Interval expected = Interval.of(expStart, expEnd);
assertEquals(true, expected.encloses(test1));
assertEquals(true, expected.encloses(test2));
}
@Test
public void test_union_disconnected() {
Interval test1 = Interval.of(NOW1, NOW2);
Interval test2 = Interval.of(NOW3, NOW4);
assertFalse(test1.isConnected(test2));
assertThrows(DateTimeException.class, () -> test1.union(test2));
}
@Test
public void test_span_disconnected() {
Interval test1 = Interval.of(NOW1, NOW2);
Interval test2 = Interval.of(NOW3, NOW4);
assertFalse(test1.isConnected(test2));
assertEquals(Interval.of(NOW1, NOW4), test1.span(test2));
}
@Test
public void test_unionAndSpan_same() {
Interval test = Interval.of(NOW2, NOW4);
assertEquals(test, test.union(test));
assertEquals(test, test.span(test));
}
public static Object[][] data_starts() {
return new Object[][] {
// normal
{Interval.of(NOW12, NOW14), NOW11, false, false, true, true},
{Interval.of(NOW12, NOW14), NOW12, false, true, false, true},
{Interval.of(NOW12, NOW14), NOW13, true, true, false, false},
{Interval.of(NOW12, NOW14), NOW14, true, true, false, false},
{Interval.of(NOW12, NOW14), NOW15, true, true, false, false},
// empty interval
{Interval.of(NOW12, NOW12), NOW11, false, false, true, true},
{Interval.of(NOW12, NOW12), NOW12, false, true, false, true},
{Interval.of(NOW12, NOW12), NOW13, true, true, false, false},
// unbounded start
{Interval.of(Instant.MIN, NOW12), Instant.MIN, false, true, false, true},
{Interval.of(Instant.MIN, NOW12), NOW11, true, true, false, false},
{Interval.of(Instant.MIN, NOW12), NOW12, true, true, false, false},
{Interval.of(Instant.MIN, NOW12), NOW13, true, true, false, false},
{Interval.of(Instant.MIN, NOW12), Instant.MAX, true, true, false, false},
// unbounded end
{Interval.of(NOW12, Instant.MAX), Instant.MIN, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), NOW11, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), NOW12, false, true, false, true},
{Interval.of(NOW12, Instant.MAX), NOW13, true, true, false, false},
{Interval.of(NOW12, Instant.MAX), Instant.MAX, true, true, false, false},
};
}
@ParameterizedTest
@MethodSource("data_starts")
public void test_starts_Instant(
Interval test,
Instant instant,
boolean expectedStartsBefore,
boolean expectedStartsAtOrBefore,
boolean expectedStartsAfter,
boolean expectedStartsAtOrAfter) {
assertEquals(expectedStartsBefore, test.startsBefore(instant));
assertEquals(expectedStartsAtOrBefore, test.startsAtOrBefore(instant));
assertEquals(expectedStartsAfter, test.startsAfter(instant));
assertEquals(expectedStartsAtOrAfter, test.startsAtOrAfter(instant));
}
@Test
public void test_starts_Instant_null() {
Interval base = Interval.of(NOW12, NOW14);
assertThrows(NullPointerException.class, () -> base.startsBefore((Instant) null));
assertThrows(NullPointerException.class, () -> base.startsAtOrBefore((Instant) null));
assertThrows(NullPointerException.class, () -> base.startsAfter((Instant) null));
assertThrows(NullPointerException.class, () -> base.startsAtOrAfter((Instant) null));
}
public static Object[][] data_ends() {
return new Object[][] {
// normal
{Interval.of(NOW12, NOW14), NOW11, false, false, true, true},
{Interval.of(NOW12, NOW14), NOW12, false, false, true, true},
{Interval.of(NOW12, NOW14), NOW13, false, false, true, true},
{Interval.of(NOW12, NOW14), NOW14, false, true, false, true},
{Interval.of(NOW12, NOW14), NOW15, true, true, false, false},
// empty interval
{Interval.of(NOW12, NOW12), NOW11, false, false, true, true},
{Interval.of(NOW12, NOW12), NOW12, false, true, false, true},
{Interval.of(NOW12, NOW12), NOW13, true, true, false, false},
// unbounded start
{Interval.of(Instant.MIN, NOW12), Instant.MIN, false, false, true, true},
{Interval.of(Instant.MIN, NOW12), NOW11, false, false, true, true},
{Interval.of(Instant.MIN, NOW12), NOW12, false, true, false, true},
{Interval.of(Instant.MIN, NOW12), NOW13, true, true, false, false},
{Interval.of(Instant.MIN, NOW12), Instant.MAX, true, true, false, false},
// unbounded end
{Interval.of(NOW12, Instant.MAX), Instant.MIN, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), NOW11, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), NOW12, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), NOW13, false, false, true, true},
{Interval.of(NOW12, Instant.MAX), Instant.MAX, false, false, true, true},
};
}
@ParameterizedTest
@MethodSource("data_ends")
public void test_ends_Instant(
Interval test,
Instant instant,
boolean expectedEndsBefore,
boolean expectedEndsAtOrBefore,
boolean expectedEndsAfter,
boolean expectedEndsAtOrAfter) {
assertEquals(expectedEndsBefore, test.endsBefore(instant));
assertEquals(expectedEndsAtOrBefore, test.endsAtOrBefore(instant));
assertEquals(expectedEndsAfter, test.endsAfter(instant));
assertEquals(expectedEndsAtOrAfter, test.endsAtOrAfter(instant));
}
@Test
public void test_ends_Instant_null() {
Interval base = Interval.of(NOW12, NOW14);
assertThrows(NullPointerException.class, () -> base.endsBefore((Instant) null));
assertThrows(NullPointerException.class, () -> base.endsAtOrBefore((Instant) null));
assertThrows(NullPointerException.class, () -> base.endsAfter((Instant) null));
assertThrows(NullPointerException.class, () -> base.endsAtOrAfter((Instant) null));
}
@Test
public void test_isAfter_Instant() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(true, test.isAfter(NOW1.minusSeconds(2)));
assertEquals(true, test.isAfter(NOW1.minusSeconds(1)));
assertEquals(false, test.isAfter(NOW1));
assertEquals(false, test.isAfter(NOW2));
assertEquals(false, test.isAfter(NOW2.plusSeconds(1)));
}
@Test
public void test_isAfter_Instant_empty() {
Interval test = Interval.of(NOW1, NOW1);
assertEquals(true, test.isAfter(NOW1.minusSeconds(2)));
assertEquals(true, test.isAfter(NOW1.minusSeconds(1)));
assertEquals(false, test.isAfter(NOW1));
assertEquals(false, test.isAfter(NOW1.plusSeconds(1)));
}
@Test
public void test_isBefore_Instant() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(false, test.isBefore(NOW1.minusSeconds(1)));
assertEquals(false, test.isBefore(NOW1));
assertEquals(true, test.isBefore(NOW2));
assertEquals(true, test.isBefore(NOW2.plusSeconds(1)));
}
@Test
public void test_isBefore_Instant_empty() {
Interval test = Interval.of(NOW1, NOW1);
assertEquals(false, test.isBefore(NOW1.minusSeconds(1)));
assertEquals(false, test.isBefore(NOW1));
assertEquals(true, test.isBefore(NOW1.plusSeconds(1)));
}
@Test
public void test_isAfter_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(true, test.isAfter(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.isAfter(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(false, test.isAfter(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(false, test.isAfter(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(false, test.isAfter(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(false, test.isAfter(Interval.of(NOW1, NOW2)));
assertEquals(false, test.isAfter(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(false, test.isAfter(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(false, test.isAfter(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(false, test.isAfter(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(false, test.isAfter(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_isAfter_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(true, test.isAfter(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(true, test.isAfter(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(false, test.isAfter(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(false, test.isAfter(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(false, test.isAfter(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_isBefore_Interval() {
Interval test = Interval.of(NOW1, NOW2);
// completely before
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(1), NOW1)));
// partly before
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(1), NOW2)));
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(1), NOW2.minusSeconds(1))));
// contained
assertEquals(false, test.isBefore(Interval.of(NOW1, NOW2.minusSeconds(1))));
assertEquals(false, test.isBefore(Interval.of(NOW1, NOW2)));
assertEquals(false, test.isBefore(Interval.of(NOW1.plusSeconds(1), NOW2)));
// partly after
assertEquals(false, test.isBefore(Interval.of(NOW1, NOW2.plusSeconds(1))));
assertEquals(false, test.isBefore(Interval.of(NOW1.plusSeconds(1), NOW2.plusSeconds(1))));
// completely after
assertEquals(true, test.isBefore(Interval.of(NOW2, NOW2.plusSeconds(1))));
assertEquals(true, test.isBefore(Interval.of(NOW2.plusSeconds(1), NOW2.plusSeconds(2))));
}
@Test
public void test_isBefore_Interval_empty() {
Interval test = Interval.of(NOW1, NOW1);
// completely before
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(2), NOW1.minusSeconds(1))));
assertEquals(false, test.isBefore(Interval.of(NOW1.minusSeconds(1), NOW1)));
// equal
assertEquals(false, test.isBefore(Interval.of(NOW1, NOW1)));
// completely after
assertEquals(true, test.isBefore(Interval.of(NOW1, NOW1.plusSeconds(1))));
assertEquals(true, test.isBefore(Interval.of(NOW1.plusSeconds(1), NOW1.plusSeconds(2))));
}
@Test
public void test_toDuration() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(Duration.between(NOW1, NOW2), test.toDuration());
}
@Test
public void test_equals() {
Interval a = Interval.of(NOW1, NOW2);
Interval a2 = Interval.of(NOW1, NOW2);
Interval b = Interval.of(NOW1, NOW3);
Interval c = Interval.of(NOW2, NOW2);
assertEquals(true, a.equals(a));
assertEquals(true, a.equals(a2));
assertEquals(false, a.equals(b));
assertEquals(false, a.equals(c));
assertEquals(false, a.equals(null));
assertEquals(false, a.equals((Object) ""));
assertEquals(true, a.hashCode() == a2.hashCode());
}
@Test
public void test_toString() {
Interval test = Interval.of(NOW1, NOW2);
assertEquals(NOW1 + "/" + NOW2, test.toString());
}
}
|
package sg.ncl;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import sg.ncl.domain.UserStatus;
import sg.ncl.testbed_interface.TeamStatus;
import sg.ncl.testbed_interface.TeamVisibility;
import javax.inject.Inject;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Te Ye
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TestApp.class)
@WebAppConfiguration
public class ConnectionPropertiesTest {
@Inject
private ConnectionProperties properties;
@Test
public void testGetSioAddress() throws Exception {
assertThat(properties.getSioAddress()).isNotNull();
assertThat(properties.getSioAddress()).isInstanceOf(String.class);
}
@Test
public void testSetSioAddress() throws Exception {
final String one = RandomStringUtils.randomAlphabetic(8);
properties.setSioAddress(one);
assertThat(properties.getSioAddress()).isEqualTo(one);
}
@Test
public void testGetSioPort() throws Exception {
assertThat(properties.getSioAddress()).isNotNull();
assertThat(properties.getSioAddress()).isInstanceOf(String.class);
}
@Test
public void testSetSioPort() throws Exception {
final String one = RandomStringUtils.randomAlphabetic(8);
properties.setSioPort(one);
assertThat(properties.getSioPort()).isEqualTo(one);
}
@Test
public void testGetAuthEndpoint() throws Exception {
assertThat(properties.getAuthEndpoint()).isEqualTo("authentications");
}
@Test
public void testGetCredEndpoint() throws Exception {
assertThat(properties.getCredEndpoint()).isEqualTo("credentials");
}
@Test
public void testGetRegEndpoint() throws Exception {
assertThat(properties.getRegEndpoint()).isEqualTo("registrations");
}
@Test
public void testGetUserEndpoint() throws Exception {
assertThat(properties.getUserEndpoint()).isEqualTo("users");
}
@Test
public void testGetTeamEndpoint() throws Exception {
assertThat(properties.getTeamEndpoint()).isEqualTo("teams");
}
@Test
public void testGetExpEndpoint() throws Exception {
assertThat(properties.getExpEndpoint()).isEqualTo("experiments");
}
@Test
public void testGetRealEndpoint() throws Exception {
assertThat(properties.getRealEndpoint()).isEqualTo("realizations");
}
@Test
public void testGetTeamVisibilityEndpoint() throws Exception {
assertThat(properties.getTeamVisibilityEndpoint()).isEqualTo("?visibility=PUBLIC");
}
@Test
public void testGetSioTeamsUrl() throws Exception {
assertThat(properties.getSioTeamsUrl()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTeamEndpoint() + "/");
}
@Test
public void testGetSioCredUrl() throws Exception {
assertThat(properties.getSioCredUrl()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getCredEndpoint() + "/");
}
@Test
public void testGetSioExpUrl() throws Exception {
assertThat(properties.getSioExpUrl()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getExpEndpoint() + "/");
}
@Test
public void testGetUpdateCredentials() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getUpdateCredentials(id)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getCredEndpoint() + "/" + id);
}
@Test
public void testGetRejectJoinRequest() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
String userId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getRejectJoinRequest(teamId, userId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/teams/" + teamId + "/members/" + userId);
}
@Test
public void testGetRegisterRequestToApplyTeam() throws Exception {
String userId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getRegisterRequestToApplyTeam(userId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/newTeam/" + userId);
}
@Test
public void testGetJoinRequestExistingUser() throws Exception {
assertThat(properties.getJoinRequestExistingUser()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/joinApplications");
}
@Test
public void testGetApproveTeam() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
String ownerId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getApproveTeam(teamId, ownerId, TeamStatus.APPROVED)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/teams/" + teamId + "/owner/" + ownerId + "?status=APPROVED");
}
@Test
public void testGetApproveJoinRequest() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
String userId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getApproveJoinRequest(teamId, userId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/teams/" + teamId + "/members/" + userId);
}
@Test
public void testGetTeamByName() throws Exception {
String teamName = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getTeamByName(teamName)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTeamEndpoint() + "?name=" + teamName);
}
@Test
public void testGetTeamById() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getTeamById(teamId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTeamEndpoint() + "/" + teamId);
}
@Test
public void testGetTeamsByVisibility() throws Exception {
assertThat(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString())).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTeamEndpoint() + "?visibility=" + TeamVisibility.PUBLIC.toString());
}
@Test
public void testGetUser() throws Exception {
String userId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getUser(userId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getUserEndpoint() + "/" + userId);
}
@Test
public void testGetUserStatus() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getSioUsersStatusUrl(id, UserStatus.APPROVED.name())).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getUserEndpoint() + "/" + id + "/status/" + UserStatus.APPROVED);
}
@Test
public void testGetExpListByTeamId() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getExpListByTeamId(teamId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getExpEndpoint() + "/teams/" + teamId);
}
@Test
public void testGetRealizationByTeam() throws Exception {
String teamName = RandomStringUtils.randomAlphanumeric(20);
String expId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getRealizationByTeam(teamName, expId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRealEndpoint() + "/team/" + teamName + "/experiment/" + expId);
}
@Test
public void testGetDeleteExperiment() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
String expId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getDeleteExperiment(teamId, expId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getExpEndpoint() + "/teams/" + teamId + "/experiments/" + expId);
}
@Test
public void testGetStartExperiment() throws Exception {
String teamName = RandomStringUtils.randomAlphanumeric(20);
String expId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getStartExperiment(teamName, expId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRealEndpoint() + "/start/team/" + teamName + "/experiment/" + expId);
}
@Test
public void testGetStopExperiment() throws Exception {
String teamName = RandomStringUtils.randomAlphanumeric(20);
String expId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getStopExperiment(teamName, expId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRealEndpoint() + "/stop/team/" + teamName + "/experiment/" + expId);
}
@Test
public void testGetTelemetryAddress() throws Exception {
assertThat(properties.getTelemetryAddress()).isNotNull();
assertThat(properties.getTelemetryAddress()).isInstanceOf(String.class);
}
@Test
public void testSetTelemetryAddress() throws Exception {
final String one = RandomStringUtils.randomAlphabetic(8);
properties.setTelemetryAddress(one);
assertThat(properties.getTelemetryAddress()).isEqualTo(one);
}
@Test
public void testGetTelemetryPort() throws Exception {
// null because not configured in application.properties
assertThat(properties.getTelemetryPort()).isNull();
}
@Test
public void testSetTelemetryPort() throws Exception {
final String one = RandomStringUtils.randomAlphabetic(8);
properties.setTelemetryPort(one);
assertThat(properties.getTelemetryPort()).isEqualTo(one);
}
@Test
public void testGetFreeNodes() throws Exception {
assertThat(properties.getFreeNodes()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTelemetryEndpoint());
}
@Test
public void testGetAllImages() throws Exception {
assertThat(properties.getAllImages()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getImageEndpoint());
}
@Test
public void testGetTeamImages() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getTeamImages(teamId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getImageEndpoint() + "?teamId=" + teamId);
}
@Test
public void testGetTeamSavedImages() throws Exception {
String teamId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getTeamSavedImages(teamId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getImageEndpoint() + "/teams/" + teamId);
}
@Test
public void testGetTeamStatus() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getSioTeamsStatusUrl(id, TeamStatus.APPROVED)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getTeamEndpoint() + "/" + id + "/status/" + TeamStatus.APPROVED);
}
@Test
public void testSaveImage() throws Exception {
assertThat(properties.saveImage()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getImageEndpoint());
}
@Test
public void testGetPasswordResetRequestURI() {
assertThat(properties.getPasswordResetRequestURI()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getCredEndpoint() + "/password/resets");
}
@Test
public void testGetPasswordResetURI() {
assertThat(properties.getPasswordResetURI()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getCredEndpoint() + "/password");
}
@Test
public void testGetAllExperiments() throws Exception {
assertThat(properties.getAllExperiments()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getExpEndpoint());
}
@Test
public void testGetAllRealizations() throws Exception {
assertThat(properties.getAllRealizations()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRealEndpoint());
}
@Test
public void testGetData() throws Exception {
assertThat(properties.getData()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint());
}
@Test
public void testGetDataset() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getDataset(id)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/" + id);
}
@Test
public void testGetDeterUid() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getDeterUid(id)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRegEndpoint() + "/user/" + id);
}
@Test
public void testGetPublicData() throws Exception {
assertThat(properties.getPublicData()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "?visibility=PUBLIC");
}
@Test
public void testDownloadResource() throws Exception {
String dataId = RandomStringUtils.randomAlphanumeric(20);
String resourceId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.downloadResource(dataId, resourceId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/" + dataId + "/resources/" + resourceId + "/download");
}
@Test
public void testGetResource() throws Exception {
String dataId = RandomStringUtils.randomAlphanumeric(20);
String resourceId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getResource(dataId, resourceId)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/" + dataId + "/resources/" + resourceId);
}
@Test
public void testGetSioDataUrl() throws Exception {
assertThat(properties.getSioDataUrl()).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/");
}
@Test
public void testGetTopology() throws Exception {
String name = RandomStringUtils.randomAlphanumeric(20);
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getTopology(name, id)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getExpEndpoint() + "/teams/" + name + "/experiments/" + id + "/topology");
}
@Test
public void testGetUsageStatisticsByTeamId() throws Exception {
String id = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.getUsageStatisticsByTeamId(id)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getRealEndpoint() + "/teams/" + id + "/usage");
}
@Test
public void testCheckUploadChunk() throws Exception {
Integer chunkNumber = Integer.parseInt(RandomStringUtils.randomNumeric(8));
String dataId = RandomStringUtils.randomAlphanumeric(20);
String identifier = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.checkUploadChunk(dataId, chunkNumber, identifier)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/" + dataId + "/chunks/" + chunkNumber + "/files/" + identifier);
}
@Test
public void testSendUploadChunk() throws Exception {
Integer chunkNumber = Integer.parseInt(RandomStringUtils.randomNumeric(8));
String dataId = RandomStringUtils.randomAlphanumeric(20);
assertThat(properties.sendUploadChunk(dataId, chunkNumber)).isEqualTo("http://" + properties.getSioAddress() + ":" + properties.getSioPort() + "/" + properties.getDataEndpoint() + "/" + dataId + "/chunks/" + chunkNumber);
}
}
|
package com.intellij.refactoring.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Collection;
/**
* @author dsl
*/
public class CanonicalTypes {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.util.CanonicalTypes");
public static abstract class Type {
public abstract PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException;
public abstract String getTypeText();
public abstract void addImportsTo(final PsiCodeFragment codeFragment);
}
private static class Primitive extends Type {
private PsiPrimitiveType myType;
private Primitive(PsiPrimitiveType type) {
myType = type;
}
public PsiType getType(PsiElement context, final PsiManager manager) {
return myType;
}
public String getTypeText() {
return myType.getPresentableText();
}
public void addImportsTo(final PsiCodeFragment codeFragment) {}
}
private static class Array extends Type {
private Type myComponentType;
private Array(Type componentType) {
myComponentType = componentType;
}
public PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException {
return myComponentType.getType(context, manager).createArrayType();
}
public String getTypeText() {
return myComponentType.getTypeText() + "[]";
}
public void addImportsTo(final PsiCodeFragment codeFragment) {
myComponentType.addImportsTo(codeFragment);
}
}
private static class Ellipsis extends Type {
private Type myComponentType;
private Ellipsis(Type componentType) {
myComponentType = componentType;
}
public PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException {
return new PsiEllipsisType(myComponentType.getType(context, manager));
}
public String getTypeText() {
return myComponentType.getTypeText() + "...";
}
public void addImportsTo(final PsiCodeFragment codeFragment) {
myComponentType.addImportsTo(codeFragment);
}
}
private static class WildcardType extends Type {
private final boolean myIsExtending;
private final Type myBound;
private WildcardType(boolean isExtending, Type bound) {
myIsExtending = isExtending;
myBound = bound;
}
public PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException {
if(myBound == null) return PsiWildcardType.createUnbounded(context.getManager());
if (myIsExtending) {
return PsiWildcardType.createExtends(context.getManager(), myBound.getType(context, manager));
}
else {
return PsiWildcardType.createSuper(context.getManager(), myBound.getType(context, manager));
}
}
public String getTypeText() {
if (myBound == null) return "?";
return "? " + (myIsExtending ? "extends " : "super ") + myBound.getTypeText();
}
public void addImportsTo(final PsiCodeFragment codeFragment) {
if (myBound != null) myBound.addImportsTo(codeFragment);
}
}
private static class WrongType extends Type {
private String myText;
private WrongType(String text) {
myText = text;
}
public PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException {
return context.getManager().getElementFactory().createTypeFromText(myText, context);
}
public String getTypeText() {
return myText;
}
public void addImportsTo(final PsiCodeFragment codeFragment) {}
}
private static class Class extends Type {
private final String myOriginalText;
private String myClassQName;
private Map<String,Type> mySubstitutor;
private Class(String originalText, String classQName, Map<String, Type> substitutor) {
myOriginalText = originalText;
myClassQName = classQName;
mySubstitutor = substitutor;
}
public PsiType getType(PsiElement context, final PsiManager manager) throws IncorrectOperationException {
final PsiElementFactory factory = manager.getElementFactory();
final PsiResolveHelper resolveHelper = manager.getResolveHelper();
final PsiClass aClass = resolveHelper.resolveReferencedClass(myClassQName, context);
if (aClass == null) {
return factory.createTypeFromText(myClassQName, context);
}
Map<PsiTypeParameter, PsiType> substMap = new HashMap<PsiTypeParameter,PsiType>();
final Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aClass);
while (iterator.hasNext()) {
PsiTypeParameter typeParameter = iterator.next();
final String name = typeParameter.getName();
final Type type = mySubstitutor.get(name);
if (type != null) {
substMap.put(typeParameter, type.getType(context, manager));
} else {
substMap.put(typeParameter, null);
}
}
return factory.createType(aClass, factory.createSubstitutor(substMap));
}
public String getTypeText() {
return myOriginalText;
}
public void addImportsTo(final PsiCodeFragment codeFragment) {
codeFragment.addImportsFromString(myClassQName);
final Collection<Type> types = mySubstitutor.values();
for (Type type : types) {
if (type != null) {
type.addImportsTo(codeFragment);
}
}
}
}
private static class Creator extends PsiTypeVisitor<Type> {
public static final Creator INSTANCE = new Creator();
public Type visitPrimitiveType(PsiPrimitiveType primitiveType) {
return new Primitive(primitiveType);
}
public Type visitEllipsisType(PsiEllipsisType ellipsisType) {
return new Ellipsis(ellipsisType.getComponentType().accept(this));
}
public Type visitArrayType(PsiArrayType arrayType) {
return new Array(arrayType.getComponentType().accept(this));
}
public Type visitWildcardType(PsiWildcardType wildcardType) {
final PsiType wildcardBound = wildcardType.getBound();
final Type bound = wildcardBound == null ? null : wildcardBound.accept(this);
return new WildcardType(wildcardType.isExtends(), bound);
}
public Type visitClassType(PsiClassType classType) {
final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
final PsiClass aClass = resolveResult.getElement();
final String originalText = classType.getPresentableText();
if (aClass == null) {
return new WrongType(originalText);
} else {
Map<String,Type> substMap = new HashMap<String,Type>();
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
final Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aClass);
while (iterator.hasNext()) {
PsiTypeParameter typeParameter = iterator.next();
final PsiType substType = substitutor.substitute(typeParameter);
final String name = typeParameter.getName();
if (substType == null) {
substMap.put(name, null);
} else {
substMap.put(name, substType.accept(this));
}
}
final String qualifiedName = aClass.getQualifiedName();
LOG.assertTrue(aClass.getName() != null);
return new Class(originalText, qualifiedName != null ? qualifiedName : aClass.getName(), substMap);
}
}
}
public static Type createTypeWrapper(PsiType type) {
return type.accept(Creator.INSTANCE);
}
}
|
package net.sourceforge.texlipse.builder;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.texlipse.properties.TexlipseProperties;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
/**
* Run the external latex program.
*
* @author Kimmo Karlsson
* @author Oskar Ojala
* @author Boris von Loesch
*/
public class LatexRunner extends AbstractProgramRunner {
private Stack parsingStack;
/**
* Create a new ProgramRunner.
*/
public LatexRunner() {
super();
this.parsingStack = new Stack();
}
protected String getWindowsProgramName() {
return "latex.exe";
}
protected String getUnixProgramName() {
return "latex";
}
public String getDescription() {
return "Latex program";
}
public String getDefaultArguments() {
return "-interaction=scrollmode --src-specials %input";
}
public String getInputFormat() {
return TexlipseProperties.INPUT_FORMAT_TEX;
}
/**
* Used by the DviBuilder to figure out what the latex program produces.
*
* @return output file format (dvi)
*/
public String getOutputFormat() {
return TexlipseProperties.OUTPUT_FORMAT_DVI;
}
protected String[] getQueryString() {
return new String[] { "\nPlease type another input file name:" , "\nEnter file name:" };
}
/**
* Adds a problem marker
*
* @param error The error or warning string
* @param causingSourceFile name of the sourcefile
* @param linenr where the error occurs
* @param severity
* @param resource
* @param layout true, if this is a layout warning
*/
private void addProblemMarker(String error, String causingSourceFile,
int linenr, int severity, IResource resource, boolean layout) {
IProject project = resource.getProject();
IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project);
if (sourceDir == null)
sourceDir = project;
IResource extResource = null;
if (causingSourceFile != null)
extResource = sourceDir.findMember(causingSourceFile);
if (extResource == null)
createMarker(resource, null, error + " (Occurance: "
+ causingSourceFile + ")", severity);
else {
if (linenr >= 0) {
if (layout)
createLayoutMarker(extResource, new Integer(linenr), error);
else
createMarker(extResource, new Integer(linenr), error, severity);
} else
createMarker(extResource, null, error, severity);
}
}
/**
* Parse the output of the LaTeX program.
*
* @param resource the input file that was processed
* @param output the output of the external program
* @return true, if error messages were found in the output, false otherwise
*/
protected boolean parseErrors(IResource resource, String output) {
TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, null);
TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, null);
parsingStack.clear();
boolean errorsFound = false;
StringTokenizer st = new StringTokenizer(output, "\r\n");
final Pattern LATEXERROR = Pattern.compile("^! LaTeX Error: (.*)$");
final Pattern TEXERROR = Pattern.compile("^!\\s+(.*)$");
final Pattern FULLBOX = Pattern.compile("^(?:Over|Under)full \\\\[hv]box .* at lines? (\\d+)-?-?(\\d+)?");
final Pattern WARNING = Pattern.compile("^.+Warning.*: (.*)$");
final Pattern ATLINE = Pattern.compile("^l\\.(\\d+)(.*)$");
final Pattern ATLINE2 = Pattern.compile(".* line (\\d+).*");
String line;
boolean hasProblem = false;
String error = null;
int severity = IMarker.SEVERITY_WARNING;
int linenr = -1;
String occurance = null;
while (st.hasMoreTokens()) {
line = st.nextToken();
Matcher m = TEXERROR.matcher(line);
if (m.matches()) {
if (hasProblem) {
// We have a not reported problem
addProblemMarker(error, occurance, linenr, severity, resource, false);
linenr = -1;
}
hasProblem = true;
errorsFound = true;
severity = IMarker.SEVERITY_ERROR;
occurance = determineSourceFile();
Matcher m2 = LATEXERROR.matcher(line);
if (m2.matches()) {
// LaTex error
error = m2.group(1);
String part2 = st.nextToken().trim();
if (Character.isLowerCase(part2.charAt(0))) {
error += ' ' + part2;
}
updateParsedFile(part2);
continue;
}
if (line.startsWith("! Undefined control sequence.")){
// Undefined Control Sequence
error = "Undefined control sequence: ";
continue;
}
m2 = WARNING.matcher(line);
if (m2.matches())
severity = IMarker.SEVERITY_WARNING;
error = m.group(1);
continue;
}
m = WARNING.matcher(line);
if (m.matches()){
if (hasProblem){
// We have a not reported problem
addProblemMarker(error, occurance, linenr, severity, resource, false);
linenr = -1;
hasProblem = false;
}
if (line.indexOf("Label(s) may have changed.") > 0) {
// prepare to re-run latex
TexlipseProperties.setSessionProperty(resource.getProject(),
TexlipseProperties.SESSION_LATEX_RERUN, "true");
continue;
}
else if (line.indexOf("There were undefined references.") > 0) {
// prepare to run bibtex
TexlipseProperties.setSessionProperty(resource.getProject(),
TexlipseProperties.SESSION_BIBTEX_RERUN, "true");
continue;
}
// Ignore undefined references or citations because they are
// found by the parser
if (line.startsWith("LaTeX Warning: Reference `"))
continue;
if (line.startsWith("LaTeX Warning: Citation `"))
continue;
severity = IMarker.SEVERITY_WARNING;
occurance = determineSourceFile();
hasProblem = true;
if (line.startsWith("LaTeX Warning: ")) {
error = line.substring(15);
//Try to get the line number
Matcher pM = ATLINE2.matcher(line);
if (pM.matches()) {
linenr = Integer.parseInt(pM.group(1));
}
String nextLine = st.nextToken();
pM = ATLINE2.matcher(nextLine);
if (pM.matches()) {
linenr = Integer.parseInt(pM.group(1));
}
updateParsedFile(nextLine);
error += " " + nextLine;
if (linenr != -1) {
addProblemMarker(line, occurance, linenr, severity,
resource, false);
hasProblem = false;
linenr = -1;
}
continue;
} else {
error = line;
//Try to get the line number
Matcher pM = ATLINE2.matcher(line);
if (pM.matches()) {
linenr = Integer.parseInt(pM.group(1));
}
continue;
}
}
m = FULLBOX.matcher(line);
if (m.matches()) {
if (hasProblem) {
// We have a not reported problem
addProblemMarker(error, occurance, linenr, severity,
resource, false);
linenr = -1;
hasProblem = false;
}
severity = IMarker.SEVERITY_WARNING;
occurance = determineSourceFile();
error = line;
linenr = Integer.parseInt(m.group(1));
addProblemMarker(line, occurance, linenr, severity, resource,
true);
hasProblem = false;
linenr = -1;
continue;
}
m = ATLINE.matcher(line);
if (hasProblem && m.matches()) {
linenr = Integer.parseInt(m.group(1));
String part2 = st.nextToken();
int index = line.indexOf(' ');
error += " " + line.substring(index).trim() + " (followed by: "
+ part2.trim() + ")";
addProblemMarker(error, occurance, linenr, severity, resource,
false);
linenr = -1;
hasProblem = false;
continue;
}
m = ATLINE2.matcher(line);
if (hasProblem && m.matches()) {
linenr = Integer.parseInt(m.group(1));
addProblemMarker(error, occurance, linenr, severity, resource,
false);
linenr = -1;
hasProblem = false;
continue;
}
updateParsedFile(line);
}
if (hasProblem) {
// We have a not reported problem
addProblemMarker(error, occurance, linenr, severity, resource, false);
}
return errorsFound;
}
/**
* Updates the stack that determines which file we are currently
* parsing, so that errors can be annotated in the correct file.
*
* @param logLine A line from latex' output containing which file we are in
*/
private void updateParsedFile(String logLine) {
if (logLine.indexOf('(') == -1 && logLine.indexOf(')') == -1)
return;
for (int i = 0; i < logLine.length(); i++) {
if (logLine.charAt(i) == '(') {
int j;
for (j = i + 1; j < logLine.length()
&& isAllowedinName(logLine.charAt(j)); j++)
;
parsingStack.push(logLine.substring(i, j).trim());
i = j - 1;
} else if (logLine.charAt(i) == ')') {
parsingStack.pop();
}
}
}
private boolean isAllowedinName(char c) {
if (c == '(' || c == ')' || c == '[')
return false;
else
return true;
}
/**
* Determines the source file we are currently parsing.
*
* @return The filename or null if no file could be determined
*/
private String determineSourceFile() {
if (!parsingStack.empty())
return ((String) parsingStack.peek()).substring(1);
else
return null;
}
}
|
package org.jasig.portal.channels.webproxy;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jasig.portal.ChannelCacheKey;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.GeneralRenderingException;
import org.jasig.portal.IMultithreadedCacheable;
import org.jasig.portal.IMultithreadedChannel;
import org.jasig.portal.IMultithreadedMimeResponse;
import org.jasig.portal.MediaManager;
import org.jasig.portal.PortalEvent;
import org.jasig.portal.PortalException;
import org.jasig.portal.ResourceMissingException;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.LocalConnectionContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.utils.AbsoluteURLFilter;
import org.jasig.portal.utils.CookieCutter;
import org.jasig.portal.utils.DTDResolver;
import org.jasig.portal.utils.ResourceLoader;
import org.jasig.portal.utils.XSLT;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xml.sax.ContentHandler;
/**
* <p>A channel which transforms and interacts with dynamic XML or HTML.
* See docs/website/developers/channel_docs/reference/CwebProxy.html
* for full documentation.
* </p>
*
* <p>Static Channel Parameters:
* Except where indicated, static parameters can be updated by equivalent
* Runtime parameters. Caching parameters can also be changed temporarily.
* Cache defaults and IPerson restrictions are loaded first from properties,
* and overridden by static data if there.
* </p>
* <ol>
* <li>"cw_xml" - a URI for the source XML document
* <li>"cw_ssl" - a URI for the corresponding .ssl (stylesheet list) file
* <li>"cw_xslTitle" - a title representing the stylesheet (optional)
* <i>If no title parameter is specified, a default
* stylesheet will be chosen according to the media</i>
* <li>"cw_xsl" - a URI for the stylesheet to use
* <i>If <code>cw_xsl</code> is supplied, <code>cw_ssl</code>
* and <code>cw_xslTitle</code> will be ignored.
* <li>"cw_passThrough" - indicates how RunTimeData is to be passed through.
* <i>If <code>cw_passThrough</code> is supplied, and not set
* to "all" or "application", additional RunTimeData
* parameters not starting with "cw_" or "upc_" will be
* passed as request parameters to the XML URI. If
* <code>cw_passThrough</code> is set to "marked", this will
* happen only if there is also a RunTimeData parameter of
* <code>cw_inChannelLink</code>. "application" is intended
* to keep application-specific links in the channel, while
* "all" should keep all links in the channel. This
* distinction is handled entirely in the URL Filters.
* <li>"cw_tidy" - output from <code>xmlUri</code> will be passed though Jtidy
* <li>"cw_info" - a URI to be called for the <code>info</code> event.
* <li>"cw_help" - a URI to be called for the <code>help</code> event.
* <li>"cw_edit" - a URI to be called for the <code>edit</code> event.
* <li>"cw_cacheDefaultMode" - Default caching mode.
* <i>May be <code>none</code> (normally don't cache), or
* <code>all</code> (cache everything).
* <li>"cw_cacheDefaultTimeout" - Default timeout in seconds.
* <li>"cw_cacheMode" - override default for this request only.
* <i>Primarily intended as a runtime parameter, but can
* used statically to override the first instance.</i>
* <li>"cw_cacheTimeout" - override default for this request only.
* <i>Primarily intended as a runtime parameter, but can
* be used statically to override the first instance.</i>
* <li>"cw_person" - IPerson attributes to pass.
* <i>A comma-separated list of IPerson attributes to
* pass to the back end application. The static data
* value will be passed on </i>all<i> requests not
* overridden by a runtime data cw_person except some
* refresh requests.</i>
* <li>"cw_personAllow" - Restrict IPerson attribute passing to this list.
* <i>A comma-separated list of IPerson attributes that
* may be passed via cw_person. An empty or non-existent
* value means use the default value from the corresponding
* property. The special value "*" means all attributes
* are allowed. The value "!*" means none are allowed.
* Static data only.</i>
* <li>"upc_localConnContext" - LocalConnectionContext implementation class.
* <i>The name of a class to use when data sent to the
* backend application needs to be modified or added
* to suit local needs. Static data only.</i>
* </ol>
* <p>Runtime Channel Parameters:</p>
* The following parameters are runtime-only.
* </p>
* <ol>
* <li>"cw_reset" - an instruction to return to reset internal variables.
* <i>The value <code>return</code> resets <code>cw_xml</code>
* to its last value before changed by button events. The
* value "reset" returns all variables to the static data
* values.</i>
* <li>"cw_download" - use download worker for this link or form
* <i>any link or form that contains this parameter will be
* handled by the download worker, if the pass-through mode
* is set to rewrite the link or form. This allows downloads
* from the proxied site to be delivered via the portal,
* primarily useful if the download requires verification
* of a session referenced by a proxied cookie</i>
*
* </ol>
* <p>This channel can be used for all XML formats with appropriate stylesheets.
* All static data parameters as well as additional runtime data parameters
* passed to this channel via HttpRequest will in turn be passed on to the
* XSLT stylesheet as stylesheet parameters. They can be read in the
* stylesheet as follows:
* <code><xsl:param
* name="yourParamName">aDefaultValue</xsl:param></code>
* </p>
* @author Andrew Draskoy, andrew@mun.ca
* @author Sarah Arnott, sarnott@mun.ca
* @version $Revision$
*/
public class CWebProxy implements IMultithreadedChannel, IMultithreadedCacheable, IMultithreadedMimeResponse
{
private static final Log log = LogFactory.getLog(CWebProxy.class);
Map stateTable;
// to prepend to the system-wide cache key
static final String systemCacheId="org.jasig.portal.channels.webproxy.CWebProxy";
static PrintWriter devNull;
static
{
try
{
devNull = getErrout();
}
catch (FileNotFoundException fnfe)
{
/* Ignore */
}
}
// All state variables stored here
private class ChannelState
{
private IPerson iperson;
private String person;
private String personAllow;
private HashSet personAllow_set;
private String fullxmlUri;
private String buttonxmlUri;
private String xmlUri;
private String key;
private String passThrough;
private String tidy;
private String sslUri;
private String xslTitle;
private String xslUri;
private String infoUri;
private String helpUri;
private String editUri;
private String cacheDefaultMode;
private String cacheMode;
private String reqParameters;
private long cacheDefaultTimeout;
private long cacheTimeout;
private ChannelRuntimeData runtimeData;
private CookieCutter cookieCutter;
private URLConnection connHolder;
private LocalConnectionContext localConnContext;
private int refresh;
public ChannelState ()
{
fullxmlUri = buttonxmlUri = xmlUri = key = passThrough = sslUri = null;
xslTitle = xslUri = infoUri = helpUri = editUri = tidy = null;
cacheMode = null;
iperson = null;
refresh = -1;
cacheTimeout = cacheDefaultTimeout = PropertiesManager.getPropertyAsLong("org.jasig.portal.channels.webproxy.CWebProxy.cache_default_timeout");
cacheMode = cacheDefaultMode = PropertiesManager.getProperty("org.jasig.portal.channels.webproxy.CWebProxy.cache_default_mode");
personAllow = PropertiesManager.getProperty("org.jasig.portal.channels.webproxy.CWebProxy.person_allow");
runtimeData = null;
cookieCutter = new CookieCutter();
localConnContext = null;
}
}
public CWebProxy ()
{
stateTable = Collections.synchronizedMap(new HashMap());
}
/**
* Passes ChannelStaticData to the channel.
* This is done during channel instantiation time.
* see org.jasig.portal.ChannelStaticData
* @param sd channel static data
* @see ChannelStaticData
*/
public void setStaticData (ChannelStaticData sd, String uid)
{
ChannelState state = new ChannelState();
state.iperson = sd.getPerson();
state.person = sd.getParameter("cw_person");
String personAllow = sd.getParameter ("cw_personAllow");
if ( personAllow != null && (!personAllow.trim().equals("")))
state.personAllow = personAllow;
// state.personAllow could have been set by a property or static data
if ( state.personAllow != null && (!state.personAllow.trim().equals("!*")) )
{
state.personAllow_set = new HashSet();
StringTokenizer st = new StringTokenizer(state.personAllow,",");
if (st != null)
{
while ( st.hasMoreElements () ) {
String pName = st.nextToken();
if (pName!=null) {
pName = pName.trim();
if (!pName.equals(""))
state.personAllow_set.add(pName);
}
}
}
}
state.xmlUri = sd.getParameter ("cw_xml");
state.sslUri = sd.getParameter ("cw_ssl");
state.xslTitle = sd.getParameter ("cw_xslTitle");
state.xslUri = sd.getParameter ("cw_xsl");
state.fullxmlUri = sd.getParameter ("cw_xml");
state.passThrough = sd.getParameter ("cw_passThrough");
state.tidy = sd.getParameter ("cw_tidy");
state.infoUri = sd.getParameter ("cw_info");
state.helpUri = sd.getParameter ("cw_help");
state.editUri = sd.getParameter ("cw_edit");
state.key = state.xmlUri;
String cacheMode = sd.getParameter ("cw_cacheDefaultMode");
if (cacheMode != null && !cacheMode.trim().equals(""))
state.cacheDefaultMode = cacheMode;
cacheMode = sd.getParameter ("cw_cacheMode");
if (cacheMode != null && !cacheMode.trim().equals(""))
state.cacheMode = cacheMode;
else
state.cacheMode = state.cacheDefaultMode;
String cacheTimeout = sd.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null && !cacheTimeout.trim().equals(""))
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = sd.getParameter("cw_cacheTimeout");
if (cacheTimeout != null && !cacheTimeout.trim().equals(""))
state.cacheTimeout = Long.parseLong(cacheTimeout);
else
state.cacheTimeout = state.cacheDefaultTimeout;
String connContext = sd.getParameter ("upc_localConnContext");
if (connContext != null && !connContext.trim().equals(""))
{
try
{
state.localConnContext = (LocalConnectionContext) Class.forName(connContext).newInstance();
state.localConnContext.init(sd);
}
catch (Exception e)
{
log.error( "CWebProxy: Cannot initialize LocalConnectionContext: ", e);
}
}
stateTable.put(uid,state);
}
/**
* Passes ChannelRuntimeData to the channel.
* This function is called prior to the renderXML() call.
* @param rd channel runtime data
* @see ChannelRuntimeData
*/
public void setRuntimeData (ChannelRuntimeData rd, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
log.error("CWebProxy:setRuntimeData() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
state.runtimeData = rd;
if ( rd.isEmpty() && (state.refresh != -1) ) {
// A refresh-- State remains the same.
if ( state.buttonxmlUri != null ) {
state.key = state.buttonxmlUri;
state.fullxmlUri = state.buttonxmlUri;
state.refresh = 0;
} else {
if ( state.refresh == 0 )
state.key = state.fullxmlUri;
state.fullxmlUri = state.xmlUri;
state.refresh = 1;
}
} else {
state.refresh = 0;
String xmlUri = state.runtimeData.getParameter("cw_xml");
if (xmlUri != null) {
state.xmlUri = xmlUri;
// don't need an explicit reset if a new URI is provided.
state.buttonxmlUri = null;
}
String sslUri = state.runtimeData.getParameter("cw_ssl");
if (sslUri != null)
state.sslUri = sslUri;
String xslTitle = state.runtimeData.getParameter("cw_xslTitle");
if (xslTitle != null)
state.xslTitle = xslTitle;
String xslUri = state.runtimeData.getParameter("cw_xsl");
if (xslUri != null)
state.xslUri = xslUri;
String passThrough = state.runtimeData.getParameter("cw_passThrough");
if (passThrough != null)
state.passThrough = passThrough;
String person = state.runtimeData.getParameter("cw_person");
if (person != null)
state.person = person;
String tidy = state.runtimeData.getParameter("cw_tidy");
if (tidy != null)
state.tidy = tidy;
String infoUri = state.runtimeData.getParameter("cw_info");
if (infoUri != null)
state.infoUri = infoUri;
String editUri = state.runtimeData.getParameter("cw_edit");
if (editUri != null)
state.editUri = editUri;
String helpUri = state.runtimeData.getParameter("cw_help");
if (helpUri != null)
state.helpUri = helpUri;
String cacheTimeout = state.runtimeData.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null)
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = state.runtimeData.getParameter("cw_cacheTimeout");
if (cacheTimeout != null)
state.cacheTimeout = Long.parseLong(cacheTimeout);
else
state.cacheTimeout = state.cacheDefaultTimeout;
String cacheDefaultMode = state.runtimeData.getParameter("cw_cacheDefaultMode");
if (cacheDefaultMode != null) {
state.cacheDefaultMode = cacheDefaultMode;
}
String cacheMode = state.runtimeData.getParameter("cw_cacheMode");
if (cacheMode != null) {
state.cacheMode = cacheMode;
} else
state.cacheMode = state.cacheDefaultMode;
// reset is a one-time thing.
String reset = state.runtimeData.getParameter("cw_reset");
if (reset != null) {
if (reset.equalsIgnoreCase("return")) {
state.buttonxmlUri = null;
}
}
if ( state.buttonxmlUri != null )
state.fullxmlUri = state.buttonxmlUri;
else
{
//log.debug("CWebProxy: xmlUri is " + state.xmlUri);
// pass IPerson atts independent of the value of cw_passThrough
StringBuffer newXML = new StringBuffer();
String appendchar = "";
// here add in attributes according to cw_person
if (state.person != null && state.personAllow_set != null)
{
StringTokenizer st = new StringTokenizer(state.person,",");
if (st != null)
{
while (st.hasMoreElements ())
{
String pName = st.nextToken();
if ((pName!=null)&&(!pName.trim().equals("")))
{
if ( state.personAllow.trim().equals("*") ||
state.personAllow_set.contains(pName) )
{
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
// note, this only gets the first one if it's a
// java.util.Vector. Should check
String pVal = (String)state.iperson.getAttribute(pName);
if (pVal != null)
try {
newXML.append(URLEncoder.encode(pVal,"UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
else {
if (log.isInfoEnabled())
log.info(
"CWebProxy: request to pass " + pName + " denied.");
}
}
}
}
}
// end cw_person code
// Is this a case where we need to pass request parameters to the xmlURI?
if ( state.passThrough != null &&
!state.passThrough.equalsIgnoreCase("none") &&
( state.passThrough.equalsIgnoreCase("all") ||
state.passThrough.equalsIgnoreCase("application") ||
rd.getParameter("cw_inChannelLink") != null ) )
{
// keyword and parameter processing
// NOTE: if both exist, only keywords are appended
String keywords = rd.getKeywords();
if (keywords != null)
{
if (appendchar.equals("&"))
newXML.append("&keywords=" + keywords);
else
newXML.append(keywords);
}
else
{
// want all runtime parameters not specific to WebProxy
Enumeration e=rd.getParameterNames ();
if (e!=null)
{
while (e.hasMoreElements ())
{
String pName = (String) e.nextElement ();
if ( !pName.startsWith("cw_") && !pName.startsWith("upc_")
&& !pName.trim().equals(""))
{
String[] value_array = rd.getParameterValues(pName);
int i = 0;
while ( i < value_array.length )
{
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
try {
newXML.append(URLEncoder.encode(value_array[i++].trim(),"UTF-8"));
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
}
}
}
}
}
state.reqParameters = newXML.toString();
state.fullxmlUri = state.xmlUri;
if (!state.runtimeData.getHttpRequestMethod().equals("POST"))
{
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals("")))
{
appendchar = (state.xmlUri.indexOf('?') == -1) ? "?" : "&";
state.fullxmlUri = state.fullxmlUri+appendchar+state.reqParameters;
}
state.reqParameters = null;
}
//log.debug("CWebProxy: fullxmlUri now: " + state.fullxmlUri);
}
// set key for cache based on request parameters
// NOTE: POST requests are not idempotent and therefore are not
// retrievable from the cache
if (!state.runtimeData.getHttpRequestMethod().equals("POST"))
state.key = state.fullxmlUri;
else //generate a unique string as key
state.key = String.valueOf((new Date()).getTime());
}
}
}
/**
* Process portal events. Currently supported events are
* EDIT_BUTTON_EVENT, HELP_BUTTON_EVENT, ABOUT_BUTTON_EVENT,
* and SESSION_DONE. The button events work by changing the xmlUri.
* The new Uri's content should contain a link that will refer back
* to the old one at the end of its task.
* @param ev the event
*/
public void receiveEvent (PortalEvent ev, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
log.error("CWebProxy:receiveEvent() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else {
int evnum = ev.getEventNumber();
switch (evnum)
{
case PortalEvent.EDIT_BUTTON_EVENT:
if (state.editUri != null)
state.buttonxmlUri = state.editUri;
break;
case PortalEvent.HELP_BUTTON_EVENT:
if (state.helpUri != null)
state.buttonxmlUri = state.helpUri;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
if (state.infoUri != null)
state.buttonxmlUri = state.infoUri;
break;
case PortalEvent.SESSION_DONE:
stateTable.remove(uid);
break;
// case PortalEvent.UNSUBSCRIBE:
default:
break;
}
}
}
/**
* Acquires ChannelRuntimeProperites from the channel.
* This function may be called by the portal framework throughout the session.
* @see ChannelRuntimeProperties
*/
public ChannelRuntimeProperties getRuntimeProperties (String uid)
{
ChannelRuntimeProperties rp=new ChannelRuntimeProperties();
// determine if such channel is registered
if (stateTable.get(uid) == null)
{
rp.setWillRender(false);
log.error("CWebProxy:getRuntimeProperties() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
}
return rp;
}
/**
* Ask channel to render its content.
* @param out the SAX ContentHandler to output content to
*/
public void renderXML (ContentHandler out, String uid) throws PortalException
{
ChannelState state=(ChannelState)stateTable.get(uid);
if (state == null)
log.error("CWebProxy:renderXML() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
Document xml = null;
String tidiedXml = null;
try
{
if (state.tidy != null && state.tidy.equals("on"))
tidiedXml = getTidiedXml(state.fullxmlUri, state);
else
xml = getXml(state.fullxmlUri, state);
}
catch (Exception e)
{
throw new GeneralRenderingException ("Problem retrieving contents of " + state.fullxmlUri + ". Please restart channel. ", e, false, true);
}
state.runtimeData.put("baseActionURL", state.runtimeData.getBaseActionURL());
state.runtimeData.put("downloadActionURL", state.runtimeData.getBaseWorkerURL("download"));
// Runtime data parameters are handed to the stylesheet.
// Add any static data parameters so it gets a full set of variables.
// We may wish to remove this feature since we don't need it for
// the default stylesheets now.
if (state.xmlUri != null)
state.runtimeData.put("cw_xml", state.xmlUri);
if (state.sslUri != null)
state.runtimeData.put("cw_ssl", state.sslUri);
if (state.xslTitle != null)
state.runtimeData.put("cw_xslTitle", state.xslTitle);
if (state.xslUri != null)
state.runtimeData.put("cw_xsl", state.xslUri);
if (state.passThrough != null)
state.runtimeData.put("cw_passThrough", state.passThrough);
if (state.tidy != null)
state.runtimeData.put("cw_tidy", state.tidy);
if (state.infoUri != null)
state.runtimeData.put("cw_info", state.infoUri);
if (state.helpUri != null)
state.runtimeData.put("cw_help", state.helpUri);
if (state.editUri != null)
state.runtimeData.put("cw_edit", state.editUri);
if (state.person != null)
state.runtimeData.put("cw_person", state.person);
if (state.personAllow != null)
state.runtimeData.put("cw_personAllow", state.personAllow);
XSLT xslt = XSLT.getTransformer(this, state.runtimeData.getLocales());
if (tidiedXml != null)
xslt.setXML(tidiedXml);
else
xslt.setXML(xml);
if (state.xslUri != null && (!state.xslUri.trim().equals("")))
xslt.setXSL(state.xslUri);
else
xslt.setXSL(state.sslUri, state.xslTitle, state.runtimeData.getBrowserInfo());
// Determine mime type
MediaManager mm = new MediaManager();
String media = mm.getMedia(state.runtimeData.getBrowserInfo());
String mimeType = mm.getReturnMimeType(media);
if (MediaManager.UNKNOWN.equals(mimeType)) {
String accept = state.runtimeData.getBrowserInfo().getHeader("accept");
if (accept != null && accept.indexOf("text/html") != -1) {
mimeType = "text/html";
}
}
CWebProxyURLFilter filter2 = CWebProxyURLFilter.newCWebProxyURLFilter(mimeType, state.runtimeData, out);
AbsoluteURLFilter filter1 = AbsoluteURLFilter.newAbsoluteURLFilter(mimeType, state.xmlUri, filter2);
xslt.setTarget(filter1);
xslt.setStylesheetParameters(state.runtimeData);
xslt.transform();
}
}
/**
* Get the contents of a URI as a Document object. This is used if tidy
* is not set or equals 'off'.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a Document object
*/
private Document getXml(String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(false);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
DTDResolver dtdResolver = new DTDResolver();
docBuilder.setEntityResolver(dtdResolver);
InputStream is = urlConnect.getInputStream();
Document doc;
try {
doc = docBuilder.parse(is);
} finally {
is.close();
}
return (doc);
}
/**
* Get the contents of a URI as a String but send it through tidy first.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a String
*/
private String getTidiedXml(String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
// get character encoding from Content-Type header
String encoding = null;
String ct = urlConnect.getContentType();
int i;
if (ct!=null && (i=ct.indexOf("charset="))!=-1)
{
encoding = ct.substring(i+8).trim();
if ((i=encoding.indexOf(";"))!=-1)
encoding = encoding.substring(0,i).trim();
if (encoding.indexOf("\"")!=-1)
encoding = encoding.substring(1,encoding.length()+1);
}
Tidy tidy = new Tidy ();
tidy.setXHTML (true);
tidy.setDocType ("omit");
tidy.setQuiet(true);
tidy.setShowWarnings(false);
tidy.setNumEntities(true);
tidy.setWord2000(true);
// If charset is specified in header, set JTidy's
// character encoding to either UTF-8, ISO-8859-1
// or ISO-2022 accordingly (NOTE that these are
// the only character encoding sets that are supported in
// JTidy). If character encoding is not specified,
// UTF-8 is the default.
if (encoding != null)
{
if (encoding.toLowerCase().equals("iso-8859-1"))
tidy.setCharEncoding(org.w3c.tidy.Configuration.LATIN1);
else if (encoding.toLowerCase().equals("iso-2022-jp"))
tidy.setCharEncoding(org.w3c.tidy.Configuration.ISO2022);
else
tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
}
else
{
tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
}
tidy.setErrout(devNull);
ByteArrayOutputStream stream = new ByteArrayOutputStream (1024);
BufferedOutputStream out = new BufferedOutputStream (stream);
tidy.parse (urlConnect.getInputStream(), out);
String tidiedXml = stream.toString();
stream.close();
out.close();
if ( tidy.getParseErrors() > 0 )
throw new GeneralRenderingException("Unable to convert input document to XHTML");
return tidiedXml;
}
private URLConnection getConnection(String uri, ChannelState state) throws Exception
{
// before making the connection, ensure all spaces in the URI are encoded
// (Note that URLEncoder.encode(String uri) cannot be used because
// this method encodes everything, including forward slashes and
// forward slashes are used for determining if the URL is
// relative or absolute)
uri = uri.trim();
if (uri.indexOf(" ") != -1)
{
StringBuffer sbuff = new StringBuffer();
int i;
while( (i= uri.indexOf(" ")) != -1)
{
sbuff.append(uri.substring(0, i));
sbuff.append("%20");
uri = uri.substring(i+1);
}
sbuff.append(uri);
uri = sbuff.toString();
}
// String.replaceAll(String,String) - since jdk 1.4
//uri = uri.replaceAll(" ", "%20");
URL url;
if (state.localConnContext != null)
url = ResourceLoader.getResourceAsURL(this.getClass(), state.localConnContext.getDescriptor(uri, state.runtimeData));
else
url = ResourceLoader.getResourceAsURL(this.getClass(), uri);
// get info from url for cookies
String domain = url.getHost().trim();
String path = url.getPath();
if ( path.indexOf("/") != -1 )
{
if (path.lastIndexOf("/") != 0)
path = path.substring(0, path.lastIndexOf("/"));
}
String port = Integer.toString(url.getPort());
//get connection
URLConnection urlConnect = url.openConnection();
String protocol = url.getProtocol();
if (protocol.equals("http") || protocol.equals("https"))
{
if (domain != null && path != null)
{
//prepare the connection by setting properties and sending data
HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
httpUrlConnect.setInstanceFollowRedirects(false);
//send any cookie headers to proxied application
if(state.cookieCutter.cookiesExist())
state.cookieCutter.sendCookieHeader(httpUrlConnect, domain, path, port);
//set connection properties if request method was post
if (state.runtimeData.getHttpRequestMethod().equals("POST"))
{
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals("")))
{
httpUrlConnect.setRequestMethod("POST");
httpUrlConnect.setAllowUserInteraction(false);
httpUrlConnect.setDoOutput(true);
}
}
//send local data, if required
//can call getOutputStream in sendLocalData (ie. to send post params)
//(getOutputStream can be called twice on an HttpURLConnection)
if (state.localConnContext != null)
{
try
{
state.localConnContext.sendLocalData(httpUrlConnect, state.runtimeData);
}
catch (Exception e)
{
log.error( "CWebProxy: Unable to send data through " + state.runtimeData.getParameter("upc_localConnContext"), e);
}
}
//send the request parameters by post, if required
//at this point, set or send methods cannot be called on the connection
//object (they must be called before sendLocalData)
if (state.runtimeData.getHttpRequestMethod().equals("POST")){
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals(""))){
PrintWriter post = new PrintWriter(httpUrlConnect.getOutputStream());
post.print(state.reqParameters);
post.flush();
post.close();
state.reqParameters=null;
}
}
//receive cookie headers
state.cookieCutter.storeCookieHeader(httpUrlConnect, domain, path, port);
int status = httpUrlConnect.getResponseCode();
String location = httpUrlConnect.getHeaderField("Location");
switch (status)
{
case HttpURLConnection.HTTP_NOT_FOUND:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 404: Not Found");
case HttpURLConnection.HTTP_FORBIDDEN:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 403: Forbidden");
case HttpURLConnection.HTTP_INTERNAL_ERROR:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 500: Internal Server Error");
case HttpURLConnection.HTTP_NO_CONTENT:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 204: No Content");
/*
* Note: these cases apply to http status codes 302 and 303
* this will handle automatic redirection to a new GET URL
*/
case HttpURLConnection.HTTP_MOVED_TEMP:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
case HttpURLConnection.HTTP_SEE_OTHER:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
/*
* Note: this cases apply to http status code 301
* it will handle the automatic redirection of GET requests.
* The spec calls for a POST redirect to be verified manually by the user
* Rather than bypass this security restriction, we will throw an exception
*/
case HttpURLConnection.HTTP_MOVED_PERM:
if (state.runtimeData.getHttpRequestMethod().equals("GET")){
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
}
else {
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 301: POST Redirection currently not supported");
}
break;
default:
break;
}
return (URLConnection) httpUrlConnect;
}
}
return urlConnect;
}
public ChannelCacheKey generateKey(String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
log.error("CWebProxy:generateKey() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return null;
}
if ( state.cacheMode.equalsIgnoreCase("none") )
return null;
// else if http see first if caching is on or off. if it's on,
// store the validity time in the state, cache it, and further
// resolve later with isValid.
// check cache-control, no-cache, must-revalidate, max-age,
// Date & Expires, expiry in past
// for 1.0 check pragma for no-cache
// add a warning to docs about not a full http 1.1 impl.
ChannelCacheKey k = new ChannelCacheKey();
StringBuffer sbKey = new StringBuffer(1024);
// Only INSTANCE scope is currently supported.
k.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
sbKey.append("sslUri:").append(state.sslUri).append(", ");
// xslUri may either be specified as a parameter to this channel
// or we will get it by looking in the stylesheet list file
String xslUriForKey = state.xslUri;
try {
if (xslUriForKey == null) {
String sslUri = ResourceLoader.getResourceAsURLString(this.getClass(), state.sslUri);
xslUriForKey = XSLT.getStylesheetURI(sslUri, state.runtimeData.getBrowserInfo());
}
} catch (Exception e) {
xslUriForKey = "Not attainable: " + e;
}
sbKey.append("xslUri:").append(xslUriForKey).append(", ");
sbKey.append("key:").append(state.key).append(", ");
sbKey.append("passThrough:").append(state.passThrough).append(", ");
sbKey.append("tidy:").append(state.tidy).append(", ");
sbKey.append("person:").append(state.person);
k.setKey(sbKey.toString());
k.setKeyValidity(new Long(System.currentTimeMillis()));
//log.debug("CWebProxy:generateKey("
// + uid + ") : cachekey=\"" + sbKey.toString() + "\"");
return k;
}
static PrintWriter getErrout() throws FileNotFoundException
{
if (System.getProperty("os.name").indexOf("Windows") != -1)
return new PrintWriter(new FileOutputStream("nul"));
else
return new PrintWriter(new FileOutputStream("/dev/null"));
}
public boolean isCacheValid(Object validity,String uid)
{
if (!(validity instanceof Long))
return false;
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
log.error("CWebProxy:isCacheValid() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return false;
}
else
return (System.currentTimeMillis() - ((Long)validity).longValue() < state.cacheTimeout*1000);
}
public String getContentType(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
return state.connHolder.getContentType();
}
public InputStream getInputStream(String uid) throws IOException {
ChannelState state = (ChannelState)stateTable.get(uid);
InputStream rs = state.connHolder.getInputStream();
state.connHolder = null;
return rs;
}
public void downloadData(OutputStream out,String uid) throws IOException {
throw(new IOException("CWebProxy: donloadData method not supported - use getInputStream only"));
}
public String getName(String uid) {
return "proxyDL";
}
public Map getHeaders(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
try {
state.connHolder= getConnection(state.fullxmlUri, state);
}
catch (Exception e){
log.error(e, e);
}
Map rhdrs = new HashMap();
int i = 0;
while (state.connHolder.getHeaderFieldKey(i) != null){
rhdrs.put(state.connHolder.getHeaderFieldKey(i),state.connHolder.getHeaderField(i));
i++;
}
return rhdrs;
}
public void reportDownloadError(Exception e) {
// We really should report this to the user somehow??
log.error(e.getMessage(), e);
}
}
|
package org.jasig.portal.channels.webproxy;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jasig.portal.ChannelCacheKey;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.GeneralRenderingException;
import org.jasig.portal.IMultithreadedCacheable;
import org.jasig.portal.IMultithreadedChannel;
import org.jasig.portal.IMultithreadedMimeResponse;
import org.jasig.portal.MediaManager;
import org.jasig.portal.PortalEvent;
import org.jasig.portal.PortalException;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.ResourceMissingException;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.LocalConnectionContext;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.AbsoluteURLFilter;
import org.jasig.portal.utils.CookieCutter;
import org.jasig.portal.utils.DTDResolver;
import org.jasig.portal.utils.ResourceLoader;
import org.jasig.portal.utils.XSLT;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xml.sax.ContentHandler;
/**
* <p>A channel which transforms and interacts with dynamic XML or HTML.
* See docs/website/developers/channel_docs/reference/CwebProxy.html
* for full documentation.
* </p>
*
* <p>Static Channel Parameters:
* Except where indicated, static parameters can be updated by equivalent
* Runtime parameters. Caching parameters can also be changed temporarily.
* Cache defaults and IPerson restrictions are loaded first from properties,
* and overridden by static data if there.
* </p>
* <ol>
* <li>"cw_xml" - a URI for the source XML document
* <li>"cw_ssl" - a URI for the corresponding .ssl (stylesheet list) file
* <li>"cw_xslTitle" - a title representing the stylesheet (optional)
* <i>If no title parameter is specified, a default
* stylesheet will be chosen according to the media</i>
* <li>"cw_xsl" - a URI for the stylesheet to use
* <i>If <code>cw_xsl</code> is supplied, <code>cw_ssl</code>
* and <code>cw_xslTitle</code> will be ignored.
* <li>"cw_passThrough" - indicates how RunTimeData is to be passed through.
* <i>If <code>cw_passThrough</code> is supplied, and not set
* to "all" or "application", additional RunTimeData
* parameters not starting with "cw_" or "upc_" will be
* passed as request parameters to the XML URI. If
* <code>cw_passThrough</code> is set to "marked", this will
* happen only if there is also a RunTimeData parameter of
* <code>cw_inChannelLink</code>. "application" is intended
* to keep application-specific links in the channel, while
* "all" should keep all links in the channel. This
* distinction is handled entirely in the URL Filters.
* <li>"cw_tidy" - output from <code>xmlUri</code> will be passed though Jtidy
* <li>"cw_info" - a URI to be called for the <code>info</code> event.
* <li>"cw_help" - a URI to be called for the <code>help</code> event.
* <li>"cw_edit" - a URI to be called for the <code>edit</code> event.
* <li>"cw_cacheDefaultMode" - Default caching mode.
* <i>May be <code>none</code> (normally don't cache), or
* <code>all</code> (cache everything).
* <li>"cw_cacheDefaultTimeout" - Default timeout in seconds.
* <li>"cw_cacheMode" - override default for this request only.
* <i>Primarily intended as a runtime parameter, but can
* used statically to override the first instance.</i>
* <li>"cw_cacheTimeout" - override default for this request only.
* <i>Primarily intended as a runtime parameter, but can
* be used statically to override the first instance.</i>
* <li>"cw_person" - IPerson attributes to pass.
* <i>A comma-separated list of IPerson attributes to
* pass to the back end application. The static data
* value will be passed on </i>all<i> requests not
* overridden by a runtime data cw_person except some
* refresh requests.</i>
* <li>"cw_personAllow" - Restrict IPerson attribute passing to this list.
* <i>A comma-separated list of IPerson attributes that
* may be passed via cw_person. An empty or non-existent
* value means use the default value from the corresponding
* property. The special value "*" means all attributes
* are allowed. The value "!*" means none are allowed.
* Static data only.</i>
* <li>"upc_localConnContext" - LocalConnectionContext implementation class.
* <i>The name of a class to use when data sent to the
* backend application needs to be modified or added
* to suit local needs. Static data only.</i>
* </ol>
* <p>Runtime Channel Parameters:</p>
* The following parameters are runtime-only.
* </p>
* <ol>
* <li>"cw_reset" - an instruction to return to reset internal variables.
* <i>The value <code>return</code> resets <code>cw_xml</code>
* to its last value before changed by button events. The
* value "reset" returns all variables to the static data
* values.</i>
* <li>"cw_download" - use download worker for this link or form
* <i>any link or form that contains this parameter will be
* handled by the download worker, if the pass-through mode
* is set to rewrite the link or form. This allows downloads
* from the proxied site to be delivered via the portal,
* primarily useful if the download requires verification
* of a session referenced by a proxied cookie</i>
*
* </ol>
* <p>This channel can be used for all XML formats with appropriate stylesheets.
* All static data parameters as well as additional runtime data parameters
* passed to this channel via HttpRequest will in turn be passed on to the
* XSLT stylesheet as stylesheet parameters. They can be read in the
* stylesheet as follows:
* <code><xsl:param
* name="yourParamName">aDefaultValue</xsl:param></code>
* </p>
* @author Andrew Draskoy, andrew@mun.ca
* @author Sarah Arnott, sarnott@mun.ca
* @version $Revision$
*/
public class CWebProxy implements IMultithreadedChannel, IMultithreadedCacheable, IMultithreadedMimeResponse
{
Map stateTable;
// to prepend to the system-wide cache key
static final String systemCacheId="org.jasig.portal.channels.webproxy.CWebProxy";
// All state variables stored here
private class ChannelState
{
private int id;
private IPerson iperson;
private String person;
private String personAllow;
private HashSet personAllow_set;
private String fullxmlUri;
private String buttonxmlUri;
private String xmlUri;
private String key;
private String passThrough;
private String tidy;
private String sslUri;
private String xslTitle;
private String xslUri;
private String infoUri;
private String helpUri;
private String editUri;
private String cacheDefaultMode;
private String cacheMode;
private String reqParameters;
private long cacheDefaultTimeout;
private long cacheTimeout;
private ChannelRuntimeData runtimeData;
private CookieCutter cookieCutter;
private URLConnection connHolder;
private LocalConnectionContext localConnContext;
private int refresh;
public ChannelState ()
{
fullxmlUri = buttonxmlUri = xmlUri = key = passThrough = sslUri = null;
xslTitle = xslUri = infoUri = helpUri = editUri = tidy = null;
id = 0;
cacheMode = null;
iperson = null;
refresh = -1;
cacheTimeout = cacheDefaultTimeout = PropertiesManager.getPropertyAsLong("org.jasig.portal.channels.webproxy.CWebProxy.cache_default_timeout");
cacheMode = cacheDefaultMode = PropertiesManager.getProperty("org.jasig.portal.channels.webproxy.CWebProxy.cache_default_mode");
personAllow = PropertiesManager.getProperty("org.jasig.portal.channels.webproxy.CWebProxy.person_allow");
runtimeData = null;
cookieCutter = new CookieCutter();
localConnContext = null;
}
}
public CWebProxy ()
{
stateTable = Collections.synchronizedMap(new HashMap());
}
/**
* Passes ChannelStaticData to the channel.
* This is done during channel instantiation time.
* see org.jasig.portal.ChannelStaticData
* @param sd channel static data
* @see ChannelStaticData
*/
public void setStaticData (ChannelStaticData sd, String uid)
{
ChannelState state = new ChannelState();
state.id = sd.getPerson().getID();
state.iperson = sd.getPerson();
state.person = sd.getParameter("cw_person");
String personAllow = sd.getParameter ("cw_personAllow");
if ( personAllow != null && (!personAllow.trim().equals("")))
state.personAllow = personAllow;
// state.personAllow could have been set by a property or static data
if ( state.personAllow != null && (!state.personAllow.trim().equals("!*")) )
{
state.personAllow_set = new HashSet();
StringTokenizer st = new StringTokenizer(state.personAllow,",");
if (st != null)
{
while ( st.hasMoreElements () ) {
String pName = st.nextToken();
if (pName!=null) {
pName = pName.trim();
if (!pName.equals(""))
state.personAllow_set.add(pName);
}
}
}
}
state.xmlUri = sd.getParameter ("cw_xml");
state.sslUri = sd.getParameter ("cw_ssl");
state.xslTitle = sd.getParameter ("cw_xslTitle");
state.xslUri = sd.getParameter ("cw_xsl");
state.fullxmlUri = sd.getParameter ("cw_xml");
state.passThrough = sd.getParameter ("cw_passThrough");
state.tidy = sd.getParameter ("cw_tidy");
state.infoUri = sd.getParameter ("cw_info");
state.helpUri = sd.getParameter ("cw_help");
state.editUri = sd.getParameter ("cw_edit");
state.key = state.xmlUri;
String cacheMode = sd.getParameter ("cw_cacheDefaultMode");
if (cacheMode != null && !cacheMode.trim().equals(""))
state.cacheDefaultMode = cacheMode;
cacheMode = sd.getParameter ("cw_cacheMode");
if (cacheMode != null && !cacheMode.trim().equals(""))
state.cacheMode = cacheMode;
else
state.cacheMode = state.cacheDefaultMode;
String cacheTimeout = sd.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null && !cacheTimeout.trim().equals(""))
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = sd.getParameter("cw_cacheTimeout");
if (cacheTimeout != null && !cacheTimeout.trim().equals(""))
state.cacheTimeout = Long.parseLong(cacheTimeout);
else
state.cacheTimeout = state.cacheDefaultTimeout;
String connContext = sd.getParameter ("upc_localConnContext");
if (connContext != null && !connContext.trim().equals(""))
{
try
{
state.localConnContext = (LocalConnectionContext) Class.forName(connContext).newInstance();
state.localConnContext.init(sd);
}
catch (Exception e)
{
LogService.log(LogService.ERROR, "CWebProxy: Cannot initialize LocalConnectionContext: " + e);
}
}
stateTable.put(uid,state);
}
/**
* Passes ChannelRuntimeData to the channel.
* This function is called prior to the renderXML() call.
* @param rd channel runtime data
* @see ChannelRuntimeData
*/
public void setRuntimeData (ChannelRuntimeData rd, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
LogService.log(LogService.ERROR,"CWebProxy:setRuntimeData() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
state.runtimeData = rd;
if ( rd.isEmpty() && (state.refresh != -1) ) {
// A refresh-- State remains the same.
if ( state.buttonxmlUri != null ) {
state.key = state.buttonxmlUri;
state.fullxmlUri = state.buttonxmlUri;
state.refresh = 0;
} else {
if ( state.refresh == 0 )
state.key = state.fullxmlUri;
state.fullxmlUri = state.xmlUri;
state.refresh = 1;
}
} else {
state.refresh = 0;
String xmlUri = state.runtimeData.getParameter("cw_xml");
if (xmlUri != null) {
state.xmlUri = xmlUri;
// don't need an explicit reset if a new URI is provided.
state.buttonxmlUri = null;
}
String sslUri = state.runtimeData.getParameter("cw_ssl");
if (sslUri != null)
state.sslUri = sslUri;
String xslTitle = state.runtimeData.getParameter("cw_xslTitle");
if (xslTitle != null)
state.xslTitle = xslTitle;
String xslUri = state.runtimeData.getParameter("cw_xsl");
if (xslUri != null)
state.xslUri = xslUri;
String passThrough = state.runtimeData.getParameter("cw_passThrough");
if (passThrough != null)
state.passThrough = passThrough;
String person = state.runtimeData.getParameter("cw_person");
if (person != null)
state.person = person;
String tidy = state.runtimeData.getParameter("cw_tidy");
if (tidy != null)
state.tidy = tidy;
String infoUri = state.runtimeData.getParameter("cw_info");
if (infoUri != null)
state.infoUri = infoUri;
String editUri = state.runtimeData.getParameter("cw_edit");
if (editUri != null)
state.editUri = editUri;
String helpUri = state.runtimeData.getParameter("cw_help");
if (helpUri != null)
state.helpUri = helpUri;
String cacheTimeout = state.runtimeData.getParameter("cw_cacheDefaultTimeout");
if (cacheTimeout != null)
state.cacheDefaultTimeout = Long.parseLong(cacheTimeout);
cacheTimeout = state.runtimeData.getParameter("cw_cacheTimeout");
if (cacheTimeout != null)
state.cacheTimeout = Long.parseLong(cacheTimeout);
else
state.cacheTimeout = state.cacheDefaultTimeout;
String cacheDefaultMode = state.runtimeData.getParameter("cw_cacheDefaultMode");
if (cacheDefaultMode != null) {
state.cacheDefaultMode = cacheDefaultMode;
}
String cacheMode = state.runtimeData.getParameter("cw_cacheMode");
if (cacheMode != null) {
state.cacheMode = cacheMode;
} else
state.cacheMode = state.cacheDefaultMode;
// reset is a one-time thing.
String reset = state.runtimeData.getParameter("cw_reset");
if (reset != null) {
if (reset.equalsIgnoreCase("return")) {
state.buttonxmlUri = null;
}
}
if ( state.buttonxmlUri != null ) // shouldn't happen here, but...
state.fullxmlUri = state.buttonxmlUri;
else
{
//LogService.log(LogService.DEBUG, "CWebProxy: xmlUri is " + state.xmlUri);
// pass IPerson atts independent of the value of cw_passThrough
StringBuffer newXML = new StringBuffer();
String appendchar = "";
// here add in attributes according to cw_person
if (state.person != null && state.personAllow_set != null)
{
StringTokenizer st = new StringTokenizer(state.person,",");
if (st != null)
{
while (st.hasMoreElements ())
{
String pName = st.nextToken();
if ((pName!=null)&&(!pName.trim().equals("")))
{
if ( state.personAllow.trim().equals("*") ||
state.personAllow_set.contains(pName) )
{
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
// note, this only gets the first one if it's a
// java.util.Vector. Should check
String pVal = (String)state.iperson.getAttribute(pName);
if (pVal != null)
newXML.append(URLEncoder.encode(pVal));
}
else {
LogService.log(LogService.INFO,
"CWebProxy: request to pass " + pName + " denied.");
}
}
}
}
}
// end cw_person code
// Is this a case where we need to pass request parameters to the xmlURI?
if ( state.passThrough != null &&
!state.passThrough.equalsIgnoreCase("none") &&
( state.passThrough.equalsIgnoreCase("all") ||
state.passThrough.equalsIgnoreCase("application") ||
rd.getParameter("cw_inChannelLink") != null ) )
{
// keyword and parameter processing
// NOTE: if both exist, only keywords are appended
String keywords = rd.getKeywords();
if (keywords != null)
{
if (appendchar.equals("&"))
newXML.append("&keywords=" + keywords);
else
newXML.append(keywords);
}
else
{
// want all runtime parameters not specific to WebProxy
Enumeration e=rd.getParameterNames ();
if (e!=null)
{
while (e.hasMoreElements ())
{
String pName = (String) e.nextElement ();
if ( !pName.startsWith("cw_") && !pName.startsWith("upc_")
&& !pName.trim().equals(""))
{
String[] value_array = rd.getParameterValues(pName);
int i = 0;
while ( i < value_array.length )
{
newXML.append(appendchar);
appendchar = "&";
newXML.append(pName);
newXML.append("=");
newXML.append(URLEncoder.encode(value_array[i++].trim()));
}
}
}
}
}
}
state.reqParameters = newXML.toString();
state.fullxmlUri = state.xmlUri;
if (!state.runtimeData.getHttpRequestMethod().equals("POST"))
{
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals("")))
{
appendchar = (state.xmlUri.indexOf('?') == -1) ? "?" : "&";
state.fullxmlUri = state.fullxmlUri+appendchar+state.reqParameters;
}
state.reqParameters = null;
}
//LogService.log(LogService.DEBUG, "CWebProxy: fullxmlUri now: " + state.fullxmlUri);
}
// set key for cache based on request parameters
// NOTE: POST requests are not idempotent and therefore are not
// retrievable from the cache
if (!state.runtimeData.getHttpRequestMethod().equals("POST"))
state.key = state.fullxmlUri;
else //generate a unique string as key
state.key = String.valueOf((new Date()).getTime());
}
}
}
/**
* Process portal events. Currently supported events are
* EDIT_BUTTON_EVENT, HELP_BUTTON_EVENT, ABOUT_BUTTON_EVENT,
* and SESSION_DONE. The button events work by changing the xmlUri.
* The new Uri's content should contain a link that will refer back
* to the old one at the end of its task.
* @param ev the event
*/
public void receiveEvent (PortalEvent ev, String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
LogService.log(LogService.ERROR,"CWebProxy:receiveEvent() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else {
int evnum = ev.getEventNumber();
switch (evnum)
{
case PortalEvent.EDIT_BUTTON_EVENT:
if (state.editUri != null)
state.buttonxmlUri = state.editUri;
break;
case PortalEvent.HELP_BUTTON_EVENT:
if (state.helpUri != null)
state.buttonxmlUri = state.helpUri;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
if (state.infoUri != null)
state.buttonxmlUri = state.infoUri;
break;
case PortalEvent.SESSION_DONE:
stateTable.remove(uid);
break;
// case PortalEvent.UNSUBSCRIBE:
default:
break;
}
}
}
/**
* Acquires ChannelRuntimeProperites from the channel.
* This function may be called by the portal framework throughout the session.
* @see ChannelRuntimeProperties
*/
public ChannelRuntimeProperties getRuntimeProperties (String uid)
{
ChannelRuntimeProperties rp=new ChannelRuntimeProperties();
// determine if such channel is registered
if (stateTable.get(uid) == null)
{
rp.setWillRender(false);
LogService.log(LogService.ERROR,"CWebProxy:getRuntimeProperties() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
}
return rp;
}
/**
* Ask channel to render its content.
* @param out the SAX ContentHandler to output content to
*/
public void renderXML (ContentHandler out, String uid) throws PortalException
{
ChannelState state=(ChannelState)stateTable.get(uid);
if (state == null)
LogService.log(LogService.ERROR,"CWebProxy:renderXML() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
else
{
Document xml = null;
String tidiedXml = null;
try
{
if (state.tidy != null && state.tidy.equals("on"))
tidiedXml = getTidiedXml(state.fullxmlUri, state);
else
xml = getXml(state.fullxmlUri, state);
}
catch (Exception e)
{
throw new GeneralRenderingException ("Problem retrieving contents of " + state.fullxmlUri + ". Please restart channel. ", e, false, true);
}
state.runtimeData.put("baseActionURL", state.runtimeData.getBaseActionURL());
state.runtimeData.put("downloadActionURL", state.runtimeData.getBaseWorkerURL("download"));
// Runtime data parameters are handed to the stylesheet.
// Add any static data parameters so it gets a full set of variables.
// We may wish to remove this feature since we don't need it for
// the default stylesheets now.
if (state.xmlUri != null)
state.runtimeData.put("cw_xml", state.xmlUri);
if (state.sslUri != null)
state.runtimeData.put("cw_ssl", state.sslUri);
if (state.xslTitle != null)
state.runtimeData.put("cw_xslTitle", state.xslTitle);
if (state.xslUri != null)
state.runtimeData.put("cw_xsl", state.xslUri);
if (state.passThrough != null)
state.runtimeData.put("cw_passThrough", state.passThrough);
if (state.tidy != null)
state.runtimeData.put("cw_tidy", state.tidy);
if (state.infoUri != null)
state.runtimeData.put("cw_info", state.infoUri);
if (state.helpUri != null)
state.runtimeData.put("cw_help", state.helpUri);
if (state.editUri != null)
state.runtimeData.put("cw_edit", state.editUri);
if (state.person != null)
state.runtimeData.put("cw_person", state.person);
if (state.personAllow != null)
state.runtimeData.put("cw_personAllow", state.personAllow);
XSLT xslt = XSLT.getTransformer(this, state.runtimeData.getLocales());
if (tidiedXml != null)
xslt.setXML(tidiedXml);
else
xslt.setXML(xml);
if (state.xslUri != null && (!state.xslUri.trim().equals("")))
xslt.setXSL(state.xslUri);
else
xslt.setXSL(state.sslUri, state.xslTitle, state.runtimeData.getBrowserInfo());
// Determine mime type
MediaManager mm = new MediaManager();
String media = mm.getMedia(state.runtimeData.getBrowserInfo());
String mimeType = mm.getReturnMimeType(media);
if (MediaManager.UNKNOWN.equals(mimeType)) {
String accept = state.runtimeData.getBrowserInfo().getHeader("accept");
if (accept != null && accept.indexOf("text/html") != -1) {
mimeType = "text/html";
}
}
CWebProxyURLFilter filter2 = CWebProxyURLFilter.newCWebProxyURLFilter(mimeType, state.runtimeData, out);
AbsoluteURLFilter filter1 = AbsoluteURLFilter.newAbsoluteURLFilter(mimeType, state.xmlUri, filter2);
xslt.setTarget(filter1);
xslt.setStylesheetParameters(state.runtimeData);
xslt.transform();
}
}
/**
* Get the contents of a URI as a Document object. This is used if tidy
* is not set or equals 'off'.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a Document object
*/
private Document getXml(String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(false);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
DTDResolver dtdResolver = new DTDResolver();
docBuilder.setEntityResolver(dtdResolver);
return docBuilder.parse(urlConnect.getInputStream());
}
/**
* Get the contents of a URI as a String but send it through tidy first.
* Also includes support for cookies.
* @param uri the URI
* @return the data pointed to by a URI as a String
*/
private String getTidiedXml(String uri, ChannelState state) throws Exception
{
URLConnection urlConnect = getConnection(uri, state);
// get character encoding from Content-Type header
String encoding = null;
String ct = urlConnect.getContentType();
int i;
if (ct!=null && (i=ct.indexOf("charset="))!=-1)
{
encoding = ct.substring(i+8).trim();
if ((i=encoding.indexOf(";"))!=-1)
encoding = encoding.substring(0,i).trim();
if (encoding.indexOf("\"")!=-1)
encoding = encoding.substring(1,encoding.length()+1);
}
Tidy tidy = new Tidy ();
tidy.setXHTML (true);
tidy.setDocType ("omit");
tidy.setQuiet(true);
tidy.setShowWarnings(false);
tidy.setNumEntities(true);
tidy.setWord2000(true);
// If charset is specified in header, set JTidy's
// character encoding to either UTF-8, ISO-8859-1
// or ISO-2022 accordingly (NOTE that these are
// the only character encoding sets that are supported in
// JTidy). If character encoding is not specified,
// UTF-8 is the default.
if (encoding != null)
{
if (encoding.toLowerCase().equals("iso-8859-1"))
tidy.setCharEncoding(org.w3c.tidy.Configuration.LATIN1);
else if (encoding.toLowerCase().equals("iso-2022-jp"))
tidy.setCharEncoding(org.w3c.tidy.Configuration.ISO2022);
else
tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
}
else
{
tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8);
}
PrintWriter pw;
if ( System.getProperty("os.name").indexOf("Windows") != -1 )
{
pw = new PrintWriter(new FileOutputStream("nul"));
tidy.setErrout(pw);
}
else
{
pw = new PrintWriter(new FileOutputStream("/dev/null"));
tidy.setErrout(pw);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream (1024);
BufferedOutputStream out = new BufferedOutputStream (stream);
tidy.parse (urlConnect.getInputStream(), out);
pw.close();
String tidiedXml = stream.toString();
stream.close();
out.close();
if ( tidy.getParseErrors() > 0 )
throw new GeneralRenderingException("Unable to convert input document to XHTML");
return tidiedXml;
}
private URLConnection getConnection(String uri, ChannelState state) throws Exception
{
// before making the connection, ensure all spaces in the URI are encoded
// (Note that URLEncoder.encode(String uri) cannot be used because
// this method encodes everything, including forward slashes and
// forward slashes are used for determining if the URL is
// relative or absolute)
uri = uri.trim();
if (uri.indexOf(" ") != -1)
{
StringBuffer sbuff = new StringBuffer();
int i;
while( (i= uri.indexOf(" ")) != -1)
{
sbuff.append(uri.substring(0, i));
sbuff.append("%20");
uri = uri.substring(i+1);
}
sbuff.append(uri);
uri = sbuff.toString();
}
// String.replaceAll(String,String) - since jdk 1.4
//uri = uri.replaceAll(" ", "%20");
URL url;
if (state.localConnContext != null)
url = ResourceLoader.getResourceAsURL(this.getClass(), state.localConnContext.getDescriptor(uri, state.runtimeData));
else
url = ResourceLoader.getResourceAsURL(this.getClass(), uri);
// get info from url for cookies
String domain = url.getHost().trim();
String path = url.getPath();
if ( path.indexOf("/") != -1 )
{
if (path.lastIndexOf("/") != 0)
path = path.substring(0, path.lastIndexOf("/"));
}
String port = Integer.toString(url.getPort());
//get connection
URLConnection urlConnect = url.openConnection();
String protocol = url.getProtocol();
if (protocol.equals("http") || protocol.equals("https"))
{
if (domain != null && path != null)
{
//prepare the connection by setting properties and sending data
HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
httpUrlConnect.setInstanceFollowRedirects(false);
//send any cookie headers to proxied application
if(state.cookieCutter.cookiesExist())
state.cookieCutter.sendCookieHeader(httpUrlConnect, domain, path, port);
//set connection properties if request method was post
if (state.runtimeData.getHttpRequestMethod().equals("POST"))
{
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals("")))
{
httpUrlConnect.setRequestMethod("POST");
httpUrlConnect.setAllowUserInteraction(false);
httpUrlConnect.setDoOutput(true);
}
}
//send local data, if required
//can call getOutputStream in sendLocalData (ie. to send post params)
//(getOutputStream can be called twice on an HttpURLConnection)
if (state.localConnContext != null)
{
try
{
state.localConnContext.sendLocalData(httpUrlConnect, state.runtimeData);
}
catch (Exception e)
{
LogService.log(LogService.ERROR, "CWebProxy: Unable to send data through " + state.runtimeData.getParameter("upc_localConnContext") + ": " + e.getMessage());
}
}
//send the request parameters by post, if required
//at this point, set or send methods cannot be called on the connection
//object (they must be called before sendLocalData)
if (state.runtimeData.getHttpRequestMethod().equals("POST")){
if ((state.reqParameters!=null) && (!state.reqParameters.trim().equals(""))){
PrintWriter post = new PrintWriter(httpUrlConnect.getOutputStream());
post.print(state.reqParameters);
post.flush();
post.close();
state.reqParameters=null;
}
}
//receive cookie headers
state.cookieCutter.storeCookieHeader(httpUrlConnect, domain, path, port);
int status = httpUrlConnect.getResponseCode();
String location = httpUrlConnect.getHeaderField("Location");
switch (status)
{
case HttpURLConnection.HTTP_NOT_FOUND:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 404: Not Found");
case HttpURLConnection.HTTP_FORBIDDEN:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 403: Forbidden");
case HttpURLConnection.HTTP_INTERNAL_ERROR:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 500: Internal Server Error");
case HttpURLConnection.HTTP_NO_CONTENT:
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 204: No Content");
/*
* Note: these cases apply to http status codes 302 and 303
* this will handle automatic redirection to a new GET URL
*/
case HttpURLConnection.HTTP_MOVED_TEMP:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
case HttpURLConnection.HTTP_SEE_OTHER:
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
break;
/*
* Note: this cases apply to http status code 301
* it will handle the automatic redirection of GET requests.
* The spec calls for a POST redirect to be verified manually by the user
* Rather than bypass this security restriction, we will throw an exception
*/
case HttpURLConnection.HTTP_MOVED_PERM:
if (state.runtimeData.getHttpRequestMethod().equals("GET")){
httpUrlConnect.disconnect();
httpUrlConnect = (HttpURLConnection) getConnection(location,state);
}
else {
throw new ResourceMissingException
(httpUrlConnect.getURL().toExternalForm(),
"", "HTTP Status-Code 301: POST Redirection currently not supported");
}
break;
default:
break;
}
return (URLConnection) httpUrlConnect;
}
}
return urlConnect;
}
public ChannelCacheKey generateKey(String uid)
{
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
LogService.log(LogService.ERROR,"CWebProxy:generateKey() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return null;
}
if ( state.cacheMode.equalsIgnoreCase("none") )
return null;
// else if http see first if caching is on or off. if it's on,
// store the validity time in the state, cache it, and further
// resolve later with isValid.
// check cache-control, no-cache, must-revalidate, max-age,
// Date & Expires, expiry in past
// for 1.0 check pragma for no-cache
// add a warning to docs about not a full http 1.1 impl.
ChannelCacheKey k = new ChannelCacheKey();
StringBuffer sbKey = new StringBuffer(1024);
// Only INSTANCE scope is currently supported.
k.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
sbKey.append("sslUri:").append(state.sslUri).append(", ");
// xslUri may either be specified as a parameter to this channel
// or we will get it by looking in the stylesheet list file
String xslUriForKey = state.xslUri;
try {
if (xslUriForKey == null) {
String sslUri = ResourceLoader.getResourceAsURLString(this.getClass(), state.sslUri);
xslUriForKey = XSLT.getStylesheetURI(sslUri, state.runtimeData.getBrowserInfo());
}
} catch (Exception e) {
xslUriForKey = "Not attainable: " + e;
}
sbKey.append("xslUri:").append(xslUriForKey).append(", ");
sbKey.append("key:").append(state.key).append(", ");
sbKey.append("passThrough:").append(state.passThrough).append(", ");
sbKey.append("tidy:").append(state.tidy).append(", ");
sbKey.append("person:").append(state.person);
k.setKey(sbKey.toString());
k.setKeyValidity(new Long(System.currentTimeMillis()));
//LogService.log(LogService.DEBUG,"CWebProxy:generateKey("
// + uid + ") : cachekey=\"" + sbKey.toString() + "\"");
return k;
}
public boolean isCacheValid(Object validity,String uid)
{
if (!(validity instanceof Long))
return false;
ChannelState state = (ChannelState)stateTable.get(uid);
if (state == null)
{
LogService.log(LogService.ERROR,"CWebProxy:isCacheValid() : attempting to access a non-established channel! setStaticData() hasn't been called on uid=\""+uid+"\"");
return false;
}
else
return (System.currentTimeMillis() - ((Long)validity).longValue() < state.cacheTimeout*1000);
}
public String getContentType(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
return state.connHolder.getContentType();
}
public InputStream getInputStream(String uid) throws IOException {
ChannelState state = (ChannelState)stateTable.get(uid);
InputStream rs = state.connHolder.getInputStream();
state.connHolder = null;
return rs;
}
public void downloadData(OutputStream out,String uid) throws IOException {
throw(new IOException("CWebProxy: donloadData method not supported - use getInputStream only"));
}
public String getName(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
return "proxyDL";
}
public Map getHeaders(String uid) {
ChannelState state = (ChannelState)stateTable.get(uid);
try {
state.connHolder= getConnection(state.fullxmlUri, state);
}
catch (Exception e){
LogService.log(LogService.ERROR,e);
}
Map rhdrs = new HashMap();
int i = 0;
while (state.connHolder.getHeaderFieldKey(i) != null){
rhdrs.put(state.connHolder.getHeaderFieldKey(i),state.connHolder.getHeaderField(i));
i++;
}
return rhdrs;
}
public void reportDownloadError(Exception e) {
// We really should report this to the user somehow??
LogService.log(LogService.ERROR, "CWebProxy::reportDownloadError(): " + e.getMessage());
}
}
|
package com.huettermann.all;
public class Main {
//here the start
public static void main ( String[] args ) {
System.out.println("hallo");
System.out.println("hallo");
for (int i = 10; i < 10; i++) {
}
int[] a = new int[10];
a[9] = 0;
a[8] = 1;
for (int i = 7; i >= 0; i
a[i] = a[i+2] + a[i+1];
}
System.out.println(a[0]);
int f(int i) {
if (i == 0 || i == 1) return i;
return f(i - 2) + f(i - 1);
}
System.out.println(f(9));
int[] a = {34, 21, 13, 8, 5, 3, 2, 1, 1, 0};
System.out.println(a[0]);
int[] b = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println(b[9]);
}
//private constructor
private Main() {}
}
|
package org.sagebionetworks.bridge.crypto;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.salt.RandomSaltGenerator;
public class BridgeEncryptor implements StringEncryptor {
private final StringEncryptor encryptor;
public BridgeEncryptor(String password) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setProvider(new BouncyCastleProvider());
encryptor.setAlgorithm("PBEWITHSHAAND256BITAES-CBC-BC");
encryptor.setPassword(password);
encryptor.setSaltGenerator(new RandomSaltGenerator());
this.encryptor = encryptor;
}
public String encrypt(String string) {
return encryptor.encrypt(string);
}
public String decrypt(String string) {
return encryptor.decrypt(string);
}
}
|
package org.sagebionetworks.bridge.services;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.dao.SurveyDao;
import org.sagebionetworks.bridge.exceptions.BadRequestException;
import org.sagebionetworks.bridge.exceptions.ConstraintViolationException;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.exceptions.PublishedSurveyException;
import org.sagebionetworks.bridge.json.DateUtils;
import org.sagebionetworks.bridge.models.ClientInfo;
import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder;
import org.sagebionetworks.bridge.models.schedules.Activity;
import org.sagebionetworks.bridge.models.schedules.CompoundActivity;
import org.sagebionetworks.bridge.models.schedules.Schedule;
import org.sagebionetworks.bridge.models.schedules.SchedulePlan;
import org.sagebionetworks.bridge.models.schedules.SurveyReference;
import org.sagebionetworks.bridge.models.sharedmodules.SharedModuleMetadata;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import org.sagebionetworks.bridge.models.surveys.Survey;
import org.sagebionetworks.bridge.models.surveys.SurveyElement;
import org.sagebionetworks.bridge.validators.SurveyPublishValidator;
import org.sagebionetworks.bridge.validators.SurveySaveValidator;
import org.sagebionetworks.bridge.validators.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Validator;
@Component
public class SurveyService {
private Validator publishValidator;
private SurveyDao surveyDao;
private SchedulePlanService schedulePlanService;
private SharedModuleMetadataService sharedModuleMetadataService;
private StudyService studyService;
@Autowired
final void setSurveyDao(SurveyDao surveyDao) {
this.surveyDao = surveyDao;
}
@Autowired
final void setPublishValidator(SurveyPublishValidator validator) {
this.publishValidator = validator;
}
@Autowired
final void setSchedulePlanService(SchedulePlanService schedulePlanService) {
this.schedulePlanService = schedulePlanService;
}
@Autowired
public final void setSharedModuleMetadataService(SharedModuleMetadataService sharedModuleMetadataService) {
this.sharedModuleMetadataService = sharedModuleMetadataService;
}
@Autowired
public final void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
/**
* Get a list of all published surveys in this study, using the most recently published version of each survey.
* These surveys will include questions (not other element types, such as info screens). Most properties beyond
* identifiers will be removed from these surveys as they are returned in the API.
*
* @param studyIdentifier
* @return
*/
public Survey getSurvey(GuidCreatedOnVersionHolder keys) {
checkArgument(StringUtils.isNotBlank(keys.getGuid()), "Survey GUID cannot be null/blank");
checkArgument(keys.getCreatedOn() != 0L, "Survey createdOn timestamp cannot be 0");
return surveyDao.getSurvey(keys);
}
/**
* Create a survey.
*
* @param survey
* @return
*/
public Survey createSurvey(Survey survey) {
checkNotNull(survey, "Survey cannot be null");
survey.setGuid(BridgeUtils.generateGuid());
for (SurveyElement element : survey.getElements()) {
element.setGuid(BridgeUtils.generateGuid());
}
Set<String> dataGroups = Collections.emptySet();
if (survey.getStudyIdentifier() != null) {
Study study = studyService.getStudy(survey.getStudyIdentifier());
dataGroups = study.getDataGroups();
}
Validate.entityThrowingException(new SurveySaveValidator(dataGroups), survey);
return surveyDao.createSurvey(survey);
}
/**
* Update an existing survey.
*
* @param survey
* @return
*/
public Survey updateSurvey(Survey survey) {
checkNotNull(survey, "Survey cannot be null");
Set<String> dataGroups = Collections.emptySet();
if (survey.getStudyIdentifier() != null) {
Study study = studyService.getStudy(survey.getStudyIdentifier());
dataGroups = study.getDataGroups();
}
Validate.entityThrowingException(new SurveySaveValidator(dataGroups), survey);
return surveyDao.updateSurvey(survey);
}
public Survey publishSurvey(StudyIdentifier study, GuidCreatedOnVersionHolder keys, boolean newSchemaRev) {
checkArgument(StringUtils.isNotBlank(keys.getGuid()), "Survey GUID cannot be null/blank");
checkArgument(keys.getCreatedOn() != 0L, "Survey createdOn timestamp cannot be 0");
Survey survey = surveyDao.getSurvey(keys);
Validate.entityThrowingException(publishValidator, survey);
return surveyDao.publishSurvey(study, survey, keys, newSchemaRev);
}
/**
* Copy the survey and return a new version of it.
*
* @param keys
* @return
*/
public Survey versionSurvey(GuidCreatedOnVersionHolder keys) {
checkArgument(StringUtils.isNotBlank(keys.getGuid()), "Survey GUID cannot be null/blank");
checkArgument(keys.getCreatedOn() != 0L, "Survey createdOn timestamp cannot be 0");
return surveyDao.versionSurvey(keys);
}
/**
* Logically delete this survey (mark it deleted and do not return it from any list-based APIs; continue
* to provide it when the version is specifically referenced). Once a survey is published, you cannot
* delete it, because we do not know if it has already been dereferenced in scheduled activities. Any
* survey version that could have been sent to users will remain in the API so you can look at its
* schema, etc. This is how study developers should delete surveys.
*/
public void deleteSurvey(GuidCreatedOnVersionHolder keys) {
checkArgument(StringUtils.isNotBlank(keys.getGuid()), "Survey GUID cannot be null/blank");
checkArgument(keys.getCreatedOn() != 0L, "Survey createdOn timestamp cannot be 0");
Survey existing = surveyDao.getSurvey(keys);
if (existing.isDeleted()) {
throw new EntityNotFoundException(Survey.class);
}
if (existing.isPublished()) {
throw new PublishedSurveyException(existing);
}
// verify if a shared module refers to it
verifySharedModuleExistence(keys);
surveyDao.deleteSurvey(existing);
}
/**
* <p>Physically remove the survey from the database. This API is mostly for test and early development
* clean up, so it ignores the publication flag, however, we do enforce some constraints:</p>
* <ol>
* <li>if a schedule references a specific survey version, don't allow it to be deleted. You can't
* make these through the Bridge Study Manager, but they're allowable in the API;</li>
*
* <li>if a schedule references the most-recently published version of a survey, verify this delete
* is not removing the last published instance of the survey. This is the more common case
* right now.</li>
* </ol>
*/
public void deleteSurveyPermanently(StudyIdentifier studyId, GuidCreatedOnVersionHolder keys) {
checkArgument(StringUtils.isNotBlank(keys.getGuid()), "Survey GUID cannot be null/blank");
checkArgument(keys.getCreatedOn() != 0L, "Survey createdOn timestamp cannot be 0");
checkConstraintsBeforePhysicalDelete(studyId, keys);
surveyDao.deleteSurveyPermanently(keys);
}
// Helper method to verify if there is any shared module related to specified survey
private void verifySharedModuleExistence(GuidCreatedOnVersionHolder keys) {
List<SharedModuleMetadata> sharedModuleMetadataList = sharedModuleMetadataService.queryAllMetadata(false, false,
"surveyGuid=\'" + keys.getGuid() + "\' AND surveyCreatedOn=" + keys.getCreatedOn(), null);
if (sharedModuleMetadataList.size() != 0) {
throw new BadRequestException("Cannot delete specified survey because a shared module still refers to it.");
}
}
/**
* Get all versions of a specific survey, ordered by most recent version first in the list.
*
* @param studyIdentifier
* @param guid
* @return
*/
public List<Survey> getSurveyAllVersions(StudyIdentifier studyIdentifier, String guid) {
checkNotNull(studyIdentifier, Validate.CANNOT_BE_NULL, "study");
checkArgument(isNotBlank(guid), Validate.CANNOT_BE_BLANK, "survey guid");
return surveyDao.getSurveyAllVersions(studyIdentifier, guid);
}
/**
* Get the most recent version of a survey, regardless of whether it is published or not.
*
* @param studyIdentifier
* @param guid
* @return
*/
public Survey getSurveyMostRecentVersion(StudyIdentifier studyIdentifier, String guid) {
checkNotNull(studyIdentifier, Validate.CANNOT_BE_NULL, "study");
checkArgument(isNotBlank(guid), Validate.CANNOT_BE_BLANK, "survey guid");
return surveyDao.getSurveyMostRecentVersion(studyIdentifier, guid);
}
/**
* Get the most recent version of a survey that is published. More recent, unpublished versions of the survey will
* be ignored.
*
* @param studyIdentifier
* @param guid
* @return
*/
public Survey getSurveyMostRecentlyPublishedVersion(StudyIdentifier studyIdentifier, String guid) {
checkNotNull(studyIdentifier, Validate.CANNOT_BE_NULL, "study");
checkArgument(isNotBlank(guid), Validate.CANNOT_BE_BLANK, "survey guid");
return surveyDao.getSurveyMostRecentlyPublishedVersion(studyIdentifier, guid);
}
/**
* Get the most recent version of each survey in the study that has been published. If a survey has not been
* published, nothing is returned.
*
* @param studyIdentifier
* @return
*/
public List<Survey> getAllSurveysMostRecentlyPublishedVersion(StudyIdentifier studyIdentifier) {
checkNotNull(studyIdentifier, Validate.CANNOT_BE_NULL, "study");
return surveyDao.getAllSurveysMostRecentlyPublishedVersion(studyIdentifier);
}
/**
* Get the most recent version of each survey in the study, whether published or not.
*
* @param studyIdentifier
* @return
*/
public List<Survey> getAllSurveysMostRecentVersion(StudyIdentifier studyIdentifier) {
checkNotNull(studyIdentifier, Validate.CANNOT_BE_NULL, "study");
return surveyDao.getAllSurveysMostRecentVersion(studyIdentifier);
}
private void checkConstraintsBeforePhysicalDelete(final StudyIdentifier studyId, final GuidCreatedOnVersionHolder keys) {
List<SchedulePlan> plans = schedulePlanService.getSchedulePlans(ClientInfo.UNKNOWN_CLIENT, studyId);
// If a schedule points to this specific survey, don't allow the physical delete.
SchedulePlan match = findFirstMatchingPlan(plans, keys, (surveyReference, theseKeys) -> {
return surveyReference.equalsSurvey(theseKeys);
});
if (match != null) {
throwConstraintViolation(match, keys);
}
// If there's a pointer to the published version of this study, make sure this is not the last one.
match = findFirstMatchingPlan(plans, keys, (surveyReference, theseKeys) -> {
return surveyReference.getGuid().equals(theseKeys.getGuid());
});
if (match != null) {
long publishedSurveys = getSurveyAllVersions(studyId, keys.getGuid()).stream()
.filter(Survey::isPublished).collect(Collectors.counting());
if (publishedSurveys == 1L) {
throwConstraintViolation(match, keys);
}
}
// verify shared module existence as well
verifySharedModuleExistence(keys);
}
private void throwConstraintViolation(SchedulePlan match, final GuidCreatedOnVersionHolder keys) {
// It's a little absurd to provide type=Survey, but in a UI that's orchestrating
// several calls, it might not be obvious.
throw new ConstraintViolationException.Builder().withEntityKey("guid", keys.getGuid())
.withEntityKey("createdOn", DateUtils.convertToISODateTime(keys.getCreatedOn()))
.withEntityKey("type", "Survey").withReferrerKey("guid", match.getGuid())
.withReferrerKey("type", "SchedulePlan").build();
}
private SchedulePlan findFirstMatchingPlan(List<SchedulePlan> plans, GuidCreatedOnVersionHolder keys,
BiPredicate<SurveyReference, GuidCreatedOnVersionHolder> predicate) {
for (SchedulePlan plan : plans) {
List<Schedule> schedules = plan.getStrategy().getAllPossibleSchedules();
for (Schedule schedule : schedules) {
for (Activity activity : schedule.getActivities()) {
if (activity.getSurvey() != null) {
if (predicate.test(activity.getSurvey(), keys)) {
return plan;
}
} else if (activity.getCompoundActivity() != null) {
CompoundActivity compoundActivity = activity.getCompoundActivity();
for (SurveyReference aSurveyRef : compoundActivity.getSurveyList()) {
if (predicate.test(aSurveyRef, keys)) {
return plan;
}
}
}
}
}
}
return null;
}
}
|
package com.trovebox.android.app;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.AdapterView.OnItemClickListener;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.trovebox.android.app.FacebookFragment.FacebookLoadingControlAccessor;
import com.trovebox.android.app.TwitterFragment.TwitterLoadingControlAccessor;
import com.trovebox.android.app.bitmapfun.util.ImageCache;
import com.trovebox.android.app.bitmapfun.util.ImageCacheUtils;
import com.trovebox.android.app.bitmapfun.util.ImageFetcher;
import com.trovebox.android.app.bitmapfun.util.ImageWorker;
import com.trovebox.android.app.common.CommonActivity;
import com.trovebox.android.app.common.CommonFragmentWithImageWorker;
import com.trovebox.android.app.facebook.FacebookProvider;
import com.trovebox.android.app.facebook.FacebookUtils;
import com.trovebox.android.app.model.Photo;
import com.trovebox.android.app.model.utils.PhotoUtils;
import com.trovebox.android.app.model.utils.PhotoUtils.PhotoDeletedHandler;
import com.trovebox.android.app.model.utils.PhotoUtils.PhotoUpdatedHandler;
import com.trovebox.android.app.net.ReturnSizes;
import com.trovebox.android.app.share.ShareUtils;
import com.trovebox.android.app.share.ShareUtils.TwitterShareRunnable;
import com.trovebox.android.app.twitter.TwitterUtils;
import com.trovebox.android.app.ui.adapter.PhotosEndlessAdapter;
import com.trovebox.android.app.ui.adapter.PhotosEndlessAdapter.DetailsReturnSizes;
import com.trovebox.android.app.ui.adapter.PhotosEndlessAdapter.ParametersHolder;
import com.trovebox.android.app.ui.widget.HorizontalListView;
import com.trovebox.android.app.ui.widget.HorizontalListView.OnDownListener;
import com.trovebox.android.app.ui.widget.PhotoViewHackyViewPager;
import com.trovebox.android.app.ui.widget.YesNoDialogFragment;
import com.trovebox.android.app.ui.widget.YesNoDialogFragment.YesNoButtonPressedHandler;
import com.trovebox.android.app.util.CommonUtils;
import com.trovebox.android.app.util.GuiUtils;
import com.trovebox.android.app.util.LoadingControl;
import com.trovebox.android.app.util.LoadingControlWithCounter;
import com.trovebox.android.app.util.ObjectAccessor;
import com.trovebox.android.app.util.ProgressDialogLoadingControl;
import com.trovebox.android.app.util.RunnableWithParameter;
import com.trovebox.android.app.util.TrackerUtils;
/**
* The general photo viewing screen
*
* @author pboos
*/
public class PhotoDetailsActivity extends CommonActivity implements TwitterLoadingControlAccessor,
FacebookLoadingControlAccessor, PhotoDeletedHandler, PhotoUpdatedHandler {
private static final String TAG = PhotoDetailsActivity.class.getSimpleName();
public static final String EXTRA_PHOTO = "EXTRA_PHOTO";
public static final String EXTRA_ADAPTER_PHOTOS = "EXTRA_ADAPTER_PHOTOS";
public final static int AUTHORIZE_ACTIVITY_REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up activity to go full screen
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new PhotoDetailsUiFragment())
.commit();
}
addRegisteredReceiver(PhotoUtils.getAndRegisterOnPhotoDeletedActionBroadcastReceiver(
TAG, this, this));
addRegisteredReceiver(PhotoUtils.getAndRegisterOnPhotoUpdatedActionBroadcastReceiver(
TAG, this, this));
addRegisteredReceiver(ImageCacheUtils.getAndRegisterOnDiskCacheClearedBroadcastReceiver(
TAG, this));
}
PhotoDetailsUiFragment getContentFragment()
{
return (PhotoDetailsUiFragment) getSupportFragmentManager().findFragmentById(
android.R.id.content);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null)
{
if (intent.getData() != null)
{
Uri uri = intent.getData();
TwitterUtils.verifyOAuthResponse(
new ProgressDialogLoadingControl(this, true,
false, getString(R.string.share_twitter_verifying_authentication)),
this,
uri,
TwitterUtils.getPhotoDetailsCallbackUrl(this),
null);
}
getContentFragment().reinitFromIntent(intent);
}
}
@Override
public LoadingControl getTwitterLoadingControl() {
return new ProgressDialogLoadingControl(this, true, false, getString(R.string.loading));
}
@Override
public LoadingControl getFacebookLoadingControl() {
return new ProgressDialogLoadingControl(this, true, false, getString(R.string.loading));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
/*
* if this is the activity result from authorization flow, do a call
* back to authorizeCallback Source Tag: login_tag
*/
case AUTHORIZE_ACTIVITY_REQUEST_CODE: {
FacebookProvider.getFacebook().authorizeCallback(requestCode,
resultCode,
data);
break;
}
}
}
@Override
public void photoDeleted(Photo photo) {
getContentFragment().photoDeleted(photo);
}
@Override
public void photoUpdated(Photo photo) {
getContentFragment().photoUpdated(photo);
}
public static class PhotoDetailsUiFragment extends CommonFragmentWithImageWorker
{
static WeakReference<PhotoDetailsUiFragment> currentInstance;
static ObjectAccessor<PhotoDetailsUiFragment> currentInstanceAccessor = new ObjectAccessor<PhotoDetailsUiFragment>() {
private static final long serialVersionUID = 1L;
@Override
public PhotoDetailsUiFragment run() {
return currentInstance == null ? null : currentInstance.get();
}
};
private PhotoViewHackyViewPager mViewPager;
private HorizontalListView thumbnailsList;
private PhotoDetailPagerAdapter mAdapter;
private ThumbnailsAdapter thumbnailsAdapter;
private ImageWorker mImageWorker2;
private ReturnSizes bigPhotoSize;
private ReturnSizes thumbSize;
private ReturnSizes returnSizes;
private int mImageThumbWithBorderSize;
TextView titleText;
TextView dateText;
ImageView privateBtn;
View detailsView;
boolean detailsVisible;
AtomicBoolean nextPageLoaded = new AtomicBoolean(false);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentInstance = new WeakReference<PhotoDetailsActivity.PhotoDetailsUiFragment>(this);
setHasOptionsMenu(true);
mImageThumbWithBorderSize = getResources().getDimensionPixelSize(
R.dimen.detail_thumbnail_with_border_size);
}
@Override
public void onDestroy() {
if (currentInstance != null)
{
if (currentInstance.get() == PhotoDetailsUiFragment.this
|| currentInstance.get() == null)
{
CommonUtils.debug(TAG, "Nullify current instance");
currentInstance = null;
} else
{
CommonUtils.debug(TAG,
"Skipped nullify of current instance, such as it is not the same");
}
}
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
FacebookUtils.extendAceessTokenIfNeeded(getActivity());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.photo_details, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
reinitMenu(menu);
super.onPrepareOptionsMenu(menu);
}
protected void reinitMenu(Menu menu) {
try {
if (Preferences.isLimitedAccountAccessType()) {
MenuItem deleteItem = menu.findItem(R.id.menu_delete_parent);
deleteItem.setVisible(false);
MenuItem editItem = menu.findItem(R.id.menu_edit);
editItem.setVisible(false);
}
} catch (Exception ex) {
GuiUtils.noAlertError(TAG, ex);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
detailsVisible = true;
boolean result = true;
switch (item.getItemId())
{
case R.id.menu_delete:
TrackerUtils.trackOptionsMenuClickEvent("menu_delete", getSupportActivity());
deleteCurrentPhoto();
break;
case R.id.menu_share:
TrackerUtils.trackOptionsMenuClickEvent("menu_share", getSupportActivity());
break;
case R.id.menu_share_email:
TrackerUtils.trackOptionsMenuClickEvent("menu_share_email",
getSupportActivity());
confirmPrivatePhotoSharingAndRun(new Runnable() {
@Override
public void run() {
shareActivePhotoViaEMail();
}
});
break;
case R.id.menu_share_system:
TrackerUtils.trackOptionsMenuClickEvent("menu_share_system",
getSupportActivity());
confirmPrivatePhotoSharingAndRun(new Runnable() {
@Override
public void run() {
shareActivePhotoViaSystem();
}
});
break;
case R.id.menu_share_twitter:
TrackerUtils.trackOptionsMenuClickEvent("menu_share_twitter",
getSupportActivity());
confirmPrivatePhotoSharingAndRun(new Runnable() {
@Override
public void run() {
shareActivePhotoViaTwitter();
}
});
break;
case R.id.menu_share_facebook:
TrackerUtils.trackOptionsMenuClickEvent("menu_share_facebook",
getSupportActivity());
confirmPrivatePhotoSharingAndRun(new Runnable() {
@Override
public void run() {
shareActivePhotoViaFacebook();
}
});
break;
case R.id.menu_edit:
TrackerUtils.trackOptionsMenuClickEvent("menu_edit", getSupportActivity());
PhotoDetailsEditFragment detailsFragment = new PhotoDetailsEditFragment();
detailsFragment.setPhoto(getActivePhoto());
detailsFragment.show(getSupportActivity());
break;
default:
result = super.onOptionsItemSelected(item);
}
return result;
}
public void shareActivePhotoViaFacebook() {
Photo photo = getActivePhoto();
if (photo != null)
{
FacebookUtils.runAfterFacebookAuthentication(getSupportActivity(),
AUTHORIZE_ACTIVITY_REQUEST_CODE,
new ShareUtils.FacebookShareRunnable(
photo, currentInstanceAccessor));
}
}
public void shareActivePhotoViaTwitter() {
Photo photo = getActivePhoto();
if (photo != null)
{
TwitterUtils.runAfterTwitterAuthentication(
new ProgressDialogLoadingControl(getSupportActivity(), true, false,
getString(R.string.share_twitter_requesting_authentication)),
getSupportActivity(),
TwitterUtils.getPhotoDetailsCallbackUrl(getActivity()),
new TwitterShareRunnable(photo, currentInstanceAccessor));
}
}
public void shareActivePhotoViaEMail() {
Photo photo = getActivePhoto();
if (photo != null)
{
ShareUtils.shareViaEMail(photo, getActivity(),
new ProgressDialogLoadingControl(
getSupportActivity(), true, false,
getString(R.string.loading)));
}
}
public void shareActivePhotoViaSystem() {
Photo photo = getActivePhoto();
if (photo != null)
{
ShareUtils.shareViaSystem(photo, getActivity(),
new ProgressDialogLoadingControl(
getSupportActivity(), true, false,
getString(R.string.loading)));
}
}
Photo getActivePhoto()
{
return mAdapter.currentPhoto;
}
public void confirmPrivatePhotoSharingAndRun(final Runnable runnable)
{
ShareUtils.confirmPrivatePhotoSharingAndRun(getActivePhoto(), runnable,
getSupportActivity());
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.activity_photo_details, container, false);
init(v, savedInstanceState);
return v;
}
void init(View v, Bundle savedInstanceState)
{
titleText = (TextView) v.findViewById(R.id.image_title);
dateText = (TextView) v.findViewById(R.id.image_date);
privateBtn = (ImageView) v.findViewById(R.id.button_private);
detailsView = v.findViewById(R.id.image_details);
int position = 0;
if (savedInstanceState != null)
{
PhotosEndlessAdapter.ParametersHolder parameters = (ParametersHolder) savedInstanceState
.getParcelable(EXTRA_ADAPTER_PHOTOS);
position = parameters.getPosition();
thumbnailsAdapter = new ThumbnailsAdapter(parameters);
} else
{
position = initFromIntent(getActivity().getIntent());
}
initImageViewers(v, position);
}
public void reinitFromIntent(Intent intent)
{
int position = initFromIntent(intent);
if (position != -1)
{
initImageViewers(getView(), position);
}
}
public int initFromIntent(Intent intent) {
int position = -1;
if (intent.hasExtra(EXTRA_PHOTO)) {
Photo photo = intent.getParcelableExtra(EXTRA_PHOTO);
ArrayList<Photo> photos = new ArrayList<Photo>();
photos.add(photo);
thumbnailsAdapter = new ThumbnailsAdapter(photos);
position = 0;
} else if (intent.hasExtra(EXTRA_ADAPTER_PHOTOS)) {
PhotosEndlessAdapter.ParametersHolder parameters = (ParametersHolder) intent
.getParcelableExtra(EXTRA_ADAPTER_PHOTOS);
position = parameters.getPosition();
thumbnailsAdapter = new ThumbnailsAdapter(parameters);
}
return position;
}
public void initImageViewers(View v, int position) {
mAdapter = new PhotoDetailPagerAdapter(thumbnailsAdapter);
initThumbnailsList(v);
mViewPager = (PhotoViewHackyViewPager) v.findViewById(R.id.photos);
mViewPager.setAdapter(mAdapter);
if (position > 0) {
mViewPager.setCurrentItem(position);
}
mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
if (!detailsVisible)
{
adjustDetailsVisibility(false);
}
}
}, 4000);
}
public void initThumbnailsList(View v) {
thumbnailsList = (HorizontalListView) v.findViewById(R.id.thumbs);
thumbnailsList.setAdapter(thumbnailsAdapter);
thumbnailsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TrackerUtils.trackButtonClickEvent("thumb", PhotoDetailsUiFragment.this);
CommonUtils.debug(TAG, "Thumb clicked.");
detailsVisible = true;
mViewPager.setCurrentItem(position);
}
});
thumbnailsList.setOnDownListener(new OnDownListener() {
@Override
public void onDown(MotionEvent e) {
CommonUtils.debug(TAG, "Thumbnails List onDown");
detailsVisible = true;
}
});
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(EXTRA_ADAPTER_PHOTOS, new ParametersHolder(thumbnailsAdapter,
mAdapter.currentPhoto));
}
@Override
protected void initImageWorker()
{
DetailsReturnSizes detailReturnSizes = PhotosEndlessAdapter
.getDetailsReturnSizes(getActivity());
bigPhotoSize = detailReturnSizes.detailsBigPhotoSize;
thumbSize = detailReturnSizes.detailsThumbSize;
returnSizes = PhotosEndlessAdapter.getReturnSizes(thumbSize, bigPhotoSize);
mImageWorker = new ImageFetcher(getActivity(), null, bigPhotoSize.getWidth(),
bigPhotoSize.getHeight());
mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(),
ImageCache.LARGE_IMAGES_CACHE_DIR, false,
ImageCache.DEFAULT_MEM_CACHE_SIZE_RATIO * 2));
mImageWorker.setImageFadeIn(false);
mImageWorker2 = new ImageFetcher(getActivity(), null, thumbSize.getWidth(),
thumbSize.getHeight());
mImageWorker2.setImageCache(ImageCache.findOrCreateCache(getActivity(),
ImageCache.THUMBS_CACHE_DIR, false,
ImageCache.DEFAULT_MEM_CACHE_SIZE_RATIO * 2));
mImageWorker2.setLoadingImage(R.drawable.empty_photo);
imageWorkers.add(mImageWorker2);
}
void photoSelected(final Photo photo)
{
ActionBar actionBar = ((Activity) getSupportActivity())
.getSupportActionBar();
String title = photo.getTitle();
if (TextUtils.isEmpty(title))
{
title = photo.getFilenameOriginal();
}
actionBar.setTitle(getString(R.string.details_title_and_date_header, title,
CommonUtils.formatDateTime(photo.getDateTaken())));
titleText.setText(title);
dateText.setText(CommonUtils.formatDateTime(photo.getDateTaken()));
privateBtn.setVisibility(photo.isPrivate() ? View.VISIBLE : View.GONE);
ensureThumbVisible(photo);
}
/**
* Ensure photo thumb is visible
*
* @param photo
*/
public void ensureThumbVisible(final Photo photo) {
thumbnailsList.post(new Runnable() {
@Override
public void run() {
int startX = thumbnailsList.getStartX();
int position = -1;
int count = 0;
for (Photo p : thumbnailsAdapter.getItems())
{
if (p.getId().equals(photo.getId()))
{
position = count;
break;
}
count++;
}
int offset = position * mImageThumbWithBorderSize;
int width = thumbnailsList.getWidth();
// mImageThumbWithBorderSize, middle);
CommonUtils.debug(TAG, "offset: " + offset + "; width: " + width + "; startX: "
+ startX);
if (offset < startX + mImageThumbWithBorderSize)
{
CommonUtils.debug(TAG, "Thumbnail is on the left, need to scroll left");
thumbnailsList.scrollTo(offset
- Math.min(mImageThumbWithBorderSize,
(width - mImageThumbWithBorderSize) / 2));
} else if (offset > startX + width - 2 * mImageThumbWithBorderSize)
{
CommonUtils.debug(TAG, "Thumbnail is on the right, need to scroll right");
thumbnailsList.scrollTo(offset
- width
+ Math.min(2 * mImageThumbWithBorderSize,
(width + mImageThumbWithBorderSize) / 2));
} else
{
CommonUtils.debug(TAG,
"Thumbnail is already visible. Only invalidating view.");
}
for (int i = 0, size = thumbnailsList.getChildCount(); i < size; i++)
{
View view = thumbnailsList.getChildAt(i);
invalidateSelection(view);
}
}
});
}
void invalidateSelection(View view)
{
View border = view.findViewById(R.id.background_container);
Photo photo = (Photo) border.getTag();
border.setBackgroundResource(isSelected(photo) ?
R.color.detail_thumb_selected_border :
R.color.detail_thumb_unselected_border);
}
boolean isSelected(Photo photo)
{
if (mAdapter != null)
{
Photo selectedPhoto = mAdapter.currentPhoto;
boolean result = selectedPhoto != null
&& selectedPhoto.getId().equals(photo.getId());
CommonUtils.debug(TAG, "Is selected: " + result);
return result;
}
return false;
}
void deleteCurrentPhoto()
{
final Photo photo = mAdapter.currentPhoto;
YesNoDialogFragment dialogFragment = YesNoDialogFragment
.newInstance(R.string.delete_photo_confirmation_question,
new YesNoButtonPressedHandler()
{
@Override
public void yesButtonPressed(
DialogInterface dialog)
{
final ProgressDialogLoadingControl loadingControl = new ProgressDialogLoadingControl(
getActivity(), true, false,
getString(R.string.deleting_photo_message)
);
PhotoUtils.deletePhoto(photo,
loadingControl);
}
@Override
public void noButtonPressed(
DialogInterface dialog)
{
// DO NOTHING
}
});
dialogFragment.show(getSupportActivity());
}
void photoDeleted(Photo photo)
{
if (thumbnailsAdapter != null)
{
thumbnailsAdapter.photoDeleted(photo);
if (thumbnailsAdapter.getCount() == 0)
{
getActivity().finish();
}
}
}
void photoUpdated(Photo photo)
{
if (thumbnailsAdapter != null)
{
thumbnailsAdapter.photoUpdated(photo);
}
}
void adjustDetailsVisibility(final boolean visible)
{
detailsVisible = visible;
if (getActivity() == null)
{
return;
}
Animation animation = AnimationUtils
.loadAnimation(
getActivity(),
visible ? android.R.anim.fade_in : android.R.anim.fade_out);
long animationDuration = 500;
animation
.setDuration(animationDuration);
thumbnailsList.startAnimation(animation);
detailsView.startAnimation(animation);
thumbnailsList.postDelayed(new Runnable()
{
@Override
public void run()
{
detailsVisible = visible;
thumbnailsList.setVisibility(detailsVisible ? View.VISIBLE : View.GONE);
detailsView.setVisibility(detailsVisible ? View.VISIBLE : View.GONE);
if (detailsVisible && nextPageLoaded.getAndSet(false))
{
ensureThumbVisible(getActivePhoto());
}
}
}, animationDuration);
ActionBar actionBar = ((Activity) getSupportActivity())
.getSupportActionBar();
if (visible)
{
actionBar.show();
} else
{
actionBar.hide();
}
}
private class PhotoDetailPagerAdapter extends PagerAdapter {
private final LayoutInflater mInflator;
private final ThumbnailsAdapter mAdapter;
private Photo currentPhoto;
private final DataSetObserver mObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
notifyDataSetChanged();
}
};
public PhotoDetailPagerAdapter(ThumbnailsAdapter adatper) {
mAdapter = adatper;
mAdapter.registerDataSetObserver(mObserver);
mInflator = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mAdapter.getCount();
}
@Override
public Object instantiateItem(View collection, int position) {
if (mAdapter.checkNeedToLoadNextPage(position))
{
mAdapter.loadNextPage();
nextPageLoaded.set(true);
}
Photo photo = (Photo) mAdapter.getItem(position);
final View view = mInflator.inflate(R.layout.item_photo_detail,
((ViewPager) collection), false);
final PhotoView imageView = (PhotoView) view.findViewById(R.id.image);
final LoadingControl loadingControl = new LoadingControlWithCounter() {
@Override
public void stopLoadingEx() {
try
{
view.findViewById(R.id.loading).setVisibility(View.GONE);
} catch (Exception ex)
{
GuiUtils.noAlertError(TAG, null, ex);
}
}
@Override
public void startLoadingEx() {
try
{
view.findViewById(R.id.loading).setVisibility(View.VISIBLE);
} catch (Exception ex)
{
GuiUtils.noAlertError(TAG, null, ex);
}
}
};
loadingControl.startLoading();
// Finally load the image asynchronously into the ImageView,
// this
// also takes care of
// setting a placeholder image while the background thread runs
PhotoUtils.validateUrlForSizeExistAsyncAndRun(photo, bigPhotoSize,
new RunnableWithParameter<Photo>() {
@Override
public void run(Photo photo) {
String url = photo.getUrl(bigPhotoSize.toString());
// #417 workaround.
// TODO remove try/catch if exception will not
// appear anymore
try
{
if (getView() != null
&& getView().getWindowToken() != null)
{
mImageWorker.loadImage(url, imageView, loadingControl);
}
} catch (Exception ex)
{
GuiUtils.noAlertError(TAG, ex);
}
}
}, loadingControl);
loadingControl.stopLoading();
imageView.setOnViewTapListener(new OnViewTapListener() {
@Override
public void onViewTap(View view, float x, float y) {
TrackerUtils.trackButtonClickEvent("image", PhotoDetailsUiFragment.this);
adjustDetailsVisibility(!detailsVisible);
}
});
// imageView.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// adjustDetailsVisibility(!detailsVisible);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View collection, int position, Object view) {
View theView = (View) view;
ImageView imageView = (ImageView) theView.findViewById(R.id.image);
ImageWorker.cancelWork(imageView);
if (isAdded())
{
imageView.setImageBitmap(null);
}
((ViewPager) collection).removeView(theView);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position < mAdapter.getCount())
{
Photo photo = (Photo) mAdapter.getItem(position);
if (photo != currentPhoto)
{
currentPhoto = photo;
photoSelected(currentPhoto);
}
}
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
private class ThumbnailsAdapter extends PhotosEndlessAdapter
{
public ThumbnailsAdapter(ArrayList<Photo> photos)
{
super(getActivity(), photos, returnSizes);
}
public ThumbnailsAdapter(PhotosEndlessAdapter.ParametersHolder parameters)
{
super(getActivity(), parameters, returnSizes);
}
@Override
public View getView(final Photo photo, View convertView, ViewGroup parent)
{
View view;
if (convertView == null)
{ // if it's not recycled, instantiate and initialize
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_details_thumb_image, null);
}
else
{ // Otherwise re-use the converted view
view = convertView;
}
final ImageView imageView = (ImageView) view.findViewById(R.id.image);
View border = view.findViewById(R.id.background_container);
border.setTag(photo);
invalidateSelection(view);
// Finally load the image asynchronously into the ImageView,
// this
// also takes care of
// setting a placeholder image while the background thread runs
PhotoUtils.validateUrlForSizeExistAsyncAndRun(photo, thumbSize,
new RunnableWithParameter<Photo>() {
@Override
public void run(Photo photo) {
String url = photo.getUrl(thumbSize.toString());
mImageWorker2.loadImage(url, imageView);
}
}, null);
return view;
}
@Override
protected void onStartLoading()
{
// loadingControl.startLoading();
}
@Override
protected void onStoppedLoading()
{
// loadingControl.stopLoading();
}
}
}
}
|
package com.desklampstudios.thyroxine;
import android.accounts.Account;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SyncRequest;
import android.content.SyncStats;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.format.DateUtils;
import android.util.Log;
import com.desklampstudios.thyroxine.eighth.EighthSyncAdapter;
import com.desklampstudios.thyroxine.news.NewsSyncAdapter;
import com.desklampstudios.thyroxine.sync.IodineAuthenticator;
import com.desklampstudios.thyroxine.sync.StubAuthenticator;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class Utils {
private static final String TAG = Utils.class.getSimpleName();
/**
* Some date formats that are useful for parsing.
* The locale MUST be explicitly set!
* Also, warning that DateFormat objects aren't synchronized. This probably won't be a
* problem in the near future.
*/
public static class FixedDateFormats {
public static final DateFormat NEWS_FEED =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
public static final DateFormat ISO =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
public static final DateFormat BASIC =
new SimpleDateFormat("yyyy-MM-dd", Locale.US);
}
/**
* Some date formats that are to be shown to the user.
* The default locale is OK.
*/
public static enum DateFormats {
FULL_DATETIME, // Monday, January 1, 1970 12:00 AM
FULL_DATE, // Monday, January 1, 1970
MED_DAYMONTH, // Jan 1
WEEKDAY; // Mon
public String format(Context context, long millis) {
if (this == FULL_DATETIME) {
return DateUtils.formatDateTime(context, millis,
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY |
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_TIME);
} else if (this == FULL_DATE) {
return DateUtils.formatDateTime(context, millis,
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY |
DateUtils.FORMAT_SHOW_YEAR);
} else if (this == MED_DAYMONTH) {
return DateUtils.formatDateTime(context, millis,
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH);
} else if (this == WEEKDAY) {
DateFormat format = new SimpleDateFormat("EEE", Locale.getDefault());
return format.format(new Date(millis));
} else {
throw new IllegalStateException();
}
}
public String formatBasicDate(Context context, String str) {
Date date = new Date(0);
try {
date = FixedDateFormats.BASIC.parse(str);
} catch (ParseException e) {
Log.e(TAG, "Parsing date failed: " + str);
}
return format(context, date.getTime());
}
}
public static String cleanHtml(String in) {
return Html.fromHtml(in).toString().trim();
}
public static String getSnippet(String in, int length) {
in = cleanHtml(in);
in = in.replaceAll("\\s+", " ");
if (length >= 0 && in.length() > length) {
in = in.substring(0, length);
}
return in;
}
public static <E> String join(Iterable<E> array, String sep) {
StringBuilder out = new StringBuilder();
boolean first = true;
for (E item : array) {
if (first) {
first = false;
} else {
out.append(sep);
}
out.append(String.valueOf(item));
}
return out.toString();
}
public static String colorToHtmlHex(int color) {
String str = Integer.toHexString(color);
while (str.length() < 8) {
str = "0" + str;
}
return "#" + str.substring(2, 8);
}
public static String readInputStream(InputStream is) {
return new Scanner(is, "UTF-8").useDelimiter("\\A").next();
}
/**
* Makes sure synchronization is set up properly, retrieving the stub and Iodine accounts
* and configuring periodic synchronization with the SyncAdapters.
* @param context Context used to get accounts
*/
public static void configureSync(Context context) {
// Make sure stub account exists
Account stubAccount = StubAuthenticator.getStubAccount(context);
// Configure News sync with stub account
NewsSyncAdapter.configureSync(stubAccount);
// Find Iodine account (may not exist)
Account iodineAccount = IodineAuthenticator.getIodineAccount(context);
if (iodineAccount != null) {
// Configure Eighth sync with Iodine account
EighthSyncAdapter.configureSync(iodineAccount);
}
}
/**
* Helper method to schedule periodic execution of a sync adapter.
* flexTime is only used on KitKat and newer devices.
*/
public static void configurePeriodicSync(Account account, String authority,
int syncInterval, int flexTime) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// we can enable inexact timers in our periodic sync
SyncRequest request = new SyncRequest.Builder()
.syncPeriodic(syncInterval, flexTime)
.setSyncAdapter(account, authority)
.setExtras(Bundle.EMPTY)
.build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(account, authority, Bundle.EMPTY, syncInterval);
}
}
public static ContentValues cursorRowToContentValues(Cursor cursor) {
ContentValues values = new ContentValues();
DatabaseUtils.cursorRowToContentValues(cursor, values);
return values;
}
public static <T, K> ArrayList<ContentProviderOperation> createMergeBatch(
@NonNull String LOG_TYPE,
@NonNull List<T> itemList,
@NonNull Cursor queryCursor,
@NonNull final Uri BASE_CONTENT_URI,
@NonNull MergeInterface<T, K> mergeInterface,
@NonNull SyncStats syncStats)
throws RemoteException, SQLiteException {
final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
final HashMap<K, T> entryMap = new HashMap<>();
for (T item : itemList) {
entryMap.put(mergeInterface.getId(item), item);
}
// Go through current database entries
while (queryCursor.moveToNext()) {
syncStats.numEntries++;
// Get item from DB
final ContentValues oldItemValues = Utils.cursorRowToContentValues(queryCursor);
final T oldItem = mergeInterface.fromContentValues(oldItemValues);
final K id = mergeInterface.getId(oldItem);
final Uri itemUri = mergeInterface.buildContentUri(id);
// Compare to new data
T newItem = entryMap.get(id);
if (newItem != null) {
// Item exists in the new data; remove to prevent insert later.
entryMap.remove(id);
// Check if an update is necessary
if (!oldItem.equals(newItem)) {
syncStats.numUpdates++;
Log.v(TAG, LOG_TYPE + " id=" + id + ", scheduling update");
ContentValues newValues = mergeInterface.toContentValues(newItem);
batch.add(ContentProviderOperation.newUpdate(itemUri)
.withValues(newValues).build());
} else {
Log.v(TAG, LOG_TYPE + " id=" + id + ", no update necessary.");
}
} else {
// Item doesn't exist in the new data; remove it from the database.
syncStats.numDeletes++;
Log.v(TAG, LOG_TYPE + " id=" + id + ", scheduling delete");
batch.add(ContentProviderOperation.newDelete(itemUri).build());
}
}
queryCursor.close();
// Add new items (everything left in the map not found in the database)
for (K id : entryMap.keySet()) {
syncStats.numInserts++;
Log.v(TAG, LOG_TYPE + " id=" + id + ", scheduling block insert");
T newItem = entryMap.get(id);
ContentValues newValues = mergeInterface.toContentValues(newItem);
batch.add(ContentProviderOperation.newInsert(BASE_CONTENT_URI)
.withValues(newValues).build());
}
Log.d(TAG, LOG_TYPE + " merge solution ready; returning batch");
return batch;
}
public interface MergeInterface<T, U> {
public ContentValues toContentValues(T item);
public T fromContentValues(ContentValues values);
public U getId(T item);
public Uri buildContentUri(U id);
}
}
|
package com.peterjosling.scroball;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.google.common.base.Optional;
import com.peterjosling.scroball.db.ScroballDB;
import java.util.ArrayList;
import java.util.List;
import de.umass.lastfm.Caller;
import de.umass.lastfm.Result;
public class Scrobbler {
private static final String TAG = Scrobbler.class.getName();
private static final int SCROBBLE_THRESHOLD = 4 * 60 * 1000;
private static final int MINIMUM_SCROBBLE_TIME = 30 * 1000;
private static final int MAX_SCROBBLES = 50;
private final LastfmClient client;
private final ScrobbleNotificationManager notificationManager;
private final ScroballDB scroballDB;
private final ConnectivityManager connectivityManager;
private final List<PlaybackItem> pendingPlaybackItems;
private final List<Scrobble> pending;
private boolean isScrobbling = false;
private long lastScrobbleTime = 0;
private long nextScrobbleDelay = 0;
public Scrobbler(
LastfmClient client,
ScrobbleNotificationManager notificationManager,
ScroballDB scroballDB,
ConnectivityManager connectivityManager) {
this.client = client;
this.notificationManager = notificationManager;
this.scroballDB = scroballDB;
this.connectivityManager = connectivityManager;
// TODO write unit test to ensure non-network plays get scrobbled with duration lookup.
this.pendingPlaybackItems = new ArrayList<>(scroballDB.readPendingPlaybackItems());
this.pending = new ArrayList<>(scroballDB.readPendingScrobbles());
}
public void updateNowPlaying(Track track) {
if (!client.isAuthenticated()) {
Log.d(TAG, "Skipping now playing update, not logged in.");
return;
}
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
return;
}
client.updateNowPlaying(
track,
message -> {
LastfmClient.Result result = (LastfmClient.Result) message.obj;
int errorCode = result.errorCode();
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
return true;
});
}
public void submit(PlaybackItem playbackItem) {
// Set final value for amount played, in case it was playing up until now.
playbackItem.updateAmountPlayed();
// Generate one scrobble per played period.
Track track = playbackItem.getTrack();
if (!track.duration().isPresent()) {
fetchTrackDurationAndSubmit(playbackItem);
return;
}
long timestamp = playbackItem.getTimestamp();
long duration = track.duration().get();
long playTime = playbackItem.getAmountPlayed();
if (playTime < 1) {
return;
}
// Handle cases where player does not report duration *and* Last.fm does not report it either.
if (duration == 0) {
duration = playTime;
}
int playCount = (int) (playTime / duration);
long scrobbleThreshold = Math.min(SCROBBLE_THRESHOLD, duration / 2);
if (duration < MINIMUM_SCROBBLE_TIME) {
return;
}
if (playTime % duration > scrobbleThreshold) {
playCount++;
}
int newScrobbles = playCount - playbackItem.getPlaysScrobbled();
for (int i = playbackItem.getPlaysScrobbled(); i < playCount; i++) {
int itemTimestamp = (int) ((timestamp + i * duration) / 1000);
Scrobble scrobble = Scrobble.builder().track(track).timestamp(itemTimestamp).build();
pending.add(scrobble);
scroballDB.writeScrobble(scrobble);
playbackItem.addScrobble();
}
if (newScrobbles > 0) {
Log.d(TAG, String.format("Queued %d scrobbles", playCount));
}
notificationManager.notifyScrobbled(track, newScrobbles);
scrobblePending();
}
public void fetchTrackDurationAndSubmit(final PlaybackItem playbackItem) {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected || !client.isAuthenticated()) {
Log.d(TAG, "Offline or unauthenticated, can't fetch track duration. Saving for later.");
queuePendingPlaybackItem(playbackItem);
return;
}
Track track = playbackItem.getTrack();
client.getTrackInfo(
track,
message -> {
if (message.obj == null) {
Result result = Caller.getInstance().getLastResult();
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (errorCode == 6) {
Log.d(TAG, "Track not found, cannot scrobble.");
// TODO prompt user to scrobble anyway
} else {
if (LastfmClient.isTransientError(errorCode)) {
Log.d(TAG, "Failed to fetch track duration, saving for later.");
queuePendingPlaybackItem(playbackItem);
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
}
return true;
}
Track updatedTrack = (Track) message.obj;
playbackItem.updateTrack(updatedTrack);
Log.d(TAG, String.format("Track info updated: %s", playbackItem));
submit(playbackItem);
return true;
});
}
public void scrobblePending() {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
boolean tracksPending = !(pending.isEmpty() && pendingPlaybackItems.isEmpty());
boolean backoff = lastScrobbleTime + nextScrobbleDelay > System.currentTimeMillis();
if (isScrobbling || !tracksPending || !isConnected || !client.isAuthenticated() || backoff) {
return;
}
List<PlaybackItem> playbackItems = new ArrayList<>(pendingPlaybackItems);
pendingPlaybackItems.clear();
scroballDB.clearPendingPlaybackItems();
if (!playbackItems.isEmpty()) {
Log.d(TAG, "Re-processing queued items with missing durations.");
}
for (PlaybackItem playbackItem : playbackItems) {
fetchTrackDurationAndSubmit(playbackItem);
}
if (pending.isEmpty()) {
return;
}
isScrobbling = true;
final List<Scrobble> tracksToScrobble = new ArrayList<>(pending);
while (tracksToScrobble.size() > MAX_SCROBBLES) {
tracksToScrobble.remove(tracksToScrobble.size() - 1);
}
client.scrobbleTracks(
tracksToScrobble,
message -> {
List<LastfmClient.Result> results = (List<LastfmClient.Result>) message.obj;
boolean shouldBackoff = false;
for (int i = 0; i < results.size(); i++) {
LastfmClient.Result result = results.get(i);
Scrobble scrobble = tracksToScrobble.get(i);
if (result.isSuccessful()) {
scrobble.status().setScrobbled(true);
scroballDB.writeScrobble(scrobble);
pending.remove(scrobble);
} else {
int errorCode = result.errorCode();
if (!LastfmClient.isTransientError(errorCode)) {
pending.remove(scrobble);
shouldBackoff = true;
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
scrobble.status().setErrorCode(errorCode);
scroballDB.writeScrobble(scrobble);
}
}
isScrobbling = false;
lastScrobbleTime = System.currentTimeMillis();
if (shouldBackoff) {
// Back off starting at 1 second, up to an hour max.
if (nextScrobbleDelay == 0) {
nextScrobbleDelay = 1000;
} else if (nextScrobbleDelay < 60 * 60 * 1000) {
nextScrobbleDelay *= 4;
}
} else {
nextScrobbleDelay = 0;
// There may be more tracks waiting to scrobble. Keep going.
scrobblePending();
}
return false;
});
}
/**
* Calculates the number of milliseconds of playback time remaining until the specified {@param
* PlaybackItem} can be scrobbled, i.e. reaches 50% of track duration or SCROBBLE_THRESHOLD.
*
* @return The number of milliseconds remaining until the next scrobble for the current playback
* item can be submitted, or -1 if the track's duration is below MINIMUM_SCROBBLE_TIME.
*/
public long getMillisecondsUntilScrobble(PlaybackItem playbackItem) {
if (playbackItem == null) {
return -1;
}
Optional<Long> optionalDuration = playbackItem.getTrack().duration();
long duration = optionalDuration.or(0L);
if (duration < MINIMUM_SCROBBLE_TIME) {
if (optionalDuration.isPresent()) {
Log.d(TAG, String.format("Not scheduling scrobble, track is too short (%d)", duration));
} else {
Log.d(TAG, "Not scheduling scrobble, track duration not known");
}
return -1;
}
long scrobbleThreshold = Math.min(duration / 2, SCROBBLE_THRESHOLD);
long nextScrobbleAt = playbackItem.getPlaysScrobbled() * duration + scrobbleThreshold;
return Math.max(0, nextScrobbleAt - playbackItem.getAmountPlayed());
}
private void queuePendingPlaybackItem(PlaybackItem playbackItem) {
pendingPlaybackItems.add(playbackItem);
scroballDB.writePendingPlaybackItem(playbackItem);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.