lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
31613e15c7fa12f7955edf015a48c89297a8dbc2
| 0
|
msdgwzhy6/k-9,dhootha/k-9,cooperpellaton/k-9,mawiegand/k-9,deepworks/k-9,leixinstar/k-9,dpereira411/k-9,jca02266/k-9,rishabhbitsg/k-9,Eagles2F/k-9,XiveZ/k-9,tsunli/k-9,bashrc/k-9,vt0r/k-9,imaeses/k-9,github201407/k-9,k9mail/k-9,herpiko/k-9,sedrubal/k-9,Valodim/k-9,KitAway/k-9,cketti/k-9,thuanpq/k-9,tsunli/k-9,konfer/k-9,sonork/k-9,indus1/k-9,farmboy0/k-9,dpereira411/k-9,tonytamsf/k-9,gnebsy/k-9,gilbertw1/k-9,dgger/k-9,sebkur/k-9,KitAway/k-9,tonytamsf/k-9,dhootha/k-9,gilbertw1/k-9,sanderbaas/k-9,Eagles2F/k-9,mawiegand/k-9,suzp1984/k-9,cooperpellaton/k-9,thuanpq/k-9,WenduanMou1/k-9,cketti/k-9,gaionim/k-9,icedman21/k-9,leixinstar/k-9,indus1/k-9,deepworks/k-9,WenduanMou1/k-9,dpereira411/k-9,jberkel/k-9,439teamwork/k-9,farmboy0/k-9,thuanpq/k-9,crr0004/k-9,cketti/k-9,icedman21/k-9,philipwhiuk/q-mail,github201407/k-9,KitAway/k-9,msdgwzhy6/k-9,denim2x/k-9,rollbrettler/k-9,philipwhiuk/q-mail,leixinstar/k-9,msdgwzhy6/k-9,ndew623/k-9,bashrc/k-9,torte71/k-9,herpiko/k-9,github201407/k-9,sanderbaas/k-9,herpiko/k-9,bashrc/k-9,philipwhiuk/q-mail,XiveZ/k-9,roscrazy/k-9,dhootha/k-9,huhu/k-9,rollbrettler/k-9,gnebsy/k-9,cliniome/pki,icedman21/k-9,crr0004/k-9,philipwhiuk/k-9,denim2x/k-9,konfer/k-9,nilsbraden/k-9,gilbertw1/k-9,dgger/k-9,huhu/k-9,rollbrettler/k-9,nilsbraden/k-9,philipwhiuk/k-9,denim2x/k-9,ndew623/k-9,sonork/k-9,gnebsy/k-9,rtreffer/openpgp-k-9,suzp1984/k-9,imaeses/k-9,torte71/k-9,sedrubal/k-9,jca02266/k-9,vasyl-khomko/k-9,cliniome/pki,439teamwork/k-9,gaionim/k-9,CodingRmy/k-9,sebkur/k-9,nilsbraden/k-9,sanderbaas/k-9,GuillaumeSmaha/k-9,moparisthebest/k-9,jca02266/k-9,cketti/k-9,XiveZ/k-9,vatsalsura/k-9,vatsalsura/k-9,cooperpellaton/k-9,dgger/k-9,moparisthebest/k-9,mawiegand/k-9,rtreffer/openpgp-k-9,G00fY2/k-9_material_design,huhu/k-9,G00fY2/k-9_material_design,torte71/k-9,ndew623/k-9,vt0r/k-9,CodingRmy/k-9,farmboy0/k-9,suzp1984/k-9,sebkur/k-9,tonytamsf/k-9,konfer/k-9,k9mail/k-9,imaeses/k-9,gaionim/k-9,GuillaumeSmaha/k-9,439teamwork/k-9,rishabhbitsg/k-9,moparisthebest/k-9,sonork/k-9,k9mail/k-9,deepworks/k-9,vasyl-khomko/k-9,jberkel/k-9,crr0004/k-9,cliniome/pki,WenduanMou1/k-9,GuillaumeSmaha/k-9,tsunli/k-9,Eagles2F/k-9,vasyl-khomko/k-9,roscrazy/k-9
|
package com.fsck.k9.mail.store;
import android.app.Application;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.controller.MessageRemovalListener;
import com.fsck.k9.controller.MessageRetrievalListener;
import com.fsck.k9.helper.Regex;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.filter.Base64OutputStream;
import com.fsck.k9.mail.internet.*;
import com.fsck.k9.provider.AttachmentProvider;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
/**
* <pre>
* Implements a SQLite database backed local store for Messages.
* </pre>
*/
public class LocalStore extends Store implements Serializable
{
private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0];
/**
* Immutable empty {@link String} array
*/
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final int DB_VERSION = 37;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN, Flag.FLAGGED };
private String mPath;
private SQLiteDatabase mDb;
private File mAttachmentsDir;
private Application mApplication;
private String uUid = null;
private static Set<String> HEADERS_TO_SAVE = new HashSet<String>();
static
{
HEADERS_TO_SAVE.add(K9.K9MAIL_IDENTITY);
HEADERS_TO_SAVE.add("To");
HEADERS_TO_SAVE.add("Cc");
HEADERS_TO_SAVE.add("From");
HEADERS_TO_SAVE.add("In-Reply-To");
HEADERS_TO_SAVE.add("References");
HEADERS_TO_SAVE.add("Content-ID");
HEADERS_TO_SAVE.add("Content-Disposition");
HEADERS_TO_SAVE.add("X-User-Agent");
}
/*
* a String containing the columns getMessages expects to work with
* in the correct order.
*/
static private String GET_MESSAGES_COLS =
"subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id, folder_id, preview ";
/**
* local://localhost/path/to/database/uuid.db
*/
public LocalStore(Account account, Application application) throws MessagingException
{
super(account);
mApplication = application;
URI uri = null;
try
{
uri = new URI(mAccount.getLocalStoreUri());
}
catch (Exception e)
{
throw new MessagingException("Invalid uri for LocalStore");
}
if (!uri.getScheme().equals("local"))
{
throw new MessagingException("Invalid scheme");
}
mPath = uri.getPath();
// We need to associate the localstore with the account. Since we don't have the account
// handy here, we'll take the filename from the DB and use the basename of the filename
// Folders probably should have references to their containing accounts
//TODO: We do have an account object now
File dbFile = new File(mPath);
String[] tokens = dbFile.getName().split("\\.");
uUid = tokens[0];
openOrCreateDataspace(application);
}
private void openOrCreateDataspace(Application application)
{
File parentDir = new File(mPath).getParentFile();
if (!parentDir.exists())
{
parentDir.mkdirs();
}
mAttachmentsDir = new File(mPath + "_att");
if (!mAttachmentsDir.exists())
{
mAttachmentsDir.mkdirs();
}
mDb = SQLiteDatabase.openOrCreateDatabase(mPath, null);
if (mDb.getVersion() != DB_VERSION)
{
doDbUpgrade(mDb, application);
}
}
private void doDbUpgrade(SQLiteDatabase mDb, Application application)
{
Log.i(K9.LOG_TAG, String.format("Upgrading database from version %d to version %d",
mDb.getVersion(), DB_VERSION));
AttachmentProvider.clear(application);
try
{
// schema version 29 was when we moved to incremental updates
// in the case of a new db or a < v29 db, we blow away and start from scratch
if (mDb.getVersion() < 29)
{
mDb.execSQL("DROP TABLE IF EXISTS folders");
mDb.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, "
+ "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT, push_state TEXT, last_pushed INTEGER, flagged_count INTEGER default 0)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)");
mDb.execSQL("DROP TABLE IF EXISTS messages");
mDb.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted INTEGER default 0, folder_id INTEGER, uid TEXT, subject TEXT, "
+ "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, "
+ "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT, preview TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS headers");
mDb.execSQL("CREATE TABLE headers (id INTEGER PRIMARY KEY, message_id INTEGER, name TEXT, value TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS header_folder ON headers (message_id)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)");
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id");
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id_date");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)");
mDb.execSQL("DROP TABLE IF EXISTS attachments");
mDb.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER,"
+ "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT,"
+ "mime_type TEXT, content_id TEXT, content_disposition TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS pending_commands");
mDb.execSQL("CREATE TABLE pending_commands " +
"(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_folder");
mDb.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_message");
mDb.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; "
+ "DELETE FROM headers where old.id = message_id; END;");
}
else
{ // in the case that we're starting out at 29 or newer, run all the needed updates
if (mDb.getVersion() < 30)
{
try
{
mDb.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0");
}
catch (SQLiteException e)
{
if (! e.toString().startsWith("duplicate column name: deleted"))
{
throw e;
}
}
}
if (mDb.getVersion() < 31)
{
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id_date");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)");
}
if (mDb.getVersion() < 32)
{
mDb.execSQL("UPDATE messages SET deleted = 1 WHERE flags LIKE '%DELETED%'");
}
if (mDb.getVersion() < 33)
{
try
{
mDb.execSQL("ALTER TABLE messages ADD preview TEXT");
}
catch (SQLiteException e)
{
if (! e.toString().startsWith("duplicate column name: preview"))
{
throw e;
}
}
}
if (mDb.getVersion() < 34)
{
try
{
mDb.execSQL("ALTER TABLE folders ADD flagged_count INTEGER default 0");
}
catch (SQLiteException e)
{
if (! e.getMessage().startsWith("duplicate column name: flagged_count"))
{
throw e;
}
}
}
if (mDb.getVersion() < 35)
{
try
{
mDb.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e);
}
}
if (mDb.getVersion() < 36)
{
try
{
mDb.execSQL("ALTER TABLE attachments ADD content_id TEXT");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments");
}
}
if (mDb.getVersion() < 37)
{
try
{
mDb.execSQL("ALTER TABLE attachments ADD content_disposition TEXT");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments");
}
}
}
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0");
mDb.setVersion(0);
throw new Error("Database upgrade failed! Resetting your DB version to 0 to force a full schema recreation.");
}
mDb.setVersion(DB_VERSION);
if (mDb.getVersion() != DB_VERSION)
{
throw new Error("Database upgrade failed!");
}
try
{
pruneCachedAttachments(true);
}
catch (Exception me)
{
Log.e(K9.LOG_TAG, "Exception while force pruning attachments during DB update", me);
}
}
public long getSize()
{
long attachmentLength = 0;
File[] files = mAttachmentsDir.listFiles();
for (File file : files)
{
if (file.exists())
{
attachmentLength += file.length();
}
}
File dbFile = new File(mPath);
return dbFile.length() + attachmentLength;
}
public void compact() throws MessagingException
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize());
mDb.execSQL("VACUUM");
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "After compaction size = " + getSize());
}
public void clear() throws MessagingException
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments(true);
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize());
Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount());
Log.i(K9.LOG_TAG, "Before clear message count = " + getMessageCount());
Log.i(K9.LOG_TAG, "After prune / before clear size = " + getSize());
}
// don't delete messages that are Local, since there is no copy on the server.
// Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have
// been deleted locally. They take up insignificant space
mDb.execSQL("DELETE FROM messages WHERE deleted = 0 and uid not like 'Local%'");
mDb.execSQL("update folders set flagged_count = 0, unread_count = 0");
compact();
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount());
Log.i(K9.LOG_TAG, "After clear size = " + getSize());
}
}
public int getMessageCount() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
public int getFolderCount() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM folders", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public LocalFolder getFolder(String name) throws MessagingException
{
return new LocalFolder(name);
}
// TODO this takes about 260-300ms, seems slow.
@Override
public List<? extends Folder> getPersonalNamespaces(boolean forceListAll) throws MessagingException
{
LinkedList<LocalFolder> folders = new LinkedList<LocalFolder>();
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT id, name, unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders", null);
while (cursor.moveToNext())
{
LocalFolder folder = new LocalFolder(cursor.getString(1));
folder.open(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8));
folders.add(folder);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return folders;
}
@Override
public void checkSettings() throws MessagingException
{
}
/**
* Delete the entire Store and it's backing database.
*/
public void delete()
{
try
{
mDb.close();
}
catch (Exception e)
{
}
try
{
File[] attachments = mAttachmentsDir.listFiles();
for (File attachment : attachments)
{
if (attachment.exists())
{
attachment.delete();
}
}
if (mAttachmentsDir.exists())
{
mAttachmentsDir.delete();
}
}
catch (Exception e)
{
}
try
{
new File(mPath).delete();
}
catch (Exception e)
{
}
}
public void recreate()
{
delete();
openOrCreateDataspace(mApplication);
}
public void pruneCachedAttachments() throws MessagingException
{
pruneCachedAttachments(false);
}
/**
* Deletes all cached attachments for the entire store.
*/
public void pruneCachedAttachments(boolean force) throws MessagingException
{
if (force)
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, null, null);
}
File[] files = mAttachmentsDir.listFiles();
for (File file : files)
{
if (file.exists())
{
if (!force)
{
Cursor cursor = null;
try
{
cursor = mDb.query(
"attachments",
new String[] { "store_data" },
"id = ?",
new String[] { file.getName() },
null,
null,
null);
if (cursor.moveToNext())
{
if (cursor.getString(0) == null)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting");
/*
* If the attachment has no store data it is not recoverable, so
* we won't delete it.
*/
continue;
}
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
if (!force)
{
try
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, "id = ?", new String[] { file.getName() });
}
catch (Exception e)
{
/*
* If the row has gone away before we got to mark it not-downloaded that's
* okay.
*/
}
}
if (!file.delete())
{
file.deleteOnExit();
}
}
}
}
public void resetVisibleLimits()
{
resetVisibleLimits(mAccount.getDisplayCount());
}
public void resetVisibleLimits(int visibleLimit)
{
ContentValues cv = new ContentValues();
cv.put("visible_limit", Integer.toString(visibleLimit));
mDb.update("folders", cv, null, null);
}
public ArrayList<PendingCommand> getPendingCommands()
{
Cursor cursor = null;
try
{
cursor = mDb.query("pending_commands",
new String[] { "id", "command", "arguments" },
null,
null,
null,
null,
"id ASC");
ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>();
while (cursor.moveToNext())
{
PendingCommand command = new PendingCommand();
command.mId = cursor.getLong(0);
command.command = cursor.getString(1);
String arguments = cursor.getString(2);
command.arguments = arguments.split(",");
for (int i = 0; i < command.arguments.length; i++)
{
command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]);
}
commands.add(command);
}
return commands;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
public void addPendingCommand(PendingCommand command)
{
try
{
for (int i = 0; i < command.arguments.length; i++)
{
command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8");
}
ContentValues cv = new ContentValues();
cv.put("command", command.command);
cv.put("arguments", Utility.combine(command.arguments, ','));
mDb.insert("pending_commands", "command", cv);
}
catch (UnsupportedEncodingException usee)
{
throw new Error("Aparently UTF-8 has been lost to the annals of history.");
}
}
public void removePendingCommand(PendingCommand command)
{
mDb.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) });
}
public void removePendingCommands()
{
mDb.delete("pending_commands", null, null);
}
public static class PendingCommand
{
private long mId;
public String command;
public String[] arguments;
@Override
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(command);
sb.append(": ");
for (String argument : arguments)
{
sb.append(", ");
sb.append(argument);
//sb.append("\n");
}
return sb.toString();
}
}
@Override
public boolean isMoveCapable()
{
return true;
}
@Override
public boolean isCopyCapable()
{
return true;
}
public Message[] searchForMessages(MessageRetrievalListener listener, String[] queryFields, String queryString,
List<LocalFolder> folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException
{
List<String> args = new LinkedList<String>();
StringBuilder whereClause = new StringBuilder();
if (queryString != null && queryString.length() > 0)
{
boolean anyAdded = false;
String likeString = "%"+queryString+"%";
whereClause.append(" AND (");
for (String queryField : queryFields)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
whereClause.append(queryField + " LIKE ? ");
args.add(likeString);
anyAdded = true;
}
whereClause.append(" )");
}
if (folders != null && folders.size() > 0)
{
whereClause.append(" AND folder_id in (");
boolean anyAdded = false;
for (LocalFolder folder : folders)
{
if (anyAdded == true)
{
whereClause.append(",");
}
anyAdded = true;
whereClause.append("?");
args.add(Long.toString(folder.getId()));
}
whereClause.append(" )");
}
if (messages != null && messages.length > 0)
{
whereClause.append(" AND ( ");
boolean anyAdded = false;
for (Message message : messages)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
anyAdded = true;
whereClause.append(" ( uid = ? AND folder_id = ? ) ");
args.add(message.getUid());
args.add(Long.toString(((LocalFolder)message.getFolder()).getId()));
}
whereClause.append(" )");
}
if (forbiddenFlags != null && forbiddenFlags.length > 0)
{
whereClause.append(" AND (");
boolean anyAdded = false;
for (Flag flag : forbiddenFlags)
{
if (anyAdded == true)
{
whereClause.append(" AND ");
}
anyAdded = true;
whereClause.append(" flags NOT LIKE ?");
args.add("%" + flag.toString() + "%");
}
whereClause.append(" )");
}
if (requiredFlags != null && requiredFlags.length > 0)
{
whereClause.append(" AND (");
boolean anyAdded = false;
for (Flag flag : requiredFlags)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
anyAdded = true;
whereClause.append(" flags LIKE ?");
args.add("%" + flag.toString() + "%");
}
whereClause.append(" )");
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "whereClause = " + whereClause.toString());
Log.v(K9.LOG_TAG, "args = " + args);
}
return getMessages(
listener,
null,
"SELECT "
+ GET_MESSAGES_COLS
+ "FROM messages WHERE deleted = 0 " + whereClause.toString() + " ORDER BY date DESC"
, args.toArray(EMPTY_STRING_ARRAY)
);
}
/*
* Given a query string, actually do the query for the messages and
* call the MessageRetrievalListener for each one
*/
private Message[] getMessages(
MessageRetrievalListener listener,
LocalFolder folder,
String queryString, String[] placeHolders
) throws MessagingException
{
ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>();
Cursor cursor = null;
try
{
// pull out messages most recent first, since that's what the default sort is
cursor = mDb.rawQuery(queryString, placeHolders);
int i = 0;
while (cursor.moveToNext())
{
LocalMessage message = new LocalMessage(null, folder);
message.populateFromGetMessageCursor(cursor);
messages.add(message);
if (listener != null)
{
listener.messageFinished(message, i, -1);
}
i++;
}
if (listener != null)
{
listener.messagesFinished(i);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
public class LocalFolder extends Folder implements Serializable
{
private String mName = null;
private long mFolderId = -1;
private int mUnreadMessageCount = -1;
private int mFlaggedMessageCount = -1;
private int mVisibleLimit = -1;
private FolderClass displayClass = FolderClass.NO_CLASS;
private FolderClass syncClass = FolderClass.INHERITED;
private FolderClass pushClass = FolderClass.SECOND_CLASS;
private boolean inTopGroup = false;
private String prefId = null;
private String mPushState = null;
private boolean mIntegrate = false;
public LocalFolder(String name)
{
super(LocalStore.this.mAccount);
this.mName = name;
if (K9.INBOX.equals(getName()))
{
syncClass = FolderClass.FIRST_CLASS;
pushClass = FolderClass.FIRST_CLASS;
inTopGroup = true;
}
}
public LocalFolder(long id)
{
super(LocalStore.this.mAccount);
this.mFolderId = id;
}
public long getId()
{
return mFolderId;
}
@Override
public void open(OpenMode mode) throws MessagingException
{
if (isOpen())
{
return;
}
Cursor cursor = null;
try
{
String baseQuery =
"SELECT id, name,unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders ";
if (mName != null)
{
cursor = mDb.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName });
}
else
{
cursor = mDb.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) });
}
if (cursor.moveToFirst())
{
int folderId = cursor.getInt(0);
if (folderId > 0)
{
open(folderId, cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8));
}
}
else
{
Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId());
create(FolderType.HOLDS_MESSAGES);
open(mode);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount) throws MessagingException
{
mFolderId = id;
mName = name;
mUnreadMessageCount = unreadCount;
mVisibleLimit = visibleLimit;
mPushState = pushState;
mFlaggedMessageCount = flaggedCount;
super.setStatus(status);
// Only want to set the local variable stored in the super class. This class
// does a DB update on setLastChecked
super.setLastChecked(lastChecked);
super.setLastPush(lastPushed);
}
@Override
public boolean isOpen()
{
return (mFolderId != -1 && mName != null);
}
@Override
public OpenMode getMode() throws MessagingException
{
return OpenMode.READ_WRITE;
}
@Override
public String getName()
{
return mName;
}
@Override
public boolean exists() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT id FROM folders "
+ "where folders.name = ?", new String[] { this
.getName()
});
if (cursor.moveToFirst())
{
int folderId = cursor.getInt(0);
return (folderId > 0) ? true : false;
}
else
{
return false;
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException
{
if (exists())
{
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[]
{
mName,
mAccount.getDisplayCount()
});
return true;
}
@Override
public boolean create(FolderType type, int visibleLimit) throws MessagingException
{
if (exists())
{
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[]
{
mName,
visibleLimit
});
return true;
}
@Override
public void close()
{
mFolderId = -1;
}
@Override
public int getMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?",
new String[]
{
Long.toString(mFolderId)
});
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public int getUnreadMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mUnreadMessageCount;
}
@Override
public int getFlaggedMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mFlaggedMessageCount;
}
public void setUnreadMessageCount(int unreadMessageCount) throws MessagingException
{
open(OpenMode.READ_WRITE);
mUnreadMessageCount = Math.max(0, unreadMessageCount);
mDb.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?",
new Object[] { mUnreadMessageCount, mFolderId });
}
public void setFlaggedMessageCount(int flaggedMessageCount) throws MessagingException
{
open(OpenMode.READ_WRITE);
mFlaggedMessageCount = Math.max(0, flaggedMessageCount);
mDb.execSQL("UPDATE folders SET flagged_count = ? WHERE id = ?",
new Object[] { mFlaggedMessageCount, mFolderId });
}
@Override
public void setLastChecked(long lastChecked) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setLastChecked(lastChecked);
mDb.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
@Override
public void setLastPush(long lastChecked) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setLastPush(lastChecked);
mDb.execSQL("UPDATE folders SET last_pushed = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
public int getVisibleLimit() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mVisibleLimit;
}
public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException
{
open(OpenMode.READ_WRITE);
Message[] messages = getMessages(null, false);
for (int i = mVisibleLimit; i < messages.length; i++)
{
if (listener != null)
{
listener.messageRemoved(messages[i]);
}
messages[i].setFlag(Flag.X_DESTROYED, true);
}
}
public void setVisibleLimit(int visibleLimit) throws MessagingException
{
open(OpenMode.READ_WRITE);
mVisibleLimit = visibleLimit;
mDb.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?",
new Object[] { mVisibleLimit, mFolderId });
}
@Override
public void setStatus(String status) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setStatus(status);
mDb.execSQL("UPDATE folders SET status = ? WHERE id = ?",
new Object[] { status, mFolderId });
}
public void setPushState(String pushState) throws MessagingException
{
open(OpenMode.READ_WRITE);
mPushState = pushState;
mDb.execSQL("UPDATE folders SET push_state = ? WHERE id = ?",
new Object[] { pushState, mFolderId });
}
public String getPushState()
{
return mPushState;
}
@Override
public FolderClass getDisplayClass()
{
return displayClass;
}
@Override
public FolderClass getSyncClass()
{
if (FolderClass.INHERITED == syncClass)
{
return getDisplayClass();
}
else
{
return syncClass;
}
}
public FolderClass getRawSyncClass()
{
return syncClass;
}
@Override
public FolderClass getPushClass()
{
if (FolderClass.INHERITED == pushClass)
{
return getSyncClass();
}
else
{
return pushClass;
}
}
public FolderClass getRawPushClass()
{
return pushClass;
}
public void setDisplayClass(FolderClass displayClass)
{
this.displayClass = displayClass;
}
public void setSyncClass(FolderClass syncClass)
{
this.syncClass = syncClass;
}
public void setPushClass(FolderClass pushClass)
{
this.pushClass = pushClass;
}
public boolean isIntegrate()
{
return mIntegrate;
}
public void setIntegrate(boolean integrate)
{
mIntegrate = integrate;
}
private String getPrefId() throws MessagingException
{
open(OpenMode.READ_WRITE);
if (prefId == null)
{
prefId = uUid + "." + mName;
}
return prefId;
}
public void delete(Preferences preferences) throws MessagingException
{
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode");
editor.remove(id + ".pushMode");
editor.remove(id + ".inTopGroup");
editor.remove(id + ".integrate");
editor.commit();
}
public void save(Preferences preferences) throws MessagingException
{
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
if (displayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".displayMode");
}
else
{
editor.putString(id + ".displayMode", displayClass.name());
}
if (syncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".syncMode");
}
else
{
editor.putString(id + ".syncMode", syncClass.name());
}
if (pushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".pushMode");
}
else
{
editor.putString(id + ".pushMode", pushClass.name());
}
editor.putBoolean(id + ".inTopGroup", inTopGroup);
editor.putBoolean(id + ".integrate", mIntegrate);
editor.commit();
}
public FolderClass getDisplayClass(Preferences preferences) throws MessagingException
{
String id = getPrefId();
return FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NO_CLASS.name()));
}
@Override
public void refresh(Preferences preferences) throws MessagingException
{
String id = getPrefId();
try
{
displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NO_CLASS.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e);
displayClass = FolderClass.NO_CLASS;
}
if (displayClass == FolderClass.NONE)
{
displayClass = FolderClass.NO_CLASS;
}
FolderClass defSyncClass = FolderClass.INHERITED;
if (K9.INBOX.equals(getName()))
{
defSyncClass = FolderClass.FIRST_CLASS;
}
try
{
syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode",
defSyncClass.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e);
syncClass = defSyncClass;
}
if (syncClass == FolderClass.NONE)
{
syncClass = FolderClass.INHERITED;
}
FolderClass defPushClass = FolderClass.SECOND_CLASS;
boolean defInTopGroup = false;
boolean defIntegrate = false;
if (K9.INBOX.equals(getName()))
{
defPushClass = FolderClass.FIRST_CLASS;
defInTopGroup = true;
defIntegrate = true;
}
try
{
pushClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".pushMode",
defPushClass.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e);
pushClass = defPushClass;
}
if (pushClass == FolderClass.NONE)
{
pushClass = FolderClass.INHERITED;
}
inTopGroup = preferences.getPreferences().getBoolean(id + ".inTopGroup", defInTopGroup);
mIntegrate = preferences.getPreferences().getBoolean(id + ".integrate", defIntegrate);
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
if (fp.contains(FetchProfile.Item.BODY))
{
for (Message message : messages)
{
LocalMessage localMessage = (LocalMessage)message;
Cursor cursor = null;
MimeMultipart mp = new MimeMultipart();
mp.setSubType("mixed");
try
{
cursor = mDb.rawQuery("SELECT html_content, text_content FROM messages "
+ "WHERE id = ?",
new String[] { Long.toString(localMessage.mId) });
cursor.moveToNext();
String htmlContent = cursor.getString(0);
String textContent = cursor.getString(1);
if (textContent != null)
{
LocalTextBody body = new LocalTextBody(textContent, htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
else
{
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
try
{
cursor = mDb.query(
"attachments",
new String[]
{
"id",
"size",
"name",
"mime_type",
"store_data",
"content_uri",
"content_id",
"content_disposition"
},
"message_id = ?",
new String[] { Long.toString(localMessage.mId) },
null,
null,
null);
while (cursor.moveToNext())
{
long id = cursor.getLong(0);
int size = cursor.getInt(1);
String name = cursor.getString(2);
String type = cursor.getString(3);
String storeData = cursor.getString(4);
String contentUri = cursor.getString(5);
String contentId = cursor.getString(6);
String contentDisposition = cursor.getString(7);
Body body = null;
if (contentDisposition == null)
{
contentDisposition = "attachment";
}
if (contentUri != null)
{
body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication);
}
MimeBodyPart bp = new LocalAttachmentBodyPart(body, id);
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
type,
name));
bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format("%s;\n filename=\"%s\";\n size=%d",
contentDisposition,
name,
size));
bp.setHeader(MimeHeader.HEADER_CONTENT_ID, contentId);
/*
* HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that
* we can later pull the attachment from the remote store if neccesary.
*/
bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData);
mp.addBodyPart(bp);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
if (mp.getCount() == 1)
{
BodyPart part = mp.getBodyPart(0);
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType());
localMessage.setBody(part.getBody());
}
else
{
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
localMessage.setBody(mp);
}
}
}
}
@Override
public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
throw new MessagingException(
"LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented");
}
/**
* Populate the header fields of the given list of messages by reading
* the saved header data from the database.
*
* @param messages
* The messages whose headers should be loaded.
*/
private void populateHeaders(List<LocalMessage> messages)
{
Cursor cursor = null;
if (messages.size() == 0)
{
return;
}
try
{
Map<Long, LocalMessage> popMessages = new HashMap<Long, LocalMessage>();
List<String> ids = new ArrayList<String>();
StringBuffer questions = new StringBuffer();
for (int i = 0; i < messages.size(); i++)
{
if (i != 0)
{
questions.append(", ");
}
questions.append("?");
LocalMessage message = messages.get(i);
Long id = message.getId();
ids.add(Long.toString(id));
popMessages.put(id, message);
}
cursor = mDb.rawQuery(
"SELECT message_id, name, value FROM headers " + "WHERE message_id in ( " + questions + ") ",
ids.toArray(EMPTY_STRING_ARRAY));
while (cursor.moveToNext())
{
Long id = cursor.getLong(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
//Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id);
popMessages.get(id).addHeader(name, value);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public Message getMessage(String uid) throws MessagingException
{
open(OpenMode.READ_WRITE);
LocalMessage message = new LocalMessage(uid, this);
Cursor cursor = null;
try
{
cursor = mDb.rawQuery(
"SELECT "
+ GET_MESSAGES_COLS
+ "FROM messages WHERE uid = ? AND folder_id = ?",
new String[]
{
message.getUid(), Long.toString(mFolderId)
});
if (!cursor.moveToNext())
{
return null;
}
message.populateFromGetMessageCursor(cursor);
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return message;
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException
{
return getMessages(listener, true);
}
@Override
public Message[] getMessages(MessageRetrievalListener listener, boolean includeDeleted) throws MessagingException
{
open(OpenMode.READ_WRITE);
return LocalStore.this.getMessages(
listener,
this,
"SELECT " + GET_MESSAGES_COLS
+ "FROM messages WHERE "
+ (includeDeleted ? "" : "deleted = 0 AND ")
+ " folder_id = ? ORDER BY date DESC"
, new String[]
{
Long.toString(mFolderId)
}
);
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
if (uids == null)
{
return getMessages(listener);
}
ArrayList<Message> messages = new ArrayList<Message>();
for (String uid : uids)
{
Message message = getMessage(uid);
if (message != null)
{
messages.add(message);
}
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
@Override
public void copyMessages(Message[] msgs, Folder folder) throws MessagingException
{
if (!(folder instanceof LocalFolder))
{
throw new MessagingException("copyMessages called with incorrect Folder");
}
((LocalFolder) folder).appendMessages(msgs, true);
}
@Override
public void moveMessages(Message[] msgs, Folder destFolder) throws MessagingException
{
if (!(destFolder instanceof LocalFolder))
{
throw new MessagingException("moveMessages called with non-LocalFolder");
}
LocalFolder lDestFolder = (LocalFolder)destFolder;
lDestFolder.open(OpenMode.READ_WRITE);
for (Message message : msgs)
{
LocalMessage lMessage = (LocalMessage)message;
if (!message.isSet(Flag.SEEN))
{
setUnreadMessageCount(getUnreadMessageCount() - 1);
lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1);
}
if (message.isSet(Flag.FLAGGED))
{
setFlaggedMessageCount(getFlaggedMessageCount() - 1);
lDestFolder.setFlaggedMessageCount(lDestFolder.getFlaggedMessageCount() + 1);
}
String oldUID = message.getUid();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID "
+ message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName());
message.setUid(K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
mDb.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[]
{
lDestFolder.getId(),
message.getUid(),
lMessage.getId()
});
LocalMessage placeHolder = new LocalMessage(oldUID, this);
placeHolder.setFlagInternal(Flag.DELETED, true);
placeHolder.setFlagInternal(Flag.SEEN, true);
appendMessages(new Message[] { placeHolder });
}
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException
{
appendMessages(messages, false);
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
*/
private void appendMessages(Message[] messages, boolean copy) throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : messages)
{
if (!(message instanceof MimeMessage))
{
throw new Error("LocalStore can only store Messages that extend MimeMessage");
}
String uid = message.getUid();
if (uid == null || copy)
{
uid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString();
if (!copy)
{
message.setUid(uid);
}
}
else
{
Message oldMessage = getMessage(uid);
if (oldMessage != null && oldMessage.isSet(Flag.SEEN) == false)
{
setUnreadMessageCount(getUnreadMessageCount() - 1);
}
if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED) == true)
{
setFlaggedMessageCount(getFlaggedMessageCount() - 1);
}
/*
* The message may already exist in this Folder, so delete it first.
*/
deleteAttachments(message.getUid());
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?",
new Object[] { mFolderId, message.getUid() });
}
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (Part viewable : viewables)
{
try
{
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html"))
{
sbHtml.append(text);
}
else
{
sbText.append(text);
}
}
catch (Exception e)
{
throw new MessagingException("Unable to get text for message part", e);
}
}
String text = sbText.toString();
String html = markupContent(text, sbHtml.toString());
String preview = calculateContentPreview(text);
try
{
ContentValues cv = new ContentValues();
cv.put("uid", uid);
cv.put("subject", message.getSubject());
cv.put("sender_list", Address.pack(message.getFrom()));
cv.put("date", message.getSentDate() == null
? System.currentTimeMillis() : message.getSentDate().getTime());
cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase());
cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0);
cv.put("folder_id", mFolderId);
cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
cv.put("html_content", html.length() > 0 ? html : null);
cv.put("text_content", text.length() > 0 ? text : null);
cv.put("preview", preview.length() > 0 ? preview : null);
cv.put("reply_to_list", Address.pack(message.getReplyTo()));
cv.put("attachment_count", attachments.size());
cv.put("internal_date", message.getInternalDate() == null
? System.currentTimeMillis() : message.getInternalDate().getTime());
String messageId = message.getMessageId();
if (messageId != null)
{
cv.put("message_id", messageId);
}
long messageUid = mDb.insert("messages", "uid", cv);
for (Part attachment : attachments)
{
saveAttachment(messageUid, attachment, copy);
}
saveHeaders(messageUid, (MimeMessage)message);
if (message.isSet(Flag.SEEN) == false)
{
setUnreadMessageCount(getUnreadMessageCount() + 1);
}
if (message.isSet(Flag.FLAGGED) == true)
{
setFlaggedMessageCount(getFlaggedMessageCount() + 1);
}
}
catch (Exception e)
{
throw new MessagingException("Error appending message", e);
}
}
}
/**
* Update the given message in the LocalStore without first deleting the existing
* message (contrast with appendMessages). This method is used to store changes
* to the given message while updating attachments and not removing existing
* attachment data.
* TODO In the future this method should be combined with appendMessages since the Message
* contains enough data to decide what to do.
* @param message
* @throws MessagingException
*/
public void updateMessage(LocalMessage message) throws MessagingException
{
open(OpenMode.READ_WRITE);
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
message.buildMimeRepresentation();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (int i = 0, count = viewables.size(); i < count; i++)
{
Part viewable = viewables.get(i);
try
{
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html"))
{
sbHtml.append(text);
}
else
{
sbText.append(text);
}
}
catch (Exception e)
{
throw new MessagingException("Unable to get text for message part", e);
}
}
String text = sbText.toString();
String html = markupContent(text, sbHtml.toString());
String preview = calculateContentPreview(text);
try
{
mDb.execSQL("UPDATE messages SET "
+ "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, "
+ "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, "
+ "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, "
+ "attachment_count = ? WHERE id = ?",
new Object[]
{
message.getUid(),
message.getSubject(),
Address.pack(message.getFrom()),
message.getSentDate() == null ? System
.currentTimeMillis() : message.getSentDate()
.getTime(),
Utility.combine(message.getFlags(), ',').toUpperCase(),
mFolderId,
Address.pack(message
.getRecipients(RecipientType.TO)),
Address.pack(message
.getRecipients(RecipientType.CC)),
Address.pack(message
.getRecipients(RecipientType.BCC)),
html.length() > 0 ? html : null,
text.length() > 0 ? text : null,
preview.length() > 0 ? preview : null,
Address.pack(message.getReplyTo()),
attachments.size(),
message.mId
});
for (int i = 0, count = attachments.size(); i < count; i++)
{
Part attachment = attachments.get(i);
saveAttachment(message.mId, attachment, false);
}
saveHeaders(message.getId(), message);
}
catch (Exception e)
{
throw new MessagingException("Error appending message", e);
}
}
/**
* Save the headers of the given message. Note that the message is not
* necessarily a {@link LocalMessage} instance.
*/
private void saveHeaders(long id, MimeMessage message) throws MessagingException
{
boolean saveAllHeaders = mAccount.isSaveAllHeaders();
boolean gotAdditionalHeaders = false;
deleteHeaders(id);
for (String name : message.getHeaderNames())
{
if (saveAllHeaders || HEADERS_TO_SAVE.contains(name))
{
String[] values = message.getHeader(name);
for (String value : values)
{
ContentValues cv = new ContentValues();
cv.put("message_id", id);
cv.put("name", name);
cv.put("value", value);
mDb.insert("headers", "name", cv);
}
}
else
{
gotAdditionalHeaders = true;
}
}
if (!gotAdditionalHeaders)
{
// Remember that all headers for this message have been saved, so it is
// not necessary to download them again in case the user wants to see all headers.
List<Flag> appendedFlags = new ArrayList<Flag>();
appendedFlags.addAll(Arrays.asList(message.getFlags()));
appendedFlags.add(Flag.X_GOT_ALL_HEADERS);
mDb.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[]
{ Utility.combine(appendedFlags.toArray(), ',').toUpperCase(), id });
}
}
private void deleteHeaders(long id)
{
mDb.execSQL("DELETE FROM headers WHERE id = ?",
new Object[]
{
id
});
}
/**
* @param messageId
* @param attachment
* @param attachmentId -1 to create a new attachment or >= 0 to update an existing
* @throws IOException
* @throws MessagingException
*/
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew)
throws IOException, MessagingException
{
long attachmentId = -1;
Uri contentUri = null;
int size = -1;
File tempAttachmentFile = null;
if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart))
{
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId();
}
if (attachment.getBody() != null)
{
Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody)
{
contentUri = ((LocalAttachmentBody) body).getContentUri();
}
else
{
/*
* If the attachment has a body we're expected to save it into the local store
* so we copy the data into a cached attachment file.
*/
InputStream in = attachment.getBody().getInputStream();
tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
size = IOUtils.copy(in, out);
in.close();
out.close();
}
}
if (size == -1)
{
/*
* If the attachment is not yet downloaded see if we can pull a size
* off the Content-Disposition.
*/
String disposition = attachment.getDisposition();
if (disposition != null)
{
String s = MimeUtility.getHeaderParameter(disposition, "size");
if (s != null)
{
size = Integer.parseInt(s);
}
}
}
if (size == -1)
{
size = 0;
}
String storeData =
Utility.combine(attachment.getHeader(
MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ',');
String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name");
String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null);
String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition());
if (name == null && contentDisposition != null)
{
name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
}
if (attachmentId == -1)
{
ContentValues cv = new ContentValues();
cv.put("message_id", messageId);
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("store_data", storeData);
cv.put("size", size);
cv.put("name", name);
cv.put("mime_type", attachment.getMimeType());
cv.put("content_id", contentId);
cv.put("content_disposition", contentDisposition);
attachmentId = mDb.insert("attachments", "message_id", cv);
}
else
{
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("size", size);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (attachmentId != -1 && tempAttachmentFile != null)
{
File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId));
tempAttachmentFile.renameTo(attachmentFile);
contentUri = AttachmentProvider.getAttachmentUri(
new File(mPath).getName(),
attachmentId);
attachment.setBody(new LocalAttachmentBody(contentUri, mApplication));
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
/* The message has attachment with Content-ID */
if (contentId != null && contentUri != null)
{
Cursor cursor = null;
cursor = mDb.query("messages", new String[] { "html_content" }, "id = ?", new String[] { Long.toString(messageId) }, null, null, null);
try
{
if (cursor.moveToNext())
{
String new_html;
new_html = cursor.getString(0);
new_html = new_html.replaceAll("cid:" + contentId, contentUri.toString());
ContentValues cv = new ContentValues();
cv.put("html_content", new_html);
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) });
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart)
{
((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId);
}
}
/**
* Changes the stored uid of the given message (using it's internal id as a key) to
* the uid in the message.
* @param message
*/
public void changeUid(LocalMessage message) throws MessagingException
{
open(OpenMode.READ_WRITE);
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) });
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : messages)
{
message.setFlags(flags, value);
}
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : getMessages(null))
{
message.setFlags(flags, value);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException
{
throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder");
}
public void deleteMessagesOlderThan(long cutoff) throws MessagingException
{
open(OpenMode.READ_ONLY);
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? and date < ?", new Object[]
{
Long.toString(mFolderId), new Long(cutoff)
});
resetUnreadAndFlaggedCounts();
}
private void resetUnreadAndFlaggedCounts()
{
try
{
int newUnread = 0;
int newFlagged = 0;
Message[] messages = getMessages(null);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
newUnread++;
}
if (message.isSet(Flag.FLAGGED) == true)
{
newFlagged++;
}
}
setUnreadMessageCount(newUnread);
setFlaggedMessageCount(newFlagged);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to fetch all messages from LocalStore", e);
}
}
@Override
public void delete(boolean recurse) throws MessagingException
{
// We need to open the folder first to make sure we've got it's id
open(OpenMode.READ_ONLY);
Message[] messages = getMessages(null);
for (Message message : messages)
{
deleteAttachments(message.getUid());
}
mDb.execSQL("DELETE FROM folders WHERE id = ?", new Object[]
{
Long.toString(mFolderId),
});
}
@Override
public boolean equals(Object o)
{
if (o instanceof LocalFolder)
{
return ((LocalFolder)o).mName.equals(mName);
}
return super.equals(o);
}
@Override
public int hashCode()
{
return mName.hashCode();
}
@Override
public Flag[] getPermanentFlags() throws MessagingException
{
return PERMANENT_FLAGS;
}
private void deleteAttachments(long messageId) throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor attachmentsCursor = null;
try
{
attachmentsCursor = mDb.query(
"attachments",
new String[] { "id" },
"message_id = ?",
new String[] { Long.toString(messageId) },
null,
null,
null);
while (attachmentsCursor.moveToNext())
{
long attachmentId = attachmentsCursor.getLong(0);
try
{
File file = new File(mAttachmentsDir, Long.toString(attachmentId));
if (file.exists())
{
file.delete();
}
}
catch (Exception e)
{
}
}
}
finally
{
if (attachmentsCursor != null)
{
attachmentsCursor.close();
}
}
}
private void deleteAttachments(String uid) throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor messagesCursor = null;
try
{
messagesCursor = mDb.query(
"messages",
new String[] { "id" },
"folder_id = ? AND uid = ?",
new String[] { Long.toString(mFolderId), uid },
null,
null,
null);
while (messagesCursor.moveToNext())
{
long messageId = messagesCursor.getLong(0);
deleteAttachments(messageId);
}
}
finally
{
if (messagesCursor != null)
{
messagesCursor.close();
}
}
}
/*
* calcualteContentPreview
* Takes a plain text message body as a string.
* Returns a message summary as a string suitable for showing in a message list
*
* A message summary should be about the first 160 characters
* of unique text written by the message sender
* Quoted text, "On $date" and so on will be stripped out.
* All newlines and whitespace will be compressed.
*
*/
public String calculateContentPreview(String text)
{
if (text == null)
{
return null;
}
text = text.replaceAll("(?ms)^-----BEGIN PGP SIGNED MESSAGE-----.(Hash:\\s*?.*?$)?","");
text = text.replaceAll("https?://\\S+","...");
text = text.replaceAll("^.*\\w.*:","");
text = text.replaceAll("(?m)^>.*$","");
text = text.replaceAll("^On .*wrote.?$","");
text = text.replaceAll("(\\r|\\n)+"," ");
text = text.replaceAll("\\s+"," ");
if (text.length() <= 250)
{
return text;
}
else
{
text = text.substring(0,250);
return text;
}
}
public String markupContent(String text, String html)
{
if (text.length() > 0 && html.length() == 0)
{
html = htmlifyString(text);
}
html = convertEmoji2ImgForDocomo(html);
return html;
}
public String htmlifyString(String text)
{
StringReader reader = new StringReader(text);
StringBuilder buff = new StringBuilder(text.length() + 512);
int c = 0;
try
{
while ((c = reader.read()) != -1)
{
switch (c)
{
case '&':
buff.append("&");
break;
case '<':
buff.append("<");
break;
case '>':
buff.append(">");
break;
case '\r':
break;
default:
buff.append((char)c);
}//switch
}
}
catch (IOException e)
{
//Should never happen
Log.e(K9.LOG_TAG, null, e);
}
text = buff.toString();
text = text.replaceAll("\\s*([-=_]{30,}+)\\s*","<hr />");
text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])","$1 ");
text = text.replaceAll("(?m)(\r\n|\n|\r){4,}","\n\n");
Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
StringBuffer sb = new StringBuffer(text.length() + 512);
sb.append("<html><head><meta name=\"viewport\" content=\"width=device-width, height=device-height\"></head><body>");
sb.append(htmlifyMessageHeader());
while (m.find())
{
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@'))
{
m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
}
else
{
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
sb.append(htmlifyMessageFooter());
sb.append("</body></html>");
text = sb.toString();
return text;
}
private String htmlifyMessageHeader()
{
if (K9.messageViewFixedWidthFont())
{
return "<pre style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
else
{
return "<div style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
}
private String htmlifyMessageFooter()
{
if (K9.messageViewFixedWidthFont())
{
return "</pre>";
}
else
{
return "</div>";
}
}
public String convertEmoji2ImgForDocomo(String html)
{
StringReader reader = new StringReader(html);
StringBuilder buff = new StringBuilder(html.length() + 512);
int c = 0;
try
{
while ((c = reader.read()) != -1)
{
switch (c)
{
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
case 0xE6F9: //docomo kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE729: //docomo wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xE6D2: //docomo info02
buff.append("<img src=\"file:///android_asset/emoticons/info02.gif\" alt=\"info02\" />");
break;
case 0xE753: //docomo smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE68D: //docomo heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE6A5: //docomo downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE6AD: //docomo pouch
buff.append("<img src=\"file:///android_asset/emoticons/pouch.gif\" alt=\"pouch\" />");
break;
case 0xE6D4: //docomo by-d
buff.append("<img src=\"file:///android_asset/emoticons/by-d.gif\" alt=\"by-d\" />");
break;
case 0xE6D7: //docomo free
buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />");
break;
case 0xE6E8: //docomo seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE74E: //docomo snail
buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />");
break;
case 0xE658: //docomo basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE65A: //docomo pocketbell
buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />");
break;
case 0xE6E3: //docomo two
buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />");
break;
case 0xE74A: //docomo cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE6D0: //docomo faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
case 0xE661: //docomo ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE64B: //docomo virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE67E: //docomo ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE6D6: //docomo yen
buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />");
break;
case 0xE6E0: //docomo sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE6FE: //docomo bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE6E1: //docomo mobaq
buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />");
break;
case 0xE70A: //docomo sign05
buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />");
break;
case 0xE667: //docomo bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE731: //docomo copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE678: //docomo upwardright
buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />");
break;
case 0xE694: //docomo scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE682: //docomo bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE64D: //docomo scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE6D9: //docomo key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE734: //docomo secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE74F: //docomo chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE691: //docomo eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE70B: //docomo ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE714: //docomo door
buff.append("<img src=\"file:///android_asset/emoticons/door.gif\" alt=\"door\" />");
break;
case 0xE64F: //docomo capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xE674: //docomo boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE726: //docomo lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE68F: //docomo diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE69B: //docomo wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xE747: //docomo maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE64C: //docomo libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE647: //docomo taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE645: //docomo sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xE6FC: //docomo annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE6E6: //docomo five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE676: //docomo karaoke
buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />");
break;
case 0xE69D: //docomo moon1
buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />");
break;
case 0xE709: //docomo sign04
buff.append("<img src=\"file:///android_asset/emoticons/sign04.gif\" alt=\"sign04\" />");
break;
case 0xE72A: //docomo happy02
buff.append("<img src=\"file:///android_asset/emoticons/happy02.gif\" alt=\"happy02\" />");
break;
case 0xE669: //docomo hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE71B: //docomo ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
case 0xE644: //docomo mist
buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />");
break;
case 0xE73B: //docomo full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xE683: //docomo book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE707: //docomo sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE716: //docomo pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE671: //docomo bar
buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />");
break;
case 0xE72B: //docomo bearing
buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />");
break;
case 0xE65C: //docomo subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE725: //docomo gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xE745: //docomo apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE65F: //docomo rvcar
buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />");
break;
case 0xE664: //docomo building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE737: //docomo danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE702: //docomo sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xE6EC: //docomo heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xE660: //docomo bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE72D: //docomo crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE652: //docomo sports
buff.append("<img src=\"file:///android_asset/emoticons/sports.gif\" alt=\"sports\" />");
break;
case 0xE6B8: //docomo on
buff.append("<img src=\"file:///android_asset/emoticons/on.gif\" alt=\"on\" />");
break;
case 0xE73C: //docomo leftright
buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />");
break;
case 0xE6BA: //docomo clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xE6F0: //docomo happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE701: //docomo sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE63E: //docomo sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xE67D: //docomo event
buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />");
break;
case 0xE689: //docomo memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
case 0xE68B: //docomo game
buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />");
break;
case 0xE718: //docomo wrench
buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />");
break;
case 0xE741: //docomo clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE693: //docomo rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE6F6: //docomo note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xE67A: //docomo music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE743: //docomo tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xE656: //docomo soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE69C: //docomo newmoon
buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />");
break;
case 0xE73E: //docomo school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE750: //docomo penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE696: //docomo downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE6CE: //docomo phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE728: //docomo bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE662: //docomo airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE74C: //docomo noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE704: //docomo sign03
buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />");
break;
case 0xE68E: //docomo spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE698: //docomo foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE712: //docomo snowboard
buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />");
break;
case 0xE684: //docomo ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE6DA: //docomo enter
buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />");
break;
case 0xE6EA: //docomo nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE722: //docomo coldsweats01
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />");
break;
case 0xE6F7: //docomo spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE710: //docomo rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xE73F: //docomo wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE686: //docomo birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE721: //docomo confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE6FF: //docomo notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE724: //docomo pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE6A4: //docomo xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE6FB: //docomo flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE71D: //docomo bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE6DC: //docomo search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE757: //docomo shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE680: //docomo nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xE66D: //docomo signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE66A: //docomo 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE6F4: //docomo wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE641: //docomo snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE6AE: //docomo pen
buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />");
break;
case 0xE70D: //docomo appli02
buff.append("<img src=\"file:///android_asset/emoticons/appli02.gif\" alt=\"appli02\" />");
break;
case 0xE732: //docomo tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE755: //docomo pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE648: //docomo gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE6DE: //docomo flag
buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />");
break;
case 0xE6A1: //docomo dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE6EF: //docomo heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xE643: //docomo typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE65B: //docomo train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE746: //docomo bud
buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />");
break;
case 0xE653: //docomo baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE6B2: //docomo chair
buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />");
break;
case 0xE64A: //docomo leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE6E7: //docomo six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE6E4: //docomo three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xE6DF: //docomo freedial
buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />");
break;
case 0xE744: //docomo banana
buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />");
break;
case 0xE6DB: //docomo clear
buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />");
break;
case 0xE6AC: //docomo slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE666: //docomo hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE663: //docomo house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE695: //docomo paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE67F: //docomo smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE65D: //docomo bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE6B1: //docomo shadow
buff.append("<img src=\"file:///android_asset/emoticons/shadow.gif\" alt=\"shadow\" />");
break;
case 0xE670: //docomo cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xE654: //docomo golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE708: //docomo dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE748: //docomo cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE6F1: //docomo angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE736: //docomo r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xE6A2: //docomo cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE6D1: //docomo info01
buff.append("<img src=\"file:///android_asset/emoticons/info01.gif\" alt=\"info01\" />");
break;
case 0xE687: //docomo telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE68C: //docomo cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE70E: //docomo t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE733: //docomo run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xE679: //docomo carouselpony
buff.append("<img src=\"file:///android_asset/emoticons/carouselpony.gif\" alt=\"carouselpony\" />");
break;
case 0xE646: //docomo aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE690: //docomo club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE64E: //docomo sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xE6F5: //docomo up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xE720: //docomo think
buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />");
break;
case 0xE6E2: //docomo one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xE6D8: //docomo id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE675: //docomo hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
case 0xE6B7: //docomo soon
buff.append("<img src=\"file:///android_asset/emoticons/soon.gif\" alt=\"soon\" />");
break;
case 0xE717: //docomo loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE673: //docomo fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE719: //docomo pencil
buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />");
break;
case 0xE697: //docomo upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xE730: //docomo clip
buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />");
break;
case 0xE6ED: //docomo heart02
buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />");
break;
case 0xE69A: //docomo eyeglass
buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />");
break;
case 0xE65E: //docomo car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xE742: //docomo cherry
buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />");
break;
case 0xE71C: //docomo sandclock
buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />");
break;
case 0xE735: //docomo recycle
buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />");
break;
case 0xE752: //docomo delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE69E: //docomo moon2
buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />");
break;
case 0xE68A: //docomo tv
buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />");
break;
case 0xE706: //docomo sweat01
buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />");
break;
case 0xE738: //docomo ban
buff.append("<img src=\"file:///android_asset/emoticons/ban.gif\" alt=\"ban\" />");
break;
case 0xE672: //docomo beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xE640: //docomo rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xE69F: //docomo moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE657: //docomo ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE70C: //docomo appli01
buff.append("<img src=\"file:///android_asset/emoticons/appli01.gif\" alt=\"appli01\" />");
break;
case 0xE6E5: //docomo four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE699: //docomo shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xE63F: //docomo cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE72F: //docomo ng
buff.append("<img src=\"file:///android_asset/emoticons/ng.gif\" alt=\"ng\" />");
break;
case 0xE6A3: //docomo yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE73A: //docomo pass
buff.append("<img src=\"file:///android_asset/emoticons/pass.gif\" alt=\"pass\" />");
break;
case 0xE67C: //docomo drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xE727: //docomo good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE6EB: //docomo zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xE72C: //docomo catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE6D5: //docomo d-point
buff.append("<img src=\"file:///android_asset/emoticons/d-point.gif\" alt=\"d-point\" />");
break;
case 0xE6F2: //docomo despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE700: //docomo down
buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />");
break;
case 0xE655: //docomo tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE703: //docomo sign02
buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />");
break;
case 0xE711: //docomo denim
buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />");
break;
case 0xE705: //docomo impact
buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />");
break;
case 0xE642: //docomo thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE66C: //docomo parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE6F3: //docomo sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE71E: //docomo japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xE6FD: //docomo punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xE73D: //docomo updown
buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />");
break;
case 0xE66F: //docomo restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE66E: //docomo toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
case 0xE739: //docomo empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE723: //docomo coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE6B9: //docomo end
buff.append("<img src=\"file:///android_asset/emoticons/end.gif\" alt=\"end\" />");
break;
case 0xE67B: //docomo art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xE72E: //docomo weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE715: //docomo dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE6CF: //docomo mailto
buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />");
break;
case 0xE6F8: //docomo cute
buff.append("<img src=\"file:///android_asset/emoticons/cute.gif\" alt=\"cute\" />");
break;
case 0xE6DD: //docomo new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE651: //docomo pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE756: //docomo wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE649: //docomo cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xE650: //docomo aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE740: //docomo fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE681: //docomo camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE71F: //docomo watch
buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />");
break;
case 0xE6EE: //docomo heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE71A: //docomo crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE6B3: //docomo night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE66B: //docomo gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE692: //docomo ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE685: //docomo present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE6E9: //docomo eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE70F: //docomo moneybag
buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />");
break;
case 0xE749: //docomo riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE6A0: //docomo fullmoon
buff.append("<img src=\"file:///android_asset/emoticons/fullmoon.gif\" alt=\"fullmoon\" />");
break;
case 0xE74D: //docomo bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE665: //docomo postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xE677: //docomo movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE668: //docomo atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE688: //docomo mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE6FA: //docomo shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xE713: //docomo bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xE74B: //docomo bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xE754: //docomo horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE751: //docomo fish
buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />");
break;
case 0xE659: //docomo motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE6D3: //docomo mail
buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />");
break;
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
// The spaces between the < and the img are a hack to avoid triggering
// K-9's 'load images' button
case 0xE223: //softbank eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE415: //softbank coldsweats01
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />");
break;
case 0xE21F: //softbank four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE125: //softbank ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE148: //softbank book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE242: //softbank cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xE31C: //softbank rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xE252: //softbank danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE011: //softbank scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE342: //softbank riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE04B: //softbank rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xE03E: //softbank note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xE43C: //softbank sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xE20A: //softbank wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xE42A: //softbank basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE03D: //softbank movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE30E: //softbank smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE003: //softbank kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE21C: //softbank one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xE237: //softbank upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xE407: //softbank sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE03B: //softbank fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE40E: //softbank gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xE245: //softbank libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE24A: //softbank pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE443: //softbank typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE052: //softbank dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE244: //softbank virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE523: //softbank chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE023: //softbank heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE325: //softbank bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xE239: //softbank downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE20C: //softbank heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE211: //softbank freedial
buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />");
break;
case 0xE11F: //softbank chair
buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />");
break;
case 0xE108: //softbank coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE330: //softbank dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE404: //softbank smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE304: //softbank tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xE419: //softbank eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE13D: //softbank thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE013: //softbank ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE136: //softbank bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE059: //softbank angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE01D: //softbank airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE048: //softbank snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE435: //softbank bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE20E: //softbank spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE247: //softbank sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xE157: //softbank school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE10F: //softbank flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE502: //softbank art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xE338: //softbank japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xE34B: //softbank birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE22B: //softbank empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE311: //softbank bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE012: //softbank paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE151: //softbank toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
case 0xE01A: //softbank horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE03A: //softbank gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE03F: //softbank key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE00D: //softbank punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xE24D: //softbank ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE105: //softbank bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE00E: //softbank good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE154: //softbank atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE405: //softbank wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xE030: //softbank cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE057: //softbank happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE229: //softbank id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE016: //softbank baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE044: //softbank wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE115: //softbank run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xE14F: //softbank parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE327: //softbank heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xE014: //softbank golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE021: //softbank sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xE30A: //softbank music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE411: //softbank crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE536: //softbank foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE047: //softbank beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xE43E: //softbank wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE022: //softbank heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xE007: //softbank shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xE010: //softbank rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE32E: //softbank shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xE055: //softbank penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE03C: //softbank karaoke
buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />");
break;
case 0xE018: //softbank soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE159: //softbank bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE107: //softbank shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE04A: //softbank sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xE156: //softbank 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE110: //softbank clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE034: //softbank ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
case 0xE24F: //softbank r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xE112: //softbank present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE14D: //softbank bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE42E: //softbank rvcar
buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />");
break;
case 0xE13E: //softbank boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE413: //softbank weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE241: //softbank gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE212: //softbank new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE324: //softbank slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE220: //softbank five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE503: //softbank drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xE248: //softbank capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xE049: //softbank cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE243: //softbank leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE326: //softbank notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE00B: //softbank faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
case 0xE221: //softbank six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE240: //softbank taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE24E: //softbank copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE224: //softbank nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE008: //softbank camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE01E: //softbank train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE20D: //softbank diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE009: //softbank telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE019: //softbank fish
buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />");
break;
case 0xE01C: //softbank yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE40A: //softbank confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE246: //softbank scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE120: //softbank fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE323: //softbank bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE345: //softbank apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE339: //softbank bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE13C: //softbank sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE106: //softbank lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE340: //softbank noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE20F: //softbank club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE114: //softbank search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE10E: //softbank crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE406: //softbank wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE331: //softbank sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE04F: //softbank cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE301: //softbank memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
case 0xE01B: //softbank car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xE314: //softbank ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE315: //softbank secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE236: //softbank up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xE208: //softbank nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xE006: //softbank t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE12A: //softbank tv
buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />");
break;
case 0xE238: //softbank downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE10B: //softbank pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE126: //softbank cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE402: //softbank catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE416: //softbank pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE045: //softbank cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xE41B: //softbank ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE23F: //softbank aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE21E: //softbank three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xE056: //softbank delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE14E: //softbank signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE155: //softbank hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE033: //softbank xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE22A: //softbank full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xE123: //softbank spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE132: //softbank motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE434: //softbank subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE403: //softbank think
buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />");
break;
case 0xE043: //softbank restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE537: //softbank tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE058: //softbank despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE04C: //softbank moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE21D: //softbank two
buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />");
break;
case 0xE202: //softbank ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE30B: //softbank bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xE118: //softbank maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE103: //softbank loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE225: //softbank zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xE00C: //softbank pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE210: //softbank sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE015: //softbank tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE038: //softbank building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE02D: //softbank clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xE334: //softbank annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE153: //softbank postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xE222: //softbank seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE12F: //softbank dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE00A: //softbank mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE158: //softbank hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE249: //softbank aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE036: //softbank house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE046: //softbank cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE104: //softbank phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE44B: //softbank night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE313: //softbank hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
// The spaces between the < and the img are a hack to avoid triggering
// K-9's 'load images' button
case 0xE488: //kddi sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xEA88: //kddi id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE4BA: //kddi baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE525: //kddi four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE578: //kddi free
buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />");
break;
case 0xE4C1: //kddi wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE512: //kddi bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xEB83: //kddi rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE4D0: //kddi cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE473: //kddi crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE48C: //kddi rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xEAC2: //kddi bearing
buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />");
break;
case 0xE47E: //kddi nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xEAC0: //kddi despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE559: //kddi r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xEB2D: //kddi up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xEA89: //kddi full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xEAC9: //kddi gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xEB79: //kddi recycle
buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />");
break;
case 0xE5AC: //kddi zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xEAAE: //kddi japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xEB30: //kddi sign03
buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />");
break;
case 0xE4B6: //kddi soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE556: //kddi downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE4BE: //kddi slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE4A5: //kddi toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
// Skipping kddi codepoint E523 two
// It conflicts with an earlier definition from another carrier:
// softbank chick
case 0xE496: //kddi scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE4C6: //kddi game
buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />");
break;
case 0xE5A0: //kddi birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE5B8: //kddi pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE516: //kddi hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
case 0xE475: //kddi sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE4A3: //kddi atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE59A: //kddi basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE497: //kddi sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xEACD: //kddi delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE5A8: //kddi newmoon
buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />");
break;
case 0xE49E: //kddi ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE5AE: //kddi wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE4E6: //kddi sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE59E: //kddi event
buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />");
break;
case 0xE4AB: //kddi house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE491: //kddi gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE4C9: //kddi xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE5BE: //kddi note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xEB2F: //kddi sign02
buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />");
break;
case 0xE508: //kddi music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE5DF: //kddi hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE5BC: //kddi subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE5C9: //kddi crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE4BC: //kddi spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE514: //kddi ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
// Skipping kddi codepoint E502 tv
// It conflicts with an earlier definition from another carrier:
// softbank art
case 0xE4AC: //kddi restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE529: //kddi eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE518: //kddi search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE505: //kddi notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE498: //kddi capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xEB7E: //kddi snail
buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />");
break;
case 0xEA97: //kddi bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xEB08: //kddi phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE4D2: //kddi cherry
buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />");
break;
case 0xE54D: //kddi downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE5C3: //kddi wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xEAAC: //kddi ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE515: //kddi camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE5B6: //kddi t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE5C4: //kddi lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE4AD: //kddi building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE4CE: //kddi maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE5AA: //kddi moon2
buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />");
break;
case 0xE5B4: //kddi noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE5A6: //kddi scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE4AA: //kddi bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE4B5: //kddi train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE477: //kddi heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE481: //kddi danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE597: //kddi cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xEB2B: //kddi shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xEB7C: //kddi wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE471: //kddi happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE4CA: //kddi cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE4D5: //kddi riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE587: //kddi wrench
buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />");
break;
case 0xEB2A: //kddi foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE47D: //kddi smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE4DC: //kddi penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE4B3: //kddi airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE4DE: //kddi pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE59B: //kddi pocketbell
buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />");
break;
case 0xE4AF: //kddi bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE4A6: //kddi parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE486: //kddi moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE5A4: //kddi eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE50C: //kddi cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE54C: //kddi upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xEA82: //kddi ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE4B1: //kddi car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xEB80: //kddi smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE5B0: //kddi impact
buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />");
break;
case 0xE504: //kddi moneybag
buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />");
break;
case 0xE4B9: //kddi motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE494: //kddi virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE595: //kddi heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xEB03: //kddi pen
buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />");
break;
case 0xE57D: //kddi yen
buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />");
break;
case 0xE598: //kddi mist
buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />");
break;
case 0xE5A2: //kddi diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE4A4: //kddi 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE524: //kddi three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xEB7B: //kddi updown
buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />");
break;
case 0xE5A1: //kddi spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE495: //kddi libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE588: //kddi mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE599: //kddi golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE520: //kddi faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
// Skipping kddi codepoint E503 karaoke
// It conflicts with an earlier definition from another carrier:
// softbank drama
case 0xE4D6: //kddi fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE4A1: //kddi pencil
buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />");
break;
case 0xE522: //kddi one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xEB84: //kddi sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE476: //kddi flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE46B: //kddi run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xEAF5: //kddi drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xEAB9: //kddi apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE4EB: //kddi kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE55D: //kddi enter
buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />");
break;
case 0xE59F: //kddi ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE526: //kddi five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE571: //kddi gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE517: //kddi movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE4B8: //kddi snowboard
buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />");
break;
case 0xEAE8: //kddi sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xEA80: //kddi school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE47C: //kddi sandclock
buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />");
break;
case 0xEB31: //kddi sign05
buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />");
break;
case 0xE5AB: //kddi clear
buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />");
break;
case 0xE5DE: //kddi postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xEB62: //kddi mailto
buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />");
break;
case 0xE528: //kddi seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE4C2: //kddi bar
buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />");
break;
case 0xE487: //kddi thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE5A9: //kddi moon1
buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />");
break;
case 0xEB7A: //kddi leftright
buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />");
break;
case 0xE513: //kddi clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE492: //kddi cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xEB78: //kddi loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE4E0: //kddi chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE4CF: //kddi present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE478: //kddi heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xEAC3: //kddi sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE52A: //kddi nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE482: //kddi sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xEABF: //kddi catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE527: //kddi six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE52C: //kddi mobaq
buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />");
break;
case 0xE485: //kddi snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE4B7: //kddi tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE5BD: //kddi fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE558: //kddi copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE4D8: //kddi horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE4B0: //kddi bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE596: //kddi telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE48F: //kddi aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE46A: //kddi signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE472: //kddi angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE54E: //kddi tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE51A: //kddi boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE493: //kddi leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE5A3: //kddi club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE499: //kddi aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE4AE: //kddi bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE4E7: //kddi bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE49F: //kddi book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE5AD: //kddi ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE5A7: //kddi paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE4E5: //kddi annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE4A0: //kddi clip
buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />");
break;
case 0xE509: //kddi rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xEAAF: //kddi bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE519: //kddi key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE594: //kddi clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xEB7D: //kddi bud
buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />");
break;
case 0xEA8A: //kddi empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE5B5: //kddi new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE47A: //kddi bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE5C6: //kddi coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE49A: //kddi pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE4F3: //kddi punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xEB5D: //kddi pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE469: //kddi typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE5B1: //kddi sweat01
buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />");
break;
case 0xE4C7: //kddi dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE5C5: //kddi shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE4F9: //kddi good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE4F1: //kddi secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE4E4: //kddi tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xEA81: //kddi hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE4FE: //kddi eyeglass
buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />");
break;
case 0xEAF1: //kddi night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE555: //kddi upwardright
buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />");
break;
case 0xEB2E: //kddi down
buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />");
break;
case 0xE4DB: //kddi cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE59C: //kddi art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xEB69: //kddi weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE4F4: //kddi dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE490: //kddi taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE57A: //kddi watch
buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />");
break;
case 0xEB2C: //kddi flag
buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />");
break;
case 0xEB77: //kddi denim
buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />");
break;
case 0xEAC5: //kddi confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE4B4: //kddi yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE49C: //kddi bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE5A5: //kddi ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE4E1: //kddi dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE521: //kddi mail
buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />");
break;
case 0xEB35: //kddi banana
buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />");
break;
case 0xEAA5: //kddi heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE47F: //kddi wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xEB75: //kddi heart02
buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />");
break;
case 0xE48D: //kddi cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE4C3: //kddi beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xEAAB: //kddi shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xEA92: //kddi memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
default:
buff.append((char)c);
}//switch
}
}
catch (IOException e)
{
//Should never happen
Log.e(K9.LOG_TAG, null, e);
}
return buff.toString();
}
@Override
public boolean isInTopGroup()
{
return inTopGroup;
}
public void setInTopGroup(boolean inTopGroup)
{
this.inTopGroup = inTopGroup;
}
}
public class LocalTextBody extends TextBody
{
private String mBodyForDisplay;
public LocalTextBody(String body)
{
super(body);
}
public LocalTextBody(String body, String bodyForDisplay) throws MessagingException
{
super(body);
this.mBodyForDisplay = bodyForDisplay;
}
public String getBodyForDisplay()
{
return mBodyForDisplay;
}
public void setBodyForDisplay(String mBodyForDisplay)
{
this.mBodyForDisplay = mBodyForDisplay;
}
}//LocalTextBody
public class LocalMessage extends MimeMessage
{
private long mId;
private int mAttachmentCount;
private String mSubject;
private String mPreview = "";
private boolean mHeadersLoaded = false;
private boolean mMessageDirty = false;
public LocalMessage()
{
}
LocalMessage(String uid, Folder folder) throws MessagingException
{
this.mUid = uid;
this.mFolder = folder;
}
private void populateFromGetMessageCursor(Cursor cursor)
throws MessagingException
{
this.setSubject(cursor.getString(0) == null ? "" : cursor.getString(0));
Address[] from = Address.unpack(cursor.getString(1));
if (from.length > 0)
{
this.setFrom(from[0]);
}
this.setInternalSentDate(new Date(cursor.getLong(2)));
this.setUid(cursor.getString(3));
String flagList = cursor.getString(4);
if (flagList != null && flagList.length() > 0)
{
String[] flags = flagList.split(",");
for (String flag : flags)
{
try
{
this.setFlagInternal(Flag.valueOf(flag), true);
}
catch (Exception e)
{
if ("X_BAD_FLAG".equals(flag) == false)
{
Log.w(K9.LOG_TAG, "Unable to parse flag " + flag);
}
}
}
}
this.mId = cursor.getLong(5);
this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6)));
this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7)));
this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8)));
this.setReplyTo(Address.unpack(cursor.getString(9)));
this.mAttachmentCount = cursor.getInt(10);
this.setInternalDate(new Date(cursor.getLong(11)));
this.setMessageId(cursor.getString(12));
mPreview = (cursor.getString(14) == null ? "" : cursor.getString(14));
if (this.mFolder == null)
{
LocalFolder f = new LocalFolder(cursor.getInt(13));
f.open(LocalFolder.OpenMode.READ_WRITE);
this.mFolder = f;
}
}
/* Custom version of writeTo that updates the MIME message based on localMessage
* changes.
*/
@Override
public void writeTo(OutputStream out) throws IOException, MessagingException
{
if (mMessageDirty) buildMimeRepresentation();
super.writeTo(out);
}
private void buildMimeRepresentation() throws MessagingException
{
if (!mMessageDirty)
{
return;
}
super.setSubject(mSubject);
if (this.mFrom != null && this.mFrom.length > 0)
{
super.setFrom(this.mFrom[0]);
}
super.setReplyTo(mReplyTo);
super.setSentDate(this.getSentDate());
super.setRecipients(RecipientType.TO, mTo);
super.setRecipients(RecipientType.CC, mCc);
super.setRecipients(RecipientType.BCC, mBcc);
if (mMessageId != null) super.setMessageId(mMessageId);
mMessageDirty = false;
return;
}
public String getPreview()
{
return mPreview;
}
@Override
public String getSubject() throws MessagingException
{
return mSubject;
}
@Override
public void setSubject(String subject) throws MessagingException
{
mSubject = subject;
mMessageDirty = true;
}
@Override
public void setMessageId(String messageId)
{
mMessageId = messageId;
mMessageDirty = true;
}
public int getAttachmentCount()
{
return mAttachmentCount;
}
@Override
public void setFrom(Address from) throws MessagingException
{
this.mFrom = new Address[] { from };
mMessageDirty = true;
}
@Override
public void setReplyTo(Address[] replyTo) throws MessagingException
{
if (replyTo == null || replyTo.length == 0)
{
mReplyTo = null;
}
else
{
mReplyTo = replyTo;
}
mMessageDirty = true;
}
/*
* For performance reasons, we add headers instead of setting them (see super implementation)
* which removes (expensive) them before adding them
*/
@Override
public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException
{
if (type == RecipientType.TO)
{
if (addresses == null || addresses.length == 0)
{
this.mTo = null;
}
else
{
this.mTo = addresses;
}
}
else if (type == RecipientType.CC)
{
if (addresses == null || addresses.length == 0)
{
this.mCc = null;
}
else
{
this.mCc = addresses;
}
}
else if (type == RecipientType.BCC)
{
if (addresses == null || addresses.length == 0)
{
this.mBcc = null;
}
else
{
this.mBcc = addresses;
}
}
else
{
throw new MessagingException("Unrecognized recipient type.");
}
mMessageDirty = true;
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException
{
super.setFlag(flag, set);
}
public long getId()
{
return mId;
}
@Override
public void setFlag(Flag flag, boolean set) throws MessagingException
{
if (flag == Flag.DELETED && set)
{
delete();
}
else if (flag == Flag.X_DESTROYED && set)
{
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL("DELETE FROM messages WHERE id = ?",
new Object[] { mId });
((LocalFolder)mFolder).deleteHeaders(mId);
}
/*
* Update the unread count on the folder.
*/
try
{
if (flag == Flag.DELETED || flag == Flag.X_DESTROYED
|| (flag == Flag.SEEN && !isSet(Flag.DELETED)))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set && !isSet(Flag.SEEN))
{
folder.setUnreadMessageCount(folder.getUnreadMessageCount() - 1);
}
else if (!set && isSet(Flag.SEEN))
{
folder.setUnreadMessageCount(folder.getUnreadMessageCount() + 1);
}
}
if ((flag == Flag.DELETED || flag == Flag.X_DESTROYED) && isSet(Flag.FLAGGED))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set)
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() - 1);
}
else
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + 1);
}
}
if (flag == Flag.FLAGGED && !isSet(Flag.DELETED))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set)
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + 1);
}
else
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() - 1);
}
}
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to update LocalStore unread message count",
me);
throw new RuntimeException(me);
}
super.setFlag(flag, set);
/*
* Set the flags on the message.
*/
mDb.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[]
{
Utility.combine(getFlags(), ',').toUpperCase(), mId
});
}
private void delete() throws MessagingException
{
/*
* Delete all of the message's content to save space.
*/
mDb.execSQL(
"UPDATE messages SET " +
"deleted = 1," +
"subject = NULL, " +
"sender_list = NULL, " +
"date = NULL, " +
"to_list = NULL, " +
"cc_list = NULL, " +
"bcc_list = NULL, " +
"preview = NULL, " +
"html_content = NULL, " +
"text_content = NULL, " +
"reply_to_list = NULL " +
"WHERE id = ?",
new Object[]
{
mId
});
/*
* Delete all of the message's attachments to save space.
* We do this explicit deletion here because we're not deleting the record
* in messages, which means our ON DELETE trigger for messages won't cascade
*/
mDb.execSQL("DELETE FROM attachments WHERE message_id = ?",
new Object[]
{
mId
});
((LocalFolder)mFolder).deleteAttachments(mId);
((LocalFolder)mFolder).deleteHeaders(mId);
}
private void loadHeaders()
{
ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>();
messages.add(this);
mHeadersLoaded = true; // set true before calling populate headers to stop recursion
((LocalFolder) mFolder).populateHeaders(messages);
}
@Override
public void addHeader(String name, String value)
{
if (!mHeadersLoaded)
loadHeaders();
super.addHeader(name, value);
}
@Override
public void setHeader(String name, String value)
{
if (!mHeadersLoaded)
loadHeaders();
super.setHeader(name, value);
}
@Override
public String[] getHeader(String name)
{
if (!mHeadersLoaded)
loadHeaders();
return super.getHeader(name);
}
@Override
public void removeHeader(String name)
{
if (!mHeadersLoaded)
loadHeaders();
super.removeHeader(name);
}
@Override
public Set<String> getHeaderNames()
{
if (!mHeadersLoaded)
loadHeaders();
return super.getHeaderNames();
}
}
public class LocalAttachmentBodyPart extends MimeBodyPart
{
private long mAttachmentId = -1;
public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException
{
super(body);
mAttachmentId = attachmentId;
}
/**
* Returns the local attachment id of this body, or -1 if it is not stored.
* @return
*/
public long getAttachmentId()
{
return mAttachmentId;
}
public void setAttachmentId(long attachmentId)
{
mAttachmentId = attachmentId;
}
@Override
public String toString()
{
return "" + mAttachmentId;
}
}
public static class LocalAttachmentBody implements Body
{
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private Application mApplication;
private Uri mUri;
public LocalAttachmentBody(Uri uri, Application application)
{
mApplication = application;
mUri = uri;
}
public InputStream getInputStream() throws MessagingException
{
try
{
return mApplication.getContentResolver().openInputStream(mUri);
}
catch (FileNotFoundException fnfe)
{
/*
* Since it's completely normal for us to try to serve up attachments that
* have been blown away, we just return an empty stream.
*/
return new ByteArrayInputStream(EMPTY_BYTE_ARRAY);
}
}
public void writeTo(OutputStream out) throws IOException, MessagingException
{
InputStream in = getInputStream();
Base64OutputStream base64Out = new Base64OutputStream(out);
IOUtils.copy(in, base64Out);
base64Out.close();
}
public Uri getContentUri()
{
return mUri;
}
}
}
|
src/com/fsck/k9/mail/store/LocalStore.java
|
package com.fsck.k9.mail.store;
import android.app.Application;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.controller.MessageRemovalListener;
import com.fsck.k9.controller.MessageRetrievalListener;
import com.fsck.k9.helper.Regex;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.filter.Base64OutputStream;
import com.fsck.k9.mail.internet.*;
import com.fsck.k9.provider.AttachmentProvider;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
/**
* <pre>
* Implements a SQLite database backed local store for Messages.
* </pre>
*/
public class LocalStore extends Store implements Serializable
{
private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0];
/**
* Immutable empty {@link String} array
*/
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final int DB_VERSION = 37;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN, Flag.FLAGGED };
private String mPath;
private SQLiteDatabase mDb;
private File mAttachmentsDir;
private Application mApplication;
private String uUid = null;
private static Set<String> HEADERS_TO_SAVE = new HashSet<String>();
static
{
HEADERS_TO_SAVE.add(K9.K9MAIL_IDENTITY);
HEADERS_TO_SAVE.add("To");
HEADERS_TO_SAVE.add("Cc");
HEADERS_TO_SAVE.add("From");
HEADERS_TO_SAVE.add("In-Reply-To");
HEADERS_TO_SAVE.add("References");
HEADERS_TO_SAVE.add("Content-ID");
HEADERS_TO_SAVE.add("Content-Disposition");
HEADERS_TO_SAVE.add("X-User-Agent");
}
/*
* a String containing the columns getMessages expects to work with
* in the correct order.
*/
static private String GET_MESSAGES_COLS =
"subject, sender_list, date, uid, flags, id, to_list, cc_list, "
+ "bcc_list, reply_to_list, attachment_count, internal_date, message_id, folder_id, preview ";
/**
* local://localhost/path/to/database/uuid.db
*/
public LocalStore(Account account, Application application) throws MessagingException
{
super(account);
mApplication = application;
URI uri = null;
try
{
uri = new URI(mAccount.getLocalStoreUri());
}
catch (Exception e)
{
throw new MessagingException("Invalid uri for LocalStore");
}
if (!uri.getScheme().equals("local"))
{
throw new MessagingException("Invalid scheme");
}
mPath = uri.getPath();
// We need to associate the localstore with the account. Since we don't have the account
// handy here, we'll take the filename from the DB and use the basename of the filename
// Folders probably should have references to their containing accounts
//TODO: We do have an account object now
File dbFile = new File(mPath);
String[] tokens = dbFile.getName().split("\\.");
uUid = tokens[0];
openOrCreateDataspace(application);
}
private void openOrCreateDataspace(Application application)
{
File parentDir = new File(mPath).getParentFile();
if (!parentDir.exists())
{
parentDir.mkdirs();
}
mAttachmentsDir = new File(mPath + "_att");
if (!mAttachmentsDir.exists())
{
mAttachmentsDir.mkdirs();
}
mDb = SQLiteDatabase.openOrCreateDatabase(mPath, null);
if (mDb.getVersion() != DB_VERSION)
{
doDbUpgrade(mDb, application);
}
}
private void doDbUpgrade(SQLiteDatabase mDb, Application application)
{
Log.i(K9.LOG_TAG, String.format("Upgrading database from version %d to version %d",
mDb.getVersion(), DB_VERSION));
AttachmentProvider.clear(application);
try
{
// schema version 29 was when we moved to incremental updates
// in the case of a new db or a < v29 db, we blow away and start from scratch
if (mDb.getVersion() < 29)
{
mDb.execSQL("DROP TABLE IF EXISTS folders");
mDb.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, "
+ "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT, push_state TEXT, last_pushed INTEGER, flagged_count INTEGER default 0)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)");
mDb.execSQL("DROP TABLE IF EXISTS messages");
mDb.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted INTEGER default 0, folder_id INTEGER, uid TEXT, subject TEXT, "
+ "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, "
+ "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT, preview TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS headers");
mDb.execSQL("CREATE TABLE headers (id INTEGER PRIMARY KEY, message_id INTEGER, name TEXT, value TEXT)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS header_folder ON headers (message_id)");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)");
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id");
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id_date");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)");
mDb.execSQL("DROP TABLE IF EXISTS attachments");
mDb.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER,"
+ "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT,"
+ "mime_type TEXT, content_id TEXT, content_disposition TEXT)");
mDb.execSQL("DROP TABLE IF EXISTS pending_commands");
mDb.execSQL("CREATE TABLE pending_commands " +
"(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_folder");
mDb.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;");
mDb.execSQL("DROP TRIGGER IF EXISTS delete_message");
mDb.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; "
+ "DELETE FROM headers where old.id = message_id; END;");
}
else
{ // in the case that we're starting out at 29 or newer, run all the needed updates
if (mDb.getVersion() < 30)
{
try
{
mDb.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0");
}
catch (SQLiteException e)
{
if (! e.toString().startsWith("duplicate column name: deleted"))
{
throw e;
}
}
}
if (mDb.getVersion() < 31)
{
mDb.execSQL("DROP INDEX IF EXISTS msg_folder_id_date");
mDb.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)");
}
if (mDb.getVersion() < 32)
{
mDb.execSQL("UPDATE messages SET deleted = 1 WHERE flags LIKE '%DELETED%'");
}
if (mDb.getVersion() < 33)
{
try
{
mDb.execSQL("ALTER TABLE messages ADD preview TEXT");
}
catch (SQLiteException e)
{
if (! e.toString().startsWith("duplicate column name: preview"))
{
throw e;
}
}
}
if (mDb.getVersion() < 34)
{
try
{
mDb.execSQL("ALTER TABLE folders ADD flagged_count INTEGER default 0");
}
catch (SQLiteException e)
{
if (! e.getMessage().startsWith("duplicate column name: flagged_count"))
{
throw e;
}
}
}
if (mDb.getVersion() < 35)
{
try
{
mDb.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e);
}
}
if (mDb.getVersion() < 36)
{
try
{
mDb.execSQL("ALTER TABLE attachments ADD content_id TEXT");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments");
}
}
if (mDb.getVersion() < 37)
{
try
{
mDb.execSQL("ALTER TABLE attachments ADD content_disposition TEXT");
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments");
}
}
}
}
catch (SQLiteException e)
{
Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0");
mDb.setVersion(0);
throw new Error("Database upgrade failed! Resetting your DB version to 0 to force a full schema recreation.");
}
mDb.setVersion(DB_VERSION);
if (mDb.getVersion() != DB_VERSION)
{
throw new Error("Database upgrade failed!");
}
try
{
pruneCachedAttachments(true);
}
catch (Exception me)
{
Log.e(K9.LOG_TAG, "Exception while force pruning attachments during DB update", me);
}
}
public long getSize()
{
long attachmentLength = 0;
File[] files = mAttachmentsDir.listFiles();
for (File file : files)
{
if (file.exists())
{
attachmentLength += file.length();
}
}
File dbFile = new File(mPath);
return dbFile.length() + attachmentLength;
}
public void compact() throws MessagingException
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize());
mDb.execSQL("VACUUM");
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "After compaction size = " + getSize());
}
public void clear() throws MessagingException
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Before prune size = " + getSize());
pruneCachedAttachments(true);
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize());
Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount());
Log.i(K9.LOG_TAG, "Before clear message count = " + getMessageCount());
Log.i(K9.LOG_TAG, "After prune / before clear size = " + getSize());
}
// don't delete messages that are Local, since there is no copy on the server.
// Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have
// been deleted locally. They take up insignificant space
mDb.execSQL("DELETE FROM messages WHERE deleted = 0 and uid not like 'Local%'");
mDb.execSQL("update folders set flagged_count = 0, unread_count = 0");
compact();
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount());
Log.i(K9.LOG_TAG, "After clear size = " + getSize());
}
}
public int getMessageCount() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
public int getFolderCount() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM folders", null);
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public LocalFolder getFolder(String name) throws MessagingException
{
return new LocalFolder(name);
}
// TODO this takes about 260-300ms, seems slow.
@Override
public List<? extends Folder> getPersonalNamespaces(boolean forceListAll) throws MessagingException
{
LinkedList<LocalFolder> folders = new LinkedList<LocalFolder>();
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT id, name, unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders", null);
while (cursor.moveToNext())
{
LocalFolder folder = new LocalFolder(cursor.getString(1));
folder.open(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8));
folders.add(folder);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return folders;
}
@Override
public void checkSettings() throws MessagingException
{
}
/**
* Delete the entire Store and it's backing database.
*/
public void delete()
{
try
{
mDb.close();
}
catch (Exception e)
{
}
try
{
File[] attachments = mAttachmentsDir.listFiles();
for (File attachment : attachments)
{
if (attachment.exists())
{
attachment.delete();
}
}
if (mAttachmentsDir.exists())
{
mAttachmentsDir.delete();
}
}
catch (Exception e)
{
}
try
{
new File(mPath).delete();
}
catch (Exception e)
{
}
}
public void recreate()
{
delete();
openOrCreateDataspace(mApplication);
}
public void pruneCachedAttachments() throws MessagingException
{
pruneCachedAttachments(false);
}
/**
* Deletes all cached attachments for the entire store.
*/
public void pruneCachedAttachments(boolean force) throws MessagingException
{
if (force)
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, null, null);
}
File[] files = mAttachmentsDir.listFiles();
for (File file : files)
{
if (file.exists())
{
if (!force)
{
Cursor cursor = null;
try
{
cursor = mDb.query(
"attachments",
new String[] { "store_data" },
"id = ?",
new String[] { file.getName() },
null,
null,
null);
if (cursor.moveToNext())
{
if (cursor.getString(0) == null)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting");
/*
* If the attachment has no store data it is not recoverable, so
* we won't delete it.
*/
continue;
}
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
if (!force)
{
try
{
ContentValues cv = new ContentValues();
cv.putNull("content_uri");
mDb.update("attachments", cv, "id = ?", new String[] { file.getName() });
}
catch (Exception e)
{
/*
* If the row has gone away before we got to mark it not-downloaded that's
* okay.
*/
}
}
if (!file.delete())
{
file.deleteOnExit();
}
}
}
}
public void resetVisibleLimits()
{
resetVisibleLimits(mAccount.getDisplayCount());
}
public void resetVisibleLimits(int visibleLimit)
{
ContentValues cv = new ContentValues();
cv.put("visible_limit", Integer.toString(visibleLimit));
mDb.update("folders", cv, null, null);
}
public ArrayList<PendingCommand> getPendingCommands()
{
Cursor cursor = null;
try
{
cursor = mDb.query("pending_commands",
new String[] { "id", "command", "arguments" },
null,
null,
null,
null,
"id ASC");
ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>();
while (cursor.moveToNext())
{
PendingCommand command = new PendingCommand();
command.mId = cursor.getLong(0);
command.command = cursor.getString(1);
String arguments = cursor.getString(2);
command.arguments = arguments.split(",");
for (int i = 0; i < command.arguments.length; i++)
{
command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]);
}
commands.add(command);
}
return commands;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
public void addPendingCommand(PendingCommand command)
{
try
{
for (int i = 0; i < command.arguments.length; i++)
{
command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8");
}
ContentValues cv = new ContentValues();
cv.put("command", command.command);
cv.put("arguments", Utility.combine(command.arguments, ','));
mDb.insert("pending_commands", "command", cv);
}
catch (UnsupportedEncodingException usee)
{
throw new Error("Aparently UTF-8 has been lost to the annals of history.");
}
}
public void removePendingCommand(PendingCommand command)
{
mDb.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) });
}
public void removePendingCommands()
{
mDb.delete("pending_commands", null, null);
}
public static class PendingCommand
{
private long mId;
public String command;
public String[] arguments;
@Override
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(command);
sb.append(": ");
for (String argument : arguments)
{
sb.append(", ");
sb.append(argument);
//sb.append("\n");
}
return sb.toString();
}
}
@Override
public boolean isMoveCapable()
{
return true;
}
@Override
public boolean isCopyCapable()
{
return true;
}
public Message[] searchForMessages(MessageRetrievalListener listener, String[] queryFields, String queryString,
List<LocalFolder> folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException
{
List<String> args = new LinkedList<String>();
StringBuilder whereClause = new StringBuilder();
if (queryString != null && queryString.length() > 0)
{
boolean anyAdded = false;
String likeString = "%"+queryString+"%";
whereClause.append(" AND (");
for (String queryField : queryFields)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
whereClause.append(queryField + " LIKE ? ");
args.add(likeString);
anyAdded = true;
}
whereClause.append(" )");
}
if (folders != null && folders.size() > 0)
{
whereClause.append(" AND folder_id in (");
boolean anyAdded = false;
for (LocalFolder folder : folders)
{
if (anyAdded == true)
{
whereClause.append(",");
}
anyAdded = true;
whereClause.append("?");
args.add(Long.toString(folder.getId()));
}
whereClause.append(" )");
}
if (messages != null && messages.length > 0)
{
whereClause.append(" AND ( ");
boolean anyAdded = false;
for (Message message : messages)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
anyAdded = true;
whereClause.append(" ( uid = ? AND folder_id = ? ) ");
args.add(message.getUid());
args.add(Long.toString(((LocalFolder)message.getFolder()).getId()));
}
whereClause.append(" )");
}
if (forbiddenFlags != null && forbiddenFlags.length > 0)
{
whereClause.append(" AND (");
boolean anyAdded = false;
for (Flag flag : forbiddenFlags)
{
if (anyAdded == true)
{
whereClause.append(" AND ");
}
anyAdded = true;
whereClause.append(" flags NOT LIKE ?");
args.add("%" + flag.toString() + "%");
}
whereClause.append(" )");
}
if (requiredFlags != null && requiredFlags.length > 0)
{
whereClause.append(" AND (");
boolean anyAdded = false;
for (Flag flag : requiredFlags)
{
if (anyAdded == true)
{
whereClause.append(" OR ");
}
anyAdded = true;
whereClause.append(" flags LIKE ?");
args.add("%" + flag.toString() + "%");
}
whereClause.append(" )");
}
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "whereClause = " + whereClause.toString());
Log.v(K9.LOG_TAG, "args = " + args);
}
return getMessages(
listener,
null,
"SELECT "
+ GET_MESSAGES_COLS
+ "FROM messages WHERE deleted = 0 " + whereClause.toString() + " ORDER BY date DESC"
, args.toArray(EMPTY_STRING_ARRAY)
);
}
/*
* Given a query string, actually do the query for the messages and
* call the MessageRetrievalListener for each one
*/
private Message[] getMessages(
MessageRetrievalListener listener,
LocalFolder folder,
String queryString, String[] placeHolders
) throws MessagingException
{
ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>();
Cursor cursor = null;
try
{
// pull out messages most recent first, since that's what the default sort is
cursor = mDb.rawQuery(queryString, placeHolders);
int i = 0;
while (cursor.moveToNext())
{
LocalMessage message = new LocalMessage(null, folder);
message.populateFromGetMessageCursor(cursor);
messages.add(message);
if (listener != null)
{
listener.messageFinished(message, i, -1);
}
i++;
}
if (listener != null)
{
listener.messagesFinished(i);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
public class LocalFolder extends Folder implements Serializable
{
private String mName = null;
private long mFolderId = -1;
private int mUnreadMessageCount = -1;
private int mFlaggedMessageCount = -1;
private int mVisibleLimit = -1;
private FolderClass displayClass = FolderClass.NO_CLASS;
private FolderClass syncClass = FolderClass.INHERITED;
private FolderClass pushClass = FolderClass.SECOND_CLASS;
private boolean inTopGroup = false;
private String prefId = null;
private String mPushState = null;
private boolean mIntegrate = false;
public LocalFolder(String name)
{
super(LocalStore.this.mAccount);
this.mName = name;
if (K9.INBOX.equals(getName()))
{
syncClass = FolderClass.FIRST_CLASS;
pushClass = FolderClass.FIRST_CLASS;
inTopGroup = true;
}
}
public LocalFolder(long id)
{
super(LocalStore.this.mAccount);
this.mFolderId = id;
}
public long getId()
{
return mFolderId;
}
@Override
public void open(OpenMode mode) throws MessagingException
{
if (isOpen())
{
return;
}
Cursor cursor = null;
try
{
String baseQuery =
"SELECT id, name,unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders ";
if (mName != null)
{
cursor = mDb.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName });
}
else
{
cursor = mDb.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) });
}
if (cursor.moveToFirst())
{
int folderId = cursor.getInt(0);
if (folderId > 0)
{
open(folderId, cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8));
}
}
else
{
Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId());
create(FolderType.HOLDS_MESSAGES);
open(mode);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount) throws MessagingException
{
mFolderId = id;
mName = name;
mUnreadMessageCount = unreadCount;
mVisibleLimit = visibleLimit;
mPushState = pushState;
mFlaggedMessageCount = flaggedCount;
super.setStatus(status);
// Only want to set the local variable stored in the super class. This class
// does a DB update on setLastChecked
super.setLastChecked(lastChecked);
super.setLastPush(lastPushed);
}
@Override
public boolean isOpen()
{
return (mFolderId != -1 && mName != null);
}
@Override
public OpenMode getMode() throws MessagingException
{
return OpenMode.READ_WRITE;
}
@Override
public String getName()
{
return mName;
}
@Override
public boolean exists() throws MessagingException
{
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT id FROM folders "
+ "where folders.name = ?", new String[] { this
.getName()
});
if (cursor.moveToFirst())
{
int folderId = cursor.getInt(0);
return (folderId > 0) ? true : false;
}
else
{
return false;
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException
{
if (exists())
{
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[]
{
mName,
mAccount.getDisplayCount()
});
return true;
}
@Override
public boolean create(FolderType type, int visibleLimit) throws MessagingException
{
if (exists())
{
throw new MessagingException("Folder " + mName + " already exists.");
}
mDb.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[]
{
mName,
visibleLimit
});
return true;
}
@Override
public void close()
{
mFolderId = -1;
}
@Override
public int getMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor cursor = null;
try
{
cursor = mDb.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?",
new String[]
{
Long.toString(mFolderId)
});
cursor.moveToFirst();
int messageCount = cursor.getInt(0);
return messageCount;
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public int getUnreadMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mUnreadMessageCount;
}
@Override
public int getFlaggedMessageCount() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mFlaggedMessageCount;
}
public void setUnreadMessageCount(int unreadMessageCount) throws MessagingException
{
open(OpenMode.READ_WRITE);
mUnreadMessageCount = Math.max(0, unreadMessageCount);
mDb.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?",
new Object[] { mUnreadMessageCount, mFolderId });
}
public void setFlaggedMessageCount(int flaggedMessageCount) throws MessagingException
{
open(OpenMode.READ_WRITE);
mFlaggedMessageCount = Math.max(0, flaggedMessageCount);
mDb.execSQL("UPDATE folders SET flagged_count = ? WHERE id = ?",
new Object[] { mFlaggedMessageCount, mFolderId });
}
@Override
public void setLastChecked(long lastChecked) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setLastChecked(lastChecked);
mDb.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
@Override
public void setLastPush(long lastChecked) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setLastPush(lastChecked);
mDb.execSQL("UPDATE folders SET last_pushed = ? WHERE id = ?",
new Object[] { lastChecked, mFolderId });
}
public int getVisibleLimit() throws MessagingException
{
open(OpenMode.READ_WRITE);
return mVisibleLimit;
}
public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException
{
open(OpenMode.READ_WRITE);
Message[] messages = getMessages(null, false);
for (int i = mVisibleLimit; i < messages.length; i++)
{
if (listener != null)
{
listener.messageRemoved(messages[i]);
}
messages[i].setFlag(Flag.X_DESTROYED, true);
}
}
public void setVisibleLimit(int visibleLimit) throws MessagingException
{
open(OpenMode.READ_WRITE);
mVisibleLimit = visibleLimit;
mDb.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?",
new Object[] { mVisibleLimit, mFolderId });
}
@Override
public void setStatus(String status) throws MessagingException
{
open(OpenMode.READ_WRITE);
super.setStatus(status);
mDb.execSQL("UPDATE folders SET status = ? WHERE id = ?",
new Object[] { status, mFolderId });
}
public void setPushState(String pushState) throws MessagingException
{
open(OpenMode.READ_WRITE);
mPushState = pushState;
mDb.execSQL("UPDATE folders SET push_state = ? WHERE id = ?",
new Object[] { pushState, mFolderId });
}
public String getPushState()
{
return mPushState;
}
@Override
public FolderClass getDisplayClass()
{
return displayClass;
}
@Override
public FolderClass getSyncClass()
{
if (FolderClass.INHERITED == syncClass)
{
return getDisplayClass();
}
else
{
return syncClass;
}
}
public FolderClass getRawSyncClass()
{
return syncClass;
}
@Override
public FolderClass getPushClass()
{
if (FolderClass.INHERITED == pushClass)
{
return getSyncClass();
}
else
{
return pushClass;
}
}
public FolderClass getRawPushClass()
{
return pushClass;
}
public void setDisplayClass(FolderClass displayClass)
{
this.displayClass = displayClass;
}
public void setSyncClass(FolderClass syncClass)
{
this.syncClass = syncClass;
}
public void setPushClass(FolderClass pushClass)
{
this.pushClass = pushClass;
}
public boolean isIntegrate()
{
return mIntegrate;
}
public void setIntegrate(boolean integrate)
{
mIntegrate = integrate;
}
private String getPrefId() throws MessagingException
{
open(OpenMode.READ_WRITE);
if (prefId == null)
{
prefId = uUid + "." + mName;
}
return prefId;
}
public void delete(Preferences preferences) throws MessagingException
{
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.remove(id + ".displayMode");
editor.remove(id + ".syncMode");
editor.remove(id + ".pushMode");
editor.remove(id + ".inTopGroup");
editor.remove(id + ".integrate");
editor.commit();
}
public void save(Preferences preferences) throws MessagingException
{
String id = getPrefId();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
// there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX
if (displayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".displayMode");
}
else
{
editor.putString(id + ".displayMode", displayClass.name());
}
if (syncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".syncMode");
}
else
{
editor.putString(id + ".syncMode", syncClass.name());
}
if (pushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName()))
{
editor.remove(id + ".pushMode");
}
else
{
editor.putString(id + ".pushMode", pushClass.name());
}
editor.putBoolean(id + ".inTopGroup", inTopGroup);
editor.putBoolean(id + ".integrate", mIntegrate);
editor.commit();
}
public FolderClass getDisplayClass(Preferences preferences) throws MessagingException
{
String id = getPrefId();
return FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NO_CLASS.name()));
}
@Override
public void refresh(Preferences preferences) throws MessagingException
{
String id = getPrefId();
try
{
displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode",
FolderClass.NO_CLASS.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e);
displayClass = FolderClass.NO_CLASS;
}
if (displayClass == FolderClass.NONE)
{
displayClass = FolderClass.NO_CLASS;
}
FolderClass defSyncClass = FolderClass.INHERITED;
if (K9.INBOX.equals(getName()))
{
defSyncClass = FolderClass.FIRST_CLASS;
}
try
{
syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode",
defSyncClass.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e);
syncClass = defSyncClass;
}
if (syncClass == FolderClass.NONE)
{
syncClass = FolderClass.INHERITED;
}
FolderClass defPushClass = FolderClass.SECOND_CLASS;
boolean defInTopGroup = false;
boolean defIntegrate = false;
if (K9.INBOX.equals(getName()))
{
defPushClass = FolderClass.FIRST_CLASS;
defInTopGroup = true;
defIntegrate = true;
}
try
{
pushClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".pushMode",
defPushClass.name()));
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e);
pushClass = defPushClass;
}
if (pushClass == FolderClass.NONE)
{
pushClass = FolderClass.INHERITED;
}
inTopGroup = preferences.getPreferences().getBoolean(id + ".inTopGroup", defInTopGroup);
mIntegrate = preferences.getPreferences().getBoolean(id + ".integrate", defIntegrate);
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
if (fp.contains(FetchProfile.Item.BODY))
{
for (Message message : messages)
{
LocalMessage localMessage = (LocalMessage)message;
Cursor cursor = null;
MimeMultipart mp = new MimeMultipart();
mp.setSubType("mixed");
try
{
cursor = mDb.rawQuery("SELECT html_content, text_content FROM messages "
+ "WHERE id = ?",
new String[] { Long.toString(localMessage.mId) });
cursor.moveToNext();
String htmlContent = cursor.getString(0);
String textContent = cursor.getString(1);
if (textContent != null)
{
LocalTextBody body = new LocalTextBody(textContent, htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/plain");
mp.addBodyPart(bp);
}
else
{
TextBody body = new TextBody(htmlContent);
MimeBodyPart bp = new MimeBodyPart(body, "text/html");
mp.addBodyPart(bp);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
try
{
cursor = mDb.query(
"attachments",
new String[]
{
"id",
"size",
"name",
"mime_type",
"store_data",
"content_uri",
"content_id",
"content_disposition"
},
"message_id = ?",
new String[] { Long.toString(localMessage.mId) },
null,
null,
null);
while (cursor.moveToNext())
{
long id = cursor.getLong(0);
int size = cursor.getInt(1);
String name = cursor.getString(2);
String type = cursor.getString(3);
String storeData = cursor.getString(4);
String contentUri = cursor.getString(5);
String contentId = cursor.getString(6);
String contentDisposition = cursor.getString(7);
Body body = null;
if (contentDisposition == null)
{
contentDisposition = "attachment";
}
if (contentUri != null)
{
body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication);
}
MimeBodyPart bp = new LocalAttachmentBodyPart(body, id);
bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
type,
name));
bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION,
String.format("%s;\n filename=\"%s\";\n size=%d",
contentDisposition,
name,
size));
bp.setHeader(MimeHeader.HEADER_CONTENT_ID, contentId);
/*
* HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that
* we can later pull the attachment from the remote store if neccesary.
*/
bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData);
mp.addBodyPart(bp);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
if (mp.getCount() == 1)
{
BodyPart part = mp.getBodyPart(0);
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType());
localMessage.setBody(part.getBody());
}
else
{
localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
localMessage.setBody(mp);
}
}
}
}
@Override
public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
throw new MessagingException(
"LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented");
}
/**
* Populate the header fields of the given list of messages by reading
* the saved header data from the database.
*
* @param messages
* The messages whose headers should be loaded.
*/
private void populateHeaders(List<LocalMessage> messages)
{
Cursor cursor = null;
if (messages.size() == 0)
{
return;
}
try
{
Map<Long, LocalMessage> popMessages = new HashMap<Long, LocalMessage>();
List<String> ids = new ArrayList<String>();
StringBuffer questions = new StringBuffer();
for (int i = 0; i < messages.size(); i++)
{
if (i != 0)
{
questions.append(", ");
}
questions.append("?");
LocalMessage message = messages.get(i);
Long id = message.getId();
ids.add(Long.toString(id));
popMessages.put(id, message);
}
cursor = mDb.rawQuery(
"SELECT message_id, name, value FROM headers " + "WHERE message_id in ( " + questions + ") ",
ids.toArray(EMPTY_STRING_ARRAY));
while (cursor.moveToNext())
{
Long id = cursor.getLong(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
//Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id);
popMessages.get(id).addHeader(name, value);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
@Override
public Message getMessage(String uid) throws MessagingException
{
open(OpenMode.READ_WRITE);
LocalMessage message = new LocalMessage(uid, this);
Cursor cursor = null;
try
{
cursor = mDb.rawQuery(
"SELECT "
+ GET_MESSAGES_COLS
+ "FROM messages WHERE uid = ? AND folder_id = ?",
new String[]
{
message.getUid(), Long.toString(mFolderId)
});
if (!cursor.moveToNext())
{
return null;
}
message.populateFromGetMessageCursor(cursor);
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return message;
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException
{
return getMessages(listener, true);
}
@Override
public Message[] getMessages(MessageRetrievalListener listener, boolean includeDeleted) throws MessagingException
{
open(OpenMode.READ_WRITE);
return LocalStore.this.getMessages(
listener,
this,
"SELECT " + GET_MESSAGES_COLS
+ "FROM messages WHERE "
+ (includeDeleted ? "" : "deleted = 0 AND ")
+ " folder_id = ? ORDER BY date DESC"
, new String[]
{
Long.toString(mFolderId)
}
);
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException
{
open(OpenMode.READ_WRITE);
if (uids == null)
{
return getMessages(listener);
}
ArrayList<Message> messages = new ArrayList<Message>();
for (String uid : uids)
{
Message message = getMessage(uid);
if (message != null)
{
messages.add(message);
}
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
@Override
public void copyMessages(Message[] msgs, Folder folder) throws MessagingException
{
if (!(folder instanceof LocalFolder))
{
throw new MessagingException("copyMessages called with incorrect Folder");
}
((LocalFolder) folder).appendMessages(msgs, true);
}
@Override
public void moveMessages(Message[] msgs, Folder destFolder) throws MessagingException
{
if (!(destFolder instanceof LocalFolder))
{
throw new MessagingException("moveMessages called with non-LocalFolder");
}
LocalFolder lDestFolder = (LocalFolder)destFolder;
lDestFolder.open(OpenMode.READ_WRITE);
for (Message message : msgs)
{
LocalMessage lMessage = (LocalMessage)message;
if (!message.isSet(Flag.SEEN))
{
setUnreadMessageCount(getUnreadMessageCount() - 1);
lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1);
}
if (message.isSet(Flag.FLAGGED))
{
setFlaggedMessageCount(getFlaggedMessageCount() - 1);
lDestFolder.setFlaggedMessageCount(lDestFolder.getFlaggedMessageCount() + 1);
}
String oldUID = message.getUid();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID "
+ message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName());
message.setUid(K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString());
mDb.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[]
{
lDestFolder.getId(),
message.getUid(),
lMessage.getId()
});
LocalMessage placeHolder = new LocalMessage(oldUID, this);
placeHolder.setFlagInternal(Flag.DELETED, true);
placeHolder.setFlagInternal(Flag.SEEN, true);
appendMessages(new Message[] { placeHolder });
}
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException
{
appendMessages(messages, false);
}
/**
* The method differs slightly from the contract; If an incoming message already has a uid
* assigned and it matches the uid of an existing message then this message will replace the
* old message. It is implemented as a delete/insert. This functionality is used in saving
* of drafts and re-synchronization of updated server messages.
*
* NOTE that although this method is located in the LocalStore class, it is not guaranteed
* that the messages supplied as parameters are actually {@link LocalMessage} instances (in
* fact, in most cases, they are not). Therefore, if you want to make local changes only to a
* message, retrieve the appropriate local message instance first (if it already exists).
*/
private void appendMessages(Message[] messages, boolean copy) throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : messages)
{
if (!(message instanceof MimeMessage))
{
throw new Error("LocalStore can only store Messages that extend MimeMessage");
}
String uid = message.getUid();
if (uid == null || copy)
{
uid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString();
if (!copy)
{
message.setUid(uid);
}
}
else
{
Message oldMessage = getMessage(uid);
if (oldMessage != null && oldMessage.isSet(Flag.SEEN) == false)
{
setUnreadMessageCount(getUnreadMessageCount() - 1);
}
if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED) == true)
{
setFlaggedMessageCount(getFlaggedMessageCount() - 1);
}
/*
* The message may already exist in this Folder, so delete it first.
*/
deleteAttachments(message.getUid());
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?",
new Object[] { mFolderId, message.getUid() });
}
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (Part viewable : viewables)
{
try
{
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html"))
{
sbHtml.append(text);
}
else
{
sbText.append(text);
}
}
catch (Exception e)
{
throw new MessagingException("Unable to get text for message part", e);
}
}
String text = sbText.toString();
String html = markupContent(text, sbHtml.toString());
String preview = calculateContentPreview(text);
try
{
ContentValues cv = new ContentValues();
cv.put("uid", uid);
cv.put("subject", message.getSubject());
cv.put("sender_list", Address.pack(message.getFrom()));
cv.put("date", message.getSentDate() == null
? System.currentTimeMillis() : message.getSentDate().getTime());
cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase());
cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0);
cv.put("folder_id", mFolderId);
cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO)));
cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC)));
cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC)));
cv.put("html_content", html.length() > 0 ? html : null);
cv.put("text_content", text.length() > 0 ? text : null);
cv.put("preview", preview.length() > 0 ? preview : null);
cv.put("reply_to_list", Address.pack(message.getReplyTo()));
cv.put("attachment_count", attachments.size());
cv.put("internal_date", message.getInternalDate() == null
? System.currentTimeMillis() : message.getInternalDate().getTime());
String messageId = message.getMessageId();
if (messageId != null)
{
cv.put("message_id", messageId);
}
long messageUid = mDb.insert("messages", "uid", cv);
for (Part attachment : attachments)
{
saveAttachment(messageUid, attachment, copy);
}
saveHeaders(messageUid, (MimeMessage)message);
if (message.isSet(Flag.SEEN) == false)
{
setUnreadMessageCount(getUnreadMessageCount() + 1);
}
if (message.isSet(Flag.FLAGGED) == true)
{
setFlaggedMessageCount(getFlaggedMessageCount() + 1);
}
}
catch (Exception e)
{
throw new MessagingException("Error appending message", e);
}
}
}
/**
* Update the given message in the LocalStore without first deleting the existing
* message (contrast with appendMessages). This method is used to store changes
* to the given message while updating attachments and not removing existing
* attachment data.
* TODO In the future this method should be combined with appendMessages since the Message
* contains enough data to decide what to do.
* @param message
* @throws MessagingException
*/
public void updateMessage(LocalMessage message) throws MessagingException
{
open(OpenMode.READ_WRITE);
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
message.buildMimeRepresentation();
MimeUtility.collectParts(message, viewables, attachments);
StringBuffer sbHtml = new StringBuffer();
StringBuffer sbText = new StringBuffer();
for (int i = 0, count = viewables.size(); i < count; i++)
{
Part viewable = viewables.get(i);
try
{
String text = MimeUtility.getTextFromPart(viewable);
/*
* Anything with MIME type text/html will be stored as such. Anything
* else will be stored as text/plain.
*/
if (viewable.getMimeType().equalsIgnoreCase("text/html"))
{
sbHtml.append(text);
}
else
{
sbText.append(text);
}
}
catch (Exception e)
{
throw new MessagingException("Unable to get text for message part", e);
}
}
String text = sbText.toString();
String html = markupContent(text, sbHtml.toString());
String preview = calculateContentPreview(text);
try
{
mDb.execSQL("UPDATE messages SET "
+ "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, "
+ "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, "
+ "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, "
+ "attachment_count = ? WHERE id = ?",
new Object[]
{
message.getUid(),
message.getSubject(),
Address.pack(message.getFrom()),
message.getSentDate() == null ? System
.currentTimeMillis() : message.getSentDate()
.getTime(),
Utility.combine(message.getFlags(), ',').toUpperCase(),
mFolderId,
Address.pack(message
.getRecipients(RecipientType.TO)),
Address.pack(message
.getRecipients(RecipientType.CC)),
Address.pack(message
.getRecipients(RecipientType.BCC)),
html.length() > 0 ? html : null,
text.length() > 0 ? text : null,
preview.length() > 0 ? preview : null,
Address.pack(message.getReplyTo()),
attachments.size(),
message.mId
});
for (int i = 0, count = attachments.size(); i < count; i++)
{
Part attachment = attachments.get(i);
saveAttachment(message.mId, attachment, false);
}
saveHeaders(message.getId(), message);
}
catch (Exception e)
{
throw new MessagingException("Error appending message", e);
}
}
/**
* Save the headers of the given message. Note that the message is not
* necessarily a {@link LocalMessage} instance.
*/
private void saveHeaders(long id, MimeMessage message) throws MessagingException
{
boolean saveAllHeaders = mAccount.isSaveAllHeaders();
boolean gotAdditionalHeaders = false;
deleteHeaders(id);
for (String name : message.getHeaderNames())
{
if (saveAllHeaders || HEADERS_TO_SAVE.contains(name))
{
String[] values = message.getHeader(name);
for (String value : values)
{
ContentValues cv = new ContentValues();
cv.put("message_id", id);
cv.put("name", name);
cv.put("value", value);
mDb.insert("headers", "name", cv);
}
}
else
{
gotAdditionalHeaders = true;
}
}
if (!gotAdditionalHeaders)
{
// Remember that all headers for this message have been saved, so it is
// not necessary to download them again in case the user wants to see all headers.
List<Flag> appendedFlags = new ArrayList<Flag>();
appendedFlags.addAll(Arrays.asList(message.getFlags()));
appendedFlags.add(Flag.X_GOT_ALL_HEADERS);
mDb.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[]
{ Utility.combine(appendedFlags.toArray(), ',').toUpperCase(), id });
}
}
private void deleteHeaders(long id)
{
mDb.execSQL("DELETE FROM headers WHERE id = ?",
new Object[]
{
id
});
}
/**
* @param messageId
* @param attachment
* @param attachmentId -1 to create a new attachment or >= 0 to update an existing
* @throws IOException
* @throws MessagingException
*/
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew)
throws IOException, MessagingException
{
long attachmentId = -1;
Uri contentUri = null;
int size = -1;
File tempAttachmentFile = null;
if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart))
{
attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId();
}
if (attachment.getBody() != null)
{
Body body = attachment.getBody();
if (body instanceof LocalAttachmentBody)
{
contentUri = ((LocalAttachmentBody) body).getContentUri();
}
else
{
/*
* If the attachment has a body we're expected to save it into the local store
* so we copy the data into a cached attachment file.
*/
InputStream in = attachment.getBody().getInputStream();
tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir);
FileOutputStream out = new FileOutputStream(tempAttachmentFile);
size = IOUtils.copy(in, out);
in.close();
out.close();
}
}
if (size == -1)
{
/*
* If the attachment is not yet downloaded see if we can pull a size
* off the Content-Disposition.
*/
String disposition = attachment.getDisposition();
if (disposition != null)
{
String s = MimeUtility.getHeaderParameter(disposition, "size");
if (s != null)
{
size = Integer.parseInt(s);
}
}
}
if (size == -1)
{
size = 0;
}
String storeData =
Utility.combine(attachment.getHeader(
MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ',');
String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name");
String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null);
String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition());
if (name == null && contentDisposition != null)
{
name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
}
if (attachmentId == -1)
{
ContentValues cv = new ContentValues();
cv.put("message_id", messageId);
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("store_data", storeData);
cv.put("size", size);
cv.put("name", name);
cv.put("mime_type", attachment.getMimeType());
cv.put("content_id", contentId);
cv.put("content_disposition", contentDisposition);
attachmentId = mDb.insert("attachments", "message_id", cv);
}
else
{
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
cv.put("size", size);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
if (attachmentId != -1 && tempAttachmentFile != null)
{
File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId));
tempAttachmentFile.renameTo(attachmentFile);
contentUri = AttachmentProvider.getAttachmentUri(
new File(mPath).getName(),
attachmentId);
attachment.setBody(new LocalAttachmentBody(contentUri, mApplication));
ContentValues cv = new ContentValues();
cv.put("content_uri", contentUri != null ? contentUri.toString() : null);
mDb.update(
"attachments",
cv,
"id = ?",
new String[] { Long.toString(attachmentId) });
}
/* The message has attachment with Content-ID */
if (contentId != null && contentUri != null)
{
Cursor cursor = null;
cursor = mDb.query("messages", new String[] { "html_content" }, "id = ?", new String[] { Long.toString(messageId) }, null, null, null);
try
{
if (cursor.moveToNext())
{
String new_html;
new_html = cursor.getString(0);
new_html = new_html.replaceAll("cid:" + contentId, contentUri.toString());
ContentValues cv = new ContentValues();
cv.put("html_content", new_html);
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) });
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart)
{
((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId);
}
}
/**
* Changes the stored uid of the given message (using it's internal id as a key) to
* the uid in the message.
* @param message
*/
public void changeUid(LocalMessage message) throws MessagingException
{
open(OpenMode.READ_WRITE);
ContentValues cv = new ContentValues();
cv.put("uid", message.getUid());
mDb.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) });
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : messages)
{
message.setFlags(flags, value);
}
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException
{
open(OpenMode.READ_WRITE);
for (Message message : getMessages(null))
{
message.setFlags(flags, value);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException
{
throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder");
}
public void deleteMessagesOlderThan(long cutoff) throws MessagingException
{
open(OpenMode.READ_ONLY);
mDb.execSQL("DELETE FROM messages WHERE folder_id = ? and date < ?", new Object[]
{
Long.toString(mFolderId), new Long(cutoff)
});
resetUnreadAndFlaggedCounts();
}
private void resetUnreadAndFlaggedCounts()
{
try
{
int newUnread = 0;
int newFlagged = 0;
Message[] messages = getMessages(null);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
newUnread++;
}
if (message.isSet(Flag.FLAGGED) == true)
{
newFlagged++;
}
}
setUnreadMessageCount(newUnread);
setFlaggedMessageCount(newFlagged);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to fetch all messages from LocalStore", e);
}
}
@Override
public void delete(boolean recurse) throws MessagingException
{
// We need to open the folder first to make sure we've got it's id
open(OpenMode.READ_ONLY);
Message[] messages = getMessages(null);
for (Message message : messages)
{
deleteAttachments(message.getUid());
}
mDb.execSQL("DELETE FROM folders WHERE id = ?", new Object[]
{
Long.toString(mFolderId),
});
}
@Override
public boolean equals(Object o)
{
if (o instanceof LocalFolder)
{
return ((LocalFolder)o).mName.equals(mName);
}
return super.equals(o);
}
@Override
public int hashCode()
{
return mName.hashCode();
}
@Override
public Flag[] getPermanentFlags() throws MessagingException
{
return PERMANENT_FLAGS;
}
private void deleteAttachments(long messageId) throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor attachmentsCursor = null;
try
{
attachmentsCursor = mDb.query(
"attachments",
new String[] { "id" },
"message_id = ?",
new String[] { Long.toString(messageId) },
null,
null,
null);
while (attachmentsCursor.moveToNext())
{
long attachmentId = attachmentsCursor.getLong(0);
try
{
File file = new File(mAttachmentsDir, Long.toString(attachmentId));
if (file.exists())
{
file.delete();
}
}
catch (Exception e)
{
}
}
}
finally
{
if (attachmentsCursor != null)
{
attachmentsCursor.close();
}
}
}
private void deleteAttachments(String uid) throws MessagingException
{
open(OpenMode.READ_WRITE);
Cursor messagesCursor = null;
try
{
messagesCursor = mDb.query(
"messages",
new String[] { "id" },
"folder_id = ? AND uid = ?",
new String[] { Long.toString(mFolderId), uid },
null,
null,
null);
while (messagesCursor.moveToNext())
{
long messageId = messagesCursor.getLong(0);
deleteAttachments(messageId);
}
}
finally
{
if (messagesCursor != null)
{
messagesCursor.close();
}
}
}
/*
* calcualteContentPreview
* Takes a plain text message body as a string.
* Returns a message summary as a string suitable for showing in a message list
*
* A message summary should be about the first 160 characters
* of unique text written by the message sender
* Quoted text, "On $date" and so on will be stripped out.
* All newlines and whitespace will be compressed.
*
*/
public String calculateContentPreview(String text)
{
if (text == null)
{
return null;
}
text = text.replaceAll("(?ms)^-----BEGIN PGP SIGNED MESSAGE-----.(Hash:\\s*?.*?$)?","");
text = text.replaceAll("https?://\\S+","...");
text = text.replaceAll("^.*\\w.*:","");
text = text.replaceAll("(?m)^>.*$","");
text = text.replaceAll("^On .*wrote.?$","");
text = text.replaceAll("(\\r|\\n)+"," ");
text = text.replaceAll("\\s+"," ");
if (text.length() <= 250)
{
return text;
}
else
{
text = text.substring(0,250);
return text;
}
}
public String markupContent(String text, String html)
{
if (text.length() > 0 && html.length() == 0)
{
html = htmlifyString(text);
}
html = convertEmoji2ImgForDocomo(html);
return html;
}
public String htmlifyString(String text)
{
StringReader reader = new StringReader(text);
StringBuilder buff = new StringBuilder(text.length() + 512);
int c = 0;
try
{
while ((c = reader.read()) != -1)
{
switch (c)
{
case '&':
buff.append("&");
break;
case '<':
buff.append("<");
break;
case '>':
buff.append(">");
break;
case '\r':
break;
default:
buff.append((char)c);
}//switch
}
}
catch (IOException e)
{
//Should never happen
Log.e(K9.LOG_TAG, null, e);
}
text = buff.toString();
text = text.replaceAll("\\s*([-=_]{30,}+)\\s*","<hr />");
text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])","$1 ");
text = text.replaceAll("(?m)(\r\n|\n|\r){4,}","\n\n");
Matcher m = Regex.WEB_URL_PATTERN.matcher(text);
StringBuffer sb = new StringBuffer(text.length() + 512);
sb.append("<html><head><meta name=\"viewport\" content=\"width=device-width, height=device-height\"></head><body>");
sb.append(htmlifyMessageHeader());
while (m.find())
{
int start = m.start();
if (start == 0 || (start != 0 && text.charAt(start - 1) != '@'))
{
m.appendReplacement(sb, "<a href=\"$0\">$0</a>");
}
else
{
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
sb.append(htmlifyMessageFooter());
sb.append("</body></html>");
text = sb.toString();
return text;
}
private String htmlifyMessageHeader()
{
if (K9.messageViewFixedWidthFont())
{
return "<pre style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
else
{
return "<div style=\"white-space: pre-wrap; word-wrap:break-word; \">";
}
}
private String htmlifyMessageFooter()
{
if (K9.messageViewFixedWidthFont())
{
return "</pre>";
}
else
{
return "</div>";
}
}
public String convertEmoji2ImgForDocomo(String html)
{
StringReader reader = new StringReader(html);
StringBuilder buff = new StringBuilder(html.length() + 512);
int c = 0;
try
{
while ((c = reader.read()) != -1)
{
switch (c)
{
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
case 0xE6F9: //docomo kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE729: //docomo wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xE6D2: //docomo info02
buff.append("<img src=\"file:///android_asset/emoticons/info02.gif\" alt=\"info02\" />");
break;
case 0xE753: //docomo smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE68D: //docomo heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE6A5: //docomo downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE6AD: //docomo pouch
buff.append("<img src=\"file:///android_asset/emoticons/pouch.gif\" alt=\"pouch\" />");
break;
case 0xE6D4: //docomo by-d
buff.append("<img src=\"file:///android_asset/emoticons/by-d.gif\" alt=\"by-d\" />");
break;
case 0xE6D7: //docomo free
buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />");
break;
case 0xE6E8: //docomo seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE74E: //docomo snail
buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />");
break;
case 0xE658: //docomo basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE65A: //docomo pocketbell
buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />");
break;
case 0xE6E3: //docomo two
buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />");
break;
case 0xE74A: //docomo cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE6D0: //docomo faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
case 0xE661: //docomo ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE64B: //docomo virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE67E: //docomo ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE6D6: //docomo yen
buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />");
break;
case 0xE6E0: //docomo sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE6FE: //docomo bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE6E1: //docomo mobaq
buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />");
break;
case 0xE70A: //docomo sign05
buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />");
break;
case 0xE667: //docomo bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE731: //docomo copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE678: //docomo upwardright
buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />");
break;
case 0xE694: //docomo scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE682: //docomo bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE64D: //docomo scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE6D9: //docomo key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE734: //docomo secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE74F: //docomo chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE691: //docomo eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE70B: //docomo ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE714: //docomo door
buff.append("<img src=\"file:///android_asset/emoticons/door.gif\" alt=\"door\" />");
break;
case 0xE64F: //docomo capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xE674: //docomo boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE726: //docomo lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE68F: //docomo diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE69B: //docomo wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xE747: //docomo maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE64C: //docomo libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE647: //docomo taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE645: //docomo sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xE6FC: //docomo annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE6E6: //docomo five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE676: //docomo karaoke
buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />");
break;
case 0xE69D: //docomo moon1
buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />");
break;
case 0xE709: //docomo sign04
buff.append("<img src=\"file:///android_asset/emoticons/sign04.gif\" alt=\"sign04\" />");
break;
case 0xE72A: //docomo happy02
buff.append("<img src=\"file:///android_asset/emoticons/happy02.gif\" alt=\"happy02\" />");
break;
case 0xE669: //docomo hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE71B: //docomo ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
case 0xE644: //docomo mist
buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />");
break;
case 0xE73B: //docomo full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xE683: //docomo book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE707: //docomo sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE716: //docomo pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE671: //docomo bar
buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />");
break;
case 0xE72B: //docomo bearing
buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />");
break;
case 0xE65C: //docomo subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE725: //docomo gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xE745: //docomo apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE65F: //docomo rvcar
buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />");
break;
case 0xE664: //docomo building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE737: //docomo danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE702: //docomo sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xE6EC: //docomo heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xE660: //docomo bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE72D: //docomo crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE652: //docomo sports
buff.append("<img src=\"file:///android_asset/emoticons/sports.gif\" alt=\"sports\" />");
break;
case 0xE6B8: //docomo on
buff.append("<img src=\"file:///android_asset/emoticons/on.gif\" alt=\"on\" />");
break;
case 0xE73C: //docomo leftright
buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />");
break;
case 0xE6BA: //docomo clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xE6F0: //docomo happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE701: //docomo sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE63E: //docomo sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xE67D: //docomo event
buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />");
break;
case 0xE689: //docomo memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
case 0xE68B: //docomo game
buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />");
break;
case 0xE718: //docomo wrench
buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />");
break;
case 0xE741: //docomo clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE693: //docomo rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE6F6: //docomo note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xE67A: //docomo music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE743: //docomo tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xE656: //docomo soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE69C: //docomo newmoon
buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />");
break;
case 0xE73E: //docomo school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE750: //docomo penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE696: //docomo downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE6CE: //docomo phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE728: //docomo bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE662: //docomo airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE74C: //docomo noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE704: //docomo sign03
buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />");
break;
case 0xE68E: //docomo spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE698: //docomo foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE712: //docomo snowboard
buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />");
break;
case 0xE684: //docomo ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE6DA: //docomo enter
buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />");
break;
case 0xE6EA: //docomo nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE722: //docomo coldsweats01
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />");
break;
case 0xE6F7: //docomo spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE710: //docomo rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xE73F: //docomo wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE686: //docomo birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE721: //docomo confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE6FF: //docomo notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE724: //docomo pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE6A4: //docomo xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE6FB: //docomo flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE71D: //docomo bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE6DC: //docomo search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE757: //docomo shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE680: //docomo nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xE66D: //docomo signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE66A: //docomo 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE6F4: //docomo wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE641: //docomo snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE6AE: //docomo pen
buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />");
break;
case 0xE70D: //docomo appli02
buff.append("<img src=\"file:///android_asset/emoticons/appli02.gif\" alt=\"appli02\" />");
break;
case 0xE732: //docomo tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE755: //docomo pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE648: //docomo gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE6DE: //docomo flag
buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />");
break;
case 0xE6A1: //docomo dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE6EF: //docomo heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xE643: //docomo typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE65B: //docomo train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE746: //docomo bud
buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />");
break;
case 0xE653: //docomo baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE6B2: //docomo chair
buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />");
break;
case 0xE64A: //docomo leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE6E7: //docomo six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE6E4: //docomo three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xE6DF: //docomo freedial
buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />");
break;
case 0xE744: //docomo banana
buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />");
break;
case 0xE6DB: //docomo clear
buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />");
break;
case 0xE6AC: //docomo slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE666: //docomo hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE663: //docomo house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE695: //docomo paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE67F: //docomo smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE65D: //docomo bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE6B1: //docomo shadow
buff.append("<img src=\"file:///android_asset/emoticons/shadow.gif\" alt=\"shadow\" />");
break;
case 0xE670: //docomo cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xE654: //docomo golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE708: //docomo dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE748: //docomo cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE6F1: //docomo angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE736: //docomo r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xE6A2: //docomo cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE6D1: //docomo info01
buff.append("<img src=\"file:///android_asset/emoticons/info01.gif\" alt=\"info01\" />");
break;
case 0xE687: //docomo telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE68C: //docomo cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE70E: //docomo t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE733: //docomo run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xE679: //docomo carouselpony
buff.append("<img src=\"file:///android_asset/emoticons/carouselpony.gif\" alt=\"carouselpony\" />");
break;
case 0xE646: //docomo aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE690: //docomo club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE64E: //docomo sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xE6F5: //docomo up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xE720: //docomo think
buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />");
break;
case 0xE6E2: //docomo one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xE6D8: //docomo id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE675: //docomo hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
case 0xE6B7: //docomo soon
buff.append("<img src=\"file:///android_asset/emoticons/soon.gif\" alt=\"soon\" />");
break;
case 0xE717: //docomo loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE673: //docomo fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE719: //docomo pencil
buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />");
break;
case 0xE697: //docomo upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xE730: //docomo clip
buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />");
break;
case 0xE6ED: //docomo heart02
buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />");
break;
case 0xE69A: //docomo eyeglass
buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />");
break;
case 0xE65E: //docomo car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xE742: //docomo cherry
buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />");
break;
case 0xE71C: //docomo sandclock
buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />");
break;
case 0xE735: //docomo recycle
buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />");
break;
case 0xE752: //docomo delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE69E: //docomo moon2
buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />");
break;
case 0xE68A: //docomo tv
buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />");
break;
case 0xE706: //docomo sweat01
buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />");
break;
case 0xE738: //docomo ban
buff.append("<img src=\"file:///android_asset/emoticons/ban.gif\" alt=\"ban\" />");
break;
case 0xE672: //docomo beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xE640: //docomo rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xE69F: //docomo moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE657: //docomo ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE70C: //docomo appli01
buff.append("<img src=\"file:///android_asset/emoticons/appli01.gif\" alt=\"appli01\" />");
break;
case 0xE6E5: //docomo four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE699: //docomo shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xE63F: //docomo cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE72F: //docomo ng
buff.append("<img src=\"file:///android_asset/emoticons/ng.gif\" alt=\"ng\" />");
break;
case 0xE6A3: //docomo yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE73A: //docomo pass
buff.append("<img src=\"file:///android_asset/emoticons/pass.gif\" alt=\"pass\" />");
break;
case 0xE67C: //docomo drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xE727: //docomo good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE6EB: //docomo zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xE72C: //docomo catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE6D5: //docomo d-point
buff.append("<img src=\"file:///android_asset/emoticons/d-point.gif\" alt=\"d-point\" />");
break;
case 0xE6F2: //docomo despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE700: //docomo down
buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />");
break;
case 0xE655: //docomo tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE703: //docomo sign02
buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />");
break;
case 0xE711: //docomo denim
buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />");
break;
case 0xE705: //docomo impact
buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />");
break;
case 0xE642: //docomo thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE66C: //docomo parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE6F3: //docomo sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE71E: //docomo japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xE6FD: //docomo punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xE73D: //docomo updown
buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />");
break;
case 0xE66F: //docomo restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE66E: //docomo toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
case 0xE739: //docomo empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE723: //docomo coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE6B9: //docomo end
buff.append("<img src=\"file:///android_asset/emoticons/end.gif\" alt=\"end\" />");
break;
case 0xE67B: //docomo art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xE72E: //docomo weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE715: //docomo dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE6CF: //docomo mailto
buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />");
break;
case 0xE6F8: //docomo cute
buff.append("<img src=\"file:///android_asset/emoticons/cute.gif\" alt=\"cute\" />");
break;
case 0xE6DD: //docomo new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE651: //docomo pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE756: //docomo wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE649: //docomo cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xE650: //docomo aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE740: //docomo fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE681: //docomo camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE71F: //docomo watch
buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />");
break;
case 0xE6EE: //docomo heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE71A: //docomo crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE6B3: //docomo night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE66B: //docomo gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE692: //docomo ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE685: //docomo present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE6E9: //docomo eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE70F: //docomo moneybag
buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />");
break;
case 0xE749: //docomo riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE6A0: //docomo fullmoon
buff.append("<img src=\"file:///android_asset/emoticons/fullmoon.gif\" alt=\"fullmoon\" />");
break;
case 0xE74D: //docomo bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE665: //docomo postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xE677: //docomo movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE668: //docomo atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE688: //docomo mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE6FA: //docomo shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xE713: //docomo bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xE74B: //docomo bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xE754: //docomo horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE751: //docomo fish
buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />");
break;
case 0xE659: //docomo motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE6D3: //docomo mail
buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />");
break;
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
// The spaces between the < and the img are a hack to avoid triggering
// K-9's 'load images' button
case 0xE223: //softbank eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE415: //softbank coldsweats01
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />");
break;
case 0xE21F: //softbank four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE125: //softbank ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE148: //softbank book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE242: //softbank cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xE31C: //softbank rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xE252: //softbank danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE011: //softbank scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE342: //softbank riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE04B: //softbank rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xE03E: //softbank note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xE43C: //softbank sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xE20A: //softbank wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xE42A: //softbank basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE03D: //softbank movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE30E: //softbank smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE003: //softbank kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE21C: //softbank one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xE237: //softbank upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xE407: //softbank sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE03B: //softbank fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE40E: //softbank gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xE245: //softbank libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE24A: //softbank pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE443: //softbank typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE052: //softbank dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE244: //softbank virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE523: //softbank chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE023: //softbank heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE325: //softbank bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xE239: //softbank downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE20C: //softbank heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE211: //softbank freedial
buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />");
break;
case 0xE11F: //softbank chair
buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />");
break;
case 0xE108: //softbank coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE330: //softbank dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE404: //softbank smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE304: //softbank tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xE419: //softbank eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE13D: //softbank thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE013: //softbank ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE136: //softbank bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE059: //softbank angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE01D: //softbank airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE048: //softbank snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE435: //softbank bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE20E: //softbank spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE247: //softbank sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xE157: //softbank school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE10F: //softbank flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE502: //softbank art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xE338: //softbank japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xE34B: //softbank birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE22B: //softbank empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE311: //softbank bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE012: //softbank paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE151: //softbank toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
case 0xE01A: //softbank horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE03A: //softbank gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE03F: //softbank key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE00D: //softbank punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xE24D: //softbank ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE105: //softbank bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE00E: //softbank good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE154: //softbank atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE405: //softbank wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xE030: //softbank cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE057: //softbank happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE229: //softbank id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE016: //softbank baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE044: //softbank wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE115: //softbank run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xE14F: //softbank parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE327: //softbank heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xE014: //softbank golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE021: //softbank sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xE30A: //softbank music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE411: //softbank crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE536: //softbank foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE047: //softbank beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xE43E: //softbank wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE022: //softbank heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xE007: //softbank shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xE010: //softbank rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE32E: //softbank shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xE055: //softbank penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE03C: //softbank karaoke
buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />");
break;
case 0xE018: //softbank soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE159: //softbank bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE107: //softbank shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE04A: //softbank sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xE156: //softbank 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE110: //softbank clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE034: //softbank ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
case 0xE24F: //softbank r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xE112: //softbank present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE14D: //softbank bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE42E: //softbank rvcar
buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />");
break;
case 0xE13E: //softbank boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE413: //softbank weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE241: //softbank gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE212: //softbank new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE324: //softbank slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE220: //softbank five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE503: //softbank drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xE248: //softbank capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xE049: //softbank cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE243: //softbank leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE326: //softbank notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE00B: //softbank faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
case 0xE221: //softbank six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE240: //softbank taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE24E: //softbank copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE224: //softbank nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE008: //softbank camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE01E: //softbank train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE20D: //softbank diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE009: //softbank telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE019: //softbank fish
buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />");
break;
case 0xE01C: //softbank yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE40A: //softbank confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE246: //softbank scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE120: //softbank fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE323: //softbank bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE345: //softbank apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE339: //softbank bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE13C: //softbank sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE106: //softbank lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE340: //softbank noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE20F: //softbank club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE114: //softbank search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE10E: //softbank crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE406: //softbank wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE331: //softbank sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE04F: //softbank cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE301: //softbank memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
case 0xE01B: //softbank car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xE314: //softbank ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE315: //softbank secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE236: //softbank up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xE208: //softbank nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xE006: //softbank t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE12A: //softbank tv
buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />");
break;
case 0xE238: //softbank downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE10B: //softbank pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE126: //softbank cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE402: //softbank catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE416: //softbank pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE045: //softbank cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xE41B: //softbank ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE23F: //softbank aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE21E: //softbank three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xE056: //softbank delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE14E: //softbank signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE155: //softbank hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE033: //softbank xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE22A: //softbank full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xE123: //softbank spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE132: //softbank motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE434: //softbank subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE403: //softbank think
buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />");
break;
case 0xE043: //softbank restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE537: //softbank tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE058: //softbank despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE04C: //softbank moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE21D: //softbank two
buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />");
break;
case 0xE202: //softbank ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE30B: //softbank bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xE118: //softbank maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE103: //softbank loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE225: //softbank zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xE00C: //softbank pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE210: //softbank sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE015: //softbank tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE038: //softbank building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE02D: //softbank clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xE334: //softbank annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE153: //softbank postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xE222: //softbank seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE12F: //softbank dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE00A: //softbank mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE158: //softbank hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE249: //softbank aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE036: //softbank house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE046: //softbank cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE104: //softbank phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE44B: //softbank night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE313: //softbank hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
// These emoji codepoints are generated by tools/make_emoji in the K-9 source tree
// The spaces between the < and the img are a hack to avoid triggering
// K-9's 'load images' button
case 0xE488: //kddi sun
buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />");
break;
case 0xEA88: //kddi id
buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />");
break;
case 0xE4BA: //kddi baseball
buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />");
break;
case 0xE525: //kddi four
buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />");
break;
case 0xE578: //kddi free
buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />");
break;
case 0xE4C1: //kddi wine
buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />");
break;
case 0xE512: //kddi bell
buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />");
break;
case 0xEB83: //kddi rock
buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />");
break;
case 0xE4D0: //kddi cake
buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />");
break;
case 0xE473: //kddi crying
buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />");
break;
case 0xE48C: //kddi rain
buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />");
break;
case 0xEAC2: //kddi bearing
buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />");
break;
case 0xE47E: //kddi nosmoking
buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />");
break;
case 0xEAC0: //kddi despair
buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />");
break;
case 0xE559: //kddi r-mark
buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />");
break;
case 0xEB2D: //kddi up
buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />");
break;
case 0xEA89: //kddi full
buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />");
break;
case 0xEAC9: //kddi gawk
buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />");
break;
case 0xEB79: //kddi recycle
buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />");
break;
case 0xE5AC: //kddi zero
buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />");
break;
case 0xEAAE: //kddi japanesetea
buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />");
break;
case 0xEB30: //kddi sign03
buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />");
break;
case 0xE4B6: //kddi soccer
buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />");
break;
case 0xE556: //kddi downwardleft
buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />");
break;
case 0xE4BE: //kddi slate
buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />");
break;
case 0xE4A5: //kddi toilet
buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />");
break;
// Skipping kddi codepoint E523 two
// It conflicts with an earlier definition from another carrier:
// softbank chick
case 0xE496: //kddi scorpius
buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />");
break;
case 0xE4C6: //kddi game
buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />");
break;
case 0xE5A0: //kddi birthday
buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />");
break;
case 0xE5B8: //kddi pc
buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />");
break;
case 0xE516: //kddi hairsalon
buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />");
break;
case 0xE475: //kddi sleepy
buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />");
break;
case 0xE4A3: //kddi atm
buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />");
break;
case 0xE59A: //kddi basketball
buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />");
break;
case 0xE497: //kddi sagittarius
buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />");
break;
case 0xEACD: //kddi delicious
buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />");
break;
case 0xE5A8: //kddi newmoon
buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />");
break;
case 0xE49E: //kddi ticket
buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />");
break;
case 0xE5AE: //kddi wobbly
buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />");
break;
case 0xE4E6: //kddi sweat02
buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />");
break;
case 0xE59E: //kddi event
buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />");
break;
case 0xE4AB: //kddi house
buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />");
break;
case 0xE491: //kddi gemini
buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />");
break;
case 0xE4C9: //kddi xmas
buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />");
break;
case 0xE5BE: //kddi note
buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />");
break;
case 0xEB2F: //kddi sign02
buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />");
break;
case 0xE508: //kddi music
buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />");
break;
case 0xE5DF: //kddi hospital
buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />");
break;
case 0xE5BC: //kddi subway
buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />");
break;
case 0xE5C9: //kddi crown
buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />");
break;
case 0xE4BC: //kddi spa
buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />");
break;
case 0xE514: //kddi ring
buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />");
break;
// Skipping kddi codepoint E502 tv
// It conflicts with an earlier definition from another carrier:
// softbank art
case 0xE4AC: //kddi restaurant
buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />");
break;
case 0xE529: //kddi eight
buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />");
break;
case 0xE518: //kddi search
buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />");
break;
case 0xE505: //kddi notes
buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />");
break;
case 0xE498: //kddi capricornus
buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />");
break;
case 0xEB7E: //kddi snail
buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />");
break;
case 0xEA97: //kddi bottle
buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />");
break;
case 0xEB08: //kddi phoneto
buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />");
break;
case 0xE4D2: //kddi cherry
buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />");
break;
case 0xE54D: //kddi downwardright
buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />");
break;
case 0xE5C3: //kddi wink
buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />");
break;
case 0xEAAC: //kddi ski
buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />");
break;
case 0xE515: //kddi camera
buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />");
break;
case 0xE5B6: //kddi t-shirt
buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />");
break;
case 0xE5C4: //kddi lovely
buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />");
break;
case 0xE4AD: //kddi building
buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />");
break;
case 0xE4CE: //kddi maple
buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />");
break;
case 0xE5AA: //kddi moon2
buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />");
break;
case 0xE5B4: //kddi noodle
buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />");
break;
case 0xE5A6: //kddi scissors
buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />");
break;
case 0xE4AA: //kddi bank
buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />");
break;
case 0xE4B5: //kddi train
buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />");
break;
case 0xE477: //kddi heart03
buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />");
break;
case 0xE481: //kddi danger
buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />");
break;
case 0xE597: //kddi cafe
buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />");
break;
case 0xEB2B: //kddi shoe
buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />");
break;
case 0xEB7C: //kddi wave
buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />");
break;
case 0xE471: //kddi happy01
buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />");
break;
case 0xE4CA: //kddi cherryblossom
buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />");
break;
case 0xE4D5: //kddi riceball
buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />");
break;
case 0xE587: //kddi wrench
buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />");
break;
case 0xEB2A: //kddi foot
buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />");
break;
case 0xE47D: //kddi smoking
buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />");
break;
case 0xE4DC: //kddi penguin
buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />");
break;
case 0xE4B3: //kddi airplane
buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />");
break;
case 0xE4DE: //kddi pig
buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />");
break;
case 0xE59B: //kddi pocketbell
buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />");
break;
case 0xE4AF: //kddi bus
buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />");
break;
case 0xE4A6: //kddi parking
buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />");
break;
case 0xE486: //kddi moon3
buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />");
break;
case 0xE5A4: //kddi eye
buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />");
break;
case 0xE50C: //kddi cd
buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />");
break;
case 0xE54C: //kddi upwardleft
buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />");
break;
case 0xEA82: //kddi ship
buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />");
break;
case 0xE4B1: //kddi car
buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />");
break;
case 0xEB80: //kddi smile
buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />");
break;
case 0xE5B0: //kddi impact
buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />");
break;
case 0xE504: //kddi moneybag
buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />");
break;
case 0xE4B9: //kddi motorsports
buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />");
break;
case 0xE494: //kddi virgo
buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />");
break;
case 0xE595: //kddi heart01
buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />");
break;
case 0xEB03: //kddi pen
buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />");
break;
case 0xE57D: //kddi yen
buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />");
break;
case 0xE598: //kddi mist
buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />");
break;
case 0xE5A2: //kddi diamond
buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />");
break;
case 0xE4A4: //kddi 24hours
buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />");
break;
case 0xE524: //kddi three
buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />");
break;
case 0xEB7B: //kddi updown
buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />");
break;
case 0xE5A1: //kddi spade
buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />");
break;
case 0xE495: //kddi libra
buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />");
break;
case 0xE588: //kddi mobilephone
buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />");
break;
case 0xE599: //kddi golf
buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />");
break;
case 0xE520: //kddi faxto
buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />");
break;
// Skipping kddi codepoint E503 karaoke
// It conflicts with an earlier definition from another carrier:
// softbank drama
case 0xE4D6: //kddi fastfood
buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />");
break;
case 0xE4A1: //kddi pencil
buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />");
break;
case 0xE522: //kddi one
buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />");
break;
case 0xEB84: //kddi sharp
buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />");
break;
case 0xE476: //kddi flair
buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />");
break;
case 0xE46B: //kddi run
buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />");
break;
case 0xEAF5: //kddi drama
buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />");
break;
case 0xEAB9: //kddi apple
buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />");
break;
case 0xE4EB: //kddi kissmark
buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />");
break;
case 0xE55D: //kddi enter
buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />");
break;
case 0xE59F: //kddi ribbon
buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />");
break;
case 0xE526: //kddi five
buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />");
break;
case 0xE571: //kddi gasstation
buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />");
break;
case 0xE517: //kddi movie
buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />");
break;
case 0xE4B8: //kddi snowboard
buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />");
break;
case 0xEAE8: //kddi sprinkle
buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />");
break;
case 0xEA80: //kddi school
buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />");
break;
case 0xE47C: //kddi sandclock
buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />");
break;
case 0xEB31: //kddi sign05
buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />");
break;
case 0xE5AB: //kddi clear
buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />");
break;
case 0xE5DE: //kddi postoffice
buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />");
break;
case 0xEB62: //kddi mailto
buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />");
break;
case 0xE528: //kddi seven
buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />");
break;
case 0xE4C2: //kddi bar
buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />");
break;
case 0xE487: //kddi thunder
buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />");
break;
case 0xE5A9: //kddi moon1
buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />");
break;
case 0xEB7A: //kddi leftright
buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />");
break;
case 0xE513: //kddi clover
buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />");
break;
case 0xE492: //kddi cancer
buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />");
break;
case 0xEB78: //kddi loveletter
buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />");
break;
case 0xE4E0: //kddi chick
buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />");
break;
case 0xE4CF: //kddi present
buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />");
break;
case 0xE478: //kddi heart04
buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />");
break;
case 0xEAC3: //kddi sad
buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />");
break;
case 0xE52A: //kddi nine
buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />");
break;
case 0xE482: //kddi sign01
buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />");
break;
case 0xEABF: //kddi catface
buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />");
break;
case 0xE527: //kddi six
buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />");
break;
case 0xE52C: //kddi mobaq
buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />");
break;
case 0xE485: //kddi snow
buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />");
break;
case 0xE4B7: //kddi tennis
buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />");
break;
case 0xE5BD: //kddi fuji
buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />");
break;
case 0xE558: //kddi copyright
buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />");
break;
case 0xE4D8: //kddi horse
buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />");
break;
case 0xE4B0: //kddi bullettrain
buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />");
break;
case 0xE596: //kddi telephone
buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />");
break;
case 0xE48F: //kddi aries
buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />");
break;
case 0xE46A: //kddi signaler
buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />");
break;
case 0xE472: //kddi angry
buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />");
break;
case 0xE54E: //kddi tm
buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />");
break;
case 0xE51A: //kddi boutique
buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />");
break;
case 0xE493: //kddi leo
buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />");
break;
case 0xE5A3: //kddi club
buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />");
break;
case 0xE499: //kddi aquarius
buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />");
break;
case 0xE4AE: //kddi bicycle
buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />");
break;
case 0xE4E7: //kddi bleah
buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />");
break;
case 0xE49F: //kddi book
buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />");
break;
case 0xE5AD: //kddi ok
buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />");
break;
case 0xE5A7: //kddi paper
buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />");
break;
case 0xE4E5: //kddi annoy
buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />");
break;
case 0xE4A0: //kddi clip
buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />");
break;
case 0xE509: //kddi rouge
buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />");
break;
case 0xEAAF: //kddi bread
buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />");
break;
case 0xE519: //kddi key
buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />");
break;
case 0xE594: //kddi clock
buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />");
break;
case 0xEB7D: //kddi bud
buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />");
break;
case 0xEA8A: //kddi empty
buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />");
break;
case 0xE5B5: //kddi new
buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />");
break;
case 0xE47A: //kddi bomb
buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />");
break;
case 0xE5C6: //kddi coldsweats02
buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />");
break;
case 0xE49A: //kddi pisces
buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />");
break;
case 0xE4F3: //kddi punch
buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />");
break;
case 0xEB5D: //kddi pout
buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />");
break;
case 0xE469: //kddi typhoon
buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />");
break;
case 0xE5B1: //kddi sweat01
buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />");
break;
case 0xE4C7: //kddi dollar
buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />");
break;
case 0xE5C5: //kddi shock
buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />");
break;
case 0xE4F9: //kddi good
buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />");
break;
case 0xE4F1: //kddi secret
buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />");
break;
case 0xE4E4: //kddi tulip
buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />");
break;
case 0xEA81: //kddi hotel
buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />");
break;
case 0xE4FE: //kddi eyeglass
buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />");
break;
case 0xEAF1: //kddi night
buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />");
break;
case 0xE555: //kddi upwardright
buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />");
break;
case 0xEB2E: //kddi down
buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />");
break;
case 0xE4DB: //kddi cat
buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />");
break;
case 0xE59C: //kddi art
buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />");
break;
case 0xEB69: //kddi weep
buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />");
break;
case 0xE4F4: //kddi dash
buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />");
break;
case 0xE490: //kddi taurus
buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />");
break;
case 0xE57A: //kddi watch
buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />");
break;
case 0xEB2C: //kddi flag
buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />");
break;
case 0xEB77: //kddi denim
buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />");
break;
case 0xEAC5: //kddi confident
buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />");
break;
case 0xE4B4: //kddi yacht
buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />");
break;
case 0xE49C: //kddi bag
buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />");
break;
case 0xE5A5: //kddi ear
buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />");
break;
case 0xE4E1: //kddi dog
buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />");
break;
case 0xE521: //kddi mail
buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />");
break;
case 0xEB35: //kddi banana
buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />");
break;
case 0xEAA5: //kddi heart
buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />");
break;
case 0xE47F: //kddi wheelchair
buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />");
break;
case 0xEB75: //kddi heart02
buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />");
break;
case 0xE48D: //kddi cloud
buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />");
break;
case 0xE4C3: //kddi beer
buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />");
break;
case 0xEAAB: //kddi shine
buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />");
break;
case 0xEA92: //kddi memo
buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />");
break;
default:
buff.append((char)c);
}//switch
}
}
catch (IOException e)
{
//Should never happen
Log.e(K9.LOG_TAG, null, e);
}
return buff.toString();
}
@Override
public boolean isInTopGroup()
{
return inTopGroup;
}
public void setInTopGroup(boolean inTopGroup)
{
this.inTopGroup = inTopGroup;
}
}
public class LocalTextBody extends TextBody
{
private String mBodyForDisplay;
public LocalTextBody(String body)
{
super(body);
}
public LocalTextBody(String body, String bodyForDisplay) throws MessagingException
{
super(body);
this.mBodyForDisplay = bodyForDisplay;
}
public String getBodyForDisplay()
{
return mBodyForDisplay;
}
public void setBodyForDisplay(String mBodyForDisplay)
{
this.mBodyForDisplay = mBodyForDisplay;
}
}//LocalTextBody
public class LocalMessage extends MimeMessage
{
private long mId;
private int mAttachmentCount;
private String mSubject;
private String mPreview = "";
private boolean mHeadersLoaded = false;
private boolean mMessageDirty = false;
public LocalMessage()
{
}
LocalMessage(String uid, Folder folder) throws MessagingException
{
this.mUid = uid;
this.mFolder = folder;
}
private void populateFromGetMessageCursor(Cursor cursor)
throws MessagingException
{
this.setSubject(cursor.getString(0) == null ? "" : cursor.getString(0));
Address[] from = Address.unpack(cursor.getString(1));
if (from.length > 0)
{
this.setFrom(from[0]);
}
this.setInternalSentDate(new Date(cursor.getLong(2)));
this.setUid(cursor.getString(3));
String flagList = cursor.getString(4);
if (flagList != null && flagList.length() > 0)
{
String[] flags = flagList.split(",");
for (String flag : flags)
{
try
{
this.setFlagInternal(Flag.valueOf(flag), true);
}
catch (Exception e)
{
if ("X_BAD_FLAG".equals(flag) == false)
{
Log.w(K9.LOG_TAG, "Unable to parse flag " + flag);
}
}
}
}
this.mId = cursor.getLong(5);
this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6)));
this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7)));
this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8)));
this.setReplyTo(Address.unpack(cursor.getString(9)));
this.mAttachmentCount = cursor.getInt(10);
this.setInternalDate(new Date(cursor.getLong(11)));
this.setMessageId(cursor.getString(12));
mPreview = (cursor.getString(14) == null ? "" : cursor.getString(14));
if (this.mFolder == null)
{
LocalFolder f = new LocalFolder(cursor.getInt(13));
f.open(LocalFolder.OpenMode.READ_WRITE);
this.mFolder = f;
}
}
/* Custom version of writeTo that updates the MIME message based on localMessage
* changes.
*/
@Override
public void writeTo(OutputStream out) throws IOException, MessagingException
{
if (mMessageDirty) buildMimeRepresentation();
super.writeTo(out);
}
private void buildMimeRepresentation() throws MessagingException
{
if (!mMessageDirty)
{
return;
}
super.setSubject(mSubject);
if (this.mFrom != null && this.mFrom.length > 0)
{
super.setFrom(this.mFrom[0]);
}
super.setReplyTo(mReplyTo);
super.setSentDate(this.getSentDate());
super.setRecipients(RecipientType.TO, mTo);
super.setRecipients(RecipientType.CC, mCc);
super.setRecipients(RecipientType.BCC, mBcc);
if (mMessageId != null) super.setMessageId(mMessageId);
mMessageDirty = false;
return;
}
public String getPreview()
{
return mPreview;
}
@Override
public String getSubject() throws MessagingException
{
return mSubject;
}
@Override
public void setSubject(String subject) throws MessagingException
{
mSubject = subject;
mMessageDirty = true;
}
@Override
public void setMessageId(String messageId)
{
mMessageId = messageId;
mMessageDirty = true;
}
public int getAttachmentCount()
{
return mAttachmentCount;
}
@Override
public void setFrom(Address from) throws MessagingException
{
this.mFrom = new Address[] { from };
mMessageDirty = true;
}
@Override
public void setReplyTo(Address[] replyTo) throws MessagingException
{
if (replyTo == null || replyTo.length == 0)
{
mReplyTo = null;
}
else
{
mReplyTo = replyTo;
}
mMessageDirty = true;
}
/*
* For performance reasons, we add headers instead of setting them (see super implementation)
* which removes (expensive) them before adding them
*/
@Override
public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException
{
if (type == RecipientType.TO)
{
if (addresses == null || addresses.length == 0)
{
this.mTo = null;
}
else
{
this.mTo = addresses;
}
}
else if (type == RecipientType.CC)
{
if (addresses == null || addresses.length == 0)
{
this.mCc = null;
}
else
{
this.mCc = addresses;
}
}
else if (type == RecipientType.BCC)
{
if (addresses == null || addresses.length == 0)
{
this.mBcc = null;
}
else
{
this.mBcc = addresses;
}
}
else
{
throw new MessagingException("Unrecognized recipient type.");
}
mMessageDirty = true;
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException
{
super.setFlag(flag, set);
}
public long getId()
{
return mId;
}
@Override
public void setFlag(Flag flag, boolean set) throws MessagingException
{
if (flag == Flag.DELETED && set)
{
/*
* If a message is being marked as deleted we want to clear out it's content
* and attachments as well. Delete will not actually remove the row since we need
* to retain the uid for synchronization purposes.
*/
/*
* Delete all of the messages' content to save space.
*/
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL(
"UPDATE messages SET " +
"deleted = 1," +
"subject = NULL, " +
"sender_list = NULL, " +
"date = NULL, " +
"to_list = NULL, " +
"cc_list = NULL, " +
"bcc_list = NULL, " +
"preview = NULL, " +
"html_content = NULL, " +
"text_content = NULL, " +
"reply_to_list = NULL " +
"WHERE id = ?",
new Object[]
{
mId
});
/*
* Delete all of the messages' attachments to save space.
*/
mDb.execSQL("DELETE FROM attachments WHERE message_id = ?",
new Object[]
{
mId
});
((LocalFolder)mFolder).deleteHeaders(mId);
}
else if (flag == Flag.X_DESTROYED && set)
{
((LocalFolder) mFolder).deleteAttachments(getUid());
mDb.execSQL("DELETE FROM messages WHERE id = ?",
new Object[] { mId });
((LocalFolder)mFolder).deleteHeaders(mId);
}
/*
* Update the unread count on the folder.
*/
try
{
if (flag == Flag.DELETED || flag == Flag.X_DESTROYED
|| (flag == Flag.SEEN && !isSet(Flag.DELETED)))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set && !isSet(Flag.SEEN))
{
folder.setUnreadMessageCount(folder.getUnreadMessageCount() - 1);
}
else if (!set && isSet(Flag.SEEN))
{
folder.setUnreadMessageCount(folder.getUnreadMessageCount() + 1);
}
}
if ((flag == Flag.DELETED || flag == Flag.X_DESTROYED) && isSet(Flag.FLAGGED))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set)
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() - 1);
}
else
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + 1);
}
}
if (flag == Flag.FLAGGED && !isSet(Flag.DELETED))
{
LocalFolder folder = (LocalFolder)mFolder;
if (set)
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + 1);
}
else
{
folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() - 1);
}
}
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to update LocalStore unread message count",
me);
throw new RuntimeException(me);
}
super.setFlag(flag, set);
/*
* Set the flags on the message.
*/
mDb.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[]
{
Utility.combine(getFlags(), ',').toUpperCase(), mId
});
}
private void loadHeaders()
{
ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>();
messages.add(this);
mHeadersLoaded = true; // set true before calling populate headers to stop recursion
((LocalFolder) mFolder).populateHeaders(messages);
}
@Override
public void addHeader(String name, String value)
{
if (!mHeadersLoaded)
loadHeaders();
super.addHeader(name, value);
}
@Override
public void setHeader(String name, String value)
{
if (!mHeadersLoaded)
loadHeaders();
super.setHeader(name, value);
}
@Override
public String[] getHeader(String name)
{
if (!mHeadersLoaded)
loadHeaders();
return super.getHeader(name);
}
@Override
public void removeHeader(String name)
{
if (!mHeadersLoaded)
loadHeaders();
super.removeHeader(name);
}
@Override
public Set<String> getHeaderNames()
{
if (!mHeadersLoaded)
loadHeaders();
return super.getHeaderNames();
}
}
public class LocalAttachmentBodyPart extends MimeBodyPart
{
private long mAttachmentId = -1;
public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException
{
super(body);
mAttachmentId = attachmentId;
}
/**
* Returns the local attachment id of this body, or -1 if it is not stored.
* @return
*/
public long getAttachmentId()
{
return mAttachmentId;
}
public void setAttachmentId(long attachmentId)
{
mAttachmentId = attachmentId;
}
@Override
public String toString()
{
return "" + mAttachmentId;
}
}
public static class LocalAttachmentBody implements Body
{
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private Application mApplication;
private Uri mUri;
public LocalAttachmentBody(Uri uri, Application application)
{
mApplication = application;
mUri = uri;
}
public InputStream getInputStream() throws MessagingException
{
try
{
return mApplication.getContentResolver().openInputStream(mUri);
}
catch (FileNotFoundException fnfe)
{
/*
* Since it's completely normal for us to try to serve up attachments that
* have been blown away, we just return an empty stream.
*/
return new ByteArrayInputStream(EMPTY_BYTE_ARRAY);
}
}
public void writeTo(OutputStream out) throws IOException, MessagingException
{
InputStream in = getInputStream();
Base64OutputStream base64Out = new Base64OutputStream(out);
IOUtils.copy(in, base64Out);
base64Out.close();
}
public Uri getContentUri()
{
return mUri;
}
}
}
|
extract the method for "delete a message" from the "Set flags" method
|
src/com/fsck/k9/mail/store/LocalStore.java
|
extract the method for "delete a message" from the "Set flags" method
|
|
Java
|
apache-2.0
|
76ebd0b59b9a56c5883b721be3625c9b71e4fefe
| 0
|
siyuanh/apex-malhar,tweise/incubator-apex-malhar,davidyan74/apex-malhar,siyuanh/apex-malhar,yogidevendra/incubator-apex-malhar,ilganeli/incubator-apex-malhar,chandnisingh/apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,patilvikram/apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,vrozov/apex-malhar,yogidevendra/incubator-apex-malhar,DataTorrent/Megh,ananthc/apex-malhar,brightchen/apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,prasannapramod/apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,trusli/apex-malhar,DataTorrent/incubator-apex-malhar,skekre98/apex-mlhr,prasannapramod/apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,apache/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,vrozov/apex-malhar,davidyan74/apex-malhar,siyuanh/incubator-apex-malhar,apache/incubator-apex-malhar,ilganeli/incubator-apex-malhar,skekre98/apex-mlhr,siyuanh/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,tweise/apex-malhar,siyuanh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/apex-malhar,prasannapramod/apex-malhar,trusli/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,vrozov/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/apex-malhar,yogidevendra/incubator-apex-malhar,vrozov/apex-malhar,yogidevendra/incubator-apex-malhar,davidyan74/apex-malhar,apache/incubator-apex-malhar,prasannapramod/apex-malhar,yogidevendra/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,vrozov/apex-malhar,brightchen/apex-malhar,DataTorrent/Megh,tweise/apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,siyuanh/apex-malhar,tweise/apex-malhar,apache/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,siyuanh/apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/apex-malhar,apache/incubator-apex-malhar,tweise/incubator-apex-malhar,siyuanh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,ilganeli/incubator-apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,yogidevendra/apex-malhar,chinmaykolhatkar/apex-malhar,ilganeli/incubator-apex-malhar,tweise/incubator-apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,vrozov/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,prasannapramod/apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,vrozov/incubator-apex-malhar,prasannapramod/apex-malhar,trusli/apex-malhar,sandeep-n/incubator-apex-malhar,skekre98/apex-mlhr,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/apex-malhar,ananthc/apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,apache/incubator-apex-malhar,ananthc/apex-malhar,tweise/incubator-apex-malhar,chandnisingh/apex-malhar,chandnisingh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,apache/incubator-apex-malhar,davidyan74/apex-malhar,chandnisingh/apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chandnisingh/apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/incubator-apex-malhar,siyuanh/apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/apex-malhar,tweise/apex-malhar,yogidevendra/apex-malhar,trusli/apex-malhar,skekre98/apex-mlhr
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.kafka;
import java.io.Closeable;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import kafka.message.Message;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Pattern.Flag;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.datatorrent.api.Context;
import com.esotericsoftware.kryo.serializers.FieldSerializer.Bind;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
/**
* Base Kafka Consumer class used by kafka input operator
*
* @since 0.9.0
*/
public abstract class KafkaConsumer implements Closeable
{
protected final static String HIGHLEVEL_CONSUMER_ID_SUFFIX = "_stream_";
protected final static String SIMPLE_CONSUMER_ID_SUFFIX = "_partition_";
public KafkaConsumer()
{
}
public KafkaConsumer(String topic)
{
this();
this.topic = topic;
}
public KafkaConsumer(SetMultimap<String, String> zks, String topic)
{
this.topic = topic;
this.zookeeper = zks;
}
private int cacheSize = 1024;
protected transient boolean isAlive = false;
private transient ArrayBlockingQueue<KafkaMessage> holdingBuffer;
/**
* The topic that this consumer consumes
*/
@NotNull
protected String topic = "default_topic";
/**
* A zookeeper map keyed by cluster id
* It's mandatory field
*/
@NotNull
@Bind(JavaSerializer.class)
protected SetMultimap<String, String> zookeeper;
protected transient SetMultimap<String, String> brokers;
/**
* The initialOffset could be either earliest or latest
* Earliest means the beginning the queue
* Latest means the current sync point to consume the queue
* This setting is case_insensitive
* By default it always consume from the beginning of the queue
*/
@Pattern(flags={Flag.CASE_INSENSITIVE}, regexp = "earliest|latest")
protected String initialOffset = "latest";
protected transient SnapShot statsSnapShot = new SnapShot();
protected transient KafkaMeterStats stats = new KafkaMeterStats();
/**
* This method is called in setup method of the operator
*/
public void create(){
initBrokers();
holdingBuffer = new ArrayBlockingQueue<KafkaMessage>(cacheSize);
}
public void initBrokers()
{
if(brokers!=null){
return ;
}
if(zookeeper!=null){
brokers = HashMultimap.create();
for (String clusterId: zookeeper.keySet()) {
try {
brokers.putAll(clusterId, KafkaMetadataUtil.getBrokers(zookeeper.get(clusterId)));
} catch (Exception e) {
// let the user know where we tried to connect to
throw new RuntimeException("Error resolving brokers for cluster " + clusterId + " " + zookeeper.get(clusterId), e);
}
}
}
}
/**
* This method is called in the activate method of the operator
*/
public void start()
{
isAlive = true;
statsSnapShot.start();
}
/**
* The method is called in the deactivate method of the operator
*/
public void stop() {
isAlive = false;
statsSnapShot.stop();
holdingBuffer.clear();
IOUtils.closeQuietly(this);
};
/**
* This method is called in teardown method of the operator
*/
public void teardown()
{
holdingBuffer.clear();
}
public boolean isAlive()
{
return isAlive;
}
public void setAlive(boolean isAlive)
{
this.isAlive = isAlive;
}
public void setTopic(String topic)
{
this.topic = topic;
}
public String getTopic()
{
return topic;
}
public KafkaMessage pollMessage()
{
return holdingBuffer.poll();
}
public int messageSize()
{
return holdingBuffer.size();
}
public void setZookeeper(SetMultimap<String, String> zks)
{
this.zookeeper = zks;
}
public SetMultimap<String, String> getZookeeper()
{
return zookeeper;
}
public void setInitialOffset(String initialOffset)
{
this.initialOffset = initialOffset;
}
public String getInitialOffset()
{
return initialOffset;
}
public int getCacheSize()
{
return cacheSize;
}
public void setCacheSize(int cacheSize)
{
this.cacheSize = cacheSize;
}
final protected void putMessage(KafkaPartition partition, Message msg, long offset) throws InterruptedException{
// block from receiving more message
holdingBuffer.put(new KafkaMessage(partition, msg, offset));
statsSnapShot.mark(partition, msg.payloadSize());
}
protected abstract void commitOffset();
protected abstract Map<KafkaPartition, Long> getCurrentOffsets();
public KafkaMeterStats getConsumerStats()
{
statsSnapShot.setupStats(stats);
return stats;
}
protected abstract void resetPartitionsAndOffset(Set<KafkaPartition> partitionIds, Map<KafkaPartition, Long> startOffset);
/**
* Counter class which gives the statistic value from the consumer
*/
public static class KafkaMeterStats implements Serializable
{
private static final long serialVersionUID = -2867402654990209006L;
/**
* A compact partition counter. The data collected for each partition is 4bytes brokerId + 1byte connected + 8bytes msg/s + 8bytes bytes/s + 8bytes offset
*/
public ConcurrentHashMap<KafkaPartition, PartitionStats> partitionStats = new ConcurrentHashMap<KafkaPartition, PartitionStats>();
/**
* A compact overall counter. The data collected is 4bytes connection number + 8bytes aggregate msg/s + 8bytes aggregate bytes/s
*/
public long totalMsgPerSec;
public long totalBytesPerSec;
public KafkaMeterStats()
{
}
public void set_1minMovingAvgPerPartition(KafkaPartition kp, long[] _1minAvgPar)
{
PartitionStats ps = putPartitionStatsIfNotPresent(kp);
ps.msgsPerSec = _1minAvgPar[0];
ps.bytesPerSec = _1minAvgPar[1];
}
public void set_1minMovingAvg(long[] _1minAvg)
{
totalMsgPerSec = _1minAvg[0];
totalBytesPerSec = _1minAvg[1];
}
public void updateOffsets(Map<KafkaPartition, Long> offsets){
for (Entry<KafkaPartition, Long> os : offsets.entrySet()) {
PartitionStats ps = putPartitionStatsIfNotPresent(os.getKey());
ps.offset = os.getValue();
}
}
public int getConnections()
{
int r = 0;
for (PartitionStats ps : partitionStats.values()) {
if (!StringUtils.isEmpty(ps.brokerHost)) {
r++;
}
}
return r;
}
public void updatePartitionStats(KafkaPartition kp,int brokerId, String host)
{
PartitionStats ps = putPartitionStatsIfNotPresent(kp);
ps.brokerHost = host;
ps.brokerId = brokerId;
}
private synchronized PartitionStats putPartitionStatsIfNotPresent(KafkaPartition kp){
PartitionStats ps = partitionStats.get(kp);
if (ps == null) {
ps = new PartitionStats();
partitionStats.put(kp, ps);
}
return ps;
}
}
public static class KafkaMessage
{
KafkaPartition kafkaPart;
Message msg;
long offSet;
public KafkaMessage(KafkaPartition kafkaPart, Message msg, long offset)
{
this.kafkaPart = kafkaPart;
this.msg = msg;
this.offSet = offset;
}
}
public static class KafkaMeterStatsUtil {
public static Map<KafkaPartition, Long> getOffsetsForPartitions(List<KafkaMeterStats> kafkaMeterStats)
{
Map<KafkaPartition, Long> result = Maps.newHashMap();
for (KafkaMeterStats kms : kafkaMeterStats) {
for (Entry<KafkaPartition, PartitionStats> item : kms.partitionStats.entrySet()) {
result.put(item.getKey(), item.getValue().offset);
}
}
return result;
}
public static Map<KafkaPartition, long[]> get_1minMovingAvgParMap(KafkaMeterStats kafkaMeterStats)
{
Map<KafkaPartition, long[]> result = Maps.newHashMap();
for (Entry<KafkaPartition, PartitionStats> item : kafkaMeterStats.partitionStats.entrySet()) {
result.put(item.getKey(), new long[]{item.getValue().msgsPerSec, item.getValue().bytesPerSec});
}
return result;
}
}
public static class KafkaMeterStatsAggregator implements Context.CountersAggregator, Serializable{
/**
*
*/
private static final long serialVersionUID = 729987800215151678L;
@Override
public Object aggregate(Collection<?> countersList)
{
KafkaMeterStats kms = new KafkaMeterStats();
for (Object o : countersList) {
if (o instanceof KafkaMeterStats){
KafkaMeterStats subKMS = (KafkaMeterStats)o;
kms.partitionStats.putAll(subKMS.partitionStats);
kms.totalBytesPerSec += subKMS.totalBytesPerSec;
kms.totalMsgPerSec += subKMS.totalMsgPerSec;
}
}
return kms;
}
}
public static class PartitionStats implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6572690643487689766L;
public int brokerId = -1;
public long msgsPerSec;
public long bytesPerSec;
public long offset;
public String brokerHost = "";
}
/**
* A snapshot of consuming rate within 1 min
*/
static class SnapShot {
// msgs/s and bytes/s for each partition
/**
* 1 min total msg number for each partition
*/
private final Map<KafkaPartition, long[]> _1_min_msg_sum_par = new HashMap<KafkaPartition, long[]>();
/**
* 1 min total byte number for each partition
*/
private final Map<KafkaPartition, long[]> _1_min_byte_sum_par = new HashMap<KafkaPartition, long[]>();
private static int cursor = 0;
/**
* total msg for each sec, msgSec[60] is total msg for a min
*/
private final long[] msgSec = new long[61];
/**
* total bytes for each sec, bytesSec[60] is total bytes for a min
*/
private final long[] bytesSec = new long[61];
private short last = 1;
private ScheduledExecutorService service;
public synchronized void moveNext()
{
cursor = (cursor + 1) % 60;
msgSec[60] -= msgSec[cursor];
bytesSec[60] -= bytesSec[cursor];
msgSec[cursor] = 0;
bytesSec[cursor] = 0;
for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
long[] msgv = item.getValue();
long[] bytesv = _1_min_byte_sum_par.get(item.getKey());
msgv[60] -= msgv[cursor];
bytesv[60] -= bytesv[cursor];
msgv[cursor] = 0;
bytesv[cursor] = 0;
}
}
public void start(){
if(service==null){
service = Executors.newScheduledThreadPool(1);
}
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run()
{
moveNext();
if(last<60)last++;
}
}, 1, 1, TimeUnit.SECONDS);
}
public void stop(){
if(service!=null){
service.shutdown();
}
}
public synchronized void mark(KafkaPartition partition, long bytes){
msgSec[cursor]++;
msgSec[60]++;
bytesSec[cursor] += bytes;
bytesSec[60] += bytes;
long[] msgv = _1_min_msg_sum_par.get(partition);
long[] bytev = _1_min_byte_sum_par.get(partition);
if(msgv == null){
msgv = new long[61];
bytev = new long[61];
_1_min_msg_sum_par.put(partition, msgv);
_1_min_byte_sum_par.put(partition, bytev);
}
msgv[cursor]++;
msgv[60]++;
bytev[cursor] += bytes;
bytev[60] += bytes;
}
public synchronized void setupStats(KafkaMeterStats stat){
long[] _1minAvg = {msgSec[60]/last, bytesSec[60]/last};
for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
long[] msgv =item.getValue();
long[] bytev = _1_min_byte_sum_par.get(item.getKey());
long[] _1minAvgPar = {msgv[60]/last, bytev[60]/last};
stat.set_1minMovingAvgPerPartition(item.getKey(), _1minAvgPar);
}
stat.set_1minMovingAvg(_1minAvg);
}
}
}
|
contrib/src/main/java/com/datatorrent/contrib/kafka/KafkaConsumer.java
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.kafka;
import java.io.Closeable;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import kafka.message.Message;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Pattern.Flag;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.datatorrent.api.Context;
import com.esotericsoftware.kryo.serializers.FieldSerializer.Bind;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
/**
* Base Kafka Consumer class used by kafka input operator
*
* @since 0.9.0
*/
public abstract class KafkaConsumer implements Closeable
{
protected final static String HIGHLEVEL_CONSUMER_ID_SUFFIX = "_stream_";
protected final static String SIMPLE_CONSUMER_ID_SUFFIX = "_partition_";
public KafkaConsumer()
{
}
public KafkaConsumer(String topic)
{
this();
this.topic = topic;
}
public KafkaConsumer(SetMultimap<String, String> zks, String topic)
{
this.topic = topic;
this.zookeeper = zks;
}
private int cacheSize = 1024;
protected transient boolean isAlive = false;
private transient ArrayBlockingQueue<KafkaMessage> holdingBuffer;
/**
* The topic that this consumer consumes
*/
@NotNull
protected String topic = "default_topic";
/**
* A zookeeper map keyed by cluster id
* It's mandatory field
*/
@NotNull
@Bind(JavaSerializer.class)
protected SetMultimap<String, String> zookeeper;
protected transient SetMultimap<String, String> brokers;
/**
* The initialOffset could be either earliest or latest
* Earliest means the beginning the queue
* Latest means the current sync point to consume the queue
* This setting is case_insensitive
* By default it always consume from the beginning of the queue
*/
@Pattern(flags={Flag.CASE_INSENSITIVE}, regexp = "earliest|latest")
protected String initialOffset = "latest";
protected transient SnapShot statsSnapShot = new SnapShot();
protected transient KafkaMeterStats stats = new KafkaMeterStats();
/**
* This method is called in setup method of the operator
*/
public void create(){
initBrokers();
holdingBuffer = new ArrayBlockingQueue<KafkaMessage>(cacheSize);
}
public void initBrokers()
{
if(brokers!=null){
return ;
}
if(zookeeper!=null){
brokers = HashMultimap.create();
for (String clusterId: zookeeper.keySet()) {
brokers.putAll(clusterId, KafkaMetadataUtil.getBrokers(zookeeper.get(clusterId)));
}
}
}
/**
* This method is called in the activate method of the operator
*/
public void start()
{
isAlive = true;
statsSnapShot.start();
}
/**
* The method is called in the deactivate method of the operator
*/
public void stop() {
isAlive = false;
statsSnapShot.stop();
holdingBuffer.clear();
IOUtils.closeQuietly(this);
};
/**
* This method is called in teardown method of the operator
*/
public void teardown()
{
holdingBuffer.clear();
}
public boolean isAlive()
{
return isAlive;
}
public void setAlive(boolean isAlive)
{
this.isAlive = isAlive;
}
public void setTopic(String topic)
{
this.topic = topic;
}
public String getTopic()
{
return topic;
}
public KafkaMessage pollMessage()
{
return holdingBuffer.poll();
}
public int messageSize()
{
return holdingBuffer.size();
}
public void setZookeeper(SetMultimap<String, String> zks)
{
this.zookeeper = zks;
}
public SetMultimap<String, String> getZookeeper()
{
return zookeeper;
}
public void setInitialOffset(String initialOffset)
{
this.initialOffset = initialOffset;
}
public String getInitialOffset()
{
return initialOffset;
}
public int getCacheSize()
{
return cacheSize;
}
public void setCacheSize(int cacheSize)
{
this.cacheSize = cacheSize;
}
final protected void putMessage(KafkaPartition partition, Message msg, long offset) throws InterruptedException{
// block from receiving more message
holdingBuffer.put(new KafkaMessage(partition, msg, offset));
statsSnapShot.mark(partition, msg.payloadSize());
}
protected abstract void commitOffset();
protected abstract Map<KafkaPartition, Long> getCurrentOffsets();
public KafkaMeterStats getConsumerStats()
{
statsSnapShot.setupStats(stats);
return stats;
}
protected abstract void resetPartitionsAndOffset(Set<KafkaPartition> partitionIds, Map<KafkaPartition, Long> startOffset);
/**
* Counter class which gives the statistic value from the consumer
*/
public static class KafkaMeterStats implements Serializable
{
private static final long serialVersionUID = -2867402654990209006L;
/**
* A compact partition counter. The data collected for each partition is 4bytes brokerId + 1byte connected + 8bytes msg/s + 8bytes bytes/s + 8bytes offset
*/
public ConcurrentHashMap<KafkaPartition, PartitionStats> partitionStats = new ConcurrentHashMap<KafkaPartition, PartitionStats>();
/**
* A compact overall counter. The data collected is 4bytes connection number + 8bytes aggregate msg/s + 8bytes aggregate bytes/s
*/
public long totalMsgPerSec;
public long totalBytesPerSec;
public KafkaMeterStats()
{
}
public void set_1minMovingAvgPerPartition(KafkaPartition kp, long[] _1minAvgPar)
{
PartitionStats ps = putPartitionStatsIfNotPresent(kp);
ps.msgsPerSec = _1minAvgPar[0];
ps.bytesPerSec = _1minAvgPar[1];
}
public void set_1minMovingAvg(long[] _1minAvg)
{
totalMsgPerSec = _1minAvg[0];
totalBytesPerSec = _1minAvg[1];
}
public void updateOffsets(Map<KafkaPartition, Long> offsets){
for (Entry<KafkaPartition, Long> os : offsets.entrySet()) {
PartitionStats ps = putPartitionStatsIfNotPresent(os.getKey());
ps.offset = os.getValue();
}
}
public int getConnections()
{
int r = 0;
for (PartitionStats ps : partitionStats.values()) {
if (!StringUtils.isEmpty(ps.brokerHost)) {
r++;
}
}
return r;
}
public void updatePartitionStats(KafkaPartition kp,int brokerId, String host)
{
PartitionStats ps = putPartitionStatsIfNotPresent(kp);
ps.brokerHost = host;
ps.brokerId = brokerId;
}
private synchronized PartitionStats putPartitionStatsIfNotPresent(KafkaPartition kp){
PartitionStats ps = partitionStats.get(kp);
if (ps == null) {
ps = new PartitionStats();
partitionStats.put(kp, ps);
}
return ps;
}
}
public static class KafkaMessage
{
KafkaPartition kafkaPart;
Message msg;
long offSet;
public KafkaMessage(KafkaPartition kafkaPart, Message msg, long offset)
{
this.kafkaPart = kafkaPart;
this.msg = msg;
this.offSet = offset;
}
}
public static class KafkaMeterStatsUtil {
public static Map<KafkaPartition, Long> getOffsetsForPartitions(List<KafkaMeterStats> kafkaMeterStats)
{
Map<KafkaPartition, Long> result = Maps.newHashMap();
for (KafkaMeterStats kms : kafkaMeterStats) {
for (Entry<KafkaPartition, PartitionStats> item : kms.partitionStats.entrySet()) {
result.put(item.getKey(), item.getValue().offset);
}
}
return result;
}
public static Map<KafkaPartition, long[]> get_1minMovingAvgParMap(KafkaMeterStats kafkaMeterStats)
{
Map<KafkaPartition, long[]> result = Maps.newHashMap();
for (Entry<KafkaPartition, PartitionStats> item : kafkaMeterStats.partitionStats.entrySet()) {
result.put(item.getKey(), new long[]{item.getValue().msgsPerSec, item.getValue().bytesPerSec});
}
return result;
}
}
public static class KafkaMeterStatsAggregator implements Context.CountersAggregator, Serializable{
/**
*
*/
private static final long serialVersionUID = 729987800215151678L;
@Override
public Object aggregate(Collection<?> countersList)
{
KafkaMeterStats kms = new KafkaMeterStats();
for (Object o : countersList) {
if (o instanceof KafkaMeterStats){
KafkaMeterStats subKMS = (KafkaMeterStats)o;
kms.partitionStats.putAll(subKMS.partitionStats);
kms.totalBytesPerSec += subKMS.totalBytesPerSec;
kms.totalMsgPerSec += subKMS.totalMsgPerSec;
}
}
return kms;
}
}
public static class PartitionStats implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6572690643487689766L;
public int brokerId = -1;
public long msgsPerSec;
public long bytesPerSec;
public long offset;
public String brokerHost = "";
}
/**
* A snapshot of consuming rate within 1 min
*/
static class SnapShot {
// msgs/s and bytes/s for each partition
/**
* 1 min total msg number for each partition
*/
private final Map<KafkaPartition, long[]> _1_min_msg_sum_par = new HashMap<KafkaPartition, long[]>();
/**
* 1 min total byte number for each partition
*/
private final Map<KafkaPartition, long[]> _1_min_byte_sum_par = new HashMap<KafkaPartition, long[]>();
private static int cursor = 0;
/**
* total msg for each sec, msgSec[60] is total msg for a min
*/
private final long[] msgSec = new long[61];
/**
* total bytes for each sec, bytesSec[60] is total bytes for a min
*/
private final long[] bytesSec = new long[61];
private short last = 1;
private ScheduledExecutorService service;
public synchronized void moveNext()
{
cursor = (cursor + 1) % 60;
msgSec[60] -= msgSec[cursor];
bytesSec[60] -= bytesSec[cursor];
msgSec[cursor] = 0;
bytesSec[cursor] = 0;
for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
long[] msgv = item.getValue();
long[] bytesv = _1_min_byte_sum_par.get(item.getKey());
msgv[60] -= msgv[cursor];
bytesv[60] -= bytesv[cursor];
msgv[cursor] = 0;
bytesv[cursor] = 0;
}
}
public void start(){
if(service==null){
service = Executors.newScheduledThreadPool(1);
}
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run()
{
moveNext();
if(last<60)last++;
}
}, 1, 1, TimeUnit.SECONDS);
}
public void stop(){
if(service!=null){
service.shutdown();
}
}
public synchronized void mark(KafkaPartition partition, long bytes){
msgSec[cursor]++;
msgSec[60]++;
bytesSec[cursor] += bytes;
bytesSec[60] += bytes;
long[] msgv = _1_min_msg_sum_par.get(partition);
long[] bytev = _1_min_byte_sum_par.get(partition);
if(msgv == null){
msgv = new long[61];
bytev = new long[61];
_1_min_msg_sum_par.put(partition, msgv);
_1_min_byte_sum_par.put(partition, bytev);
}
msgv[cursor]++;
msgv[60]++;
bytev[cursor] += bytes;
bytev[60] += bytes;
}
public synchronized void setupStats(KafkaMeterStats stat){
long[] _1minAvg = {msgSec[60]/last, bytesSec[60]/last};
for (Entry<KafkaPartition, long[]> item : _1_min_msg_sum_par.entrySet()) {
long[] msgv =item.getValue();
long[] bytev = _1_min_byte_sum_par.get(item.getKey());
long[] _1minAvgPar = {msgv[60]/last, bytev[60]/last};
stat.set_1minMovingAvgPerPartition(item.getKey(), _1minAvgPar);
}
stat.set_1minMovingAvg(_1minAvg);
}
}
}
|
Let the user know what Zookeeper we tried to connect to.
|
contrib/src/main/java/com/datatorrent/contrib/kafka/KafkaConsumer.java
|
Let the user know what Zookeeper we tried to connect to.
|
|
Java
|
apache-2.0
|
96c75147adc32acaa4441f449e3e636517585ce1
| 0
|
robovm/robovm-studio,ol-loginov/intellij-community,clumsy/intellij-community,signed/intellij-community,ibinti/intellij-community,amith01994/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,robovm/robovm-studio,supersven/intellij-community,da1z/intellij-community,fnouama/intellij-community,adedayo/intellij-community,caot/intellij-community,ryano144/intellij-community,clumsy/intellij-community,xfournet/intellij-community,samthor/intellij-community,ryano144/intellij-community,diorcety/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ernestp/consulo,gnuhub/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,joewalnes/idea-community,hurricup/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,signed/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,da1z/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,izonder/intellij-community,robovm/robovm-studio,asedunov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,diorcety/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,fitermay/intellij-community,allotria/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ryano144/intellij-community,jagguli/intellij-community,signed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,slisson/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,allotria/intellij-community,kool79/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,amith01994/intellij-community,samthor/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,dslomov/intellij-community,fitermay/intellij-community,allotria/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,joewalnes/idea-community,amith01994/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,holmes/intellij-community,slisson/intellij-community,kool79/intellij-community,ryano144/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,robovm/robovm-studio,robovm/robovm-studio,samthor/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,robovm/robovm-studio,vladmm/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fnouama/intellij-community,supersven/intellij-community,signed/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,da1z/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ryano144/intellij-community,vladmm/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,caot/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,izonder/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,da1z/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,slisson/intellij-community,ernestp/consulo,orekyuu/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,slisson/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,asedunov/intellij-community,Distrotech/intellij-community,izonder/intellij-community,slisson/intellij-community,petteyg/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,supersven/intellij-community,semonte/intellij-community,retomerz/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,allotria/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ryano144/intellij-community,blademainer/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,consulo/consulo,TangHao1987/intellij-community,hurricup/intellij-community,holmes/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,orekyuu/intellij-community,izonder/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,da1z/intellij-community,clumsy/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,fnouama/intellij-community,supersven/intellij-community,diorcety/intellij-community,slisson/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,kdwink/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,kool79/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ernestp/consulo,samthor/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,signed/intellij-community,caot/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,izonder/intellij-community,samthor/intellij-community,consulo/consulo,joewalnes/idea-community,Distrotech/intellij-community,holmes/intellij-community,signed/intellij-community,asedunov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,semonte/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,kool79/intellij-community,ernestp/consulo,kool79/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,allotria/intellij-community,samthor/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,caot/intellij-community,fitermay/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,diorcety/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,xfournet/intellij-community,joewalnes/idea-community,asedunov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,slisson/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,kool79/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ernestp/consulo,izonder/intellij-community,izonder/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,slisson/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,consulo/consulo,fnouama/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,slisson/intellij-community,ernestp/consulo,apixandru/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,blademainer/intellij-community,consulo/consulo,supersven/intellij-community,caot/intellij-community,ibinti/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,holmes/intellij-community,holmes/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ibinti/intellij-community,semonte/intellij-community,gnuhub/intellij-community,semonte/intellij-community,jagguli/intellij-community,ryano144/intellij-community,kdwink/intellij-community,adedayo/intellij-community,retomerz/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,allotria/intellij-community,jagguli/intellij-community,signed/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,consulo/consulo,suncycheng/intellij-community,caot/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,signed/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,semonte/intellij-community,fitermay/intellij-community,semonte/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,hurricup/intellij-community,jagguli/intellij-community,allotria/intellij-community,samthor/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,kool79/intellij-community,petteyg/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,allotria/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,holmes/intellij-community,caot/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,retomerz/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,FHannes/intellij-community,caot/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,semonte/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,jagguli/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,apixandru/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.application.options.editor.WebEditorOptions;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.template.Expression;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingAdapter;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.MacroCallNode;
import com.intellij.codeInsight.template.macro.MacroFactory;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlElementDescriptorWithCDataContent;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.util.HtmlUtil;
import com.intellij.xml.util.XmlUtil;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class XmlTagInsertHandler implements InsertHandler<LookupElement> {
public static final XmlTagInsertHandler INSTANCE = new XmlTagInsertHandler();
public void handleInsert(InsertionContext context, LookupElement item) {
Project project = context.getProject();
Editor editor = context.getEditor();
// Need to insert " " to prevent creating tags like <tagThis is my text
final int offset = editor.getCaretModel().getOffset();
editor.getDocument().insertString(offset, " ");
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
PsiElement current = context.getFile().findElementAt(context.getStartOffset());
editor.getDocument().deleteString(offset, offset + 1);
final XmlTag tag = PsiTreeUtil.getContextOfType(current, XmlTag.class, true);
if (tag == null) return;
context.setAddCompletionChar(false);
final XmlElementDescriptor descriptor = tag.getDescriptor();
if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) == null &&
XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null) {
Template t = TemplateManager.getInstance(project).getActiveTemplate(editor);
if (t == null && descriptor != null) {
insertIncompleteTag(context.getCompletionChar(), editor, project, descriptor, tag);
}
}
else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
int caretOffset = editor.getCaretModel().getOffset();
PsiElement otherTag = PsiTreeUtil.getParentOfType(context.getFile().findElementAt(caretOffset), XmlTag.class);
PsiElement endTagStart = XmlUtil.getTokenOfType(otherTag, XmlTokenType.XML_END_TAG_START);
if (endTagStart != null) {
PsiElement sibling = endTagStart.getNextSibling();
if (sibling.getNode().getElementType() == XmlTokenType.XML_NAME) {
int sOffset = sibling.getTextRange().getStartOffset();
int eOffset = sibling.getTextRange().getEndOffset();
editor.getDocument().deleteString(sOffset, eOffset);
editor.getDocument().insertString(sOffset, ((XmlTag)otherTag).getName());
}
}
editor.getCaretModel().moveToOffset(caretOffset + 1);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
}
if (context.getCompletionChar() == ' ' && TemplateManager.getInstance(project).getActiveTemplate(editor) != null) {
return;
}
final TailType tailType = LookupItem.handleCompletionChar(editor, item, context.getCompletionChar());
tailType.processTail(editor, editor.getCaretModel().getOffset());
}
private static void insertIncompleteTag(char completionChar, final Editor editor, final Project project, XmlElementDescriptor descriptor, XmlTag tag) {
TemplateManager templateManager = TemplateManager.getInstance(project);
Template template = templateManager.createTemplate("", "");
template.setToIndent(true);
// temp code
boolean htmlCode = HtmlUtil.hasHtml(tag.getContainingFile());
Set<String> notRequiredAttributes = Collections.emptySet();
if (tag instanceof HtmlTag) {
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
LocalInspectionToolWrapper localInspectionToolWrapper = (LocalInspectionToolWrapper) profile.getInspectionTool(
RequiredAttributesInspection.SHORT_NAME, tag);
RequiredAttributesInspection inspection = localInspectionToolWrapper != null ?
(RequiredAttributesInspection) localInspectionToolWrapper.getTool(): null;
if (inspection != null) {
StringTokenizer tokenizer = new StringTokenizer(inspection.getAdditionalEntries(0));
notRequiredAttributes = new HashSet<String>(1);
while(tokenizer.hasMoreElements()) notRequiredAttributes.add(tokenizer.nextToken());
}
}
boolean toReformat = true;
boolean weInsertedSomeCodeThatCouldBeInvalidated = false;
if (htmlCode) {
toReformat = false;
}
template.setToReformat(toReformat);
XmlAttributeDescriptor[] attributes = descriptor.getAttributesDescriptors(tag);
StringBuilder indirectRequiredAttrs = null;
final XmlExtension extension = XmlExtension.getExtension(tag.getContainingFile());
if (WebEditorOptions.getInstance().isAutomaticallyInsertRequiredAttributes()) {
for (XmlAttributeDescriptor attributeDecl : attributes) {
String attributeName = attributeDecl.getName(tag);
if (attributeDecl.isRequired() && tag.getAttributeValue(attributeName) == null) {
if (!notRequiredAttributes.contains(attributeName)) {
if (!extension.isIndirectSyntax(attributeDecl)) {
template.addTextSegment(" " + attributeName + "=\"");
Expression expression = new MacroCallNode(MacroFactory.createMacro("complete"));
template.addVariable(attributeName, expression, expression, true);
template.addTextSegment("\"");
}
else {
if (indirectRequiredAttrs == null) indirectRequiredAttrs = new StringBuilder();
indirectRequiredAttrs.append("\n<jsp:attribute name=\"").append(attributeName).append("\"></jsp:attribute>\n");
}
}
}
else if (attributeDecl.isRequired() && attributeDecl.isFixed() && attributeDecl.getDefaultValue() != null && !htmlCode) {
template.addTextSegment(" " + attributeName + "=\"" + attributeDecl.getDefaultValue() + "\"");
}
}
}
if (completionChar == '>' || (completionChar == '/' && indirectRequiredAttrs != null)) {
template.addTextSegment(">");
boolean toInsertCDataEnd = false;
if (descriptor instanceof XmlElementDescriptorWithCDataContent) {
final XmlElementDescriptorWithCDataContent cDataContainer = (XmlElementDescriptorWithCDataContent)descriptor;
if (cDataContainer.requiresCdataBracesInContext(tag)) {
template.addTextSegment("<![CDATA[\n");
toInsertCDataEnd = true;
}
}
if (indirectRequiredAttrs != null) template.addTextSegment(indirectRequiredAttrs.toString());
template.addEndVariable();
if (toInsertCDataEnd) template.addTextSegment("\n]]>");
if ((!(tag instanceof HtmlTag) || !HtmlUtil.isSingleHtmlTag(tag.getName())) && tag.getAttributes().length == 0) {
if (WebEditorOptions.getInstance().isAutomaticallyInsertClosingTag()) {
final String name = descriptor.getName(tag);
if (name != null) {
template.addTextSegment("</");
template.addTextSegment(name);
template.addTextSegment(">");
}
}
}
}
else if (completionChar == '/') {
template.addTextSegment("/>");
} else if (completionChar == ' ' && template.getSegmentsCount() == 0) {
if (WebEditorOptions.getInstance().isAutomaticallyStartAttribute() &&
(attributes.length > 0 || isTagFromHtml(tag) && !HtmlUtil.isTagWithoutAttributes(tag.getName()))) {
template.addTextSegment(" ");
final MacroCallNode completeAttrExpr = new MacroCallNode(MacroFactory.createMacro("complete"));
template.addVariable("attrComplete", completeAttrExpr, completeAttrExpr, true);
weInsertedSomeCodeThatCouldBeInvalidated = true;
template.addTextSegment("=\"");
template.addEndVariable();
template.addTextSegment("\"");
}
} else if ((completionChar == Lookup.AUTO_INSERT_SELECT_CHAR || completionChar == Lookup.NORMAL_SELECT_CHAR) && WebEditorOptions.getInstance().isAutomaticallyInsertClosingTag() && HtmlUtil.isSingleHtmlTag(tag.getName())) {
template.addTextSegment(tag instanceof HtmlTag ? ">" : "/>");
}
final boolean weInsertedSomeCodeThatCouldBeInvalidated1 = weInsertedSomeCodeThatCouldBeInvalidated;
templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {
public void templateFinished(final Template template, boolean brokenOff) {
final int offset = editor.getCaretModel().getOffset();
if (weInsertedSomeCodeThatCouldBeInvalidated1 &&
offset >= 3 &&
editor.getDocument().getCharsSequence().charAt(offset - 3) == '/') {
new WriteCommandAction.Simple(project) {
protected void run() throws Throwable {
editor.getDocument().replaceString(offset - 2, offset + 1, ">");
}
}.execute();
}
}
public void templateCancelled(final Template template) {
//final int offset = editor.getCaretModel().getOffset();
//if (weInsertedSomeCodeThatCouldBeInvalidated1) {}
}
});
}
private static boolean isTagFromHtml(final XmlTag tag) {
final String ns = tag.getNamespace();
return XmlUtil.XHTML_URI.equals(ns) || XmlUtil.HTML_URI.equals(ns);
}
}
|
xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.application.options.editor.WebEditorOptions;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.template.Expression;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingAdapter;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.MacroCallNode;
import com.intellij.codeInsight.template.macro.MacroFactory;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlElementDescriptorWithCDataContent;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.util.HtmlUtil;
import com.intellij.xml.util.XmlUtil;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class XmlTagInsertHandler implements InsertHandler<LookupElement> {
public static final XmlTagInsertHandler INSTANCE = new XmlTagInsertHandler();
public void handleInsert(InsertionContext context, LookupElement item) {
Project project = context.getProject();
Editor editor = context.getEditor();
// Need to insert " " to prevent creating tags like <tagThis is my text
final int offset = editor.getCaretModel().getOffset();
editor.getDocument().insertString(offset, " ");
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
PsiElement current = context.getFile().findElementAt(context.getStartOffset());
editor.getDocument().deleteString(offset, offset + 1);
final XmlTag tag = PsiTreeUtil.getContextOfType(current, XmlTag.class, true);
if (tag == null) return;
context.setAddCompletionChar(false);
final XmlElementDescriptor descriptor = tag.getDescriptor();
if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) == null &&
XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null) {
Template t = TemplateManager.getInstance(project).getActiveTemplate(editor);
if (t == null && descriptor != null) {
insertIncompleteTag(context.getCompletionChar(), editor, project, descriptor, tag);
}
}
else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
int caretOffset = editor.getCaretModel().getOffset();
PsiElement otherTag = PsiTreeUtil.getParentOfType(context.getFile().findElementAt(caretOffset), XmlTag.class);
PsiElement endTagStart = XmlUtil.getTokenOfType(otherTag, XmlTokenType.XML_END_TAG_START);
if (endTagStart != null) {
PsiElement sibling = endTagStart.getNextSibling();
if (sibling.getNode().getElementType() == XmlTokenType.XML_NAME) {
int sOffset = sibling.getTextRange().getStartOffset();
int eOffset = sibling.getTextRange().getEndOffset();
editor.getDocument().deleteString(sOffset, eOffset);
editor.getDocument().insertString(sOffset, ((XmlTag)otherTag).getName());
}
}
editor.getCaretModel().moveToOffset(caretOffset + 1);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
}
if (context.getCompletionChar() == ' ' && TemplateManager.getInstance(project).getActiveTemplate(editor) != null) {
return;
}
final TailType tailType = LookupItem.handleCompletionChar(editor, item, context.getCompletionChar());
tailType.processTail(editor, editor.getCaretModel().getOffset());
}
private static void insertIncompleteTag(char completionChar, final Editor editor, final Project project, XmlElementDescriptor descriptor, XmlTag tag) {
TemplateManager templateManager = TemplateManager.getInstance(project);
Template template = templateManager.createTemplate("", "");
template.setToIndent(true);
// temp code
boolean htmlCode = HtmlUtil.hasHtml(tag.getContainingFile());
Set<String> notRequiredAttributes = Collections.emptySet();
if (tag instanceof HtmlTag) {
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
LocalInspectionToolWrapper localInspectionToolWrapper = (LocalInspectionToolWrapper) profile.getInspectionTool(
RequiredAttributesInspection.SHORT_NAME, tag);
RequiredAttributesInspection inspection = localInspectionToolWrapper != null ?
(RequiredAttributesInspection) localInspectionToolWrapper.getTool(): null;
if (inspection != null) {
StringTokenizer tokenizer = new StringTokenizer(inspection.getAdditionalEntries(0));
notRequiredAttributes = new HashSet<String>(1);
while(tokenizer.hasMoreElements()) notRequiredAttributes.add(tokenizer.nextToken());
}
}
boolean toReformat = true;
boolean weInsertedSomeCodeThatCouldBeInvalidated = false;
if (htmlCode) {
toReformat = false;
}
template.setToReformat(toReformat);
XmlAttributeDescriptor[] attributes = descriptor.getAttributesDescriptors(tag);
StringBuilder indirectRequiredAttrs = null;
final XmlExtension extension = XmlExtension.getExtension(tag.getContainingFile());
if (WebEditorOptions.getInstance().isAutomaticallyInsertRequiredAttributes()) {
for (XmlAttributeDescriptor attributeDecl : attributes) {
String attributeName = attributeDecl.getName(tag);
if (attributeDecl.isRequired() && tag.getAttributeValue(attributeName) == null) {
if (!notRequiredAttributes.contains(attributeName)) {
if (!extension.isIndirectSyntax(attributeDecl)) {
template.addTextSegment(" " + attributeName + "=\"");
Expression expression = new MacroCallNode(MacroFactory.createMacro("complete"));
template.addVariable(attributeName, expression, expression, true);
template.addTextSegment("\"");
}
else {
if (indirectRequiredAttrs == null) indirectRequiredAttrs = new StringBuilder();
indirectRequiredAttrs.append("\n<jsp:attribute name=\"").append(attributeName).append("\"></jsp:attribute>\n");
}
}
}
else if (attributeDecl.isFixed() && attributeDecl.getDefaultValue() != null && !htmlCode) {
template.addTextSegment(" " + attributeName + "=\"" + attributeDecl.getDefaultValue() + "\"");
}
}
}
if (completionChar == '>' || (completionChar == '/' && indirectRequiredAttrs != null)) {
template.addTextSegment(">");
boolean toInsertCDataEnd = false;
if (descriptor instanceof XmlElementDescriptorWithCDataContent) {
final XmlElementDescriptorWithCDataContent cDataContainer = (XmlElementDescriptorWithCDataContent)descriptor;
if (cDataContainer.requiresCdataBracesInContext(tag)) {
template.addTextSegment("<![CDATA[\n");
toInsertCDataEnd = true;
}
}
if (indirectRequiredAttrs != null) template.addTextSegment(indirectRequiredAttrs.toString());
template.addEndVariable();
if (toInsertCDataEnd) template.addTextSegment("\n]]>");
if ((!(tag instanceof HtmlTag) || !HtmlUtil.isSingleHtmlTag(tag.getName())) && tag.getAttributes().length == 0) {
if (WebEditorOptions.getInstance().isAutomaticallyInsertClosingTag()) {
final String name = descriptor.getName(tag);
if (name != null) {
template.addTextSegment("</");
template.addTextSegment(name);
template.addTextSegment(">");
}
}
}
}
else if (completionChar == '/') {
template.addTextSegment("/>");
} else if (completionChar == ' ' && template.getSegmentsCount() == 0) {
if (WebEditorOptions.getInstance().isAutomaticallyStartAttribute() &&
(attributes.length > 0 || isTagFromHtml(tag) && !HtmlUtil.isTagWithoutAttributes(tag.getName()))) {
template.addTextSegment(" ");
final MacroCallNode completeAttrExpr = new MacroCallNode(MacroFactory.createMacro("complete"));
template.addVariable("attrComplete", completeAttrExpr, completeAttrExpr, true);
weInsertedSomeCodeThatCouldBeInvalidated = true;
template.addTextSegment("=\"");
template.addEndVariable();
template.addTextSegment("\"");
}
} else if ((completionChar == Lookup.AUTO_INSERT_SELECT_CHAR || completionChar == Lookup.NORMAL_SELECT_CHAR) && WebEditorOptions.getInstance().isAutomaticallyInsertClosingTag() && HtmlUtil.isSingleHtmlTag(tag.getName())) {
template.addTextSegment(tag instanceof HtmlTag ? ">" : "/>");
}
final boolean weInsertedSomeCodeThatCouldBeInvalidated1 = weInsertedSomeCodeThatCouldBeInvalidated;
templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {
public void templateFinished(final Template template, boolean brokenOff) {
final int offset = editor.getCaretModel().getOffset();
if (weInsertedSomeCodeThatCouldBeInvalidated1 &&
offset >= 3 &&
editor.getDocument().getCharsSequence().charAt(offset - 3) == '/') {
new WriteCommandAction.Simple(project) {
protected void run() throws Throwable {
editor.getDocument().replaceString(offset - 2, offset + 1, ">");
}
}.execute();
}
}
public void templateCancelled(final Template template) {
//final int offset = editor.getCaretModel().getOffset();
//if (weInsertedSomeCodeThatCouldBeInvalidated1) {}
}
});
}
private static boolean isTagFromHtml(final XmlTag tag) {
final String ns = tag.getNamespace();
return XmlUtil.XHTML_URI.equals(ns) || XmlUtil.HTML_URI.equals(ns);
}
}
|
do not complete fixed attributes if they are optional
|
xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
|
do not complete fixed attributes if they are optional
|
|
Java
|
apache-2.0
|
09a4a0667238c0e62dcab07b2170a55d19020804
| 0
|
suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui;
import com.intellij.ide.WelcomeWizardUtil;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.ComponentTreeEventDispatcher;
import com.intellij.util.PlatformUtils;
import com.intellij.util.SystemProperties;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.xmlb.Accessor;
import com.intellij.util.xmlb.SerializationFilter;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import java.awt.*;
import static com.intellij.util.ui.UIUtil.isValidFont;
@State(
name = "UISettings",
storages = @Storage("ui.lnf.xml")
)
public class UISettings extends SimpleModificationTracker implements PersistentStateComponent<UISettings> {
/** Not tabbed pane. */
public static final int TABS_NONE = 0;
private static UISettings ourSettings;
public static UISettings getInstance() {
return ourSettings = ServiceManager.getService(UISettings.class);
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@NotNull
public static UISettings getShadowInstance() {
Application application = ApplicationManager.getApplication();
UISettings settings = application == null ? null : getInstance();
return settings == null ? new UISettings().withDefFont() : settings;
}
// These font properties should not be set in the default ctor,
// so that to make the serialization logic judge if a property
// should be stored or shouldn't by the provided filter only.
@Property(filter = FontFilter.class) public String FONT_FACE;
@Property(filter = FontFilter.class) public int FONT_SIZE;
@Property(filter = FontFilter.class) private float FONT_SCALE;
public int RECENT_FILES_LIMIT = 50;
public int CONSOLE_COMMAND_HISTORY_LIMIT = 300;
public boolean OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false;
public int CONSOLE_CYCLE_BUFFER_SIZE_KB = 1024;
public int EDITOR_TAB_LIMIT = 10;
public boolean REUSE_NOT_MODIFIED_TABS = false;
public boolean ANIMATE_WINDOWS = true;
public int ANIMATION_DURATION = 300; // Milliseconds
public boolean SHOW_TOOL_WINDOW_NUMBERS = true;
public boolean HIDE_TOOL_STRIPES = true;
public boolean WIDESCREEN_SUPPORT = false;
public boolean LEFT_HORIZONTAL_SPLIT = false;
public boolean RIGHT_HORIZONTAL_SPLIT = false;
public boolean SHOW_EDITOR_TOOLTIP = true;
public boolean SHOW_MEMORY_INDICATOR = false;
public boolean ALLOW_MERGE_BUTTONS = true;
public boolean SHOW_MAIN_TOOLBAR = false;
public boolean SHOW_STATUS_BAR = true;
public boolean SHOW_NAVIGATION_BAR = true;
public boolean ALWAYS_SHOW_WINDOW_BUTTONS = false;
public boolean CYCLE_SCROLLING = true;
public boolean SCROLL_TAB_LAYOUT_IN_EDITOR = true;
public boolean HIDE_TABS_IF_NEED = true;
public boolean SHOW_CLOSE_BUTTON = true;
public int EDITOR_TAB_PLACEMENT = 1;
public boolean HIDE_KNOWN_EXTENSION_IN_TABS = false;
public boolean SHOW_ICONS_IN_QUICK_NAVIGATION = true;
public boolean CLOSE_NON_MODIFIED_FILES_FIRST = false;
public boolean ACTIVATE_MRU_EDITOR_ON_CLOSE = false;
public boolean ACTIVATE_RIGHT_EDITOR_ON_CLOSE = false;
public AntialiasingType IDE_AA_TYPE = AntialiasingType.SUBPIXEL;
public AntialiasingType EDITOR_AA_TYPE = AntialiasingType.SUBPIXEL;
public ColorBlindness COLOR_BLINDNESS;
public boolean MOVE_MOUSE_ON_DEFAULT_BUTTON = false;
public boolean ENABLE_ALPHA_MODE = false;
public int ALPHA_MODE_DELAY = 1500;
public float ALPHA_MODE_RATIO = 0.5f;
public int MAX_CLIPBOARD_CONTENTS = 5;
public boolean OVERRIDE_NONIDEA_LAF_FONTS = false;
public boolean SHOW_ICONS_IN_MENUS = true;
public boolean DISABLE_MNEMONICS = SystemInfo.isMac; // IDEADEV-33409, should be disabled by default on MacOS
public boolean DISABLE_MNEMONICS_IN_CONTROLS = false;
public boolean USE_SMALL_LABELS_ON_TABS = SystemInfo.isMac;
public int MAX_LOOKUP_WIDTH2 = 500;
public int MAX_LOOKUP_LIST_HEIGHT = 11;
public boolean HIDE_NAVIGATION_ON_FOCUS_LOSS = true;
public boolean DND_WITH_PRESSED_ALT_ONLY = false;
public boolean DEFAULT_AUTOSCROLL_TO_SOURCE = false;
@Transient
public boolean PRESENTATION_MODE = false;
public int PRESENTATION_MODE_FONT_SIZE = 24;
public boolean MARK_MODIFIED_TABS_WITH_ASTERISK = false;
public boolean SHOW_TABS_TOOLTIPS = true;
public boolean SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
public boolean NAVIGATE_TO_PREVIEW = false;
public boolean SORT_BOOKMARKS = false;
private final ComponentTreeEventDispatcher<UISettingsListener> myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener.class);
private final UISettingsState myState = new UISettingsState();
public UISettings() {
tweakPlatformDefaults();
Boolean scrollToSource = WelcomeWizardUtil.getAutoScrollToSource();
if (scrollToSource != null) {
DEFAULT_AUTOSCROLL_TO_SOURCE = scrollToSource;
}
}
@OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY")
public boolean isSortLookupElementsLexicographically() {
return myState.getSortLookupElementsLexicographically();
}
public void setSortLookupElementsLexicographically(boolean value) {
myState.setSortLookupElementsLexicographically(value);
}
@OptionTag("MERGE_EQUAL_STACKTRACES")
public boolean isMergeEqualStackTraces() {
return myState.getMergeEqualStackTraces();
}
public void setMergeEqualStackTraces(boolean value) {
myState.setMergeEqualStackTraces(value);
}
@Override
public long getModificationCount() {
return super.getModificationCount() + myState.getModificationCount();
}
private UISettings withDefFont() {
initDefFont();
return this;
}
private void tweakPlatformDefaults() {
// TODO[anton] consider making all IDEs use the same settings
if (PlatformUtils.isAppCode()) {
SCROLL_TAB_LAYOUT_IN_EDITOR = true;
ACTIVATE_RIGHT_EDITOR_ON_CLOSE = true;
SHOW_ICONS_IN_MENUS = false;
}
}
/**
* @deprecated Please use {@link UISettingsListener#TOPIC}
*/
@Deprecated
public void addUISettingsListener(@NotNull UISettingsListener listener, @NotNull Disposable parentDisposable) {
ApplicationManager.getApplication().getMessageBus().connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener);
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
public void fireUISettingsChanged() {
ColorBlindnessSupport support = ColorBlindnessSupport.get(COLOR_BLINDNESS);
IconLoader.setFilter(support == null ? null : support.getFilter());
if (incAndGetModificationCount() == 1) {
return;
}
if (ourSettings == this) {
// if this is the main UISettings instance push event to bus and to all current components
myTreeDispatcher.getMulticaster().uiSettingsChanged(this);
ApplicationManager.getApplication().getMessageBus().syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this);
}
}
private void initDefFont() {
Pair<String, Integer> fontData = getSystemFontFaceAndSize();
if (FONT_FACE == null) FONT_FACE = fontData.first;
if (FONT_SIZE <= 0) FONT_SIZE = fontData.second;
if (FONT_SCALE <= 0) FONT_SCALE = JBUI.scale(1f);
}
private static Pair<String, Integer> getSystemFontFaceAndSize() {
final Pair<String,Integer> fontData = UIUtil.getSystemFontData();
if (fontData != null) {
return fontData;
}
return Pair.create("Dialog", 12);
}
public static class FontFilter implements SerializationFilter {
@Override
public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) {
UISettings settings = (UISettings)bean;
final Pair<String, Integer> fontData = getSystemFontFaceAndSize();
if ("FONT_FACE".equals(accessor.getName())) {
return !fontData.first.equals(settings.FONT_FACE);
}
// store only in pair
return !(fontData.second.equals(settings.FONT_SIZE) && 1f == settings.FONT_SCALE);
}
}
@Override
public UISettings getState() {
return this;
}
@Override
public void loadState(UISettings object) {
XmlSerializerUtil.copyBean(object, this);
myState.resetModificationCount();
// Check tab placement in editor
if (EDITOR_TAB_PLACEMENT != TABS_NONE &&
EDITOR_TAB_PLACEMENT != SwingConstants.TOP &&
EDITOR_TAB_PLACEMENT != SwingConstants.LEFT &&
EDITOR_TAB_PLACEMENT != SwingConstants.BOTTOM &&
EDITOR_TAB_PLACEMENT != SwingConstants.RIGHT) {
EDITOR_TAB_PLACEMENT = SwingConstants.TOP;
}
// Check that alpha delay and ratio are valid
if (ALPHA_MODE_DELAY < 0) {
ALPHA_MODE_DELAY = 1500;
}
if (ALPHA_MODE_RATIO < 0.0f || ALPHA_MODE_RATIO > 1.0f) {
ALPHA_MODE_RATIO = 0.5f;
}
if (FONT_SCALE <= 0) {
// Reset font to default on switch from IDEA-managed HiDPI to JDK-managed HiDPI. Doesn't affect OSX.
if (UIUtil.isJDKManagedHiDPI() && !SystemInfo.isMac) FONT_SIZE = (int)UIUtil.DEF_SYSTEM_FONT_SIZE;
}
else {
FONT_SIZE = (int)JBUI.scale(FONT_SIZE / FONT_SCALE);
}
FONT_SCALE = JBUI.scale(1f);
initDefFont();
// 1. Sometimes system font cannot display standard ASCII symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
boolean fontIsValid = isValidFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE));
if (!fontIsValid) {
@NonNls final String[] preferredFonts = {"dialog", "Arial", "Tahoma"};
for (String preferredFont : preferredFonts) {
if (isValidFont(new Font(preferredFont, Font.PLAIN, FONT_SIZE))) {
FONT_FACE = preferredFont;
fontIsValid = true;
break;
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if (!fontIsValid) {
String[] fontNames = UIUtil.getValidFontNames(false);
if (fontNames.length > 0) {
FONT_FACE = fontNames[0];
}
}
}
if (MAX_CLIPBOARD_CONTENTS <= 0) {
MAX_CLIPBOARD_CONTENTS = 5;
}
fireUISettingsChanged();
}
public static final boolean FORCE_USE_FRACTIONAL_METRICS =
SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false);
public static void setupFractionalMetrics(final Graphics2D g2d) {
if (FORCE_USE_FRACTIONAL_METRICS) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, {@link #setupComponentAntialiasing(JComponent)} method should be called from
* <code>updateUI()</code> or <code>setUI()</code> method of component.
*/
public static void setupAntialiasing(final Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue());
Application application = ApplicationManager.getApplication();
if (application == null) {
// We cannot use services while Application has not been loaded yet
// So let's apply the default hints.
UIUtil.applyRenderingHints(g);
return;
}
UISettings uiSettings = getInstance();
if (uiSettings != null) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false));
} else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
setupFractionalMetrics(g2d);
}
/**
* @see #setupAntialiasing(Graphics)
*/
public static void setupComponentAntialiasing(JComponent component) {
component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent());
}
public static void setupEditorAntialiasing(JComponent component) {
AntialiasingType aaType = getInstance().EDITOR_AA_TYPE;
if (aaType != null) {
component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaType.getTextInfo());
}
}
}
|
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui;
import com.intellij.ide.WelcomeWizardUtil;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.ComponentTreeEventDispatcher;
import com.intellij.util.PlatformUtils;
import com.intellij.util.SystemProperties;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.xmlb.Accessor;
import com.intellij.util.xmlb.SerializationFilter;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import java.awt.*;
import static com.intellij.util.ui.UIUtil.isValidFont;
@State(
name = "UISettings",
storages = @Storage("ui.lnf.xml")
)
public class UISettings extends SimpleModificationTracker implements PersistentStateComponent<UISettings> {
/** Not tabbed pane. */
public static final int TABS_NONE = 0;
private static UISettings ourSettings;
public static UISettings getInstance() {
return ourSettings = ServiceManager.getService(UISettings.class);
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@NotNull
public static UISettings getShadowInstance() {
Application application = ApplicationManager.getApplication();
UISettings settings = application == null ? null : getInstance();
return settings == null ? new UISettings().withDefFont() : settings;
}
// These font properties should not be set in the default ctor,
// so that to make the serialization logic judge if a property
// should be stored or shouldn't by the provided filter only.
@Property(filter = FontFilter.class) public String FONT_FACE;
@Property(filter = FontFilter.class) public int FONT_SIZE;
@Property(filter = FontFilter.class) private float FONT_SCALE;
public int RECENT_FILES_LIMIT = 50;
public int CONSOLE_COMMAND_HISTORY_LIMIT = 300;
public boolean OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false;
public int CONSOLE_CYCLE_BUFFER_SIZE_KB = 1024;
public int EDITOR_TAB_LIMIT = 10;
public boolean REUSE_NOT_MODIFIED_TABS = false;
public boolean ANIMATE_WINDOWS = true;
public int ANIMATION_DURATION = 300; // Milliseconds
public boolean SHOW_TOOL_WINDOW_NUMBERS = true;
public boolean HIDE_TOOL_STRIPES = true;
public boolean WIDESCREEN_SUPPORT = false;
public boolean LEFT_HORIZONTAL_SPLIT = false;
public boolean RIGHT_HORIZONTAL_SPLIT = false;
public boolean SHOW_EDITOR_TOOLTIP = true;
public boolean SHOW_MEMORY_INDICATOR = false;
public boolean ALLOW_MERGE_BUTTONS = true;
public boolean SHOW_MAIN_TOOLBAR = false;
public boolean SHOW_STATUS_BAR = true;
public boolean SHOW_NAVIGATION_BAR = true;
public boolean ALWAYS_SHOW_WINDOW_BUTTONS = false;
public boolean CYCLE_SCROLLING = true;
public boolean SCROLL_TAB_LAYOUT_IN_EDITOR = true;
public boolean HIDE_TABS_IF_NEED = true;
public boolean SHOW_CLOSE_BUTTON = true;
public int EDITOR_TAB_PLACEMENT = 1;
public boolean HIDE_KNOWN_EXTENSION_IN_TABS = false;
public boolean SHOW_ICONS_IN_QUICK_NAVIGATION = true;
public boolean CLOSE_NON_MODIFIED_FILES_FIRST = false;
public boolean ACTIVATE_MRU_EDITOR_ON_CLOSE = false;
public boolean ACTIVATE_RIGHT_EDITOR_ON_CLOSE = false;
public AntialiasingType IDE_AA_TYPE = AntialiasingType.SUBPIXEL;
public AntialiasingType EDITOR_AA_TYPE = AntialiasingType.SUBPIXEL;
public ColorBlindness COLOR_BLINDNESS;
public boolean MOVE_MOUSE_ON_DEFAULT_BUTTON = false;
public boolean ENABLE_ALPHA_MODE = false;
public int ALPHA_MODE_DELAY = 1500;
public float ALPHA_MODE_RATIO = 0.5f;
public int MAX_CLIPBOARD_CONTENTS = 5;
public boolean OVERRIDE_NONIDEA_LAF_FONTS = false;
public boolean SHOW_ICONS_IN_MENUS = true;
public boolean DISABLE_MNEMONICS = SystemInfo.isMac; // IDEADEV-33409, should be disabled by default on MacOS
public boolean DISABLE_MNEMONICS_IN_CONTROLS = false;
public boolean USE_SMALL_LABELS_ON_TABS = SystemInfo.isMac;
public int MAX_LOOKUP_WIDTH2 = 500;
public int MAX_LOOKUP_LIST_HEIGHT = 11;
public boolean HIDE_NAVIGATION_ON_FOCUS_LOSS = true;
public boolean DND_WITH_PRESSED_ALT_ONLY = false;
public boolean DEFAULT_AUTOSCROLL_TO_SOURCE = false;
@Transient
public boolean PRESENTATION_MODE = false;
public int PRESENTATION_MODE_FONT_SIZE = 24;
public boolean MARK_MODIFIED_TABS_WITH_ASTERISK = false;
public boolean SHOW_TABS_TOOLTIPS = true;
public boolean SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true;
public boolean NAVIGATE_TO_PREVIEW = false;
public boolean SORT_BOOKMARKS = false;
private final ComponentTreeEventDispatcher<UISettingsListener> myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener.class);
private final UISettingsState myState = new UISettingsState();
public UISettings() {
tweakPlatformDefaults();
Boolean scrollToSource = WelcomeWizardUtil.getAutoScrollToSource();
if (scrollToSource != null) {
DEFAULT_AUTOSCROLL_TO_SOURCE = scrollToSource;
}
}
@OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY")
public boolean isSortLookupElementsLexicographically() {
return myState.getSortLookupElementsLexicographically();
}
public void setSortLookupElementsLexicographically(boolean value) {
myState.setSortLookupElementsLexicographically(value);
}
@OptionTag("MERGE_EQUAL_STACKTRACES")
public boolean isMergeEqualStackTraces() {
return myState.getMergeEqualStackTraces();
}
public void setMergeEqualStackTraces(boolean value) {
myState.setMergeEqualStackTraces(value);
}
@Override
public long getModificationCount() {
return super.getModificationCount() + myState.getModificationCount();
}
private UISettings withDefFont() {
initDefFont();
return this;
}
private void tweakPlatformDefaults() {
// TODO[anton] consider making all IDEs use the same settings
if (PlatformUtils.isAppCode()) {
SCROLL_TAB_LAYOUT_IN_EDITOR = true;
ACTIVATE_RIGHT_EDITOR_ON_CLOSE = true;
SHOW_ICONS_IN_MENUS = false;
}
}
/**
* @deprecated Please use {@link UISettingsListener#TOPIC}
*/
@Deprecated
public void addUISettingsListener(@NotNull UISettingsListener listener, @NotNull Disposable parentDisposable) {
ApplicationManager.getApplication().getMessageBus().connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener);
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
public void fireUISettingsChanged() {
ColorBlindnessSupport support = ColorBlindnessSupport.get(COLOR_BLINDNESS);
IconLoader.setFilter(support == null ? null : support.getFilter());
if (incAndGetModificationCount() == 1) {
return;
}
if (ourSettings == this) {
// if this is the main UISettings instance push event to bus and to all current components
myTreeDispatcher.getMulticaster().uiSettingsChanged(this);
ApplicationManager.getApplication().getMessageBus().syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this);
}
}
private void initDefFont() {
Pair<String, Integer> fontData = getSystemFontFaceAndSize();
if (FONT_FACE == null) FONT_FACE = fontData.first;
if (FONT_SIZE <= 0) FONT_SIZE = fontData.second;
if (FONT_SCALE <= 0) FONT_SCALE = JBUI.scale(1f);
}
private static Pair<String, Integer> getSystemFontFaceAndSize() {
final Pair<String,Integer> fontData = UIUtil.getSystemFontData();
if (fontData != null) {
return fontData;
}
return Pair.create("Dialog", 12);
}
public static class FontFilter implements SerializationFilter {
@Override
public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) {
UISettings settings = (UISettings)bean;
final Pair<String, Integer> fontData = getSystemFontFaceAndSize();
if ("FONT_FACE".equals(accessor.getName())) {
return !fontData.first.equals(settings.FONT_FACE);
}
// store only in pair
return !(fontData.second.equals(settings.FONT_SIZE) && 1f == settings.FONT_SCALE);
}
}
@Override
public UISettings getState() {
return this;
}
@Override
public void loadState(UISettings object) {
XmlSerializerUtil.copyBean(object, this);
myState.resetModificationCount();
// Check tab placement in editor
if (EDITOR_TAB_PLACEMENT != TABS_NONE &&
EDITOR_TAB_PLACEMENT != SwingConstants.TOP &&
EDITOR_TAB_PLACEMENT != SwingConstants.LEFT &&
EDITOR_TAB_PLACEMENT != SwingConstants.BOTTOM &&
EDITOR_TAB_PLACEMENT != SwingConstants.RIGHT) {
EDITOR_TAB_PLACEMENT = SwingConstants.TOP;
}
// Check that alpha delay and ratio are valid
if (ALPHA_MODE_DELAY < 0) {
ALPHA_MODE_DELAY = 1500;
}
if (ALPHA_MODE_RATIO < 0.0f || ALPHA_MODE_RATIO > 1.0f) {
ALPHA_MODE_RATIO = 0.5f;
}
if (FONT_SCALE <= 0) {
// Reset font to default on switch from IDEA-managed HiDPI to JDK-managed HiDPI. Doesn't affect OSX.
if (UIUtil.isJDKManagedHiDPI() && !SystemInfo.isMac) FONT_SIZE = (int)UIUtil.DEF_SYSTEM_FONT_SIZE;
}
else {
FONT_SIZE = (int)JBUI.scale(FONT_SIZE / FONT_SCALE);
}
FONT_SCALE = JBUI.scale(1f);
initDefFont();
// 1. Sometimes system font cannot display standard ASCII symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
boolean fontIsValid = isValidFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE));
if (!fontIsValid) {
@NonNls final String[] preferredFonts = {"dialog", "Arial", "Tahoma"};
for (String preferredFont : preferredFonts) {
if (isValidFont(new Font(preferredFont, Font.PLAIN, FONT_SIZE))) {
FONT_FACE = preferredFont;
fontIsValid = true;
break;
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if (!fontIsValid) {
String[] fontNames = UIUtil.getValidFontNames(false);
if (fontNames.length > 0) {
FONT_FACE = fontNames[0];
}
}
}
if (MAX_CLIPBOARD_CONTENTS <= 0) {
MAX_CLIPBOARD_CONTENTS = 5;
}
fireUISettingsChanged();
}
public static final boolean FORCE_USE_FRACTIONAL_METRICS =
SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false);
public static void setupFractionalMetrics(final Graphics2D g2d) {
if (FORCE_USE_FRACTIONAL_METRICS) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, {@link #setupComponentAntialiasing(JComponent)} method should be called from
* <code>updateUI()</code> or <code>setUI()</code> method of component.
*/
public static void setupAntialiasing(final Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue());
Application application = ApplicationManager.getApplication();
if (application == null) {
// We cannot use services while Application has not been loaded yet
// So let's apply the default hints.
UIUtil.applyRenderingHints(g);
return;
}
UISettings uiSettings = getInstance();
if (uiSettings != null) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false));
} else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
setupFractionalMetrics(g2d);
}
/**
* @see #setupComponentAntialiasing(JComponent)
*/
public static void setupComponentAntialiasing(JComponent component) {
component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent());
}
public static void setupEditorAntialiasing(JComponent component) {
AntialiasingType aaType = getInstance().EDITOR_AA_TYPE;
if (aaType != null) {
component.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaType.getTextInfo());
}
}
}
|
fix javadoc
|
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
|
fix javadoc
|
|
Java
|
apache-2.0
|
f1f33a890bc66d9a4fa65685c61cb7da5bb62c33
| 0
|
yanagishima/yanagishima,gradleupdate/yanagishima,gradleupdate/yanagishima,dkazuma/yanagishima,gradleupdate/yanagishima,yanagishima/yanagishima,dkazuma/yanagishima,gradleupdate/yanagishima,dkazuma/yanagishima,dkazuma/yanagishima,yanagishima/yanagishima,yanagishima/yanagishima
|
package yanagishima.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yanagishima.result.PrestoQueryResult;
import yanagishima.service.PrestoService;
@Singleton
public class PrestoServlet extends HttpServlet {
private static Logger LOGGER = LoggerFactory.getLogger(PrestoServlet.class);
private static final long serialVersionUID = 1L;
private final PrestoService prestoService;
@Inject
public PrestoServlet(PrestoService prestoService) {
this.prestoService = prestoService;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Optional<String> queryOptional = Optional.ofNullable(request
.getParameter("query"));
queryOptional.ifPresent(query -> {
HashMap<String, Object> retVal = new HashMap<String, Object>();
if (query.trim().substring(0, 4).toLowerCase().equals("drop")) {
retVal.put("error", "drop operation is not allowed.");
} else {
try {
PrestoQueryResult prestoQueryResult = prestoService
.doQuery(query, 10000);
if (prestoQueryResult.getUpdateType() == null) {// select
retVal.put("headers", prestoQueryResult.getColumns());
retVal.put("results", prestoQueryResult.getRecords());
Optional<String> warningMessageOptinal = Optional
.ofNullable(prestoQueryResult.getWarningMessage());
warningMessageOptinal.ifPresent(warningMessage -> {
retVal.put("warn", warningMessage);
});
}
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
retVal.put("error", e.getMessage());
}
}
try {
writeJSON(response, retVal);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
private void writeJSON(HttpServletResponse resp, Object obj)
throws IOException {
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
OutputStream stream = resp.getOutputStream();
mapper.writeValue(stream, obj);
}
}
|
src/main/java/yanagishima/servlet/PrestoServlet.java
|
package yanagishima.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yanagishima.result.PrestoQueryResult;
import yanagishima.service.PrestoService;
@Singleton
public class PrestoServlet extends HttpServlet {
private static Logger LOGGER = LoggerFactory.getLogger(PrestoServlet.class);
private static final long serialVersionUID = 1L;
private final PrestoService prestoService;
@Inject
public PrestoServlet(PrestoService prestoService) {
this.prestoService = prestoService;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Optional<String> queryOptional = Optional.ofNullable(request
.getParameter("query"));
queryOptional.ifPresent(query -> {
HashMap<String, Object> retVal = new HashMap<String, Object>();
if (query.trim().substring(0, 4).toLowerCase().equals("drop")) {
retVal.put("error", "drop operation is not allowed.");
} else {
try {
PrestoQueryResult prestoQueryResult = prestoService
.doQuery(query, 10000);
if (prestoQueryResult.getUpdateType() == null) {// select
retVal.put("headers", prestoQueryResult.getColumns());
retVal.put("results", prestoQueryResult.getRecords());
Optional<String> warningMessageOptinal = Optional
.ofNullable(prestoQueryResult.getWarningMessage());
warningMessageOptinal.ifPresent(warningMessage -> {
retVal.put("warn", warningMessage);
});
}
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
retVal.put("error", e.getMessage());
}
}
try {
writeJSON(response, retVal);
} catch (IOException e) {
throw new RuntimeException(e);
}
}) ;
}
private void writeJSON(HttpServletResponse resp, Object obj)
throws IOException {
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
OutputStream stream = resp.getOutputStream();
mapper.writeValue(stream, obj);
}
}
|
format
|
src/main/java/yanagishima/servlet/PrestoServlet.java
|
format
|
|
Java
|
apache-2.0
|
d687512b89cc0ff79584a25383b46c7fe864bc10
| 0
|
samthor/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,supersven/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ryano144/intellij-community,apixandru/intellij-community,asedunov/intellij-community,slisson/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,kool79/intellij-community,signed/intellij-community,Distrotech/intellij-community,da1z/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,samthor/intellij-community,consulo/consulo,caot/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,supersven/intellij-community,jagguli/intellij-community,signed/intellij-community,da1z/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,izonder/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,semonte/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,jagguli/intellij-community,da1z/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,caot/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,slisson/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,consulo/consulo,nicolargo/intellij-community,vladmm/intellij-community,samthor/intellij-community,fitermay/intellij-community,allotria/intellij-community,petteyg/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,signed/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,slisson/intellij-community,diorcety/intellij-community,slisson/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,fitermay/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,clumsy/intellij-community,robovm/robovm-studio,amith01994/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,blademainer/intellij-community,ryano144/intellij-community,holmes/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,retomerz/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ibinti/intellij-community,xfournet/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,kdwink/intellij-community,kool79/intellij-community,ryano144/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,supersven/intellij-community,amith01994/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,signed/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ernestp/consulo,SerCeMan/intellij-community,consulo/consulo,pwoodworth/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,caot/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,hurricup/intellij-community,apixandru/intellij-community,semonte/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,samthor/intellij-community,semonte/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,hurricup/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,vladmm/intellij-community,semonte/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,caot/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,semonte/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,slisson/intellij-community,petteyg/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ryano144/intellij-community,caot/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,allotria/intellij-community,ernestp/consulo,alphafoobar/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ernestp/consulo,caot/intellij-community,diorcety/intellij-community,jagguli/intellij-community,fnouama/intellij-community,holmes/intellij-community,petteyg/intellij-community,samthor/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,kool79/intellij-community,da1z/intellij-community,dslomov/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,kool79/intellij-community,jagguli/intellij-community,fitermay/intellij-community,supersven/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,apixandru/intellij-community,slisson/intellij-community,petteyg/intellij-community,allotria/intellij-community,blademainer/intellij-community,retomerz/intellij-community,slisson/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ibinti/intellij-community,amith01994/intellij-community,clumsy/intellij-community,kdwink/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,dslomov/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ernestp/consulo,ahb0327/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,pwoodworth/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,da1z/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,asedunov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,signed/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,caot/intellij-community,xfournet/intellij-community,samthor/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,allotria/intellij-community,asedunov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,apixandru/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,diorcety/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,signed/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,samthor/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,diorcety/intellij-community,petteyg/intellij-community,holmes/intellij-community,asedunov/intellij-community,robovm/robovm-studio,caot/intellij-community,asedunov/intellij-community,FHannes/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,clumsy/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,semonte/intellij-community,kdwink/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fitermay/intellij-community,kdwink/intellij-community,kool79/intellij-community,kool79/intellij-community,adedayo/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,diorcety/intellij-community,consulo/consulo,salguarnieri/intellij-community,FHannes/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,kool79/intellij-community,xfournet/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,vladmm/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,da1z/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,consulo/consulo,MER-GROUP/intellij-community,youdonghai/intellij-community,semonte/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,izonder/intellij-community,Lekanich/intellij-community,holmes/intellij-community,semonte/intellij-community,allotria/intellij-community,izonder/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fnouama/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,hurricup/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,tmpgit/intellij-community,signed/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,izonder/intellij-community,apixandru/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,izonder/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,allotria/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,adedayo/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,caot/intellij-community,signed/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ryano144/intellij-community,semonte/intellij-community,robovm/robovm-studio,izonder/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,holmes/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,samthor/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,izonder/intellij-community,akosyakov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,vladmm/intellij-community,ernestp/consulo,mglukhikh/intellij-community,SerCeMan/intellij-community,caot/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,petteyg/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.impl;
import com.intellij.CommonBundle;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.components.impl.stores.IProjectStore;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.*;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.AppIcon;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
/**
* @author Eugene Belyaev
*/
public class ProjectUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.impl.ProjectUtil");
private ProjectUtil() {
}
public static void updateLastProjectLocation(final String projectFilePath) {
File lastProjectLocation = new File(projectFilePath);
if (lastProjectLocation.isFile()) {
lastProjectLocation = lastProjectLocation.getParentFile(); //for directory based project storages
}
if (lastProjectLocation == null) { // the immediate parent of the ipr file
return;
}
lastProjectLocation = lastProjectLocation.getParentFile(); // the candidate directory to be saved
if (lastProjectLocation == null) {
return;
}
String path = lastProjectLocation.getPath();
try {
path = FileUtil.resolveShortWindowsName(path);
}
catch (IOException e) {
LOG.info(e);
return;
}
GeneralSettings.getInstance().setLastProjectLocation(path.replace(File.separatorChar, '/'));
}
/**
* @param project cannot be null
*/
public static boolean closeAndDispose(@NotNull final Project project) {
return ProjectManagerEx.getInstanceEx().closeAndDispose(project);
}
/**
* @param path project file path
* @param projectToClose currently active project
* @param forceOpenInNewFrame forces opening in new frame
* @return project by path if the path was recognized as IDEA project file or one of the project formats supported by
* installed importers (regardless of opening/import result)
* null otherwise
*/
@Nullable
public static Project openOrImport(@NotNull final String path, final Project projectToClose, boolean forceOpenInNewFrame) {
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
if (virtualFile == null) return null;
ProjectOpenProcessor strong = ProjectOpenProcessor.getStrongImportProvider(virtualFile);
if (strong != null) {
return strong.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame);
}
if (path.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) ||
virtualFile.isDirectory() && virtualFile.findChild(com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR) != null) {
return openProject(path, projectToClose, forceOpenInNewFrame);
}
if (virtualFile.isDirectory()) {
for (VirtualFile child : virtualFile.getChildren()) {
final String childPath = child.getPath();
if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
return openProject(childPath, projectToClose, forceOpenInNewFrame);
}
}
}
ProjectOpenProcessor provider = ProjectOpenProcessor.getImportProvider(virtualFile);
if (provider != null) {
final Project project = provider.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame);
if (project != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (!project.isDisposed()) {
final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);
if (toolWindow != null) {
toolWindow.activate(null);
}
}
}
}, ModalityState.NON_MODAL);
}
return project;
}
return null;
}
@Nullable
public static Project openProject(final String path, Project projectToClose, boolean forceOpenInNewFrame) {
File file = new File(path);
if (!file.exists()) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", path), CommonBundle.getErrorTitle());
return null;
}
if (file.isDirectory() && !new File(file, com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR).exists()) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", new File(file, com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR).getPath()), CommonBundle.getErrorTitle());
return null;
}
Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
for (Project project : openProjects) {
if (isSameProject(path, project)) {
focusProjectWindow(project, false);
return project;
}
}
if (!forceOpenInNewFrame && openProjects.length > 0) {
int exitCode = confirmOpenNewProject(false);
if (exitCode == 0) { // this window option
if (!closeAndDispose(projectToClose != null ? projectToClose : openProjects[openProjects.length - 1])) return null;
}
else if (exitCode != 1) { // not in a new window
return null;
}
}
ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
Project project = null;
try {
project = projectManager.loadAndOpenProject(path);
}
catch (IOException e) {
Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()),
IdeBundle.message("title.cannot.load.project"), Messages.getErrorIcon());
}
catch (JDOMException e) {
LOG.info(e);
Messages.showMessageDialog(IdeBundle.message("error.project.file.is.corrupted"), IdeBundle.message("title.cannot.load.project"),
Messages.getErrorIcon());
}
catch (InvalidDataException e) {
LOG.info(e);
Messages.showMessageDialog(IdeBundle.message("error.project.file.is.corrupted"), IdeBundle.message("title.cannot.load.project"),
Messages.getErrorIcon());
}
return project;
}
/**
* @return 0 - this window
* 1 - new window
* 2 - cancel
* @param isNewProject
*/
public static int confirmOpenNewProject(boolean isNewProject) {
final GeneralSettings settings = GeneralSettings.getInstance();
if (settings.getConfirmOpenNewProject() == GeneralSettings.OPEN_PROJECT_ASK) {
if (isNewProject) {
return Messages.showYesNoDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
IdeBundle.message("title.new.project"),
IdeBundle.message("button.existingframe"),
IdeBundle.message("button.newframe"),
Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption());
}
else {
return Messages.showYesNoCancelDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
IdeBundle.message("title.open.project"),
IdeBundle.message("button.existingframe"), IdeBundle.message("button.newframe"),
CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(),
new ProjectNewWindowDoNotAskOption());
}
}
return settings.getConfirmOpenNewProject();
}
private static boolean isSameProject(String path, Project p) {
final IProjectStore projectStore = ((ProjectEx)p).getStateStore();
String toOpen = FileUtil.toSystemIndependentName(path);
String existing = FileUtil.toSystemIndependentName(projectStore.getProjectFilePath());
final VirtualFile existingBaseDir = projectStore.getProjectBaseDir();
if (existingBaseDir == null) return false; // could be null if not yet initialized
final File openFile = new File(toOpen);
if (openFile.isDirectory()) {
return FileUtil.pathsEqual(toOpen, existingBaseDir.getPath());
}
if (StorageScheme.DIRECTORY_BASED == projectStore.getStorageScheme()) {
// todo: check if IPR is located not under the project base dir
return FileUtil.pathsEqual(FileUtil.toSystemIndependentName(openFile.getParentFile().getPath()), existingBaseDir.getPath());
}
return FileUtil.pathsEqual(toOpen, existing);
}
public static void focusProjectWindow(final Project p, boolean executeIfAppInactive) {
FocusCommand cmd = new FocusCommand() {
@Override
public ActionCallback run() {
JFrame f = WindowManager.getInstance().getFrame(p);
if (f != null) {
f.toFront();
//f.requestFocus();
}
return new ActionCallback.Done();
}
};
if (executeIfAppInactive) {
AppIcon.getInstance().requestFocus((IdeFrame)WindowManager.getInstance().getFrame(p));
cmd.run();
} else {
IdeFocusManager.getInstance(p).requestFocus(cmd, false);
}
}
}
|
platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.impl;
import com.intellij.CommonBundle;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.components.impl.stores.IProjectStore;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.FocusCommand;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.AppIcon;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
/**
* @author Eugene Belyaev
*/
public class ProjectUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.impl.ProjectUtil");
private ProjectUtil() {
}
public static void updateLastProjectLocation(final String projectFilePath) {
File lastProjectLocation = new File(projectFilePath);
if (lastProjectLocation.isFile()) {
lastProjectLocation = lastProjectLocation.getParentFile(); //for directory based project storages
}
if (lastProjectLocation == null) { // the immediate parent of the ipr file
return;
}
lastProjectLocation = lastProjectLocation.getParentFile(); // the candidate directory to be saved
if (lastProjectLocation == null) {
return;
}
String path = lastProjectLocation.getPath();
try {
path = FileUtil.resolveShortWindowsName(path);
}
catch (IOException e) {
LOG.info(e);
return;
}
GeneralSettings.getInstance().setLastProjectLocation(path.replace(File.separatorChar, '/'));
}
/**
* @param project cannot be null
*/
public static boolean closeAndDispose(@NotNull final Project project) {
return ProjectManagerEx.getInstanceEx().closeAndDispose(project);
}
/**
* @param path project file path
* @param projectToClose currently active project
* @param forceOpenInNewFrame forces opening in new frame
* @return project by path if the path was recognized as IDEA project file or one of the project formats supported by
* installed importers (regardless of opening/import result)
* null otherwise
*/
@Nullable
public static Project openOrImport(@NotNull final String path, final Project projectToClose, boolean forceOpenInNewFrame) {
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
if (virtualFile == null) return null;
ProjectOpenProcessor strong = ProjectOpenProcessor.getStrongImportProvider(virtualFile);
if (strong != null) {
return strong.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame);
}
if (path.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) ||
virtualFile.isDirectory() && virtualFile.findChild(com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR) != null) {
return openProject(path, projectToClose, forceOpenInNewFrame);
}
if (virtualFile.isDirectory()) {
for (VirtualFile child : virtualFile.getChildren()) {
final String childPath = child.getPath();
if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
return openProject(childPath, projectToClose, forceOpenInNewFrame);
}
}
}
ProjectOpenProcessor provider = ProjectOpenProcessor.getImportProvider(virtualFile);
if (provider != null) {
return provider.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame);
}
return null;
}
@Nullable
public static Project openProject(final String path, Project projectToClose, boolean forceOpenInNewFrame) {
File file = new File(path);
if (!file.exists()) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", path), CommonBundle.getErrorTitle());
return null;
}
if (file.isDirectory() && !new File(file, com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR).exists()) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", new File(file, com.intellij.openapi.project.ProjectUtil.DIRECTORY_BASED_PROJECT_DIR).getPath()), CommonBundle.getErrorTitle());
return null;
}
Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
for (Project project : openProjects) {
if (isSameProject(path, project)) {
focusProjectWindow(project, false);
return project;
}
}
if (!forceOpenInNewFrame && openProjects.length > 0) {
int exitCode = confirmOpenNewProject(false);
if (exitCode == 0) { // this window option
if (!closeAndDispose(projectToClose != null ? projectToClose : openProjects[openProjects.length - 1])) return null;
}
else if (exitCode != 1) { // not in a new window
return null;
}
}
ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
Project project = null;
try {
project = projectManager.loadAndOpenProject(path);
}
catch (IOException e) {
Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()),
IdeBundle.message("title.cannot.load.project"), Messages.getErrorIcon());
}
catch (JDOMException e) {
LOG.info(e);
Messages.showMessageDialog(IdeBundle.message("error.project.file.is.corrupted"), IdeBundle.message("title.cannot.load.project"),
Messages.getErrorIcon());
}
catch (InvalidDataException e) {
LOG.info(e);
Messages.showMessageDialog(IdeBundle.message("error.project.file.is.corrupted"), IdeBundle.message("title.cannot.load.project"),
Messages.getErrorIcon());
}
return project;
}
/**
* @return 0 - this window
* 1 - new window
* 2 - cancel
* @param isNewProject
*/
public static int confirmOpenNewProject(boolean isNewProject) {
final GeneralSettings settings = GeneralSettings.getInstance();
if (settings.getConfirmOpenNewProject() == GeneralSettings.OPEN_PROJECT_ASK) {
if (isNewProject) {
return Messages.showYesNoDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
IdeBundle.message("title.new.project"),
IdeBundle.message("button.existingframe"),
IdeBundle.message("button.newframe"),
Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption());
}
else {
return Messages.showYesNoCancelDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
IdeBundle.message("title.open.project"),
IdeBundle.message("button.existingframe"), IdeBundle.message("button.newframe"),
CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(),
new ProjectNewWindowDoNotAskOption());
}
}
return settings.getConfirmOpenNewProject();
}
private static boolean isSameProject(String path, Project p) {
final IProjectStore projectStore = ((ProjectEx)p).getStateStore();
String toOpen = FileUtil.toSystemIndependentName(path);
String existing = FileUtil.toSystemIndependentName(projectStore.getProjectFilePath());
final VirtualFile existingBaseDir = projectStore.getProjectBaseDir();
if (existingBaseDir == null) return false; // could be null if not yet initialized
final File openFile = new File(toOpen);
if (openFile.isDirectory()) {
return FileUtil.pathsEqual(toOpen, existingBaseDir.getPath());
}
if (StorageScheme.DIRECTORY_BASED == projectStore.getStorageScheme()) {
// todo: check if IPR is located not under the project base dir
return FileUtil.pathsEqual(FileUtil.toSystemIndependentName(openFile.getParentFile().getPath()), existingBaseDir.getPath());
}
return FileUtil.pathsEqual(toOpen, existing);
}
public static void focusProjectWindow(final Project p, boolean executeIfAppInactive) {
FocusCommand cmd = new FocusCommand() {
@Override
public ActionCallback run() {
JFrame f = WindowManager.getInstance().getFrame(p);
if (f != null) {
f.toFront();
//f.requestFocus();
}
return new ActionCallback.Done();
}
};
if (executeIfAppInactive) {
AppIcon.getInstance().requestFocus((IdeFrame)WindowManager.getInstance().getFrame(p));
cmd.run();
} else {
IdeFocusManager.getInstance(p).requestFocus(cmd, false);
}
}
}
|
AS-303 fxp import: when importing via file/open project, open the project view by default
|
platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java
|
AS-303 fxp import: when importing via file/open project, open the project view by default
|
|
Java
|
apache-2.0
|
error: pathspec 'FinallyDemo.java' did not match any file(s) known to git
|
38a6121d18dccd3d0f19b4cf449320721e4690b6
| 1
|
wolvesled/JavaBeginnerStudy
|
// Use finally.
class UseFinally {
static void genException(int what) {
int t;
int nums[] = new int[2];
System.out.println("Receiving " + what);
try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return;
}
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
return; // return from catch
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
finally {
System.out.println("Leaving try.");
}
}
}
class FinallyDemo {
public static void main(String args[]) {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
System.out.println();
}
}
}
|
FinallyDemo.java
|
Use finally
http://ideone.com/hEgJDB
|
FinallyDemo.java
|
Use finally
|
|
Java
|
apache-2.0
|
error: pathspec 'Java/Subsets.java' did not match any file(s) known to git
|
e29b80c8679ea8f7a6a7e2d09ff7d696b63d6b02
| 1
|
SuperMardle/LeetCode_Solution
|
/** Given a set of distinct integers, nums, return all possible subsets.
*
* Note:
* Elements in a subset must be in non-descending order.
* The solution set must not contain duplicate subsets.
* For example,
* If nums = [1,2,3], a solution is:
*
* [
* [3],
* [1],
* [2],
* [1,2,3],
* [1,3],
* [2,3],
* [1,2],
* []
* ]
*
* Author: matao
* 动态规划
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Subsets {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0)
return result;
Arrays.sort(nums);
List<Integer> list = new ArrayList<Integer>();
subsetsHelper(result, list, nums, 0);
return result;
}
public static void subsetsHelper(List<List<Integer>> result, List<Integer> list, int[] nums, int pos) {
result.add(new ArrayList<Integer>(list));
for(int i = pos; i < nums.length; i++) {
list.add(nums[i]);
subsetsHelper(result, list, nums, i+1);
list.remove(list.size()-1);
}
}
public static void main(String[] args) {
int[] nums = {1, 2};
List<List<Integer>> lists = subsets(nums);
for (List<Integer> arrayList : lists) {
for (Integer integer : arrayList) {
System.out.print(integer.toString() + " ");
}
System.out.println();
}
}
}
|
Java/Subsets.java
|
add subsets solution
|
Java/Subsets.java
|
add subsets solution
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/PathFinder/resources/Lead.java' did not match any file(s) known to git
|
50c1d9a7abc9e8e8a66605cc5c6d177d6a516b7e
| 1
|
emoseman/pathfinder
|
package PathFinder.resources;
import PathFinder.model.BaseResource;
/**
* Lithium
*
* @author Evan Moseman (evan.moseman@corp.aol.com)
* @version 1.0
* @since 4/20/17
*/
public class Lead
extends BaseResource {
public Lead() {
super("Lead", "A soft black metal. ", 20F, new byte[0]);
}
}
|
src/main/java/PathFinder/resources/Lead.java
|
Lead.java
|
src/main/java/PathFinder/resources/Lead.java
|
Lead.java
|
|
Java
|
apache-2.0
|
error: pathspec 'src/de/mrapp/android/adapter/ListAdapter.java' did not match any file(s) known to git
|
4b2a88b9d00639b2444d5fc6c08d380adb8fed77
| 1
|
michael-rapp/AndroidAdapters
|
/*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package de.mrapp.android.adapter;
/**
* Defines the interface, an adapter, whose underlying data is managed as a list
* of arbitrary items, must implement. Such an adapter is meant to provide the
* underlying data for visualization using a {@link ListView} widget.
*
* @param <DataType>
* The type of the adapter's underlying data
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public interface ListAdapter<DataType> extends Adapter<DataType> {
@Override
ListAdapter<DataType> clone() throws CloneNotSupportedException;
}
|
src/de/mrapp/android/adapter/ListAdapter.java
|
Added the interface ListAdapter.
|
src/de/mrapp/android/adapter/ListAdapter.java
|
Added the interface ListAdapter.
|
|
Java
|
apache-2.0
|
error: pathspec 'AdventOfCode/2019/day18/DoorLockedException.java' did not match any file(s) known to git
|
afb4071a6f86bbf117ff14f0073d46de85dc1899
| 1
|
nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/wfswarm-example-arjuna-old,nmcl/scratch,nmcl/scratch
|
public class DoorLockedException extends Exception
{
public DoorLockedException ()
{
}
public DoorLockedException (String message)
{
super(message);
}
}
|
AdventOfCode/2019/day18/DoorLockedException.java
|
Create DoorLockedException.java
|
AdventOfCode/2019/day18/DoorLockedException.java
|
Create DoorLockedException.java
|
|
Java
|
apache-2.0
|
error: pathspec 'tests/org/jasig/portal/utils/RequiresJDK15Test.java' did not match any file(s) known to git
|
e11d81497a0b5eee92b38193754364ea5038553f
| 1
|
EsupPortail/esup-uportal,stalele/uPortal,cousquer/uPortal,vertein/uPortal,pspaude/uPortal,timlevett/uPortal,Jasig/SSP-Platform,EsupPortail/esup-uportal,jameswennmacher/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,jhelmer-unicon/uPortal,EdiaEducationTechnology/uPortal,ASU-Capstone/uPortal-Forked,jonathanmtran/uPortal,kole9273/uPortal,cousquer/uPortal,Jasig/uPortal-start,apetro/uPortal,pspaude/uPortal,jonathanmtran/uPortal,timlevett/uPortal,jonathanmtran/uPortal,drewwills/uPortal,Jasig/uPortal,stalele/uPortal,ASU-Capstone/uPortal-Forked,timlevett/uPortal,doodelicious/uPortal,kole9273/uPortal,jhelmer-unicon/uPortal,andrewstuart/uPortal,EsupPortail/esup-uportal,mgillian/uPortal,GIP-RECIA/esup-uportal,joansmith/uPortal,chasegawa/uPortal,GIP-RECIA/esco-portail,cousquer/uPortal,joansmith/uPortal,drewwills/uPortal,jhelmer-unicon/uPortal,joansmith/uPortal,stalele/uPortal,vertein/uPortal,chasegawa/uPortal,apetro/uPortal,andrewstuart/uPortal,jl1955/uPortal5,groybal/uPortal,Jasig/SSP-Platform,doodelicious/uPortal,doodelicious/uPortal,bjagg/uPortal,vbonamy/esup-uportal,chasegawa/uPortal,Jasig/SSP-Platform,Mines-Albi/esup-uportal,GIP-RECIA/esup-uportal,jhelmer-unicon/uPortal,Mines-Albi/esup-uportal,EdiaEducationTechnology/uPortal,groybal/uPortal,bjagg/uPortal,ASU-Capstone/uPortal-Forked,GIP-RECIA/esco-portail,pspaude/uPortal,EsupPortail/esup-uportal,Mines-Albi/esup-uportal,phillips1021/uPortal,GIP-RECIA/esup-uportal,kole9273/uPortal,joansmith/uPortal,pspaude/uPortal,vertein/uPortal,GIP-RECIA/esup-uportal,andrewstuart/uPortal,Jasig/SSP-Platform,Mines-Albi/esup-uportal,apetro/uPortal,drewwills/uPortal,jl1955/uPortal5,vbonamy/esup-uportal,jl1955/uPortal5,MichaelVose2/uPortal,mgillian/uPortal,vertein/uPortal,jl1955/uPortal5,phillips1021/uPortal,EsupPortail/esup-uportal,ChristianMurphy/uPortal,doodelicious/uPortal,kole9273/uPortal,phillips1021/uPortal,Jasig/uPortal-start,chasegawa/uPortal,jameswennmacher/uPortal,jl1955/uPortal5,jameswennmacher/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal-Forked,vbonamy/esup-uportal,Jasig/uPortal,kole9273/uPortal,andrewstuart/uPortal,apetro/uPortal,Mines-Albi/esup-uportal,MichaelVose2/uPortal,vbonamy/esup-uportal,ASU-Capstone/uPortal,drewwills/uPortal,GIP-RECIA/esup-uportal,ASU-Capstone/uPortal,jameswennmacher/uPortal,groybal/uPortal,ASU-Capstone/uPortal,doodelicious/uPortal,GIP-RECIA/esco-portail,ChristianMurphy/uPortal,bjagg/uPortal,apetro/uPortal,stalele/uPortal,joansmith/uPortal,MichaelVose2/uPortal,andrewstuart/uPortal,phillips1021/uPortal,ASU-Capstone/uPortal-Forked,ASU-Capstone/uPortal,EdiaEducationTechnology/uPortal,EdiaEducationTechnology/uPortal,chasegawa/uPortal,Jasig/SSP-Platform,jhelmer-unicon/uPortal,ChristianMurphy/uPortal,groybal/uPortal,groybal/uPortal,stalele/uPortal,MichaelVose2/uPortal,timlevett/uPortal,ASU-Capstone/uPortal,MichaelVose2/uPortal,mgillian/uPortal,Jasig/uPortal
|
package org.jasig.portal.utils;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
/**
* uPortal 2.6 requires JDK 1.5 or later. This JUnit test case requires
* JDK 1.5 and later and so documents in code this requirement.
* @author apetro@unicon.net
*/
public class RequiresJDK15Test extends TestCase {
public void testRequiresJdk15() {
List<String> list = new ArrayList<String>();
}
}
|
tests/org/jasig/portal/utils/RequiresJDK15Test.java
|
UP-1592 adding testcase requiring JDK 1.5 to explicitly document in code this requirement of uPortal 2.6.
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@11361 f5dbab47-78f9-eb45-b975-e544023573eb
|
tests/org/jasig/portal/utils/RequiresJDK15Test.java
|
UP-1592 adding testcase requiring JDK 1.5 to explicitly document in code this requirement of uPortal 2.6.
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/ru/stqa/selenium/project/ProductPage.java' did not match any file(s) known to git
|
bea24081444af269473e4b254615cf03eed762f1
| 1
|
OlgaPushilina/selenium
|
package ru.stqa.selenium.project;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import static org.junit.Assert.assertEquals;
public class ProductPage extends TestBase {
@Test
public void testProductPage() {
WebElement product = findProduct();
String productName = product.findElement(By.cssSelector("div.name")).getText();
String regularPrice = findRegularPrice(product).getText();
String campaignPrice = findCampaignPrice(product).getText();
product.click();
String innerProductName = driver.findElement(By.cssSelector("h1.title")).getText();
WebElement innerRegularPrice = driver.findElement(By.cssSelector("s.regular-price"));
WebElement innerCampaignPrice = driver.findElement(By.cssSelector("strong.campaign-price"));
assertEquals(productName, innerProductName);
assertEquals(regularPrice, innerRegularPrice.getText());
assertEquals(campaignPrice, innerCampaignPrice.getText());
}
@Test
public void testMainPageStyle() {
WebElement product = findProduct();
String regPriceColor = findRegularPrice(product).getCssValue("color");
String regPriceTextDecor = findRegularPrice(product).getCssValue("text-decoration");
String regPriceFont = findRegularPrice(product).getCssValue("font-size");
assertEquals(regPriceColor, "rgba(119, 119, 119, 1)");
assertEquals(regPriceTextDecor, "line-through");
assertEquals(regPriceFont, "14.4px");
String campPriceColor = findCampaignPrice(product).getCssValue("color");
String campPriceFontWeight = findCampaignPrice(product).getCssValue("font-weight");
String campPriceFont = findCampaignPrice(product).getCssValue("font-size");
assertEquals(campPriceColor, "rgba(204, 0, 0, 1)");
assertEquals(campPriceFontWeight, "bold");
assertEquals(campPriceFont, "18px");
}
@Test
public void testProductPageStyle() {
findProduct().click();
WebElement regularPrice = driver.findElement(By.cssSelector("s.regular-price"));
String regPriceColor = regularPrice.getCssValue("color");
String regPriceTextDecor = regularPrice.getCssValue("text-decoration");
String regPriceFont = regularPrice.getCssValue("font-size");
assertEquals(regPriceColor, "rgba(102, 102, 102, 1)");
assertEquals(regPriceTextDecor, "line-through");
assertEquals(regPriceFont, "16px");
WebElement campaignPrice = driver.findElement(By.cssSelector("strong.campaign-price"));
String campPriceColor = campaignPrice.getCssValue("color");
String campPriceFontWeight = campaignPrice.getCssValue("font-weight");
String campPriceFont = campaignPrice.getCssValue("font-size");
assertEquals(campPriceColor, "rgba(204, 0, 0, 1)");
assertEquals(campPriceFontWeight, "bold");
assertEquals(campPriceFont, "22px");
}
private WebElement findProduct() {
driver.get(properties.getProperty("userUrl"));
return driver.findElement(By.cssSelector("#box-campaigns a[class=link]"));
}
private WebElement findRegularPrice(WebElement product) {
return product.findElement(By.cssSelector("s.regular-price"));
}
private WebElement findCampaignPrice(WebElement product) {
return product.findElement(By.cssSelector("strong.campaign-price"));
}
}
|
src/test/java/ru/stqa/selenium/project/ProductPage.java
|
Задание №10 (Проверка страницы товара)
|
src/test/java/ru/stqa/selenium/project/ProductPage.java
|
Задание №10 (Проверка страницы товара)
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/org/jboss/netty/bootstrap/BootstrapTest.java' did not match any file(s) known to git
|
82f4d193b11de75a30512e34ec00a7e63b55d7d1
| 1
|
brennangaunce/netty,chinayin/netty,luyiisme/netty,exinguu/netty,lznhust/netty,dongjiaqiang/netty,lugt/netty,liuciuse/netty,nadeeshaan/netty,zer0se7en/netty,louxiu/netty,WangJunTYTL/netty,jongyeol/netty,moyiguket/netty,AchinthaReemal/netty,doom369/netty,NiteshKant/netty,fengshao0907/netty,drowning/netty,sameira/netty,altihou/netty,nat2013/netty,yrcourage/netty,maliqq/netty,blademainer/netty,maliqq/netty,zzcclp/netty,AchinthaReemal/netty,yonglehou/netty-1,blademainer/netty,DolphinZhao/netty,doom369/netty,Spikhalskiy/netty,shenguoquan/netty,smayoorans/netty,mcanthony/netty,kyle-liu/netty4study,NiteshKant/netty,lznhust/netty,huuthang1993/netty,fenik17/netty,chinayin/netty,huuthang1993/netty,tbrooks8/netty,andsel/netty,artgon/netty,purplefox/netty-4.0.2.8-hacked,lznhust/netty,moyiguket/netty,lukw00/netty,moyiguket/netty,ngocdaothanh/netty,BrunoColin/netty,mubarak/netty,shism/netty,Mounika-Chirukuri/netty,zhoffice/netty,junjiemars/netty,Kalvar/netty,serioussam/netty,satishsaley/netty,smayoorans/netty,aperepel/netty,kvr000/netty,lugt/netty,clebertsuconic/netty,shuangqiuan/netty,jovezhougang/netty,SinaTadayon/netty,JungMinu/netty,qingsong-xu/netty,netty/netty,danbev/netty,luyiisme/netty,satishsaley/netty,danbev/netty,skyao/netty,f7753/netty,joansmith/netty,djchen/netty,castomer/netty,gerdriesselmann/netty,exinguu/netty,mx657649013/netty,fantayeneh/netty,nat2013/netty,bob329/netty,bigheary/netty,wuyinxian124/netty,johnou/netty,brennangaunce/netty,shenguoquan/netty,carlbai/netty,slandelle/netty,ejona86/netty,orika/netty,sja/netty,danny200309/netty,niuxinghua/netty,joansmith/netty,NiteshKant/netty,jenskordowski/netty,chinayin/netty,sunbeansoft/netty,qingsong-xu/netty,duqiao/netty,AnselQiao/netty,DavidAlphaFox/netty,sameira/netty,Spikhalskiy/netty,develar/netty,louiscryan/netty,Apache9/netty,yonglehou/netty-1,mikkokar/netty,nayato/netty,tbrooks8/netty,firebase/netty,jovezhougang/netty,shuangqiuan/netty,sameira/netty,WangJunTYTL/netty,unei66/netty,lightsocks/netty,buchgr/netty,altihou/netty,shenguoquan/netty,balaprasanna/netty,LuminateWireless/netty,JungMinu/netty,junjiemars/netty,ninja-/netty,sammychen105/netty,seetharamireddy540/netty,mubarak/netty,LuminateWireless/netty,codevelop/netty,luyiisme/netty,artgon/netty,kvr000/netty,blucas/netty,niuxinghua/netty,hepin1989/netty,timboudreau/netty,qingsong-xu/netty,ichaki5748/netty,fantayeneh/netty,codevelop/netty,ijuma/netty,djchen/netty,mcobrien/netty,kvr000/netty,ijuma/netty,zxhfirefox/netty,xiongzheng/netty,afds/netty,zhujingling/netty,imangry/netty-zh,windie/netty,youprofit/netty,eonezhang/netty,clebertsuconic/netty,afredlyj/learn-netty,gigold/netty,gerdriesselmann/netty,louiscryan/netty,doom369/netty,maliqq/netty,WangJunTYTL/netty,phlizik/netty,huanyi0723/netty,ngocdaothanh/netty,mosoft521/netty,mcanthony/netty,shelsonjava/netty,ejona86/netty,shism/netty,f7753/netty,castomer/netty,daschl/netty,lznhust/netty,lightsocks/netty,seetharamireddy540/netty,mway08/netty,Kalvar/netty,altihou/netty,woshilaiceshide/netty,danny200309/netty,johnou/netty,xiongzheng/netty,ijuma/netty,seetharamireddy540/netty,serioussam/netty,mosoft521/netty,kvr000/netty,ajaysarda/netty,olupotd/netty,clebertsuconic/netty,jovezhougang/netty,rovarga/netty,tbrooks8/netty,mx657649013/netty,lukehutch/netty,drowning/netty,liyang1025/netty,chanakaudaya/netty,afredlyj/learn-netty,afredlyj/learn-netty,chanakaudaya/netty,maliqq/netty,chanakaudaya/netty,phlizik/netty,ichaki5748/netty,sameira/netty,phlizik/netty,exinguu/netty,mcobrien/netty,ninja-/netty,pengzj/netty,sverkera/netty,carlbai/netty,shism/netty,wangyikai/netty,normanmaurer/netty,kiril-me/netty,imangry/netty-zh,ioanbsu/netty,Alwayswithme/netty,blademainer/netty,develar/netty,zzcclp/netty,mosoft521/netty,gigold/netty,zzcclp/netty,zer0se7en/netty,silvaran/netty,sverkera/netty,zhujingling/netty,ajaysarda/netty,xingguang2013/netty,bigheary/netty,lugt/netty,chrisprobst/netty,xiexingguang/netty,Kalvar/netty,KatsuraKKKK/netty,liuciuse/netty,daschl/netty,mway08/netty,mx657649013/netty,SinaTadayon/netty,DavidAlphaFox/netty,nat2013/netty,imangry/netty-zh,timboudreau/netty,unei66/netty,CliffYuan/netty,orika/netty,Techcable/netty,serioussam/netty,xiongzheng/netty,netty/netty,BrunoColin/netty,mcobrien/netty,ajaysarda/netty,danbev/netty,joansmith/netty,eincs/netty,golovnin/netty,Kingson4Wu/netty,s-gheldd/netty,clebertsuconic/netty,bob329/netty,f7753/netty,Kingson4Wu/netty,exinguu/netty,pengzj/netty,KeyNexus/netty,hgl888/netty,wuxiaowei907/netty,nkhuyu/netty,nadeeshaan/netty,f7753/netty,sunbeansoft/netty,zer0se7en/netty,unei66/netty,zxhfirefox/netty,chanakaudaya/netty,bigheary/netty,AchinthaReemal/netty,s-gheldd/netty,wangyikai/netty,balaprasanna/netty,satishsaley/netty,hepin1989/netty,junjiemars/netty,ioanbsu/netty,ngocdaothanh/netty,bob329/netty,sunbeansoft/netty,zxhfirefox/netty,nmittler/netty,ioanbsu/netty,niuxinghua/netty,JungMinu/netty,DavidAlphaFox/netty,jenskordowski/netty,KatsuraKKKK/netty,purplefox/netty-4.0.2.8-hacked,maliqq/netty,cnoldtree/netty,shenguoquan/netty,fengjiachun/netty,yawkat/netty,x1957/netty,lightsocks/netty,Techcable/netty,alkemist/netty,drowning/netty,zhujingling/netty,timboudreau/netty,mikkokar/netty,Apache9/netty,jchambers/netty,Squarespace/netty,kvr000/netty,danbev/netty,fengshao0907/netty,liuciuse/netty,andsel/netty,mosoft521/netty,kjniemi/netty,artgon/netty,CodingFabian/netty,golovnin/netty,blucas/netty,x1957/netty,andsel/netty,ninja-/netty,jdivy/netty,carl-mastrangelo/netty,yonglehou/netty-1,wuxiaowei907/netty,Squarespace/netty,ijuma/netty,Alwayswithme/netty,mikkokar/netty,seetharamireddy540/netty,youprofit/netty,alkemist/netty,castomer/netty,codevelop/netty,KatsuraKKKK/netty,liuciuse/netty,smayoorans/netty,bryce-anderson/netty,fenik17/netty,eonezhang/netty,yrcourage/netty,lukw00/netty,IBYoung/netty,wuyinxian124/netty,blucas/netty,woshilaiceshide/netty,Spikhalskiy/netty,normanmaurer/netty,balaprasanna/netty,menacher/netty,x1957/netty,louxiu/netty,chrisprobst/netty,daschl/netty,sunbeansoft/netty,xiongzheng/netty,slandelle/netty,louxiu/netty,eincs/netty,lznhust/netty,djchen/netty,zhujingling/netty,blademainer/netty,netty/netty,ioanbsu/netty,cnoldtree/netty,idelpivnitskiy/netty,johnou/netty,bryce-anderson/netty,carlbai/netty,SinaTadayon/netty,brennangaunce/netty,ngocdaothanh/netty,fengjiachun/netty,bryce-anderson/netty,dongjiaqiang/netty,MediumOne/netty,ifesdjeen/netty,drowning/netty,hyangtack/netty,zhoffice/netty,satishsaley/netty,jdivy/netty,lukw00/netty,DolphinZhao/netty,fantayeneh/netty,liuciuse/netty,firebase/netty,normanmaurer/netty,youprofit/netty,serioussam/netty,louiscryan/netty,ejona86/netty,xiexingguang/netty,wangyikai/netty,alkemist/netty,tbrooks8/netty,xiexingguang/netty,Kalvar/netty,orika/netty,jchambers/netty,Kingson4Wu/netty,rovarga/netty,yrcourage/netty,fenik17/netty,chrisprobst/netty,Techcable/netty,jchambers/netty,ifesdjeen/netty,kyle-liu/netty4study,nayato/netty,hgl888/netty,gigold/netty,nkhuyu/netty,pengzj/netty,jongyeol/netty,louiscryan/netty,xingguang2013/netty,castomer/netty,hyangtack/netty,zhoffice/netty,blucas/netty,slandelle/netty,phlizik/netty,AchinthaReemal/netty,shism/netty,rovarga/netty,jdivy/netty,shenguoquan/netty,WangJunTYTL/netty,duqiao/netty,yipen9/netty,huanyi0723/netty,windie/netty,sunbeansoft/netty,gerdriesselmann/netty,blademainer/netty,yrcourage/netty,danny200309/netty,carl-mastrangelo/netty,unei66/netty,mway08/netty,skyao/netty,ichaki5748/netty,SinaTadayon/netty,fantayeneh/netty,windie/netty,duqiao/netty,jongyeol/netty,caoyanwei/netty,fantayeneh/netty,liyang1025/netty,huanyi0723/netty,purplefox/netty-4.0.2.8-hacked,kjniemi/netty,jongyeol/netty,afds/netty,nayato/netty,olupotd/netty,MediumOne/netty,ichaki5748/netty,andsel/netty,sja/netty,lightsocks/netty,MediumOne/netty,timboudreau/netty,wuxiaowei907/netty,zzcclp/netty,shelsonjava/netty,nayato/netty,slandelle/netty,djchen/netty,codevelop/netty,lukehutch/netty,s-gheldd/netty,idelpivnitskiy/netty,eincs/netty,DolphinZhao/netty,pengzj/netty,KatsuraKKKK/netty,imangry/netty-zh,silvaran/netty,serioussam/netty,hgl888/netty,CodingFabian/netty,huuthang1993/netty,CodingFabian/netty,tempbottle/netty,blucas/netty,wuyinxian124/netty,nkhuyu/netty,tempbottle/netty,ngocdaothanh/netty,shuangqiuan/netty,zzcclp/netty,yonglehou/netty-1,nadeeshaan/netty,chrisprobst/netty,junjiemars/netty,IBYoung/netty,yawkat/netty,hyangtack/netty,zhujingling/netty,wuxiaowei907/netty,shism/netty,AnselQiao/netty,imangry/netty-zh,castomer/netty,skyao/netty,netty/netty,golovnin/netty,AnselQiao/netty,s-gheldd/netty,jdivy/netty,eonezhang/netty,jdivy/netty,luyiisme/netty,afds/netty,eonezhang/netty,fenik17/netty,tempbottle/netty,louxiu/netty,youprofit/netty,s-gheldd/netty,zhoffice/netty,junjiemars/netty,NiteshKant/netty,yrcourage/netty,jroper/netty,eonezhang/netty,tempbottle/netty,LuminateWireless/netty,unei66/netty,zhoffice/netty,silvaran/netty,LuminateWireless/netty,johnou/netty,Apache9/netty,chinayin/netty,woshilaiceshide/netty,CliffYuan/netty,duqiao/netty,artgon/netty,danny200309/netty,xiexingguang/netty,purplefox/netty-4.0.2.8-hacked,cnoldtree/netty,ninja-/netty,kjniemi/netty,ioanbsu/netty,moyiguket/netty,hgl888/netty,orika/netty,AnselQiao/netty,yawkat/netty,djchen/netty,buchgr/netty,IBYoung/netty,golovnin/netty,gerdriesselmann/netty,mx657649013/netty,smayoorans/netty,nkhuyu/netty,idelpivnitskiy/netty,lukehutch/netty,sammychen105/netty,Techcable/netty,Mounika-Chirukuri/netty,gigold/netty,mway08/netty,qingsong-xu/netty,satishsaley/netty,rovarga/netty,zer0se7en/netty,eincs/netty,wangyikai/netty,zxhfirefox/netty,x1957/netty,windie/netty,ichaki5748/netty,yawkat/netty,hgl888/netty,DavidAlphaFox/netty,NiteshKant/netty,Kingson4Wu/netty,BrunoColin/netty,lukehutch/netty,bob329/netty,xingguang2013/netty,huanyi0723/netty,nadeeshaan/netty,Scottmitch/netty,Alwayswithme/netty,woshilaiceshide/netty,Alwayswithme/netty,Scottmitch/netty,orika/netty,sverkera/netty,shelsonjava/netty,gerdriesselmann/netty,MediumOne/netty,MediumOne/netty,yipen9/netty,ninja-/netty,yonglehou/netty-1,hepin1989/netty,mikkokar/netty,danny200309/netty,normanmaurer/netty,Scottmitch/netty,johnou/netty,nadeeshaan/netty,DolphinZhao/netty,xingguang2013/netty,silvaran/netty,jenskordowski/netty,IBYoung/netty,caoyanwei/netty,KatsuraKKKK/netty,jenskordowski/netty,bigheary/netty,doom369/netty,carlbai/netty,shelsonjava/netty,seetharamireddy540/netty,Spikhalskiy/netty,lightsocks/netty,bryce-anderson/netty,duqiao/netty,niuxinghua/netty,ijuma/netty,olupotd/netty,windie/netty,mcobrien/netty,shelsonjava/netty,Mounika-Chirukuri/netty,huuthang1993/netty,fengjiachun/netty,ajaysarda/netty,f7753/netty,Techcable/netty,Squarespace/netty,tempbottle/netty,netty/netty,skyao/netty,lugt/netty,yipen9/netty,sameira/netty,jchambers/netty,cnoldtree/netty,clebertsuconic/netty,sja/netty,luyiisme/netty,Mounika-Chirukuri/netty,brennangaunce/netty,mcanthony/netty,mcobrien/netty,niuxinghua/netty,kiril-me/netty,golovnin/netty,ajaysarda/netty,silvaran/netty,alkemist/netty,jovezhougang/netty,Scottmitch/netty,wangyikai/netty,sverkera/netty,mcanthony/netty,Squarespace/netty,yipen9/netty,mway08/netty,eincs/netty,gigold/netty,timboudreau/netty,huuthang1993/netty,kiril-me/netty,doom369/netty,dongjiaqiang/netty,firebase/netty,AnselQiao/netty,woshilaiceshide/netty,olupotd/netty,brennangaunce/netty,nkhuyu/netty,afds/netty,afds/netty,chanakaudaya/netty,lugt/netty,nmittler/netty,carl-mastrangelo/netty,Squarespace/netty,sja/netty,liyang1025/netty,ejona86/netty,caoyanwei/netty,CodingFabian/netty,hepin1989/netty,kjniemi/netty,chrisprobst/netty,liyang1025/netty,alkemist/netty,bigheary/netty,Apache9/netty,huanyi0723/netty,joansmith/netty,buchgr/netty,Scottmitch/netty,youprofit/netty,sammychen105/netty,x1957/netty,kiril-me/netty,artgon/netty,WangJunTYTL/netty,mubarak/netty,balaprasanna/netty,CodingFabian/netty,shuangqiuan/netty,fengshao0907/netty,altihou/netty,Mounika-Chirukuri/netty,zer0se7en/netty,Kingson4Wu/netty,carlbai/netty,firebase/netty,AchinthaReemal/netty,BrunoColin/netty,KeyNexus/netty,jovezhougang/netty,mcanthony/netty,louxiu/netty,ejona86/netty,LuminateWireless/netty,mosoft521/netty,andsel/netty,dongjiaqiang/netty,liyang1025/netty,Apache9/netty,zxhfirefox/netty,caoyanwei/netty,chinayin/netty,fengjiachun/netty,skyao/netty,bob329/netty,mx657649013/netty,dongjiaqiang/netty,BrunoColin/netty,DolphinZhao/netty,xiexingguang/netty,hyangtack/netty,lukw00/netty,tbrooks8/netty,xiongzheng/netty,mikkokar/netty,olupotd/netty,fengjiachun/netty,balaprasanna/netty,xingguang2013/netty,exinguu/netty,SinaTadayon/netty,sja/netty,Kalvar/netty,JungMinu/netty,menacher/netty,idelpivnitskiy/netty,mubarak/netty,fenik17/netty,normanmaurer/netty,Spikhalskiy/netty,carl-mastrangelo/netty,qingsong-xu/netty,IBYoung/netty,bryce-anderson/netty,wuxiaowei907/netty,jongyeol/netty,caoyanwei/netty,joansmith/netty,carl-mastrangelo/netty,nayato/netty,jchambers/netty,yawkat/netty,kjniemi/netty,smayoorans/netty,Alwayswithme/netty,cnoldtree/netty,kiril-me/netty,altihou/netty,louiscryan/netty,lukehutch/netty,nmittler/netty,moyiguket/netty,wuyinxian124/netty,danbev/netty,sverkera/netty,buchgr/netty,mubarak/netty,idelpivnitskiy/netty,jenskordowski/netty,lukw00/netty,shuangqiuan/netty
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.netty.bootstrap;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Map.Entry;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.junit.Test;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
*
* @version $Rev$, $Date$
*
*/
public class BootstrapTest {
@Test(expected = IllegalStateException.class)
public void shouldNotReturnNullFactory() {
new Bootstrap().getFactory();
}
@Test(expected = IllegalStateException.class)
public void shouldNotAllowInitialFactoryToChange() {
new Bootstrap(createMock(ChannelFactory.class)).setFactory(null);
}
@Test
public void shouldNotAllowFactoryToChangeMoreThanOnce() {
Bootstrap b = new Bootstrap();
b.setFactory(createMock(ChannelFactory.class));
try {
b.setFactory(createMock(ChannelFactory.class));
fail();
} catch (IllegalStateException e) {
// Success.
}
}
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullFactory() {
new Bootstrap().setFactory(null);
}
@Test
public void shouldHaveNonNullInitialPipeline() {
assertNotNull(new Bootstrap().getPipeline());
}
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullPipeline() {
new Bootstrap().setPipeline(null);
}
@Test
public void shouldHaveNonNullInitialPipelineFactory() {
assertNotNull(new Bootstrap().getPipelineFactory());
}
@Test
public void shouldUpdatePipelineFactoryIfPipelineIsSet() {
Bootstrap b = new Bootstrap();
ChannelPipelineFactory oldPipelineFactory = b.getPipelineFactory();
b.setPipeline(createMock(ChannelPipeline.class));
assertNotSame(oldPipelineFactory, b.getPipelineFactory());
}
@Test(expected = IllegalStateException.class)
public void shouldNotReturnPipelineWhenPipelineFactoryIsSetByUser() {
Bootstrap b = new Bootstrap();
b.setPipelineFactory(createMock(ChannelPipelineFactory.class));
b.getPipeline();
}
@Test(expected = IllegalStateException.class)
public void shouldNotReturnPipelineMapWhenPipelineFactoryIsSetByUser() {
Bootstrap b = new Bootstrap();
b.setPipelineFactory(createMock(ChannelPipelineFactory.class));
b.getPipelineAsMap();
}
@Test(expected = NullPointerException.class)
public void shouldNotAllowNullPipelineFactory() {
new Bootstrap().setPipelineFactory(null);
}
@Test
public void shouldHaveInitialEmptyPipelineMap() {
assertTrue(new Bootstrap().getPipelineAsMap().isEmpty());
}
@Test
public void shouldReturnOrderedPipelineMap() {
Bootstrap b = new Bootstrap();
ChannelPipeline p = b.getPipeline();
p.addLast("a", createMock(ChannelDownstreamHandler.class));
p.addLast("b", createMock(ChannelDownstreamHandler.class));
p.addLast("c", createMock(ChannelDownstreamHandler.class));
p.addLast("d", createMock(ChannelDownstreamHandler.class));
Iterator<Entry<String, ChannelHandler>> m =
b.getPipelineAsMap().entrySet().iterator();
Entry<String, ChannelHandler> e;
e = m.next();
assertEquals("a", e.getKey());
assertSame(p.get("a"), e.getValue());
e = m.next();
assertEquals("b", e.getKey());
assertSame(p.get("b"), e.getValue());
e = m.next();
assertEquals("c", e.getKey());
assertSame(p.get("c"), e.getValue());
e = m.next();
assertEquals("d", e.getKey());
assertSame(p.get("d"), e.getValue());
assertFalse(m.hasNext());
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowUnorderedPipelineMap() {
Map<String, ChannelHandler> m = new HashMap<String, ChannelHandler>();
m.put("a", createMock(ChannelDownstreamHandler.class));
m.put("b", createMock(ChannelDownstreamHandler.class));
m.put("c", createMock(ChannelDownstreamHandler.class));
m.put("d", createMock(ChannelDownstreamHandler.class));
Bootstrap b = new Bootstrap();
b.setPipelineAsMap(m);
}
@Test
public void shouldHaveOrderedPipelineWhenSetFromMap() {
Map<String, ChannelHandler> m = new LinkedHashMap<String, ChannelHandler>();
m.put("a", createMock(ChannelDownstreamHandler.class));
m.put("b", createMock(ChannelDownstreamHandler.class));
m.put("c", createMock(ChannelDownstreamHandler.class));
m.put("d", createMock(ChannelDownstreamHandler.class));
Bootstrap b = new Bootstrap();
b.setPipelineAsMap(m);
ChannelPipeline p = b.getPipeline();
assertSame(p.getFirst(), m.get("a"));
assertEquals("a", p.getContext(p.getFirst()).getName());
p.removeFirst();
assertSame(p.getFirst(), m.get("b"));
assertEquals("b", p.getContext(p.getFirst()).getName());
p.removeFirst();
assertSame(p.getFirst(), m.get("c"));
assertEquals("c", p.getContext(p.getFirst()).getName());
p.removeFirst();
assertSame(p.getFirst(), m.get("d"));
assertEquals("d", p.getContext(p.getFirst()).getName());
p.removeFirst();
try {
p.removeFirst();
fail();
} catch (NoSuchElementException e) {
// Success.
}
}
@Test
public void shouldHaveInitialEmptyOptionMap() {
assertTrue(new Bootstrap().getOptions().isEmpty());
}
@Test
public void shouldUpdateOptionMapAsRequested() {
Bootstrap b = new Bootstrap();
b.setOption("s", "x");
b.setOption("b", true);
b.setOption("i", 42);
Map<String, Object> o = b.getOptions();
assertEquals(3, o.size());
assertEquals("x", o.get("s"));
assertEquals(true, o.get("b"));
assertEquals(42, o.get("i"));
}
@Test
public void shouldRemoveOptionIfValueIsNull() {
Bootstrap b = new Bootstrap();
b.setOption("s", "x");
assertEquals("x", b.getOptions().get("s"));
b.setOption("s", null);
assertTrue(b.getOptions().isEmpty());
}
}
|
src/test/java/org/jboss/netty/bootstrap/BootstrapTest.java
|
Added test cases for Bootstrap
|
src/test/java/org/jboss/netty/bootstrap/BootstrapTest.java
|
Added test cases for Bootstrap
|
|
Java
|
apache-2.0
|
error: pathspec 'core/src/main/java/org/apache/calcite/runtime/Resources.java' did not match any file(s) known to git
|
94e6272d57478a5913cb51e7df5c25e67511229a
| 1
|
vlsi/calcite,googleinterns/calcite,datametica/calcite,julianhyde/calcite,datametica/calcite,googleinterns/calcite,apache/calcite,looker-open-source/calcite,jcamachor/calcite,julianhyde/calcite,datametica/calcite,looker-open-source/calcite,vlsi/calcite,googleinterns/calcite,vlsi/calcite,vlsi/incubator-calcite,apache/calcite,jcamachor/calcite,vlsi/calcite,googleinterns/calcite,jcamachor/calcite,apache/calcite,looker-open-source/calcite,datametica/calcite,jcamachor/calcite,datametica/calcite,googleinterns/calcite,jcamachor/calcite,apache/calcite,julianhyde/calcite,julianhyde/calcite,looker-open-source/calcite,vlsi/calcite,julianhyde/calcite,julianhyde/calcite,looker-open-source/calcite,vlsi/incubator-calcite,apache/calcite,apache/calcite,datametica/calcite,looker-open-source/calcite,jcamachor/calcite,vlsi/calcite,googleinterns/calcite
|
/*
* Licensed to Julian Hyde under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Julian Hyde
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.runtime;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
/**
* Defining wrapper classes around resources that allow the compiler to check
* whether the resources exist and have the argument types that your code
* expects.
*
* <p>If this class belongs to a package other than
* {@code net.hydromatic.resource}, it was probably generated by the Maven
* plugin (groupId: "net.hydromatic", artifactId:
* "hydromatic-resource-maven-plugin"). Code generation allows projects to use
* this resource library without adding a runtime dependency on another JAR.
*/
public class Resources {
private static final ThreadLocal<Locale> MAP_THREAD_TO_LOCALE =
new ThreadLocal<Locale>();
private Resources() {}
/** Returns the preferred locale of the current thread, or
* the default locale if the current thread has not called
* {@link #setThreadLocale}.
*
* @return Locale */
protected static Locale getThreadOrDefaultLocale() {
Locale locale = getThreadLocale();
if (locale == null) {
return Locale.getDefault();
} else {
return locale;
}
}
/** Sets the locale for the current thread.
*
* @param locale Locale */
public static void setThreadLocale(Locale locale) {
MAP_THREAD_TO_LOCALE.set(locale);
}
/** Returns the preferred locale of the current thread, or null if the
* thread has not called {@link #setThreadLocale}.
*
* @return Locale */
public static Locale getThreadLocale() {
return MAP_THREAD_TO_LOCALE.get();
}
/** Creates an instance of the resource object, using the class's name as
* the name of the resource file.
*
* @see #create(String, Class)
*
* @param <T> Resource type
* @param clazz Interface that contains a method for each resource
* @return Instance of the interface that can be used to instantiate
* resources
*/
public static <T> T create(Class<T> clazz) {
return create(clazz.getCanonicalName(), clazz);
}
/** Creates an instance of the resource object.
*
* <p>The resource interface has methods that return {@link Inst} and
* {@link ExInst} values. Each of those methods is basically a factory method.
*
* <p>This method creates an instance of that interface backed by a resource
* bundle, using a dynamic proxy ({@link Proxy}).
*
* <p>Suppose that base = "com.example.MyResource" and the current locale is
* "en_US". A method
*
* <blockquote>
* @BaseMessage("Illegal binary string {0}")
* ExInst<IllegalArgumentException> illegalBinaryString(String a0);
* </blockquote>
*
* will look up a resource "IllegalBinaryString" from the resource file
* "com/example/MyResource_en_US.properties", and substitute in the parameter
* value {@code a0}.
*
* <p>The resource in the properties file may or may not be equal to the
* base message "Illegal binary string {0}". But in the base locale, it
* probably should be.
*
* @param <T> Resource type
* @param base Base name of the resource.properties file
* @param clazz Interface that contains a method for each resource
* @return Instance of the interface that can be used to instantiate
* resources
*/
public static <T> T create(String base, Class<T> clazz) {
return create(base, EmptyPropertyAccessor.INSTANCE, clazz);
}
/** Creates an instance of the resource object that can access properties
* but not resources. */
public static <T> T create(PropertyAccessor accessor, Class<T> clazz) {
return create(null, accessor, clazz);
}
/** Creates an instance of the resource object that can access properties
* but not resources. */
public static <T> T create(final Properties properties, Class<T> clazz) {
return create(null, new PropertiesAccessor(properties), clazz);
}
private static <T> T create(final String base,
final PropertyAccessor accessor, Class<T> clazz) {
//noinspection unchecked
return (T) Proxy.newProxyInstance(clazz.getClassLoader(),
new Class[] {clazz},
new InvocationHandler() {
final Map<String, Object> cache =
new ConcurrentHashMap<String, Object>();
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (args == null || args.length == 0) {
Object o = cache.get(method.getName());
if (o == null) {
o = create(method, args);
cache.put(method.getName(), o);
}
return o;
}
return create(method, args);
}
private Object create(Method method, Object[] args)
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
if (method.equals(BuiltinMethod.OBJECT_TO_STRING.method)) {
return toString();
}
final Class<?> returnType = method.getReturnType();
try {
if (Inst.class.isAssignableFrom(returnType)) {
final Constructor<?> constructor =
returnType.getConstructor(String.class, Locale.class,
Method.class, Object[].class);
final Locale locale = Resources.getThreadOrDefaultLocale();
return constructor.newInstance(base, locale, method,
args != null ? args : new Object[0]);
} else {
final Constructor<?> constructor =
returnType.getConstructor(PropertyAccessor.class,
Method.class);
return constructor.newInstance(accessor, method);
}
} catch (InvocationTargetException e) {
final Throwable e2 = e.getTargetException();
if (e2 instanceof RuntimeException) {
throw (RuntimeException) e2;
}
if (e2 instanceof Error) {
throw (Error) e2;
}
throw e;
}
}
});
}
/** Applies all validations to all resource methods in the given
* resource object.
*
* @param o Resource object to validate
*/
public static void validate(Object o) {
validate(o, EnumSet.allOf(Validation.class));
}
/** Applies the given validations to all resource methods in the given
* resource object.
*
* @param o Resource object to validate
* @param validations Validations to perform
*/
public static void validate(Object o, EnumSet<Validation> validations) {
int count = 0;
for (Method method : o.getClass().getMethods()) {
if (!Modifier.isStatic(method.getModifiers())
&& Inst.class.isAssignableFrom(method.getReturnType())) {
++count;
final Class<?>[] parameterTypes = method.getParameterTypes();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
args[i] = zero(parameterTypes[i]);
}
try {
Inst inst = (Inst) method.invoke(o, args);
inst.validate(validations);
} catch (IllegalAccessException e) {
throw new RuntimeException("in " + method, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("in " + method, e.getCause());
}
}
}
if (count == 0 && validations.contains(Validation.AT_LEAST_ONE)) {
throw new AssertionError("resource object " + o
+ " contains no resources");
}
}
private static Object zero(Class<?> clazz) {
return clazz == String.class ? ""
: clazz == byte.class ? (byte) 0
: clazz == char.class ? (char) 0
: clazz == short.class ? (short) 0
: clazz == int.class ? 0
: clazz == long.class ? 0L
: clazz == float.class ? 0F
: clazz == double.class ? 0D
: clazz == boolean.class ? false
: null;
}
/** Returns whether two objects are equal or are both null. */
private static boolean equal(Object o0, Object o1) {
return o0 == o1 || o0 != null && o0.equals(o1);
}
/** Element in a resource (either a resource or a property). */
public static class Element {
protected final Method method;
protected final String key;
public Element(Method method) {
this.method = method;
this.key = deriveKey();
}
protected String deriveKey() {
final Resource resource = method.getAnnotation(Resource.class);
if (resource != null) {
return resource.value();
} else {
final String name = method.getName();
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
}
}
/** Resource instance. It contains the resource method (which
* serves to identify the resource), the locale with which we
* expect to render the resource, and any arguments. */
public static class Inst extends Element {
private final Locale locale;
protected final String base;
protected final Object[] args;
public Inst(String base, Locale locale, Method method, Object... args) {
super(method);
this.base = base;
this.locale = locale;
this.args = args;
}
@Override public boolean equals(Object obj) {
return this == obj
|| obj != null
&& obj.getClass() == this.getClass()
&& locale == ((Inst) obj).locale
&& method == ((Inst) obj).method
&& Arrays.equals(args, ((Inst) obj).args);
}
@Override public int hashCode() {
return Arrays.asList(locale, method, Arrays.asList(args)).hashCode();
}
public ResourceBundle bundle() {
return ResourceBundle.getBundle(base, locale);
}
public Inst localize(Locale locale) {
return new Inst(base, locale, method, args);
}
public void validate(EnumSet<Validation> validations) {
final ResourceBundle bundle = bundle();
for (Validation validation : validations) {
switch (validation) {
case BUNDLE_HAS_RESOURCE:
if (!bundle.containsKey(key)) {
throw new AssertionError("key '" + key
+ "' not found for resource '" + method.getName()
+ "' in bundle '" + bundle + "'");
}
break;
case MESSAGE_SPECIFIED:
final BaseMessage annotation1 =
method.getAnnotation(BaseMessage.class);
if (annotation1 == null) {
throw new AssertionError("resource '" + method.getName()
+ "' must specify BaseMessage");
}
break;
case EVEN_QUOTES:
String message = method.getAnnotation(BaseMessage.class).value();
if (countQuotesIn(message) % 2 == 1) {
throw new AssertionError("resource '" + method.getName()
+ "' should have even number of quotes");
}
break;
case MESSAGE_MATCH:
final BaseMessage annotation2 =
method.getAnnotation(BaseMessage.class);
if (annotation2 != null) {
final String value = annotation2.value();
final String value2 = bundle.containsKey(key)
? bundle.getString(key)
: null;
if (!equal(value, value2)) {
throw new AssertionError("message for resource '"
+ method.getName()
+ "' is different between class and resource file");
}
}
break;
case ARGUMENT_MATCH:
String raw = raw();
MessageFormat format = new MessageFormat(raw);
final Format[] formats = format.getFormatsByArgumentIndex();
final List<Class> types = new ArrayList<Class>();
final Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < formats.length; i++) {
Format format1 = formats[i];
Class parameterType = parameterTypes[i];
final Class<?> e;
if (format1 instanceof NumberFormat) {
e = parameterType == short.class
|| parameterType == int.class
|| parameterType == long.class
|| parameterType == float.class
|| parameterType == double.class
|| Number.class.isAssignableFrom(parameterType)
? parameterType
: Number.class;
} else if (format1 instanceof DateFormat) {
e = Date.class;
} else {
e = String.class;
}
types.add(e);
}
final List<Class<?>> parameterTypeList =
Arrays.asList(parameterTypes);
if (!types.equals(parameterTypeList)) {
throw new AssertionError("type mismatch in method '"
+ method.getName() + "' between message format elements "
+ types + " and method parameters " + parameterTypeList);
}
break;
}
}
}
private int countQuotesIn(String message) {
int count = 0;
for (int i = 0, n = message.length(); i < n; i++) {
if (message.charAt(i) == '\'') {
++count;
}
}
return count;
}
public String str() {
String message = raw();
MessageFormat format = new MessageFormat(message);
format.setLocale(locale);
return format.format(args);
}
public String raw() {
try {
return bundle().getString(key);
} catch (MissingResourceException e) {
// Resource is not in the bundle. (It is probably missing from the
// .properties file.) Fall back to the base message.
return method.getAnnotation(BaseMessage.class).value();
}
}
public Map<String, String> getProperties() {
// At present, annotations allow at most one property per resource. We
// could design new annotations if any resource needed more.
final Property property = method.getAnnotation(Property.class);
if (property == null) {
return Collections.emptyMap();
} else {
return Collections.singletonMap(property.name(), property.value());
}
}
}
/** Sub-class of {@link Inst} that can throw an exception. Requires caused
* by exception.*/
public static class ExInstWithCause<T extends Exception> extends Inst {
public ExInstWithCause(String base, Locale locale, Method method,
Object... args) {
super(base, locale, method, args);
}
@Override public Inst localize(Locale locale) {
return new ExInstWithCause<T>(base, locale, method, args);
}
public T ex(Throwable cause) {
try {
//noinspection unchecked
final Class<T> exceptionClass =
getExceptionClass(method.getGenericReturnType());
Constructor<T> constructor;
final String str = str();
boolean causeInConstructor = false;
try {
constructor = exceptionClass.getConstructor(String.class,
Throwable.class);
causeInConstructor = true;
} catch (NoSuchMethodException nsmStringThrowable) {
try {
constructor = exceptionClass.getConstructor(String.class);
} catch (NoSuchMethodException nsmString) {
// Ignore nsmString to encourage users to have (String,
// Throwable) constructors.
throw nsmStringThrowable;
}
}
if (causeInConstructor) {
return constructor.newInstance(str, cause);
}
T ex = constructor.newInstance(str);
if (cause != null) {
try {
ex.initCause(cause);
} catch (IllegalStateException iae) {
// Sorry, unable to add cause via constructor and via initCause
}
}
return ex;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
} else if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
throw new RuntimeException(e);
}
}
}
public static Class getExceptionClass(Type type) {
// Get exception type from ExInstWithCause<MyException> type parameter.
// ExInstWithCause might be one of super classes.
// And, this class may be a parameter-less sub-class of a generic base.
//
// NOTE: We used to use
// com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters.
// More powerful, but we can't afford an extra dependency.
final Type type0 = type;
for (;;) {
if (type instanceof ParameterizedType) {
final Type[] types =
((ParameterizedType) type).getActualTypeArguments();
if (types.length >= 1
&& types[0] instanceof Class
&& Throwable.class.isAssignableFrom((Class) types[0])) {
return (Class) types[0];
}
throw new IllegalStateException(
"Unable to find superclass ExInstWithCause for " + type);
}
if (type instanceof Class) {
type = ((Class) type).getGenericSuperclass();
if (type == null) {
throw new IllegalStateException(
"Unable to find superclass ExInstWithCause for " + type0);
}
}
}
}
protected void validateException(Callable<Exception> exSupplier) {
Throwable cause = null;
try {
//noinspection ThrowableResultOfMethodCallIgnored
final Exception ex = exSupplier.call();
if (ex == null) {
cause = new NullPointerException();
}
} catch (AssertionError e) {
cause = e;
} catch (RuntimeException e) {
cause = e;
} catch (Exception e) {
// This can never happen since exSupplier should be just a ex() call.
// catch(Exception) is required since Callable#call throws Exception.
// Just in case we get exception somehow, we will rethrow it as a part
// of AssertionError below.
cause = e;
}
if (cause != null) {
AssertionError assertionError = new AssertionError(
"error instantiating exception for resource '"
+ method.getName() + "'");
assertionError.initCause(cause);
throw assertionError;
}
}
@Override public void validate(EnumSet<Validation> validations) {
super.validate(validations);
if (validations.contains(Validation.CREATE_EXCEPTION)) {
validateException(
new Callable<Exception>() {
public Exception call() throws Exception {
return ex(new NullPointerException("test"));
}
});
}
}
}
/** Sub-class of {@link Inst} that can throw an exception without caused
* by. */
public static class ExInst<T extends Exception> extends ExInstWithCause<T> {
public ExInst(String base, Locale locale, Method method, Object... args) {
super(base, locale, method, args);
}
public T ex() {
return ex(null);
}
@Override public void validate(EnumSet<Validation> validations) {
super.validate(validations);
if (validations.contains(Validation.CREATE_EXCEPTION)) {
validateException(
new Callable<Exception>() {
public Exception call() throws Exception {
return ex();
}
});
}
}
}
/** Property instance. */
public abstract static class Prop extends Element {
protected final PropertyAccessor accessor;
protected final boolean hasDefault;
public Prop(PropertyAccessor accessor, Method method) {
super(method);
this.accessor = accessor;
final Default resource = method.getAnnotation(Default.class);
this.hasDefault = resource != null;
}
public boolean isSet() {
return accessor.isSet(this);
}
public boolean hasDefault() {
return hasDefault;
}
void checkDefault() {
if (!hasDefault) {
throw new NoDefaultValueException("Property " + key
+ " has no default value");
}
}
void checkDefault2() {
if (!hasDefault) {
throw new NoDefaultValueException("Property " + key
+ " is not set and has no default value");
}
}
}
/** Integer property instance. */
public static class IntProp extends Prop {
private final int defaultValue;
public IntProp(PropertyAccessor accessor, Method method) {
super(accessor, method);
if (hasDefault) {
final Default resource = method.getAnnotation(Default.class);
defaultValue = Integer.parseInt(resource.value(), 10);
} else {
defaultValue = 0;
}
}
/** Returns the value of this integer property. */
public int get() {
return accessor.intValue(this);
}
/** Returns the value of this integer property, returning the given default
* value if the property is not set. */
public int get(int defaultValue) {
return accessor.intValue(this, defaultValue);
}
public int defaultValue() {
checkDefault();
return defaultValue;
}
}
/** Boolean property instance. */
public static class BooleanProp extends Prop {
private final boolean defaultValue;
public BooleanProp(PropertyAccessor accessor, Method method) {
super(accessor, method);
if (hasDefault) {
final Default resource = method.getAnnotation(Default.class);
defaultValue = Boolean.parseBoolean(resource.value());
} else {
defaultValue = false;
}
}
/** Returns the value of this boolean property. */
public boolean get() {
return accessor.booleanValue(this);
}
/** Returns the value of this boolean property, returning the given default
* value if the property is not set. */
public boolean get(boolean defaultValue) {
return accessor.booleanValue(this, defaultValue);
}
public boolean defaultValue() {
checkDefault();
return defaultValue;
}
}
/** Double property instance. */
public static class DoubleProp extends Prop {
private final double defaultValue;
public DoubleProp(PropertyAccessor accessor, Method method) {
super(accessor, method);
if (hasDefault) {
final Default resource = method.getAnnotation(Default.class);
defaultValue = Double.parseDouble(resource.value());
} else {
defaultValue = 0d;
}
}
/** Returns the value of this double property. */
public double get() {
return accessor.doubleValue(this);
}
/** Returns the value of this double property, returning the given default
* value if the property is not set. */
public double get(double defaultValue) {
return accessor.doubleValue(this, defaultValue);
}
public double defaultValue() {
checkDefault();
return defaultValue;
}
}
/** String property instance. */
public static class StringProp extends Prop {
private final String defaultValue;
public StringProp(PropertyAccessor accessor, Method method) {
super(accessor, method);
if (hasDefault) {
final Default resource = method.getAnnotation(Default.class);
defaultValue = resource.value();
} else {
defaultValue = null;
}
}
/** Returns the value of this String property. */
public String get() {
return accessor.stringValue(this);
}
/** Returns the value of this String property, returning the given default
* value if the property is not set. */
public String get(String defaultValue) {
return accessor.stringValue(this, defaultValue);
}
public String defaultValue() {
checkDefault();
return defaultValue;
}
}
/** Thrown when a default value is needed but a property does not have
* one. */
public static class NoDefaultValueException extends RuntimeException {
NoDefaultValueException(String message) {
super(message);
}
}
/** Means by which a resource can get values of properties, given their
* name. */
public interface PropertyAccessor {
boolean isSet(Prop p);
int intValue(IntProp p);
int intValue(IntProp p, int defaultValue);
String stringValue(StringProp p);
String stringValue(StringProp p, String defaultValue);
boolean booleanValue(BooleanProp p);
boolean booleanValue(BooleanProp p, boolean defaultValue);
double doubleValue(DoubleProp p);
double doubleValue(DoubleProp p, double defaultValue);
}
enum EmptyPropertyAccessor implements PropertyAccessor {
INSTANCE;
public boolean isSet(Prop p) {
return false;
}
public int intValue(IntProp p) {
return p.defaultValue();
}
public int intValue(IntProp p, int defaultValue) {
return defaultValue;
}
public String stringValue(StringProp p) {
return p.defaultValue();
}
public String stringValue(StringProp p, String defaultValue) {
return defaultValue;
}
public boolean booleanValue(BooleanProp p) {
return p.defaultValue();
}
public boolean booleanValue(BooleanProp p, boolean defaultValue) {
return defaultValue;
}
public double doubleValue(DoubleProp p) {
return p.defaultValue();
}
public double doubleValue(DoubleProp p, double defaultValue) {
return defaultValue;
}
}
/** Types of validation that can be performed on a resource. */
public enum Validation {
/** Checks that each method's resource key corresponds to a resource in the
* bundle. */
BUNDLE_HAS_RESOURCE,
/** Checks that there is at least one resource in the bundle. */
AT_LEAST_ONE,
/** Checks that the base message annotation is on every resource. */
MESSAGE_SPECIFIED,
/** Checks that every message contains even number of quotes. */
EVEN_QUOTES,
/** Checks that the base message matches the message in the bundle. */
MESSAGE_MATCH,
/** Checks that it is possible to create an exception. */
CREATE_EXCEPTION,
/** Checks that the parameters of the method are consistent with the
* format elements in the base message. */
ARGUMENT_MATCH,
}
/** The message in the default locale. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BaseMessage {
String value();
}
/** The name of the property in the resource file. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Resource {
String value();
}
/** Property of a resource. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Property {
String name();
String value();
}
/** Default value of a property. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Default {
String value();
}
/**
* <code>ShadowResourceBundle</code> is an abstract base class for
* {@link ResourceBundle} classes which are backed by a properties file. When
* the class is created, it loads a properties file with the same name as the
* class.
*
* <p> In the standard scheme (see {@link ResourceBundle}), if
* you call <code>{@link ResourceBundle#getBundle}("foo.MyResource")</code>,
* it first looks for a class called <code>foo.MyResource</code>, then
* looks for a file called <code>foo/MyResource.properties</code>. If it finds
* the file, it creates a {@link PropertyResourceBundle} and loads the class.
* The problem is if you want to load the <code>.properties</code> file
* into a dedicated class; <code>ShadowResourceBundle</code> helps with this
* case.
*
* <p> You should create a class as follows:<blockquote>
*
* <pre>package foo;
*class MyResource extends ShadowResourceBundle {
* public MyResource() throws java.io.IOException {
* }
*}</pre>
*
* </blockquote>
*
* Then when you call
* {@link ResourceBundle#getBundle ResourceBundle.getBundle("foo.MyResource")},
* it will find the class before the properties file, but still automatically
* load the properties file based upon the name of the class.
*/
public abstract static class ShadowResourceBundle extends ResourceBundle {
private PropertyResourceBundle bundle;
/**
* Creates a <code>ShadowResourceBundle</code>, and reads resources from
* a <code>.properties</code> file with the same name as the current class.
* For example, if the class is called <code>foo.MyResource_en_US</code>,
* reads from <code>foo/MyResource_en_US.properties</code>, then
* <code>foo/MyResource_en.properties</code>, then
* <code>foo/MyResource.properties</code>.
*
* @throws IOException on error
*/
protected ShadowResourceBundle() throws IOException {
super();
Class clazz = getClass();
InputStream stream = openPropertiesFile(clazz);
if (stream == null) {
throw new IOException("could not open properties file for "
+ getClass());
}
MyPropertyResourceBundle previousBundle =
new MyPropertyResourceBundle(stream);
bundle = previousBundle;
stream.close();
// Now load properties files for parent locales, which we deduce from
// the names of our super-class, and its super-class.
while (true) {
clazz = clazz.getSuperclass();
if (clazz == null
|| clazz == ShadowResourceBundle.class
|| !ResourceBundle.class.isAssignableFrom(clazz)) {
break;
}
stream = openPropertiesFile(clazz);
if (stream == null) {
continue;
}
MyPropertyResourceBundle newBundle =
new MyPropertyResourceBundle(stream);
stream.close();
previousBundle.setParentTrojan(newBundle);
previousBundle = newBundle;
}
}
/**
* Opens the properties file corresponding to a given class. The code is
* copied from {@link ResourceBundle}.
*/
private static InputStream openPropertiesFile(Class clazz) {
final ClassLoader loader = clazz.getClassLoader();
final String resName = clazz.getName().replace('.', '/') + ".properties";
return (InputStream) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
if (loader != null) {
return loader.getResourceAsStream(resName);
} else {
return ClassLoader.getSystemResourceAsStream(resName);
}
}
});
}
public Enumeration<String> getKeys() {
return bundle.getKeys();
}
protected Object handleGetObject(String key) {
return bundle.getObject(key);
}
/**
* Returns the instance of the <code>baseName</code> resource bundle
* for the given locale.
*
* <p> This method should be called from a derived class, with the proper
* casting:<blockquote>
*
* <pre>class MyResource extends ShadowResourceBundle {
* ...
*
* /**
* * Retrieves the instance of {@link MyResource} appropriate
* * to the given locale.
* **/
* public static MyResource instance(Locale locale) {
* return (MyResource) instance(
* MyResource.class.getName(), locale,
* ResourceBundle.getBundle(MyResource.class.getName(), locale));
* }
* ...
* }</pre></blockquote>
*
* @param baseName Base name
* @param locale Locale
* @param bundle Resource bundle
* @return Resource bundle
*/
protected static ShadowResourceBundle instance(
String baseName, Locale locale, ResourceBundle bundle) {
if (bundle instanceof PropertyResourceBundle) {
throw new ClassCastException(
"ShadowResourceBundle.instance('" + baseName + "','"
+ locale + "') found "
+ baseName + "_" + locale + ".properties but not "
+ baseName + "_" + locale + ".class");
}
return (ShadowResourceBundle) bundle;
}
}
/** Resource bundle based on properties. */
static class MyPropertyResourceBundle extends PropertyResourceBundle {
public MyPropertyResourceBundle(InputStream stream) throws IOException {
super(stream);
}
void setParentTrojan(ResourceBundle parent) {
super.setParent(parent);
}
}
enum BuiltinMethod {
OBJECT_TO_STRING(Object.class, "toString");
public final Method method;
BuiltinMethod(Class clazz, String methodName, Class... argumentTypes) {
this.method = lookupMethod(clazz, methodName, argumentTypes);
}
/**
* Finds a method of a given name that accepts a given set of arguments.
* Includes in its search inherited methods and methods with wider argument
* types.
*
* @param clazz Class against which method is invoked
* @param methodName Name of method
* @param argumentTypes Types of arguments
*
* @return A method with the given name that matches the arguments given
* @throws RuntimeException if method not found
*/
public static Method lookupMethod(Class clazz, String methodName,
Class... argumentTypes) {
try {
//noinspection unchecked
return clazz.getMethod(methodName, argumentTypes);
} catch (NoSuchMethodException e) {
throw new RuntimeException(
"while resolving method '" + methodName
+ Arrays.toString(argumentTypes)
+ "' in class " + clazz, e);
}
}
}
/** Implementation of {@link PropertyAccessor} that reads from a
* {@link Properties}. */
private static class PropertiesAccessor implements PropertyAccessor {
private final Properties properties;
PropertiesAccessor(Properties properties) {
this.properties = properties;
}
public boolean isSet(Prop p) {
return properties.containsKey(p.key);
}
public int intValue(IntProp p) {
final String s = properties.getProperty(p.key);
if (s != null) {
return Integer.parseInt(s, 10);
}
p.checkDefault2();
return p.defaultValue;
}
public int intValue(IntProp p, int defaultValue) {
final String s = properties.getProperty(p.key);
return s == null ? defaultValue : Integer.parseInt(s, 10);
}
public String stringValue(StringProp p) {
final String s = properties.getProperty(p.key);
if (s != null) {
return s;
}
p.checkDefault2();
return p.defaultValue;
}
public String stringValue(StringProp p, String defaultValue) {
final String s = properties.getProperty(p.key);
return s == null ? defaultValue : s;
}
public boolean booleanValue(BooleanProp p) {
final String s = properties.getProperty(p.key);
if (s != null) {
return Boolean.parseBoolean(s);
}
p.checkDefault2();
return p.defaultValue;
}
public boolean booleanValue(BooleanProp p, boolean defaultValue) {
final String s = properties.getProperty(p.key);
return s == null ? defaultValue : Boolean.parseBoolean(s);
}
public double doubleValue(DoubleProp p) {
final String s = properties.getProperty(p.key);
if (s != null) {
return Double.parseDouble(s);
}
p.checkDefault2();
return p.defaultValue;
}
public double doubleValue(DoubleProp p, double defaultValue) {
final String s = properties.getProperty(p.key);
return s == null ? defaultValue : Double.parseDouble(s);
}
}
}
// End Resources.java
|
core/src/main/java/org/apache/calcite/runtime/Resources.java
|
[CALCITE-2905] Add hydromatic-resource as plain source file
See https://issues.apache.org/jira/browse/CALCITE-2905?focusedCommentId=16851698&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-16851698
|
core/src/main/java/org/apache/calcite/runtime/Resources.java
|
[CALCITE-2905] Add hydromatic-resource as plain source file
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/example/service/LogHeadersInterceptor.java' did not match any file(s) known to git
|
10a9923b663edb71a2fdb0e44961fe199ff75465
| 1
|
afkham/msf4j-spring-sample
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.example.service;
import org.example.service.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wso2.msf4j.Interceptor;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.Response;
import org.wso2.msf4j.ServiceMethodInfo;
import java.util.Map;
/**
* Spring based MSF4J Interceptor class which print HTTP headers from incoming messages.
*/
@Component
public class LogHeadersInterceptor implements Interceptor {
@Autowired
private Util util;
@Override
public boolean preCall(Request request, Response responder, ServiceMethodInfo serviceMethodInfo) throws Exception {
Map<String, String> headers = request.getHeaders();
for (Map.Entry<String, String> entry : headers.entrySet()) {
util.print("Header - " + entry.getKey() + " : " + entry.getValue());
}
return true;
}
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {
}
}
|
src/main/java/org/example/service/LogHeadersInterceptor.java
|
Added interceptor
|
src/main/java/org/example/service/LogHeadersInterceptor.java
|
Added interceptor
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/uk/ac/ebi/phenotype/dao/GenomicFeatureDAO.java' did not match any file(s) known to git
|
087d53cd6fd5afaefd7e21ddd58835479c8494e3
| 1
|
mpi2/PhenotypeArchive,mpi2/PhenotypeArchive,mpi2/PhenotypeArchive
|
/**
* Copyright © 2011-2012 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.phenotype.dao;
/**
*
* Genomic feature data access manager interface.
*
* @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk>
* @since February 2012
*/
import java.util.Collection;
import java.util.List;
import java.util.Map;
import uk.ac.ebi.phenotype.bean.GenomicFeatureBean;
import uk.ac.ebi.phenotype.pojo.CoordinateSystem;
import uk.ac.ebi.phenotype.pojo.GenomicFeature;
public interface GenomicFeatureDAO extends HibernateDAO {
/**
* Get all genomic feature
* @return all coordinate system
*/
public List<GenomicFeature> getAllGenomicFeatures();
public List<GenomicFeatureBean> getAllGenomicFeatureBeans();
public GenomicFeature getGenomicFeatureByAccession(String accession);
public GenomicFeature getGenomicFeatureByAccessionAndDbId(String accession, int dbId);
public GenomicFeature getGenomicFeatureBySymbol(String symbol);
public int deleteAllGenomicFeatures();
public int batchInsertion(Collection<GenomicFeature> genomicFeatures);
/**
* Find a coordinate system by its name.
* @param name the coordinate system name
* @return the coordinate system
*/
public GenomicFeature getGenomicFeatureByName(String name);
public GenomicFeature getGenomicFeatureByBiotype(String biotype);
Map<String, GenomicFeature> getGenomicFeaturesByBiotypeAndNoSubtype(String biotype);
/**
* Save a genomic feature representation
* @param feature genomic feature to be saved.
*/
public void saveGenomicFeature(GenomicFeature feature);
}
|
src/main/java/uk/ac/ebi/phenotype/dao/GenomicFeatureDAO.java
|
Data access manager interface and implementation.
Move PhenotypeArchive to trunk
All DAO changes.
Contains mapping to genomic features
|
src/main/java/uk/ac/ebi/phenotype/dao/GenomicFeatureDAO.java
|
Data access manager interface and implementation. Move PhenotypeArchive to trunk All DAO changes. Contains mapping to genomic features
|
|
Java
|
apache-2.0
|
error: pathspec 'model/src/main/java/com/basistech/rosette/apimodel/GenericResponse.java' did not match any file(s) known to git
|
3e3d5a50da53217262856408d5dd61fb5e6baeac
| 1
|
rosette-api/java,rosette-api/java,rosette-api/java
|
/*
* Copyright 2021 Basis Technology Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.basistech.rosette.apimodel;
import com.basistech.rosette.annotations.JacksonMixin;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode
@Builder
@JacksonMixin
public class GenericResponse extends Response {
private Object data;
}
|
model/src/main/java/com/basistech/rosette/apimodel/GenericResponse.java
|
HEAD: WS-2246: add generic reponse
|
model/src/main/java/com/basistech/rosette/apimodel/GenericResponse.java
|
HEAD: WS-2246: add generic reponse
|
|
Java
|
apache-2.0
|
error: pathspec 'org.qiweb/org.qiweb.devshell/src/main/java/org/qiweb/devshell/JavaWatcher.java' did not match any file(s) known to git
|
726206734f2901d7fb044210b0ed8cfa3679f41b
| 1
|
werval/werval,werval/werval,werval/werval,werval/werval
|
/**
* Copyright (c) 2013 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qiweb.devshell;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.qiweb.spi.dev.DevShellSPI.SourceChangeListener;
import org.qiweb.spi.dev.DevShellSPI.SourceWatch;
import org.qiweb.spi.dev.DevShellSPI.SourceWatcher;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import static org.qiweb.runtime.util.Iterables.first;
/**
* Java WatchService based SourceWatcher.
* <p>
* Based on the <a href="http://docs.oracle.com/javase/tutorial/essential/io/notification.html">Watching a Directory
* for Changes</p> Java Tutorial.
* </p>
*/
public class JavaWatcher
implements SourceWatcher
{
private static final class SourceChangeWatcher
implements Runnable
{
private final WatchService watchService;
private final Map<WatchKey, Path> keys;
private final SourceChangeListener listener;
private boolean run = true;
private SourceChangeWatcher( WatchService watchService, Map<WatchKey, Path> keys, SourceChangeListener listener )
throws IOException
{
this.watchService = watchService;
this.keys = keys;
this.listener = listener;
}
@Override
public void run()
{
for( ;; )
{
if( !run )
{
return;
}
// wait for key to be signalled
WatchKey key;
try
{
key = watchService.take();
}
catch( InterruptedException x )
{
return;
}
Path dir = keys.get( key );
if( dir == null )
{
System.err.println( "WatchKey not recognized!!" );
continue;
}
// Notify source change
listener.onChange();
// Process events to maintain watched directories recursively
for( WatchEvent<?> event : key.pollEvents() )
{
WatchEvent.Kind<?> kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if( kind == OVERFLOW )
{
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast( event );
Path name = ev.context();
Path child = dir.resolve( name );
// debug
if( DEBUG )
{
System.out.format( "%s: %s\n", event.kind().name(), child );
}
// if directory is created, and watching recursively, then
// register it and its sub-directories
if( kind == ENTRY_CREATE )
{
try
{
if( Files.isDirectory( child, NOFOLLOW_LINKS ) )
{
registerAll( child, watchService, keys );
}
}
catch( IOException x )
{
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if( !valid )
{
keys.remove( key );
// all directories are inaccessible
if( keys.isEmpty() )
{
break;
}
}
}
}
private void stop()
{
run = false;
}
}
@SuppressWarnings( "unchecked" )
private static <T> WatchEvent<T> cast( WatchEvent<?> event )
{
return (WatchEvent<T>) event;
}
private static final boolean DEBUG = false;
private static final AtomicInteger THREAD_NUMBER = new AtomicInteger();
@Override
public synchronized SourceWatch watch( Set<File> directories, SourceChangeListener listener )
{
try
{
final WatchService watchService = FileSystems.getDefault().newWatchService();
final Map<WatchKey, Path> keys = new HashMap<>();
for( File dir : directories )
{
registerAll( dir.toPath(), watchService, keys );
}
String watchThreadName = "qiweb-devshell-watcher-" + THREAD_NUMBER.getAndIncrement();
final SourceChangeWatcher sourceChangeWatcher = new SourceChangeWatcher( watchService, keys, listener );
final Thread watchThread = new Thread( sourceChangeWatcher, watchThreadName );
watchThread.start();
return new SourceWatch()
{
@Override
public void unwatch()
{
Set<WatchKey> keySet = keys.keySet();
while( !keySet.isEmpty() )
{
WatchKey key = first( keySet );
key.cancel();
keys.remove( key );
sourceChangeWatcher.stop();
watchThread.interrupt();
}
}
};
}
catch( IOException ex )
{
throw new QiWebDevShellException( "Unable to watch sources for changes", ex );
}
}
private static void registerAll( final Path start, final WatchService watchService, final Map<WatchKey, Path> keys )
throws IOException
{
// register directory and sub-directories
Files.walkFileTree( start, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs )
throws IOException
{
register( dir, watchService, keys );
return FileVisitResult.CONTINUE;
}
} );
}
private static void register( Path dir, WatchService watchService, Map<WatchKey, Path> keys )
throws IOException
{
WatchEvent.Kind<?>[] watchedEvents = new WatchEvent.Kind<?>[]
{
ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY
};
WatchEvent.Modifier[] modifiers;
try
{
// com.sun based tuning, **really** faster on OSX
Class<?> sensitivityEnumClass = Class.forName( "com.sun.nio.file.SensitivityWatchEventModifier" );
modifiers = new WatchEvent.Modifier[]
{
(WatchEvent.Modifier) sensitivityEnumClass.getEnumConstants()[0]
};
}
catch( ClassNotFoundException ex )
{
// Sensitivity modifier not available, falling back to no modifiers
modifiers = new WatchEvent.Modifier[ 0 ];
}
WatchKey key = dir.register( watchService, watchedEvents, modifiers );
if( DEBUG )
{
Path prev = keys.get( key );
if( prev == null )
{
System.out.format( "register: %s\n", dir );
}
else
{
if( !dir.equals( prev ) )
{
System.out.format( "update: %s -> %s\n", prev, dir );
}
}
}
keys.put( key, dir );
}
}
|
org.qiweb/org.qiweb.devshell/src/main/java/org/qiweb/devshell/JavaWatcher.java
|
DevShell: introducing pure java sources watcher
JavaWatcher is based on JDK WatchService and use com.sun.* optimization tricks to get correct developer experience.
|
org.qiweb/org.qiweb.devshell/src/main/java/org/qiweb/devshell/JavaWatcher.java
|
DevShell: introducing pure java sources watcher
|
|
Java
|
apache-2.0
|
error: pathspec 'webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/api/SampleRelationsController.java' did not match any file(s) known to git
|
7d36cea59e95c038030497635169b7b5b5324793
| 1
|
EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4
|
package uk.ac.ebi.biosamples.api;
import org.springframework.hateoas.*;
import org.springframework.hateoas.core.EmbeddedWrapper;
import org.springframework.hateoas.core.EmbeddedWrappers;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.ac.ebi.biosamples.model.LegacyGroupsRelations;
import uk.ac.ebi.biosamples.model.LegacySamplesRelations;
import uk.ac.ebi.biosamples.model.Sample;
import uk.ac.ebi.biosamples.service.LegacyGroupsRelationsResourceAssembler;
import uk.ac.ebi.biosamples.service.LegacyRelationService;
import uk.ac.ebi.biosamples.service.LegacySamplesRelationsResourceAssembler;
import uk.ac.ebi.biosamples.service.SampleRepository;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
@RestController
@RequestMapping(value = "/samplesrelations/", produces = {MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE})
@ExposesResourceFor(LegacySamplesRelations.class)
public class SampleRelationsController {
private final SampleRepository sampleRepository;
private final LegacySamplesRelationsResourceAssembler relationsResourceAssembler;
private final LegacyGroupsRelationsResourceAssembler groupsRelationsResourceAssembler;
private final LegacyRelationService relationService;
public SampleRelationsController(SampleRepository sampleRepository,
LegacySamplesRelationsResourceAssembler relationsResourceAssembler,
LegacyGroupsRelationsResourceAssembler groupsRelationsResourceAssembler,
LegacyRelationService relationService) {
this.sampleRepository = sampleRepository;
this.relationsResourceAssembler = relationsResourceAssembler;
this.groupsRelationsResourceAssembler = groupsRelationsResourceAssembler;
this.relationService = relationService;
}
@GetMapping("/{accession}")
public ResponseEntity<Resource<LegacySamplesRelations>> relationsOfSample(@PathVariable String accession) {
Optional<Sample> sample = sampleRepository.findByAccession(accession);
if (!sample.isPresent()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(relationsResourceAssembler.toResource(new LegacySamplesRelations(sample.get())));
}
@GetMapping("/{accession}/groups")
public ResponseEntity<Resources> getSamplesGroupRelations(@PathVariable String accession) {
List<Resource<?>> associatedGroups = relationService
.getGroupsRelationships(accession).stream()
.map(groupsRelationsResourceAssembler::toResource)
.collect(Collectors.toList());
Link selfLink = linkTo(methodOn(this.getClass()).getSamplesGroupRelations(accession)).withSelfRel();
Resources responseBody = new Resources(wrappedCollection(associatedGroups, LegacyGroupsRelations.class), selfLink);
return ResponseEntity.ok(responseBody);
}
@GetMapping("/{accession}/{relationType}")
public ResponseEntity<Resources> getSamplesRelations(
@PathVariable String accession,
@PathVariable String relationType) {
if (!relationService.isSupportedRelation(relationType)) {
return ResponseEntity.badRequest().build();
}
List<Resource<?>> associatedSamples = relationService
.getSamplesRelations(accession, relationType).stream()
.map(relationsResourceAssembler::toResource)
.collect(Collectors.toList());
Link selfLink = linkTo(methodOn(this.getClass()).getSamplesRelations(accession, relationType)).withSelfRel();
Resources responseBody = new Resources(wrappedCollection(associatedSamples, LegacySamplesRelations.class), selfLink);
return ResponseEntity.ok(responseBody);
}
private Collection<?> wrappedCollection(List<Resource<?>> resourceCollection, Class collectionClass) {
EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
EmbeddedWrapper wrapper;
if (resourceCollection.isEmpty())
wrapper = wrappers.emptyCollectionOf(collectionClass);
else
wrapper = wrappers.wrap(resourceCollection);
return Collections.singletonList(wrapper);
}
}
|
webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/api/SampleRelationsController.java
|
Create the SampleRelationsController
|
webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/api/SampleRelationsController.java
|
Create the SampleRelationsController
|
|
Java
|
apache-2.0
|
error: pathspec 'services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java' did not match any file(s) known to git
|
a320718db5b512e7d967e135c8622d9f2ea1550a
| 1
|
cherryhill/collectionspace-services,cherryhill/collectionspace-services
|
package org.collectionspace.services.common.query;
import java.util.List;
import org.collectionspace.services.common.document.DocumentListWrapper;
// TODO: Auto-generated Javadoc
/**
* The Class QueryResultList.
*/
public class QueryResultList<LISTTYPE> {
private long totalSize = 0;
/** The wrapper object list. */
private LISTTYPE wrapperObjectList;
/**
* Instantiates a new query result list.
*/
private QueryResultList() {
//private constructor
}
/**
* Instantiates a new query result list.
*
* @param theWrapperObjectList the the wrapper object list
*/
public QueryResultList(LISTTYPE theWrapperObjectList) {
wrapperObjectList = theWrapperObjectList;
}
/**
* Gets the wrapper object list.
*
* @return the wrapper object list
*/
public LISTTYPE getWrapperObjectList() {
return this.wrapperObjectList;
}
/**
* Sets the total size. This is the total size of the non-paged result set.
*
* @param theTotalResultSize the new total size
*/
public void setTotalSize(long theTotalSize) {
totalSize = theTotalSize;
}
public long getTotalSize() {
return totalSize;
}
}
|
services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java
|
CSPACE-1432: Odd that my SVN client shows these added and checked-in, but apparently not. Original post: Apply "List - pagination (return total items, current page, total pages) " functionality to Account
|
services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java
|
CSPACE-1432: Odd that my SVN client shows these added and checked-in, but apparently not. Original post: Apply "List - pagination (return total items, current page, total pages) " functionality to Account
|
|
Java
|
apache-2.0
|
error: pathspec 'JibbrJabbr-server/JibbrJabbr-kernel/src/main/java/jj/script/RequireContinuationProcessor.java' did not match any file(s) known to git
|
bf7a4145281474c13a6b3305392d83c1309a3029
| 1
|
heinousjay/JibbrJabbr,heinousjay/JibbrJabbr,heinousjay/JibbrJabbr
|
/*
* Copyright 2012 Jason Miller
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jj.script;
/**
* @author jason
*
*/
public class RequireContinuationProcessor implements ContinuationProcessor {
/* (non-Javadoc)
* @see jj.script.ContinuationProcessor#type()
*/
@Override
public ContinuationType type() {
return ContinuationType.Require;
}
/* (non-Javadoc)
* @see jj.script.ContinuationProcessor#process(jj.script.ContinuationState)
*/
@Override
public void process(ContinuationState continuationState) {
// TODO Auto-generated method stub
}
}
|
JibbrJabbr-server/JibbrJabbr-kernel/src/main/java/jj/script/RequireContinuationProcessor.java
|
preparing to process required scripts, which may need a continuation
|
JibbrJabbr-server/JibbrJabbr-kernel/src/main/java/jj/script/RequireContinuationProcessor.java
|
preparing to process required scripts, which may need a continuation
|
|
Java
|
apache-2.0
|
error: pathspec 'modules/rampart-policy/src/main/java/org/apache/ws/secpolicy11/builders/RequiredElementsBuilder.java' did not match any file(s) known to git
|
5125e2ff34408c2d0f80d20bffe6db606b1b2742
| 1
|
apache/rampart,apache/rampart
|
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ws.secpolicy11.builders;
import java.util.Iterator;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.builders.AssertionBuilder;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.secpolicy.SP11Constants;
import org.apache.ws.secpolicy.model.RequiredElements;
public class RequiredElementsBuilder implements AssertionBuilder {
public Assertion build(OMElement element, AssertionBuilderFactory factory) throws IllegalArgumentException {
RequiredElements requiredElements = new RequiredElements(SPConstants.SP_V11);
OMAttribute attrXPathVersion = element.getAttribute(SP11Constants.ATTR_XPATH_VERSION);
if (attrXPathVersion != null) {
requiredElements.setXPathVersion(attrXPathVersion.getAttributeValue());
}
for (Iterator iterator = element.getChildElements(); iterator.hasNext();) {
processElement((OMElement) iterator.next(),requiredElements);
}
return requiredElements;
}
public QName[] getKnownElements() {
return new QName[] {SP11Constants.REQUIRED_ELEMENTS};
}
private void processElement(OMElement element, RequiredElements parent) {
QName name = element.getQName();
if (SP11Constants.XPATH.equals(name)) {
parent.addXPathExpression(element.getText());
Iterator namespaces = element.getAllDeclaredNamespaces();
while (namespaces.hasNext()) {
OMNamespace nm = (OMNamespace) namespaces.next();
parent.addDeclaredNamespaces(nm.getNamespaceURI(), nm.getPrefix());
}
}
}
}
|
modules/rampart-policy/src/main/java/org/apache/ws/secpolicy11/builders/RequiredElementsBuilder.java
|
rampart-policy related changes to support WS Security Policy 1.2
git-svn-id: 826b4206cfd113e788b1201c7dc26b81d52deb30@616351 13f79535-47bb-0310-9956-ffa450edef68
|
modules/rampart-policy/src/main/java/org/apache/ws/secpolicy11/builders/RequiredElementsBuilder.java
|
rampart-policy related changes to support WS Security Policy 1.2
|
|
Java
|
apache-2.0
|
error: pathspec 'projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/BondTradeWithEntityConverter.java' did not match any file(s) known to git
|
cd9af0e471a32902bf6101d66c0d9ca080504b2d
| 1
|
codeaudit/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,ChinaQuants/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,ChinaQuants/OG-Platform
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.conversion;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.joda.beans.impl.flexi.FlexiBean;
import org.threeten.bp.LocalDate;
import org.threeten.bp.Period;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.bond.BondFixedSecurityDefinition;
import com.opengamma.analytics.financial.instrument.bond.BondFixedTransactionDefinition;
import com.opengamma.analytics.financial.instrument.payment.PaymentFixedDefinition;
import com.opengamma.analytics.financial.legalentity.CreditRating;
import com.opengamma.analytics.financial.legalentity.LegalEntity;
import com.opengamma.analytics.financial.legalentity.Region;
import com.opengamma.analytics.financial.legalentity.Sector;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.position.Trade;
import com.opengamma.core.region.RegionSource;
import com.opengamma.financial.convention.ConventionBundle;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.convention.InMemoryConventionBundleMaster;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventions;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.frequency.Frequency;
import com.opengamma.financial.convention.frequency.PeriodFrequency;
import com.opengamma.financial.convention.frequency.SimpleFrequency;
import com.opengamma.financial.convention.yield.YieldConvention;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityVisitorAdapter;
import com.opengamma.financial.security.bond.BondSecurity;
import com.opengamma.financial.security.bond.CorporateBondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.i18n.Country;
import com.opengamma.util.money.Currency;
/**
*
*/
public class BondTradeWithEntityConverter {
/** Excluded coupon types */
private static final Set<String> EXCLUDED_TYPES = Sets.newHashSet("FLOAT RATE NOTE", "TOGGLE PIK NOTES");
/** Rating agency strings */
private static final String[] RATING_STRINGS = new String[] {"RatingMoody"};
/** Sector name string */
private static final String SECTOR_STRING = "IndustrySector";
/** Market type string */
private static final String MARKET_STRING = "Market";
/** The holiday source */
private final HolidaySource _holidaySource;
/** The convention bundle source */
private final ConventionBundleSource _conventionSource;
/** The region source */
private final RegionSource _regionSource;
/**
* @param holidaySource The holiday source, not null
* @param conventionSource The convention source, not null
* @param regionSource The region source, not null
*/
public BondTradeWithEntityConverter(final HolidaySource holidaySource, final ConventionBundleSource conventionSource, final RegionSource regionSource) {
ArgumentChecker.notNull(holidaySource, "holiday source");
ArgumentChecker.notNull(conventionSource, "convention source");
ArgumentChecker.notNull(regionSource, "region source");
_holidaySource = holidaySource;
_conventionSource = conventionSource;
_regionSource = regionSource;
}
/**
* Converts a fixed coupon bond trade into a {@link BondFixedTransactionDefinition}.
* @param trade The trade, not null. Must be a {@link BondSecurity}
* @return The transaction definition
*/
public BondFixedTransactionDefinition convert(final Trade trade) {
ArgumentChecker.notNull(trade, "trade");
ArgumentChecker.isTrue(trade.getSecurity() instanceof BondSecurity, "Can only handle trades with security type BondSecurity");
final LocalDate tradeDate = trade.getTradeDate();
if (tradeDate == null) {
throw new OpenGammaRuntimeException("Trade date should not be null");
}
if (trade.getTradeTime() == null) {
throw new OpenGammaRuntimeException("Trade time should not be null");
}
if (trade.getPremium() == null) {
throw new OpenGammaRuntimeException("Trade premium should not be null.");
}
final BondSecurity security = (BondSecurity) trade.getSecurity();
final ExternalIdBundle identifiers = security.getExternalIdBundle();
final String isin = identifiers.getValue(ExternalSchemes.ISIN);
final String ticker = isin == null ? null : isin;
final String shortName = security.getIssuerName();
Set<CreditRating> creditRatings = null;
final Map<String, String> attributes = trade.getAttributes();
for (final String ratingString : RATING_STRINGS) {
if (attributes.containsKey(ratingString)) {
if (creditRatings == null) {
creditRatings = new HashSet<>();
}
creditRatings.add(CreditRating.of(attributes.get(ratingString), ratingString, true));
}
}
final String sectorName = security.getIssuerType();
final FlexiBean classifications = new FlexiBean();
classifications.put(MARKET_STRING, security.getMarket());
if (attributes.containsKey(SECTOR_STRING)) {
classifications.put(SECTOR_STRING, attributes.get(SECTOR_STRING));
}
final Sector sector = Sector.of(sectorName, classifications);
final Region region = Region.of(security.getIssuerDomicile(), Country.of(security.getIssuerDomicile()), security.getCurrency());
final LegalEntity legalEntity = new LegalEntity(ticker, shortName, creditRatings, sector, region);
final InstrumentDefinition<?> underlying = getUnderlyingBond(security, legalEntity);
if (!(underlying instanceof BondFixedSecurityDefinition)) {
throw new OpenGammaRuntimeException("Can only handle fixed coupon bonds");
}
final BondFixedSecurityDefinition bond = (BondFixedSecurityDefinition) underlying;
final int quantity = trade.getQuantity().intValue(); // MH - 9-May-2013: changed from 1. // REVIEW: The quantity mechanism should be reviewed.
final ZonedDateTime settlementDate = trade.getTradeDate().atTime(trade.getTradeTime()).atZoneSameInstant(ZoneOffset.UTC); //TODO get the real time zone
final double price = trade.getPremium().doubleValue();
return new BondFixedTransactionDefinition(bond, quantity, settlementDate, price);
}
/**
* Creates the underlying bond using the full legal entity information available.
* @param security The bond security
* @param legalEntity The legal entity
* @return The underlying bond definition
*/
@SuppressWarnings("synthetic-access")
private InstrumentDefinition<?> getUnderlyingBond(final FinancialSecurity security, final LegalEntity legalEntity) {
return security.accept(new FinancialSecurityVisitorAdapter<InstrumentDefinition<?>>() {
@Override
public InstrumentDefinition<?> visitCorporateBondSecurity(final CorporateBondSecurity bond) {
final String domicile = bond.getIssuerDomicile();
ArgumentChecker.notNull(domicile, "bond security domicile cannot be null");
final String conventionName = domicile + "_CORPORATE_BOND_CONVENTION";
final ConventionBundle convention = _conventionSource.getConventionBundle(ExternalId.of(InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, conventionName));
if (convention == null) {
throw new OpenGammaRuntimeException("No corporate bond convention found for domicile " + domicile);
}
return visitBondSecurity(bond, convention, conventionName);
}
@Override
public InstrumentDefinition<?> visitGovernmentBondSecurity(final GovernmentBondSecurity bond) {
final String domicile = bond.getIssuerDomicile();
if (domicile == null) {
throw new OpenGammaRuntimeException("bond security domicile cannot be null");
}
final String conventionName = domicile + "_TREASURY_BOND_CONVENTION";
final ConventionBundle convention = _conventionSource.getConventionBundle(ExternalId.of(InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, conventionName));
if (convention == null) {
throw new OpenGammaRuntimeException("Convention called " + conventionName + " was null");
}
return visitBondSecurity(bond, convention, conventionName);
}
/**
* Creates {@link BondFixedSecurityDefinition} for fixed-coupon bonds or {@link PaymentFixedDefinition}
* for zero-coupon bonds.
* @param bond The security
* @param convention The convention
* @param conventionName The convention name
* @return The definition
*/
private InstrumentDefinition<?> visitBondSecurity(final BondSecurity bond, final ConventionBundle convention,
final String conventionName) {
if (EXCLUDED_TYPES.contains(bond.getCouponType())) {
throw new UnsupportedOperationException("Cannot support bonds with coupon of type " + bond.getCouponType());
}
final ExternalId regionId = ExternalSchemes.financialRegionId(bond.getIssuerDomicile());
if (regionId == null) {
throw new OpenGammaRuntimeException("Could not find region for " + bond.getIssuerDomicile());
}
final Calendar calendar = CalendarUtils.getCalendar(_regionSource, _holidaySource, regionId);
final Currency currency = bond.getCurrency();
final ZoneId zone = bond.getInterestAccrualDate().getZone();
final ZonedDateTime firstAccrualDate = ZonedDateTime.of(bond.getInterestAccrualDate().toLocalDate().atStartOfDay(), zone);
final ZonedDateTime maturityDate = ZonedDateTime.of(bond.getLastTradeDate().getExpiry().toLocalDate().atStartOfDay(), zone);
final double rate = bond.getCouponRate() / 100;
final DayCount dayCount = bond.getDayCount();
final BusinessDayConvention businessDay = BusinessDayConventions.FOLLOWING;
if (convention.isEOMConvention() == null) {
throw new OpenGammaRuntimeException("Could not get EOM convention information from " + conventionName);
}
final boolean isEOM = convention.isEOMConvention();
final YieldConvention yieldConvention = bond.getYieldConvention();
if (bond.getCouponType().equals("NONE") || bond.getCouponType().equals("ZERO COUPON")) { //TODO find where string is
return new PaymentFixedDefinition(currency, maturityDate, 1);
}
if (convention.getBondSettlementDays(firstAccrualDate, maturityDate) == null) {
throw new OpenGammaRuntimeException("Could not get bond settlement days from " + conventionName);
}
final int settlementDays = convention.getBondSettlementDays(firstAccrualDate, maturityDate);
final Period paymentPeriod = getTenor(bond.getCouponFrequency());
final ZonedDateTime firstCouponDate = ZonedDateTime.of(bond.getFirstCouponDate().toLocalDate().atStartOfDay(), zone);
return BondFixedSecurityDefinition.from(currency, firstAccrualDate, firstCouponDate, maturityDate, paymentPeriod, rate, settlementDays, calendar, dayCount, businessDay,
yieldConvention, isEOM, legalEntity);
}
});
}
/**
* Gets the tenor for a frequency.
* @param freq The frequency
* @return The tenor
*/
/* package */ static Period getTenor(final Frequency freq) {
if (freq instanceof PeriodFrequency) {
return ((PeriodFrequency) freq).getPeriod();
} else if (freq instanceof SimpleFrequency) {
return ((SimpleFrequency) freq).toPeriodFrequency().getPeriod();
}
throw new OpenGammaRuntimeException("Can only PeriodFrequency or SimpleFrequency; have " + freq.getClass());
}
}
|
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/BondTradeWithEntityConverter.java
|
[PLAT-5323] Adding a bond trade converter that constructs a legal entity.
|
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/BondTradeWithEntityConverter.java
|
[PLAT-5323] Adding a bond trade converter that constructs a legal entity.
|
|
Java
|
apache-2.0
|
error: pathspec 'engine-tests/src/test/java/org/terasology/persistence/typeHandling/gson/GsonTypeSerializationLibraryAdapterFactoryTest.java' did not match any file(s) known to git
|
2b4ee7bdd1dc771adb2dbf1a5b9f573b176e8d93
| 1
|
MovingBlocks/Terasology,Malanius/Terasology,Nanoware/Terasology,Nanoware/Terasology,Malanius/Terasology,Nanoware/Terasology,MovingBlocks/Terasology,MovingBlocks/Terasology
|
/*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.persistence.typeHandling.gson;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.terasology.math.geom.Rect2i;
import org.terasology.math.geom.Vector4f;
import org.terasology.naming.Name;
import org.terasology.persistence.typeHandling.TypeSerializationLibrary;
import org.terasology.reflection.copy.CopyStrategyLibrary;
import org.terasology.reflection.reflect.ReflectionReflectFactory;
import org.terasology.rendering.nui.Color;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class GsonTypeSerializationLibraryAdapterFactoryTest {
private static final TestClass OBJECT = new TestClass(
new Color(0xDEADBEEF),
ImmutableSet.of(Vector4f.zero(), Vector4f.one()),
ImmutableMap.of(
new Name("someRect"),
Rect2i.createFromMinAndSize(-3, -3, 10, 10)
),
-0xDECAF
);
private static final String OBJECT_JSON = "{\"color\":[222,173,190,239],\"vector4fs\":[[0.0,0.0,0.0,0.0]," +
"[1.0,1.0,1.0,1.0]],\"rect2iMap\":{\"someRect\":{\"min\":[-3,-3],\"size\":[10,10]}},\"i\":-912559}";
private final ReflectionReflectFactory reflectFactory = new ReflectionReflectFactory();
private final CopyStrategyLibrary copyStrategyLibrary = new CopyStrategyLibrary(reflectFactory);
private final TypeSerializationLibrary typeSerializationLibrary =
TypeSerializationLibrary.createDefaultLibrary(reflectFactory, copyStrategyLibrary);
private final GsonTypeSerializationLibraryAdapterFactory typeAdapterFactory =
new GsonTypeSerializationLibraryAdapterFactory(typeSerializationLibrary);
private final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(typeAdapterFactory)
.create();
@Test
public void testSerialize() {
String serializedObject = gson.toJson(OBJECT);
Assert.assertEquals(OBJECT_JSON, serializedObject);
}
@Test
public void testDeserialize() {
TestClass deserializedObject = gson.fromJson(OBJECT_JSON, TestClass.class);
Assert.assertEquals(OBJECT, deserializedObject);
}
private static class TestClass {
private final Color color;
private final Set<Vector4f> vector4fs;
private final Map<Name, Rect2i> rect2iMap;
private final int i;
private TestClass(Color color, Set<Vector4f> vector4fs, Map<Name, Rect2i> rect2iMap, int i) {
this.color = color;
this.vector4fs = vector4fs;
this.rect2iMap = rect2iMap;
this.i = i;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestClass testClass = (TestClass) o;
return i == testClass.i &&
Objects.equals(color, testClass.color) &&
Objects.equals(vector4fs, testClass.vector4fs) &&
Objects.equals(rect2iMap, testClass.rect2iMap);
}
}
}
|
engine-tests/src/test/java/org/terasology/persistence/typeHandling/gson/GsonTypeSerializationLibraryAdapterFactoryTest.java
|
Add GsonTypeSerializationLibraryAdapterFactory tests
|
engine-tests/src/test/java/org/terasology/persistence/typeHandling/gson/GsonTypeSerializationLibraryAdapterFactoryTest.java
|
Add GsonTypeSerializationLibraryAdapterFactory tests
|
|
Java
|
bsd-2-clause
|
15d34c349f9d01ea4336c546a5685469e3dedad2
| 0
|
D3jph/perun,mvocu/perun,ondrejvelisek/perun,zlamalp/perun,zoraseb/perun,licehammer/perun,CESNET/perun,mvocu/perun,Laliska/perun,zlamalp/perun,Simcsa/perun,balcirakpeter/perun,Holdo/perun,stavamichal/perun,Natrezim/perun,Natrezim/perun,jirmauritz/perun,zlamalp/perun,stavamichal/perun,zoraseb/perun,balcirakpeter/perun,zwejra/perun,ondrocks/perun,Laliska/perun,stavamichal/perun,zlamalp/perun,ondrocks/perun,ondrejvelisek/perun,Simcsa/perun,tauceti2/perun,dsarman/perun,ondrocks/perun,D3jph/perun,ondrocks/perun,zwejra/perun,tauceti2/perun,zoraseb/perun,Laliska/perun,Holdo/perun,tauceti2/perun,dsarman/perun,martin-kuba/perun,jirmauritz/perun,Natrezim/perun,jirmauritz/perun,licehammer/perun,licehammer/perun,licehammer/perun,Simcsa/perun,martin-kuba/perun,mvocu/perun,balcirakpeter/perun,balcirakpeter/perun,CESNET/perun,zoraseb/perun,Laliska/perun,zlamalp/perun,mvocu/perun,dsarman/perun,Holdo/perun,martin-kuba/perun,stavamichal/perun,stavamichal/perun,D3jph/perun,jirmauritz/perun,CESNET/perun,ondrejvelisek/perun,zwejra/perun,mvocu/perun,Natrezim/perun,Natrezim/perun,balcirakpeter/perun,licehammer/perun,zlamalp/perun,dsarman/perun,tauceti2/perun,tauceti2/perun,jirmauritz/perun,Simcsa/perun,Holdo/perun,licehammer/perun,zlamalp/perun,ondrejvelisek/perun,mvocu/perun,ondrejvelisek/perun,jirmauritz/perun,zoraseb/perun,D3jph/perun,Holdo/perun,tauceti2/perun,stavamichal/perun,Simcsa/perun,Laliska/perun,martin-kuba/perun,Natrezim/perun,balcirakpeter/perun,CESNET/perun,CESNET/perun,mvocu/perun,dsarman/perun,ondrocks/perun,martin-kuba/perun,CESNET/perun,zwejra/perun,Holdo/perun,martin-kuba/perun,dsarman/perun,stavamichal/perun,zwejra/perun,zoraseb/perun,Laliska/perun,D3jph/perun,Simcsa/perun,martin-kuba/perun,ondrocks/perun,ondrejvelisek/perun,balcirakpeter/perun,D3jph/perun,zwejra/perun,CESNET/perun
|
package cz.metacentrum.perun.notif.managers;
import cz.metacentrum.perun.auditparser.AuditParser;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.notif.utils.NotifUtils;
import cz.metacentrum.perun.notif.dao.PerunNotifPoolMessageDao;
import cz.metacentrum.perun.notif.dto.PoolMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifAuditMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifPoolMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifTemplate;
import cz.metacentrum.perun.notif.utils.ParsedMethod;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
//TODO:optimalizace, preprocesing, pro vsechny template
@Service("perunNotifPoolMessageManager")
public class PerunNotifPoolMessageManagerImpl implements PerunNotifPoolMessageManager {
public static final Logger logger = LoggerFactory.getLogger(PerunNotifPoolMessageManager.class);
@Autowired
private PerunNotifPoolMessageDao perunNotifPoolMessageDao;
@Autowired
private PerunNotifTemplateManager perunNotifTemplateManager;
@Autowired
private PerunBl perun;
private PerunSession session;
public static final String METHOD_CLASSNAME = "METHOD";
public static final String DEFAULT_LOCALE = "en";
private static final Map<String, ParsedMethod> parsedMethodCache = new ConcurrentHashMap<String, ParsedMethod>();
@SuppressWarnings("unused")
@PostConstruct
private void init() throws Exception {
perunNotifPoolMessageDao.setAllCreatedToNow();
session = NotifUtils.getPerunSession(perun);
}
public void savePerunNotifPoolMessages(List<PerunNotifPoolMessage> poolMessages) throws InternalErrorException {
for (PerunNotifPoolMessage message : poolMessages) {
perunNotifPoolMessageDao.savePerunNotifPoolMessage(message);
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public List<PerunNotifPoolMessage> createPerunNotifPoolMessagesForTemplates(Map<Integer, List<PerunNotifTemplate>> templatesWithRegexIds,
PerunNotifAuditMessage perunAuditMessage) throws InternalErrorException {
List<PerunNotifPoolMessage> result = new ArrayList<PerunNotifPoolMessage>();
// We parse recieved message from auditer to get all objects
//List<PerunBean> retrievedObjects = ParseUtils.parseMessage(perunMessage.getMessage());
List<PerunBean> retrievedObjects = AuditParser.parseLog(perunAuditMessage.getMessage());
// Objects which can be later used when proccessing managerCalls
Map<String, Object> usableObjects = parseRetrievedObjects(retrievedObjects);
usableObjects.put(parseClassName(PerunSession.class.toString()), session);
Map<String, String> retrievedProperties = new HashMap<String, String>();
for (Integer regexId : templatesWithRegexIds.keySet()) {
// We list through every regexId recognized in message
List<PerunNotifTemplate> templates = templatesWithRegexIds.get(regexId);
if ((templates != null) && (!templates.isEmpty())) {
for (PerunNotifTemplate template : templates) {
// We list through every template which uses regexId
Map<String, String> retrievedPrimaryProperties = new HashMap<String, String>();
Set<String> classNames = new HashSet<String>();
classNames.addAll(template.getPrimaryProperties().keySet());
for (String className : classNames) {
if (className != null && !className.equals(METHOD_CLASSNAME)) {
// Listing through all classNames
try {
logger.debug("Resolving class with name: " + className);
Class resolvedClass = Class.forName(className);
Object matchingObject = null;
for (Object myObject : retrievedObjects) {
if (resolvedClass.isAssignableFrom(myObject.getClass())) {
matchingObject = myObject;
logger.debug("Parsed object: " + matchingObject.toString() + " from message recognized for class: " + className);
}
}
if (matchingObject != null) {
if (template.getPrimaryProperties().get(className) != null) {
List<String> methods = template.getPrimaryProperties().get(className);
retrieveProperties(methods, className, retrievedPrimaryProperties, retrievedProperties, matchingObject);
}
} else {
logger.error("No object recognized in objects from message for class: " + className);
}
} catch (ClassNotFoundException ex) {
logger.error("Class from template cannot be resolved: " + className, ex);
}
}
}
if (template.getPrimaryProperties().get(METHOD_CLASSNAME) != null) {
for (String methodName : template.getPrimaryProperties().get(METHOD_CLASSNAME)) {
String value = retrieveMethodProperty(retrievedProperties, methodName, usableObjects);
retrievedPrimaryProperties.put(methodName, value);
}
}
if (retrievedPrimaryProperties != null && !retrievedPrimaryProperties.isEmpty()) {
PerunNotifPoolMessage poolMessage = new PerunNotifPoolMessage();
poolMessage.setCreated(new DateTime());
poolMessage.setKeyAttributes(retrievedPrimaryProperties);
poolMessage.setRegexId(regexId);
poolMessage.setTemplateId(template.getId());
poolMessage.setNotifMessage(perunAuditMessage.getMessage());
result.add(poolMessage);
}
}
} else {
logger.info("No template for regex id: " + regexId + " found.");
}
}
return result;
}
private void retrieveProperties(List<String> methods, String className, Map<String, String> resultProperties, Map<String, String> retrievedProperties, Object matchingObject) {
for (String methodName : methods) {
if (retrievedProperties.containsKey(className + "." + methodName)) {
resultProperties.put(className + "." + methodName, retrievedProperties.get(className + "." + methodName));
logger.debug("Method resolved from already retrievedProperties: " + className + "." + methodName);
} else {
Object methodResult = invokeMethodOnClassAndObject(methodName, matchingObject);
if (methodResult != null) {
resultProperties.put(className + "." + methodName, methodResult.toString());
retrievedProperties.put(className + "." + methodName, methodResult.toString());
}
}
}
}
private String retrieveMethodProperty(Map<String, String> retrievedProperties, String methodName, Map<String, Object> usableObjects) {
if (retrievedProperties.containsKey(methodName)) {
// Manager call retrieved from already retrieved
// properties
return retrievedProperties.get(methodName);
} else {
ParsedMethod parsedMethod = parsedMethodCache.get(methodName);
if (parsedMethod == null) {
parsedMethod = parseMethod(methodName, 0);
if (parsedMethod != null) {
parsedMethodCache.put(methodName, parsedMethod);
}
}
Object value = processManagerCall(null, parsedMethod, retrievedProperties, usableObjects);
if (value != null) {
retrievedProperties.put(methodName, value.toString());
return value.toString();
}
return null;
}
}
private Map<String, Object> parseRetrievedObjects(List<PerunBean> retrievedObjects) {
Map<String, Object> result = new HashMap<String, Object>();
for (Object object : retrievedObjects) {
result.put(parseClassName(object.getClass().toString()), object);
}
return result;
}
private String parseClassName(String className) {
String result = className.replace("class", "");
result = result.trim();
return result;
}
@SuppressWarnings({"rawtypes"})
private Object processManagerCall(Object target, ParsedMethod parsedMethod, Map<String, String> retrievedProperties, Map<String, Object> usableObjects) {
try {
switch (parsedMethod.getMethodType()) {
case METHOD:
Class partypes[] = new Class[parsedMethod.getParams().size()];
Object argList[] = new Object[parsedMethod.getParams().size()];
for (int i = 0; i < parsedMethod.getParams().size(); i++) {
ParsedMethod param = parsedMethod.getParams().get(i);
if (param != null) {
// Parameters of methods are always in retrieved props.
// Calling managers cannot be intersected
Object paramResult = null;
paramResult = processManagerCall(null, param, retrievedProperties, usableObjects);
if (paramResult != null) {
partypes[i] = paramResult.getClass();
argList[i] = paramResult;
}
}
}
if (target == null) {
target = perun;
}
Class targetClass = target.getClass();
Method method = findMethod(targetClass, parsedMethod.getMethodName(), partypes);
Object resultObject = method.invoke(target, argList);
if (parsedMethod.getNextMethod() == null) {
if (resultObject != null) {
return resultObject;
} else {
logger.error("Result of " + parsedMethod.getMethodName() + " is null.");
return null;
}
} else {
return processManagerCall(resultObject, parsedMethod.getNextMethod(), retrievedProperties, usableObjects);
}
case CLASS:
Object result = retrievedProperties.get(parsedMethod.getMethodName());
if (result == null) {
result = usableObjects.get(parsedMethod.getMethodName());
}
return result;
case STRING_PARAM:
return parsedMethod.getMethodName();
case INTEGER_PARAM:
Integer number = Integer.valueOf(parsedMethod.getMethodName());
return number;
}
} catch (Exception ex) {
logger.error("Error during processing manager call exception: " + ex.getCause(), ex);
}
return null;
}
@SuppressWarnings("rawtypes")
private Method findMethod(Class targetClass, String methodName, Class[] partypes) {
for (Method method : targetClass.getMethods()) {
if (!method.getName().equals(methodName)) {
continue;
}
Class<?>[] parameterTypes = method.getParameterTypes();
boolean matches = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i] != null && partypes[i] != null && !parameterTypes[i].isAssignableFrom(partypes[i])) {
matches = false;
break;
}
}
if (matches) {
return method;
}
}
return null;
}
private ParsedMethod parseMethod(String className, Integer startPosition) {
logger.debug("Parsing class name: " + className + " with start position: " + startPosition);
ParsedMethod result = new ParsedMethod();
String methodName = "";
for (int i = startPosition; i < className.length(); i++) {
char character = className.charAt(i);
if (character == '(') {
result.setMethodName(methodName);
result.setMethodType(ParsedMethod.MethodType.METHOD);
Integer position = new Integer(i + 1);
while (className.length() >= position && className.charAt(position) != ')') {
ParsedMethod param = parseMethod(className, position);
result.addParam(param);
position = param.getLastPosition();
}
i = position;
} else if (character == ')') {
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
result.setMethodName(methodName);
result.setLastPosition(i);
return result;
} else if (character == '.') {
Integer position = new Integer(i + 1);
ParsedMethod nextMethod = parseMethod(className, position);
result.setNextMethod(nextMethod);
result.setMethodName(methodName);
if (className.charAt(i - 1) != ')') {
result.setMethodType(ParsedMethod.MethodType.CLASS);
result.setMethodName(result.getMethodName() + "." + nextMethod.getMethodName());
result.setNextMethod(null);
} else {
result.setMethodType(ParsedMethod.MethodType.METHOD);
}
result.setLastPosition(nextMethod.getLastPosition());
return result;
} else if (character == ',') {
if (result.getMethodType() == null || !(result.getMethodType().equals(ParsedMethod.MethodType.METHOD) && result.getParams() != null && result.getParams().size() > 0)) {
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
result.setMethodName(methodName);
}
result.setLastPosition(i + 2);
return result;
} else if (character == '"') {
StringBuilder builder = new StringBuilder();
i++;
character = className.charAt(i);
while (character != '"') {
builder.append(character);
i++;
character = className.charAt(i);
}
result.setLastPosition(i + 1);
result.setMethodName(builder.toString());
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
return result;
} else if (Character.isDigit(character)) {
StringBuilder number = new StringBuilder();
number.append(character);
i++;
character = className.charAt(i);
while (Character.isDigit(character)) {
number.append(character);
i++;
character = className.charAt(i);
}
result.setMethodName(number.toString());
result.setMethodType(ParsedMethod.MethodType.INTEGER_PARAM);
result.setLastPosition(i + 1);
return result;
} else {
methodName += character;
}
}
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Object invokeMethodOnClassAndObject(String methodName, Object matchingObject) {
if (matchingObject == null) {
return null;
}
Class resolvedClass = matchingObject.getClass();
try {
String preparedMethodName = prepareMethodName(methodName);
logger.debug("Using reflection to get values for method: " + preparedMethodName);
Method method = resolvedClass.getMethod(preparedMethodName);
return method.invoke(matchingObject);
} catch (NoSuchMethodException ex) {
logger.error("Method for class: " + resolvedClass.toString() + " cannot be resolved: " + methodName);
} catch (InvocationTargetException ex) {
logger.error("Error during invocation of method: " + methodName, ex);
} catch (IllegalAccessException ex) {
logger.error("Illegal access using method: " + methodName + " on class: " + resolvedClass.toString(), ex);
}
return null;
}
private static String prepareMethodName(String methodName) {
if (methodName != null && methodName.endsWith("()")) {
return methodName.substring(0, methodName.length() - 2);
}
return methodName;
}
@Override
public void processPerunNotifPoolMessagesFromDb() {
//in format templateId = list<PoolMessage>
Map<Integer, List<PoolMessage>> poolMessages = perunNotifPoolMessageDao.getAllPoolMessagesForProcessing();
Set<Integer> proccessedIds = new HashSet<Integer>();
for (Integer templateId : poolMessages.keySet()) {
List<PoolMessage> notifMessages = poolMessages.get(templateId);
// holds one message for user
proccessedIds.addAll(perunNotifTemplateManager.processPoolMessages(templateId, notifMessages));
}
if (!proccessedIds.isEmpty()) {
logger.info("Starting to remove procesed ids.");
perunNotifPoolMessageDao.removeAllPoolMessages(proccessedIds);
}
}
public PerunBl getPerun() {
return perun;
}
public void setPerun(PerunBl perun) {
this.perun = perun;
}
}
|
perun-notification/src/main/java/cz/metacentrum/perun/notif/managers/PerunNotifPoolMessageManagerImpl.java
|
package cz.metacentrum.perun.notif.managers;
import cz.metacentrum.perun.auditparser.AuditParser;
import cz.metacentrum.perun.core.api.ExtSourcesManager;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunPrincipal;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.impl.Utils;
import cz.metacentrum.perun.notif.utils.NotifUtils;
import cz.metacentrum.perun.notif.dao.PerunNotifPoolMessageDao;
import cz.metacentrum.perun.notif.dto.PoolMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifAuditMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifPoolMessage;
import cz.metacentrum.perun.notif.entities.PerunNotifReceiver;
import cz.metacentrum.perun.notif.entities.PerunNotifTemplate;
import cz.metacentrum.perun.notif.utils.ParsedMethod;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
//TODO:optimalizace, preprocesing, pro vsechny template
@Service("perunNotifPoolMessageManager")
public class PerunNotifPoolMessageManagerImpl implements PerunNotifPoolMessageManager {
public static final Logger logger = LoggerFactory.getLogger(PerunNotifPoolMessageManager.class);
@Autowired
private PerunNotifPoolMessageDao perunNotifPoolMessageDao;
@Autowired
private PerunNotifTemplateManager perunNotifTemplateManager;
@Autowired
private PerunBl perun;
private PerunSession session;
public static final String METHOD_CLASSNAME = "METHOD";
public static final String DEFAULT_LOCALE = "en";
private static final Map<String, ParsedMethod> parsedMethodCache = new ConcurrentHashMap<String, ParsedMethod>();
@SuppressWarnings("unused")
@PostConstruct
private void init() throws Exception {
perunNotifPoolMessageDao.setAllCreatedToNow();
session = NotifUtils.getPerunSession(perun);
}
public void savePerunNotifPoolMessages(List<PerunNotifPoolMessage> poolMessages) throws InternalErrorException {
for (PerunNotifPoolMessage message : poolMessages) {
perunNotifPoolMessageDao.savePerunNotifPoolMessage(message);
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public List<PerunNotifPoolMessage> createPerunNotifPoolMessagesForTemplates(Map<Integer, List<PerunNotifTemplate>> templatesWithRegexIds,
PerunNotifAuditMessage perunAuditMessage) throws InternalErrorException {
List<PerunNotifPoolMessage> result = new ArrayList<PerunNotifPoolMessage>();
// We parse recieved message from auditer to get all objects
//List<PerunBean> retrievedObjects = ParseUtils.parseMessage(perunMessage.getMessage());
List<PerunBean> retrievedObjects = AuditParser.parseLog(perunAuditMessage.getMessage());
// Objects which can be later used when proccessing managerCalls
Map<String, Object> usableObjects = parseRetrievedObjects(retrievedObjects);
usableObjects.put(parseClassName(PerunSession.class.toString()), session);
Map<String, String> retrievedProperties = new HashMap<String, String>();
for (Integer regexId : templatesWithRegexIds.keySet()) {
// We list through every regexId recognized in message
List<PerunNotifTemplate> templates = templatesWithRegexIds.get(regexId);
if ((templates != null) && (!templates.isEmpty())) {
for (PerunNotifTemplate template : templates) {
// We list through every template which uses regexId
Map<String, String> retrievedPrimaryProperties = new HashMap<String, String>();
Set<String> classNames = new HashSet<String>();
classNames.addAll(template.getPrimaryProperties().keySet());
for (PerunNotifReceiver receiver : template.getReceivers()) {
Matcher emailMatcher = Utils.emailPattern.matcher(receiver.getTarget());
if (!emailMatcher.find()) {
classNames.add(receiver.getTarget());
}
}
for (String className : classNames) {
if (className != null && !className.equals(METHOD_CLASSNAME)) {
// Listing through all classNames
try {
logger.debug("Resolving class with name: " + className);
Class resolvedClass = Class.forName(className);
Object matchingObject = null;
for (Object myObject : retrievedObjects) {
if (resolvedClass.isAssignableFrom(myObject.getClass())) {
matchingObject = myObject;
logger.debug("Parsed object: " + matchingObject.toString() + " from message recognized for class: " + className);
}
}
if (matchingObject != null) {
if (template.getPrimaryProperties().get(className) != null) {
List<String> methods = template.getPrimaryProperties().get(className);
retrieveProperties(methods, className, retrievedPrimaryProperties, retrievedProperties, matchingObject);
}
} else {
logger.error("No object recognized in objects from message for class: " + className);
}
} catch (ClassNotFoundException ex) {
logger.error("Class from template cannot be resolved: " + className, ex);
}
}
}
if (template.getPrimaryProperties().get(METHOD_CLASSNAME) != null) {
for (String methodName : template.getPrimaryProperties().get(METHOD_CLASSNAME)) {
String value = retrieveMethodProperty(retrievedProperties, methodName, usableObjects);
retrievedPrimaryProperties.put(methodName, value);
}
}
if (retrievedPrimaryProperties != null && !retrievedPrimaryProperties.isEmpty()) {
PerunNotifPoolMessage poolMessage = new PerunNotifPoolMessage();
poolMessage.setCreated(new DateTime());
poolMessage.setKeyAttributes(retrievedPrimaryProperties);
poolMessage.setRegexId(regexId);
poolMessage.setTemplateId(template.getId());
poolMessage.setNotifMessage(perunAuditMessage.getMessage());
result.add(poolMessage);
}
}
} else {
logger.info("No template for regex id: " + regexId + " found.");
}
}
return result;
}
private void retrieveProperties(List<String> methods, String className, Map<String, String> resultProperties, Map<String, String> retrievedProperties, Object matchingObject) {
for (String methodName : methods) {
if (retrievedProperties.containsKey(className + "." + methodName)) {
resultProperties.put(className + "." + methodName, retrievedProperties.get(className + "." + methodName));
logger.debug("Method resolved from already retrievedProperties: " + className + "." + methodName);
} else {
Object methodResult = invokeMethodOnClassAndObject(methodName, matchingObject);
if (methodResult != null) {
resultProperties.put(className + "." + methodName, methodResult.toString());
retrievedProperties.put(className + "." + methodName, methodResult.toString());
}
}
}
}
private String retrieveMethodProperty(Map<String, String> retrievedProperties, String methodName, Map<String, Object> usableObjects) {
if (retrievedProperties.containsKey(methodName)) {
// Manager call retrieved from already retrieved
// properties
return retrievedProperties.get(methodName);
} else {
ParsedMethod parsedMethod = parsedMethodCache.get(methodName);
if (parsedMethod == null) {
parsedMethod = parseMethod(methodName, 0);
if (parsedMethod != null) {
parsedMethodCache.put(methodName, parsedMethod);
}
}
Object value = processManagerCall(null, parsedMethod, retrievedProperties, usableObjects);
if (value != null) {
retrievedProperties.put(methodName, value.toString());
return value.toString();
}
return null;
}
}
private Map<String, Object> parseRetrievedObjects(List<PerunBean> retrievedObjects) {
Map<String, Object> result = new HashMap<String, Object>();
for (Object object : retrievedObjects) {
result.put(parseClassName(object.getClass().toString()), object);
}
return result;
}
private String parseClassName(String className) {
String result = className.replace("class", "");
result = result.trim();
return result;
}
@SuppressWarnings({"rawtypes"})
private Object processManagerCall(Object target, ParsedMethod parsedMethod, Map<String, String> retrievedProperties, Map<String, Object> usableObjects) {
try {
switch (parsedMethod.getMethodType()) {
case METHOD:
Class partypes[] = new Class[parsedMethod.getParams().size()];
Object argList[] = new Object[parsedMethod.getParams().size()];
for (int i = 0; i < parsedMethod.getParams().size(); i++) {
ParsedMethod param = parsedMethod.getParams().get(i);
if (param != null) {
// Parameters of methods are always in retrieved props.
// Calling managers cannot be intersected
Object paramResult = null;
paramResult = processManagerCall(null, param, retrievedProperties, usableObjects);
if (paramResult != null) {
partypes[i] = paramResult.getClass();
argList[i] = paramResult;
}
}
}
if (target == null) {
target = perun;
}
Class targetClass = target.getClass();
Method method = findMethod(targetClass, parsedMethod.getMethodName(), partypes);
Object resultObject = method.invoke(target, argList);
if (parsedMethod.getNextMethod() == null) {
if (resultObject != null) {
return resultObject;
} else {
logger.error("Result of " + parsedMethod.getMethodName() + " is null.");
return null;
}
} else {
return processManagerCall(resultObject, parsedMethod.getNextMethod(), retrievedProperties, usableObjects);
}
case CLASS:
Object result = retrievedProperties.get(parsedMethod.getMethodName());
if (result == null) {
result = usableObjects.get(parsedMethod.getMethodName());
}
return result;
case STRING_PARAM:
return parsedMethod.getMethodName();
case INTEGER_PARAM:
Integer number = Integer.valueOf(parsedMethod.getMethodName());
return number;
}
} catch (Exception ex) {
logger.error("Error during processing manager call exception: " + ex.getCause(), ex);
}
return null;
}
@SuppressWarnings("rawtypes")
private Method findMethod(Class targetClass, String methodName, Class[] partypes) {
for (Method method : targetClass.getMethods()) {
if (!method.getName().equals(methodName)) {
continue;
}
Class<?>[] parameterTypes = method.getParameterTypes();
boolean matches = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i] != null && partypes[i] != null && !parameterTypes[i].isAssignableFrom(partypes[i])) {
matches = false;
break;
}
}
if (matches) {
return method;
}
}
return null;
}
private ParsedMethod parseMethod(String className, Integer startPosition) {
logger.debug("Parsing class name: " + className + " with start position: " + startPosition);
ParsedMethod result = new ParsedMethod();
String methodName = "";
for (int i = startPosition; i < className.length(); i++) {
char character = className.charAt(i);
if (character == '(') {
result.setMethodName(methodName);
result.setMethodType(ParsedMethod.MethodType.METHOD);
Integer position = new Integer(i + 1);
while (className.length() >= position && className.charAt(position) != ')') {
ParsedMethod param = parseMethod(className, position);
result.addParam(param);
position = param.getLastPosition();
}
i = position;
} else if (character == ')') {
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
result.setMethodName(methodName);
result.setLastPosition(i);
return result;
} else if (character == '.') {
Integer position = new Integer(i + 1);
ParsedMethod nextMethod = parseMethod(className, position);
result.setNextMethod(nextMethod);
result.setMethodName(methodName);
if (className.charAt(i - 1) != ')') {
result.setMethodType(ParsedMethod.MethodType.CLASS);
result.setMethodName(result.getMethodName() + "." + nextMethod.getMethodName());
result.setNextMethod(null);
} else {
result.setMethodType(ParsedMethod.MethodType.METHOD);
}
result.setLastPosition(nextMethod.getLastPosition());
return result;
} else if (character == ',') {
if (result.getMethodType() == null || !(result.getMethodType().equals(ParsedMethod.MethodType.METHOD) && result.getParams() != null && result.getParams().size() > 0)) {
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
result.setMethodName(methodName);
}
result.setLastPosition(i + 2);
return result;
} else if (character == '"') {
StringBuilder builder = new StringBuilder();
i++;
character = className.charAt(i);
while (character != '"') {
builder.append(character);
i++;
character = className.charAt(i);
}
result.setLastPosition(i + 1);
result.setMethodName(builder.toString());
result.setMethodType(ParsedMethod.MethodType.STRING_PARAM);
return result;
} else if (Character.isDigit(character)) {
StringBuilder number = new StringBuilder();
number.append(character);
i++;
character = className.charAt(i);
while (Character.isDigit(character)) {
number.append(character);
i++;
character = className.charAt(i);
}
result.setMethodName(number.toString());
result.setMethodType(ParsedMethod.MethodType.INTEGER_PARAM);
result.setLastPosition(i + 1);
return result;
} else {
methodName += character;
}
}
return result;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Object invokeMethodOnClassAndObject(String methodName, Object matchingObject) {
if (matchingObject == null) {
return null;
}
Class resolvedClass = matchingObject.getClass();
try {
String preparedMethodName = prepareMethodName(methodName);
logger.debug("Using reflection to get values for method: " + preparedMethodName);
Method method = resolvedClass.getMethod(preparedMethodName);
return method.invoke(matchingObject);
} catch (NoSuchMethodException ex) {
logger.error("Method for class: " + resolvedClass.toString() + " cannot be resolved: " + methodName);
} catch (InvocationTargetException ex) {
logger.error("Error during invocation of method: " + methodName, ex);
} catch (IllegalAccessException ex) {
logger.error("Illegal access using method: " + methodName + " on class: " + resolvedClass.toString(), ex);
}
return null;
}
private static String prepareMethodName(String methodName) {
if (methodName != null && methodName.endsWith("()")) {
return methodName.substring(0, methodName.length() - 2);
}
return methodName;
}
@Override
public void processPerunNotifPoolMessagesFromDb() {
//in format templateId = list<PoolMessage>
Map<Integer, List<PoolMessage>> poolMessages = perunNotifPoolMessageDao.getAllPoolMessagesForProcessing();
Set<Integer> proccessedIds = new HashSet<Integer>();
for (Integer templateId : poolMessages.keySet()) {
List<PoolMessage> notifMessages = poolMessages.get(templateId);
// holds one message for user
proccessedIds.addAll(perunNotifTemplateManager.processPoolMessages(templateId, notifMessages));
}
if (!proccessedIds.isEmpty()) {
logger.info("Starting to remove procesed ids.");
perunNotifPoolMessageDao.removeAllPoolMessages(proccessedIds);
}
}
public PerunBl getPerun() {
return perun;
}
public void setPerun(PerunBl perun) {
this.perun = perun;
}
}
|
Notifications: fix receiver class recognition
- recognition of a receiver is not managed by the Java reflection
|
perun-notification/src/main/java/cz/metacentrum/perun/notif/managers/PerunNotifPoolMessageManagerImpl.java
|
Notifications: fix receiver class recognition
|
|
Java
|
bsd-3-clause
|
error: pathspec 'src/main/java/com/pengyifan/leetcode/CloneGraph.java' did not match any file(s) known to git
|
d56264a623257fed320cfc86f5255dbd871b1672
| 1
|
yfpeng/pengyifan-leetcode,yfpeng/pengyifan-leetcode
|
package com.pengyifan.leetcode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import com.pengyifan.leetcode.commons.UndirectedGraphNode;
/**
* Clone an undirected graph. Each node in the graph contains a label and a
* list of its neighbors.
* <p>
* OJ's undirected graph serialization:
* <p>
* Nodes are labeled uniquely. We use <code>#</code> as a separator for each
* node, and <code>,</code> as a separator for node label and each neighbor of
* the node.
* <p>
* As an example, consider the serialized graph <code>{0,1,2#1,2#2,2}</code>.
* <p>
* The graph has a total of three nodes, and therefore contains three parts as
* separated by #.
* <ol>
* <li>First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
* <li>Second node is labeled as 1. Connect node 1 to node 2.
* <li>Third node is labeled as 2. Connect node 2 to node 2 (itself), thus
* forming a self-cycle. </o.> Visually, the graph looks like the following:
*
* <pre>
* 1
* / \
* / \
* 0 --- 2
* / \
* \_/
* </pre>
*/
public class CloneGraph {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return node;
}
// get nodes
Set<UndirectedGraphNode> nodes = new HashSet<UndirectedGraphNode>();
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
while (!queue.isEmpty()) {
UndirectedGraphNode cur = queue.poll();
if (!nodes.contains(cur)) {
nodes.add(cur);
for (UndirectedGraphNode next : cur.neighbors) {
if (!nodes.contains(next)) {
queue.offer(next);
}
}
}
}
// copy
UndirectedGraphNode newRoot = null;
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
for (UndirectedGraphNode n : nodes) {
UndirectedGraphNode newN = new UndirectedGraphNode(n.label);
map.put(n, newN);
if (n == node) {
newRoot = newN;
}
}
// copy link
for (UndirectedGraphNode n : nodes) {
UndirectedGraphNode newN = map.get(n);
for (UndirectedGraphNode next : n.neighbors) {
newN.neighbors.add(map.get(next));
}
}
return newRoot;
}
}
|
src/main/java/com/pengyifan/leetcode/CloneGraph.java
|
clone graph
|
src/main/java/com/pengyifan/leetcode/CloneGraph.java
|
clone graph
|
|
Java
|
bsd-3-clause
|
error: pathspec 'core/src/main/java/org/devilry/core/session/dao/DeliveryImpl.java' did not match any file(s) known to git
|
f53491f22356974b6743fd542ea709888f1a1778
| 1
|
devilry/devilry-prototype1,devilry/devilry-prototype1
|
package org.devilry.core.session.dao;
import org.devilry.core.entity.Delivery;
import org.devilry.core.entity.DeliveryCandidate;
import javax.ejb.Stateful;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
@Stateful
public class DeliveryImpl implements DeliveryRemote {
@PersistenceContext(unitName = "DevilryCore")
protected EntityManager em;
protected Delivery delivery;
public DeliveryImpl() {
}
public void init(long deliveryId) {
delivery = em.find(Delivery.class, deliveryId);
}
public long getId() {
return delivery.getId();
}
public long getAssignmentId() {
return delivery.getAssignment().getId();
}
public List<Long> getDeliveryCandidateIds() {
Query q = em.createQuery("SELECT d.id FROM DeliveryCandidate d "
+ "WHERE d.delivery.id = :id");
q.setParameter("id", delivery.getId());
return q.getResultList();
}
public long addDeliveryCandidate() {
DeliveryCandidate d = new DeliveryCandidate(delivery);
em.persist(d);
return d.getId();
}
}
|
core/src/main/java/org/devilry/core/session/dao/DeliveryImpl.java
|
Added forgotten file from my last commit.
|
core/src/main/java/org/devilry/core/session/dao/DeliveryImpl.java
|
Added forgotten file from my last commit.
|
|
Java
|
bsd-3-clause
|
error: pathspec 'blueprints-neo4j-graph/src/test/java/com/tinkerpop/blueprints/impls/neo4j/Neo4jGraphUsingANonInternalAbstractGraphClassFail.java' did not match any file(s) known to git
|
6d44ec209725a4f64cfb55468fc10733dd452c50
| 1
|
qiangswa/blueprints,joeyfreund/blueprints,iskytek/blueprints,maiklos-mirrors/tinkerpop_blueprints,wmudge/blueprints,echinopsii/net.echinopsii.3rdparty.blueprints,orientechnologies/blueprints,jwest-apigee/blueprints,nish5887/blueprints,tinkerpop/blueprints
|
package com.tinkerpop.blueprints.impls.neo4j;
import static org.junit.Assert.*;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsNull;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.KernelEventHandler;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.kernel.EmbeddedGraphDatabase;
public class Neo4jGraphUsingANonInternalAbstractGraphClassFail {
private class LazyLoadedGraphDatabase implements GraphDatabaseService {
private GraphDatabaseService lazy;
public GraphDatabaseService getLazy() {
if(lazy==null) {
// load that lazy graph in a unique folder
lazy = new EmbeddedGraphDatabase(getClass().getName()+"/"+System.currentTimeMillis());
}
return lazy;
}
/**
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#createNode()
* @category delegate
*/
public Node createNode() {
return getLazy().createNode();
}
/**
* @param id
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#getNodeById(long)
* @category delegate
*/
public Node getNodeById(long id) {
return getLazy().getNodeById(id);
}
/**
* @param id
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#getRelationshipById(long)
* @category delegate
*/
public Relationship getRelationshipById(long id) {
return getLazy().getRelationshipById(id);
}
/**
* @return
* @deprecated
* @see org.neo4j.graphdb.GraphDatabaseService#getReferenceNode()
* @category delegate
*/
public Node getReferenceNode() {
return getLazy().getReferenceNode();
}
/**
* @return
* @deprecated
* @see org.neo4j.graphdb.GraphDatabaseService#getAllNodes()
* @category delegate
*/
public Iterable<Node> getAllNodes() {
return getLazy().getAllNodes();
}
/**
* @return
* @deprecated
* @see org.neo4j.graphdb.GraphDatabaseService#getRelationshipTypes()
* @category delegate
*/
public Iterable<RelationshipType> getRelationshipTypes() {
return getLazy().getRelationshipTypes();
}
/**
*
* @see org.neo4j.graphdb.GraphDatabaseService#shutdown()
* @category delegate
*/
public void shutdown() {
getLazy().shutdown();
}
/**
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#beginTx()
* @category delegate
*/
public Transaction beginTx() {
return getLazy().beginTx();
}
/**
* @param handler
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#registerTransactionEventHandler(org.neo4j.graphdb.event.TransactionEventHandler)
* @category delegate
*/
public <T> TransactionEventHandler<T> registerTransactionEventHandler(TransactionEventHandler<T> handler) {
return getLazy().registerTransactionEventHandler(handler);
}
/**
* @param handler
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#unregisterTransactionEventHandler(org.neo4j.graphdb.event.TransactionEventHandler)
* @category delegate
*/
public <T> TransactionEventHandler<T> unregisterTransactionEventHandler(TransactionEventHandler<T> handler) {
return getLazy().unregisterTransactionEventHandler(handler);
}
/**
* @param handler
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#registerKernelEventHandler(org.neo4j.graphdb.event.KernelEventHandler)
* @category delegate
*/
public KernelEventHandler registerKernelEventHandler(KernelEventHandler handler) {
return getLazy().registerKernelEventHandler(handler);
}
/**
* @param handler
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#unregisterKernelEventHandler(org.neo4j.graphdb.event.KernelEventHandler)
* @category delegate
*/
public KernelEventHandler unregisterKernelEventHandler(KernelEventHandler handler) {
return getLazy().unregisterKernelEventHandler(handler);
}
/**
* @return
* @see org.neo4j.graphdb.GraphDatabaseService#index()
* @category delegate
*/
public IndexManager index() {
return getLazy().index();
}
}
/**
* in this test, our class is a graph database service, but not an InternalAbstractGraphDatabase instance.As a consequence, {@link Neo4jGraph#getInternalIndexKeys}
* won't load any index, with an additional {@link ClassCastException}
*/
@Test
public void loadingANeo4jGraphFromAnyGraphDatabaseClassShouldWork() throws ClassCastException {
Neo4jGraph tested = new Neo4jGraph(new LazyLoadedGraphDatabase());
assertThat(tested, IsNull.notNullValue());
assertThat(tested.getIndices().iterator().hasNext(), Is.is(true));
}
}
|
blueprints-neo4j-graph/src/test/java/com/tinkerpop/blueprints/impls/neo4j/Neo4jGraphUsingANonInternalAbstractGraphClassFail.java
|
An example test, exposing #378
|
blueprints-neo4j-graph/src/test/java/com/tinkerpop/blueprints/impls/neo4j/Neo4jGraphUsingANonInternalAbstractGraphClassFail.java
|
An example test, exposing #378
|
|
Java
|
mit
|
0cd56b5ce5c543ef69bfaf491a085aa06567e211
| 0
|
selvasingh/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,navalev/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,navalev/azure-sdk-for-java,hovsepm/azure-sdk-for-java,hovsepm/azure-sdk-for-java,navalev/azure-sdk-for-java,selvasingh/azure-sdk-for-java,jianghaolu/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,navalev/azure-sdk-for-java,hovsepm/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,hovsepm/azure-sdk-for-java,navalev/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,martinsawicki/azure-sdk-for-java,selvasingh/azure-sdk-for-java,ljhljh235/azure-sdk-for-java,jianghaolu/azure-sdk-for-java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.compute.implementation;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.compute.ApiEntityReference;
import com.microsoft.azure.management.compute.CachingTypes;
import com.microsoft.azure.management.compute.DiskCreateOptionTypes;
import com.microsoft.azure.management.compute.ImageReference;
import com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage;
import com.microsoft.azure.management.compute.KnownWindowsVirtualMachineImage;
import com.microsoft.azure.management.compute.LinuxConfiguration;
import com.microsoft.azure.management.compute.OperatingSystemTypes;
import com.microsoft.azure.management.compute.SshConfiguration;
import com.microsoft.azure.management.compute.SshPublicKey;
import com.microsoft.azure.management.compute.StorageAccountTypes;
import com.microsoft.azure.management.compute.UpgradeMode;
import com.microsoft.azure.management.compute.UpgradePolicy;
import com.microsoft.azure.management.compute.VirtualHardDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSet;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetDataDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetExtension;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetExtensionProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetManagedDiskParameters;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetNetworkProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetOSDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetOSProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetSku;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetSkuTypes;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetStorageProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetVMs;
import com.microsoft.azure.management.compute.WinRMConfiguration;
import com.microsoft.azure.management.compute.WinRMListener;
import com.microsoft.azure.management.compute.WindowsConfiguration;
import com.microsoft.azure.management.network.LoadBalancerBackend;
import com.microsoft.azure.management.network.LoadBalancerFrontend;
import com.microsoft.azure.management.network.LoadBalancerInboundNatPool;
import com.microsoft.azure.management.network.LoadBalancer;
import com.microsoft.azure.management.network.Network;
import com.microsoft.azure.management.network.VirtualMachineScaleSetNetworkInterface;
import com.microsoft.azure.management.network.implementation.NetworkManager;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils;
import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.GroupableParentResourceImpl;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter;
import com.microsoft.azure.management.resources.fluentcore.utils.ResourceNamer;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.azure.management.resources.fluentcore.utils.Utils;
import com.microsoft.azure.management.storage.StorageAccount;
import com.microsoft.azure.management.storage.implementation.StorageManager;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import rx.Completable;
import rx.Observable;
import rx.functions.Func0;
import rx.functions.Func1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of VirtualMachineScaleSet.
*/
@LangDefinition
public class VirtualMachineScaleSetImpl
extends GroupableParentResourceImpl<
VirtualMachineScaleSet,
VirtualMachineScaleSetInner,
VirtualMachineScaleSetImpl,
ComputeManager>
implements
VirtualMachineScaleSet,
VirtualMachineScaleSet.DefinitionManagedOrUnmanaged,
VirtualMachineScaleSet.DefinitionManaged,
VirtualMachineScaleSet.DefinitionUnmanaged,
VirtualMachineScaleSet.Update {
// Clients
private final StorageManager storageManager;
private final NetworkManager networkManager;
// used to generate unique name for any dependency resources
private final ResourceNamer namer;
private boolean isMarketplaceLinuxImage = false;
// name of an existing subnet in the primary network to use
private String existingPrimaryNetworkSubnetNameToAssociate;
// unique key of a creatable storage accounts to be used for virtual machines child resources that
// requires storage [OS disk]
private List<String> creatableStorageAccountKeys = new ArrayList<>();
// reference to an existing storage account to be used for virtual machines child resources that
// requires storage [OS disk]
private List<StorageAccount> existingStorageAccountsToAssociate = new ArrayList<>();
// Name of the container in the storage account to use to store the disks
private String vhdContainerName;
// the child resource extensions
private Map<String, VirtualMachineScaleSetExtension> extensions;
// reference to the primary and internal Internet facing load balancer
private LoadBalancer primaryInternetFacingLoadBalancer;
private LoadBalancer primaryInternalLoadBalancer;
// Load balancer specific variables used during update
private boolean removePrimaryInternetFacingLoadBalancerOnUpdate;
private boolean removePrimaryInternalLoadBalancerOnUpdate;
private LoadBalancer primaryInternetFacingLoadBalancerToAttachOnUpdate;
private LoadBalancer primaryInternalLoadBalancerToAttachOnUpdate;
private List<String> primaryInternetFacingLBBackendsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBBackendsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBInboundNatPoolsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBBackendsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBInboundNatPoolsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBBackendsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBInboundNatPoolsToAddOnUpdate = new ArrayList<>();
// The paged converter for virtual machine scale set sku
private PagedListConverter<VirtualMachineScaleSetSkuInner, VirtualMachineScaleSetSku> skuConverter;
// Flag indicates native disk is selected for OS and Data disks
private boolean isUnmanagedDiskSelected;
// To track the managed data disks
private final ManagedDataDiskCollection managedDataDisks;
VirtualMachineScaleSetImpl(
String name,
VirtualMachineScaleSetInner innerModel,
final ComputeManager computeManager,
final StorageManager storageManager,
final NetworkManager networkManager) {
super(name, innerModel, computeManager);
this.storageManager = storageManager;
this.networkManager = networkManager;
this.namer = SdkContext.getResourceNamerFactory().createResourceNamer(this.name());
this.skuConverter = new PagedListConverter<VirtualMachineScaleSetSkuInner, VirtualMachineScaleSetSku>() {
@Override
public VirtualMachineScaleSetSku typeConvert(VirtualMachineScaleSetSkuInner inner) {
return new VirtualMachineScaleSetSkuImpl(inner);
}
};
this.managedDataDisks = new ManagedDataDiskCollection(this);
}
@Override
protected void initializeChildrenFromInner() {
this.extensions = new HashMap<>();
if (this.inner().virtualMachineProfile().extensionProfile() != null) {
if (this.inner().virtualMachineProfile().extensionProfile().extensions() != null) {
for (VirtualMachineScaleSetExtensionInner inner : this.inner().virtualMachineProfile().extensionProfile().extensions()) {
this.extensions.put(inner.name(), new VirtualMachineScaleSetExtensionImpl(inner, this));
}
}
}
}
@Override
public VirtualMachineScaleSetVMs virtualMachines() {
return new VirtualMachineScaleSetVMsImpl(this, this.manager().inner().virtualMachineScaleSetVMs(), this.myManager);
}
@Override
public PagedList<VirtualMachineScaleSetSku> listAvailableSkus() {
return this.skuConverter.convert(this.manager().inner().virtualMachineScaleSets().listSkus(this.resourceGroupName(), this.name()));
}
@Override
public void deallocate() {
this.deallocateAsync().await();
}
@Override
public Completable deallocateAsync() {
Observable<OperationStatusResponseInner> d = this.manager().inner().virtualMachineScaleSets().deallocateAsync(this.resourceGroupName(), this.name());
Observable<VirtualMachineScaleSet> r = this.refreshAsync();
return Observable.concat(d, r).toCompletable();
}
@Override
public ServiceFuture<Void> deallocateAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.deallocateAsync().<Void>toObservable(), callback);
}
@Override
public void powerOff() {
this.powerOffAsync().await();
}
@Override
public Completable powerOffAsync() {
return this.manager().inner().virtualMachineScaleSets().powerOffAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> powerOffAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.powerOffAsync().<Void>toObservable(), callback);
}
@Override
public void restart() {
this.restartAsync().await();
}
@Override
public Completable restartAsync() {
return this.manager().inner().virtualMachineScaleSets().restartAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> restartAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.restartAsync().<Void>toObservable(), callback);
}
@Override
public void start() {
this.startAsync().await();
}
@Override
public Completable startAsync() {
return this.manager().inner().virtualMachineScaleSets().startAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> startAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.startAsync().<Void>toObservable(), callback);
}
@Override
public void reimage() {
this.reimageAsync().await();
}
@Override
public Completable reimageAsync() {
return this.manager().inner().virtualMachineScaleSets().reimageAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> reimageAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.reimageAsync().<Void>toObservable(), callback);
}
@Override
public String computerNamePrefix() {
return this.inner().virtualMachineProfile().osProfile().computerNamePrefix();
}
@Override
public OperatingSystemTypes osType() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().osType();
}
@Override
public CachingTypes osDiskCachingType() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().caching();
}
@Override
public String osDiskName() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().name();
}
@Override
public UpgradeMode upgradeModel() {
// upgradePolicy is a required property so no null check
return this.inner().upgradePolicy().mode();
}
@Override
public boolean overProvisionEnabled() {
return this.inner().overprovision();
}
@Override
public VirtualMachineScaleSetSkuTypes sku() {
return VirtualMachineScaleSetSkuTypes.fromSku(this.inner().sku());
}
@Override
public long capacity() {
return Utils.toPrimitiveLong(this.inner().sku().capacity());
}
@Override
public Network getPrimaryNetwork() throws IOException {
String subnetId = primaryNicDefaultIPConfiguration().subnet().id();
String virtualNetworkId = ResourceUtils.parentResourceIdFromResourceId(subnetId);
return this.networkManager
.networks()
.getById(virtualNetworkId);
}
@Override
public LoadBalancer getPrimaryInternetFacingLoadBalancer() throws IOException {
if (this.primaryInternetFacingLoadBalancer == null) {
loadCurrentPrimaryLoadBalancersIfAvailable();
}
return this.primaryInternetFacingLoadBalancer;
}
@Override
public Map<String, LoadBalancerBackend> listPrimaryInternetFacingLoadBalancerBackends() throws IOException {
if (this.getPrimaryInternetFacingLoadBalancer() != null) {
return getBackendsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public Map<String, LoadBalancerInboundNatPool> listPrimaryInternetFacingLoadBalancerInboundNatPools() throws IOException {
if (this.getPrimaryInternetFacingLoadBalancer() != null) {
return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public LoadBalancer getPrimaryInternalLoadBalancer() throws IOException {
if (this.primaryInternalLoadBalancer == null) {
loadCurrentPrimaryLoadBalancersIfAvailable();
}
return this.primaryInternalLoadBalancer;
}
@Override
public Map<String, LoadBalancerBackend> listPrimaryInternalLoadBalancerBackends() throws IOException {
if (this.getPrimaryInternalLoadBalancer() != null) {
return getBackendsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public Map<String, LoadBalancerInboundNatPool> listPrimaryInternalLoadBalancerInboundNatPools() throws IOException {
if (this.getPrimaryInternalLoadBalancer() != null) {
return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public List<String> primaryPublicIPAddressIds() throws IOException {
LoadBalancer loadBalancer = this.getPrimaryInternetFacingLoadBalancer();
if (loadBalancer != null) {
return loadBalancer.publicIPAddressIds();
}
return new ArrayList<>();
}
@Override
public List<String> vhdContainers() {
if (this.storageProfile() != null
&& this.storageProfile().osDisk() != null
&& this.storageProfile().osDisk().vhdContainers() != null) {
return this.storageProfile().osDisk().vhdContainers();
}
return new ArrayList<>();
}
@Override
public VirtualMachineScaleSetStorageProfile storageProfile() {
return this.inner().virtualMachineProfile().storageProfile();
}
@Override
public VirtualMachineScaleSetNetworkProfile networkProfile() {
return this.inner().virtualMachineProfile().networkProfile();
}
@Override
public Map<String, VirtualMachineScaleSetExtension> extensions() {
return Collections.unmodifiableMap(this.extensions);
}
@Override
public VirtualMachineScaleSetNetworkInterface getNetworkInterfaceByInstanceId(String instanceId, String name) {
return this.networkManager.networkInterfaces().getByVirtualMachineScaleSetInstanceId(this.resourceGroupName(),
this.name(),
instanceId,
name);
}
@Override
public PagedList<VirtualMachineScaleSetNetworkInterface> listNetworkInterfaces() {
return this.networkManager.networkInterfaces()
.listByVirtualMachineScaleSet(this.resourceGroupName(), this.name());
}
@Override
public PagedList<VirtualMachineScaleSetNetworkInterface> listNetworkInterfacesByInstanceId(String virtualMachineInstanceId) {
return this.networkManager.networkInterfaces()
.listByVirtualMachineScaleSetInstanceId(this.resourceGroupName(),
this.name(),
virtualMachineInstanceId);
}
// Fluent setters
@Override
public VirtualMachineScaleSetImpl withSku(VirtualMachineScaleSetSkuTypes skuType) {
this.inner()
.withSku(skuType.sku());
return this;
}
@Override
public VirtualMachineScaleSetImpl withSku(VirtualMachineScaleSetSku sku) {
return this.withSku(sku.skuType());
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryNetworkSubnet(Network network, String subnetName) {
this.existingPrimaryNetworkSubnetNameToAssociate = mergePath(network.id(), "subnets", subnetName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryInternetFacingLoadBalancer(LoadBalancer loadBalancer) {
if (loadBalancer.publicIPAddressIds().isEmpty()) {
throw new IllegalArgumentException("Parameter loadBalancer must be an Internet facing load balancer");
}
if (isInCreateMode()) {
this.primaryInternetFacingLoadBalancer = loadBalancer;
associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancer,
this.primaryNicDefaultIPConfiguration());
} else {
this.primaryInternetFacingLoadBalancerToAttachOnUpdate = loadBalancer;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerBackends(String... backendNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllBackendAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, defaultPrimaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
defaultPrimaryIpConfig,
backendNames);
} else {
addToList(this.primaryInternetFacingLBBackendsToAddOnUpdate, backendNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerInboundNatPools(String... natPoolNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer,
defaultPrimaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
defaultPrimaryIpConfig,
natPoolNames);
} else {
addToList(this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate, natPoolNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryInternalLoadBalancer(LoadBalancer loadBalancer) {
if (!loadBalancer.publicIPAddressIds().isEmpty()) {
throw new IllegalArgumentException("Parameter loadBalancer must be an internal load balancer");
}
String lbNetworkId = null;
for (LoadBalancerFrontend frontEnd : loadBalancer.frontends().values()) {
if (frontEnd.inner().subnet().id() != null) {
lbNetworkId = ResourceUtils.parentResourceIdFromResourceId(frontEnd.inner().subnet().id());
}
}
if (isInCreateMode()) {
String vmNICNetworkId = ResourceUtils.parentResourceIdFromResourceId(this.existingPrimaryNetworkSubnetNameToAssociate);
// Azure has a really wired BUG that - it throws exception when vnet of VMSS and LB are not same
// (code: NetworkInterfaceAndInternalLoadBalancerMustUseSameVnet) but at the same time Azure update
// the VMSS's network section to refer this invalid internal LB. This makes VMSS un-usable and portal
// will show a error above VMSS profile page.
//
if (!vmNICNetworkId.equalsIgnoreCase(lbNetworkId)) {
throw new IllegalArgumentException("Virtual network associated with scale set virtual machines"
+ " and internal load balancer must be same. "
+ "'" + vmNICNetworkId + "'"
+ "'" + lbNetworkId);
}
this.primaryInternalLoadBalancer = loadBalancer;
associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancer,
this.primaryNicDefaultIPConfiguration());
} else {
String vmNicVnetId = ResourceUtils.parentResourceIdFromResourceId(primaryNicDefaultIPConfiguration()
.subnet()
.id());
if (!vmNicVnetId.equalsIgnoreCase(lbNetworkId)) {
throw new IllegalArgumentException("Virtual network associated with scale set virtual machines"
+ " and internal load balancer must be same. "
+ "'" + vmNicVnetId + "'"
+ "'" + lbNetworkId);
}
this.primaryInternalLoadBalancerToAttachOnUpdate = loadBalancer;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerBackends(String... backendNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = primaryNicDefaultIPConfiguration();
removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancer,
defaultPrimaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancer.id(),
defaultPrimaryIpConfig,
backendNames);
} else {
addToList(this.primaryInternalLBBackendsToAddOnUpdate, backendNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerInboundNatPools(String... natPoolNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternalLoadBalancer,
defaultPrimaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancer.id(),
defaultPrimaryIpConfig,
natPoolNames);
} else {
addToList(this.primaryInternalLBInboundNatPoolsToAddOnUpdate, natPoolNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancer() {
if (this.isInUpdateMode()) {
this.removePrimaryInternalLoadBalancerOnUpdate = true;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancer() {
if (this.isInUpdateMode()) {
this.removePrimaryInternetFacingLoadBalancerOnUpdate = true;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancerBackends(String ...backendNames) {
addToList(this.primaryInternetFacingLBBackendsToRemoveOnUpdate, backendNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancerBackends(String ...backendNames) {
addToList(this.primaryInternalLBBackendsToRemoveOnUpdate, backendNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancerNatPools(String ...natPoolNames) {
addToList(this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate, natPoolNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancerNatPools(String ...natPoolNames) {
addToList(this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate, natPoolNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage) {
return withSpecificWindowsImageVersion(knownImage.imageReference());
}
@Override
public VirtualMachineScaleSetImpl withLatestWindowsImage(String publisher, String offer, String sku) {
ImageReference imageReference = new ImageReference()
.withPublisher(publisher)
.withOffer(offer)
.withSku(sku)
.withVersion("latest");
return withSpecificWindowsImageVersion(imageReference);
}
@Override
public VirtualMachineScaleSetImpl withSpecificWindowsImageVersion(ImageReference imageReference) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReference.inner());
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withWindowsCustomImage(String customImageId) {
ImageReferenceInner imageReferenceInner = new ImageReferenceInner();
imageReferenceInner.withId(customImageId);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReferenceInner);
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withStoredWindowsImage(String imageUrl) {
VirtualHardDisk userImageVhd = new VirtualHardDisk();
userImageVhd.withUri(imageUrl);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withImage(userImageVhd);
// For platform image osType will be null, azure will pick it from the image metadata.
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withOsType(OperatingSystemTypes.WINDOWS);
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withPopularLinuxImage(KnownLinuxVirtualMachineImage knownImage) {
return withSpecificLinuxImageVersion(knownImage.imageReference());
}
@Override
public VirtualMachineScaleSetImpl withLatestLinuxImage(String publisher, String offer, String sku) {
ImageReference imageReference = new ImageReference()
.withPublisher(publisher)
.withOffer(offer)
.withSku(sku)
.withVersion("latest");
return withSpecificLinuxImageVersion(imageReference);
}
@Override
public VirtualMachineScaleSetImpl withSpecificLinuxImageVersion(ImageReference imageReference) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReference.inner());
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
this.isMarketplaceLinuxImage = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withLinuxCustomImage(String customImageId) {
ImageReferenceInner imageReferenceInner = new ImageReferenceInner();
imageReferenceInner.withId(customImageId);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReferenceInner);
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
this.isMarketplaceLinuxImage = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withStoredLinuxImage(String imageUrl) {
VirtualHardDisk userImageVhd = new VirtualHardDisk();
userImageVhd.withUri(imageUrl);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withImage(userImageVhd);
// For platform image osType will be null, azure will pick it from the image metadata.
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withOsType(OperatingSystemTypes.LINUX);
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
return this;
}
@Override
public VirtualMachineScaleSetImpl withAdminUsername(String adminUserName) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminUsername(adminUserName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withRootUsername(String adminUserName) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminUsername(adminUserName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withAdminPassword(String password) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminPassword(password);
return this;
}
@Override
public VirtualMachineScaleSetImpl withRootPassword(String password) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminPassword(password);
return this;
}
@Override
public VirtualMachineScaleSetImpl withSsh(String publicKeyData) {
VirtualMachineScaleSetOSProfile osProfile = this.inner()
.virtualMachineProfile()
.osProfile();
if (osProfile.linuxConfiguration().ssh() == null) {
SshConfiguration sshConfiguration = new SshConfiguration();
sshConfiguration.withPublicKeys(new ArrayList<SshPublicKey>());
osProfile.linuxConfiguration().withSsh(sshConfiguration);
}
SshPublicKey sshPublicKey = new SshPublicKey();
sshPublicKey.withKeyData(publicKeyData);
sshPublicKey.withPath("/home/" + osProfile.adminUsername() + "/.ssh/authorized_keys");
osProfile.linuxConfiguration().ssh().publicKeys().add(sshPublicKey);
return this;
}
@Override
public VirtualMachineScaleSetImpl withVMAgent() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutVMAgent() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(false);
return this;
}
@Override
public VirtualMachineScaleSetImpl withAutoUpdate() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutAutoUpdate() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(false);
return this;
}
@Override
public VirtualMachineScaleSetImpl withTimeZone(String timeZone) {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withTimeZone(timeZone);
return this;
}
@Override
public VirtualMachineScaleSetImpl withWinRM(WinRMListener listener) {
if (this.inner().virtualMachineProfile().osProfile().windowsConfiguration().winRM() == null) {
WinRMConfiguration winRMConfiguration = new WinRMConfiguration();
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withWinRM(winRMConfiguration);
}
this.inner()
.virtualMachineProfile()
.osProfile()
.windowsConfiguration()
.winRM()
.listeners()
.add(listener);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskCaching(CachingTypes cachingType) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCaching(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskName(String name) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withName(name);
return this;
}
@Override
public VirtualMachineScaleSetImpl withComputerNamePrefix(String namePrefix) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withComputerNamePrefix(namePrefix);
return this;
}
@Override
public VirtualMachineScaleSetImpl withUpgradeMode(UpgradeMode upgradeMode) {
if (this.inner().upgradePolicy() == null) {
this.inner().withUpgradePolicy(new UpgradePolicy());
}
this.inner()
.upgradePolicy()
.withMode(upgradeMode);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOverProvision(boolean enabled) {
this.inner()
.withOverprovision(enabled);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOverProvisioning() {
return this.withOverProvision(true);
}
@Override
public VirtualMachineScaleSetImpl withoutOverProvisioning() {
return this.withOverProvision(false);
}
@Override
public VirtualMachineScaleSetImpl withCapacity(int capacity) {
this.inner()
.sku().withCapacity(new Long(capacity));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewStorageAccount(String name) {
StorageAccount.DefinitionStages.WithGroup definitionWithGroup = this.storageManager
.storageAccounts()
.define(name)
.withRegion(this.regionName());
Creatable<StorageAccount> definitionAfterGroup;
if (this.creatableGroup != null) {
definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
} else {
definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
}
return withNewStorageAccount(definitionAfterGroup);
}
@Override
public VirtualMachineScaleSetImpl withNewStorageAccount(Creatable<StorageAccount> creatable) {
this.creatableStorageAccountKeys.add(creatable.key());
this.addCreatableDependency(creatable);
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingStorageAccount(StorageAccount storageAccount) {
this.existingStorageAccountsToAssociate.add(storageAccount);
return this;
}
@Override
public VirtualMachineScaleSetImpl withCustomData(String base64EncodedCustomData) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withCustomData(base64EncodedCustomData);
return this;
}
@Override
public VirtualMachineScaleSetExtensionImpl defineNewExtension(String name) {
return new VirtualMachineScaleSetExtensionImpl(new VirtualMachineScaleSetExtensionInner().withName(name), this);
}
protected VirtualMachineScaleSetImpl withExtension(VirtualMachineScaleSetExtensionImpl extension) {
this.extensions.put(extension.name(), extension);
return this;
}
@Override
public VirtualMachineScaleSetExtensionImpl updateExtension(String name) {
return (VirtualMachineScaleSetExtensionImpl) this.extensions.get(name);
}
@Override
public VirtualMachineScaleSetImpl withoutExtension(String name) {
if (this.extensions.containsKey(name)) {
this.extensions.remove(name);
}
return this;
}
@Override
public boolean isManagedDiskEnabled() {
VirtualMachineScaleSetStorageProfile storageProfile = this.inner().virtualMachineProfile().storageProfile();
if (isOsDiskFromCustomImage(storageProfile)) {
return true;
}
if (isOSDiskFromStoredImage(storageProfile)) {
return false;
}
if (isOSDiskFromPlatformImage(storageProfile)) {
if (this.isUnmanagedDiskSelected) {
return false;
}
}
if (isInCreateMode()) {
return true;
} else {
List<String> vhdContainers = storageProfile
.osDisk()
.vhdContainers();
return vhdContainers == null || vhdContainers.size() == 0;
}
}
@Override
public VirtualMachineScaleSetImpl withUnmanagedDisks() {
this.isUnmanagedDiskSelected = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(-1)
.withDiskSizeGB(sizeInGB));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB,
int lun,
CachingTypes cachingType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(lun)
.withDiskSizeGB(sizeInGB)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB,
int lun,
CachingTypes cachingType,
StorageAccountTypes storageAccountType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters();
managedDiskParameters.withStorageAccountType(storageAccountType);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(lun)
.withDiskSizeGB(sizeInGB)
.withCaching(cachingType)
.withManagedDisk(managedDiskParameters));
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutDataDisk(int lun) {
if (!isManagedDiskEnabled()) {
return this;
}
this.managedDataDisks.diskLunsToRemove.add(lun);
return this;
}
/* TODO: Broken by change in Azure API behavior
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, CachingTypes cachingType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType)
.managedDisk()
.withStorageAccountType(storageAccountType);
return this;
}
private VirtualMachineScaleSetDataDisk getDataDiskInner(int lun) {
VirtualMachineScaleSetStorageProfile storageProfile = this
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile
.dataDisks();
if (dataDisks == null) {
return null;
}
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() == lun) {
return dataDisk;
}
}
return null;
}
*/
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun) {
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun,
int newSizeInGB,
CachingTypes cachingType) {
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun)
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun,
int newSizeInGB,
CachingTypes cachingType,
StorageAccountTypes storageAccountType) {
VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters();
managedDiskParameters.withStorageAccountType(storageAccountType);
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun)
.withDiskSizeGB(newSizeInGB)
.withManagedDisk(managedDiskParameters)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskStorageAccountType(StorageAccountTypes accountType) {
this.managedDataDisks.setDefaultStorageAccountType(accountType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskDefaultCachingType(CachingTypes cachingType) {
this.managedDataDisks.setDefaultCachingType(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskDefaultStorageAccountType(StorageAccountTypes storageAccountType) {
this.managedDataDisks.setDefaultStorageAccountType(storageAccountType);
return this;
}
// Create Update specific methods
//
@Override
protected void beforeCreating() {
if (this.extensions.size() > 0) {
this.inner()
.virtualMachineProfile()
.withExtensionProfile(new VirtualMachineScaleSetExtensionProfile())
.extensionProfile()
.withExtensions(innersFromWrappers(this.extensions.values()));
}
}
@Override
protected Observable<VirtualMachineScaleSetInner> createInner() {
if (isInCreateMode()) {
this.setOSProfileDefaults();
this.setOSDiskDefault();
}
this.setPrimaryIpConfigurationSubnet();
this.setPrimaryIpConfigurationBackendsAndInboundNatPools();
if (isManagedDiskEnabled()) {
this.managedDataDisks.setDataDisksDefaults();
} else {
List<VirtualMachineScaleSetDataDisk> dataDisks = this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks();
VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name());
}
final VirtualMachineScaleSetsInner client = this.manager().inner().virtualMachineScaleSets();
return this.handleOSDiskContainersAsync()
.flatMap(new Func1<Void, Observable<VirtualMachineScaleSetInner>>() {
@Override
public Observable<VirtualMachineScaleSetInner> call(Void aVoid) {
return client.createOrUpdateAsync(resourceGroupName(), name(), inner());
}
});
}
@Override
protected void afterCreating() {
this.clearCachedProperties();
this.initializeChildrenFromInner();
}
@Override
public Observable<VirtualMachineScaleSet> refreshAsync() {
return super.refreshAsync().map(new Func1<VirtualMachineScaleSet, VirtualMachineScaleSet>() {
@Override
public VirtualMachineScaleSet call(VirtualMachineScaleSet virtualMachineScaleSet) {
VirtualMachineScaleSetImpl impl = (VirtualMachineScaleSetImpl) virtualMachineScaleSet;
impl.clearCachedProperties();
impl.initializeChildrenFromInner();
return impl;
}
});
}
@Override
protected Observable<VirtualMachineScaleSetInner> getInnerAsync() {
return this.manager().inner().virtualMachineScaleSets().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
// Helpers
//
private boolean isInUpdateMode() {
return !this.isInCreateMode();
}
private void setOSProfileDefaults() {
if (isInUpdateMode()) {
return;
}
if (this.inner().sku().capacity() == null) {
this.withCapacity(2);
}
if (this.inner().upgradePolicy() == null
|| this.inner().upgradePolicy().mode() == null) {
this.inner()
.withUpgradePolicy(new UpgradePolicy()
.withMode(UpgradeMode.AUTOMATIC));
}
VirtualMachineScaleSetOSProfile osProfile = this.inner()
.virtualMachineProfile()
.osProfile();
VirtualMachineScaleSetOSDisk osDisk = this.inner().virtualMachineProfile().storageProfile().osDisk();
if (isOSDiskFromImage(osDisk)) {
// ODDisk CreateOption: FROM_IMAGE
//
if (this.osType() == OperatingSystemTypes.LINUX || this.isMarketplaceLinuxImage) {
if (osProfile.linuxConfiguration() == null) {
osProfile.withLinuxConfiguration(new LinuxConfiguration());
}
osProfile
.linuxConfiguration()
.withDisablePasswordAuthentication(osProfile.adminPassword() == null);
}
if (this.computerNamePrefix() == null) {
// VM name cannot contain only numeric values and cannot exceed 15 chars
if (this.name().matches("[0-9]+")) {
withComputerNamePrefix(this.namer.randomName("vmss-vm", 12));
} else if (this.name().length() <= 12) {
withComputerNamePrefix(this.name() + "-vm");
} else {
withComputerNamePrefix(this.namer.randomName("vmss-vm", 12));
}
}
} else {
// NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS]
this.inner()
.virtualMachineProfile()
.withOsProfile(null);
}
}
private void setOSDiskDefault() {
if (isInUpdateMode()) {
return;
}
VirtualMachineScaleSetStorageProfile storageProfile = this.inner().virtualMachineProfile().storageProfile();
VirtualMachineScaleSetOSDisk osDisk = storageProfile.osDisk();
if (isOSDiskFromImage(osDisk)) {
// ODDisk CreateOption: FROM_IMAGE
//
if (isManagedDiskEnabled()) {
// Note:
// Managed disk
// Supported: PlatformImage and CustomImage
// UnSupported: StoredImage
//
if (osDisk.managedDisk() == null) {
osDisk.withManagedDisk(new VirtualMachineScaleSetManagedDiskParameters());
}
if (osDisk.managedDisk().storageAccountType() == null) {
osDisk.managedDisk()
.withStorageAccountType(StorageAccountTypes.STANDARD_LRS);
}
osDisk.withVhdContainers(null);
// We won't set osDisk.name() explicitly for managed disk, if it is null CRP generates unique
// name for the disk resource within the resource group.
} else {
// Note:
// Native (un-managed) disk
// Supported: PlatformImage and StoredImage
// UnSupported: CustomImage
//
osDisk.withManagedDisk(null);
if (osDisk.name() == null) {
withOSDiskName(this.name() + "-os-disk");
}
}
} else {
// NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS]
}
if (this.osDiskCachingType() == null) {
withOSDiskCaching(CachingTypes.READ_WRITE);
}
}
private Observable<Void> handleOSDiskContainersAsync() {
final VirtualMachineScaleSetStorageProfile storageProfile = inner()
.virtualMachineProfile()
.storageProfile();
if (isManagedDiskEnabled()) {
storageProfile.osDisk()
.withVhdContainers(null);
return Observable.just(null);
}
if (isOSDiskFromStoredImage(storageProfile)) {
// There is a restriction currently that virtual machine's disk cannot be stored in multiple storage
// accounts if scale set is based on stored image. Remove this check once azure start supporting it.
//
storageProfile.osDisk()
.vhdContainers()
.clear();
return Observable.just(null);
}
if (this.isInCreateMode()
&& this.creatableStorageAccountKeys.isEmpty()
&& this.existingStorageAccountsToAssociate.isEmpty()) {
// If storage account(s) are not explicitly asked to create then create one implicitly
//
return Utils.<StorageAccount>rootResource(this.storageManager.storageAccounts()
.define(this.namer.randomName("stg", 24).replace("-", ""))
.withRegion(this.regionName())
.withExistingResourceGroup(this.resourceGroupName())
.createAsync())
.map(new Func1<StorageAccount, Void>() {
@Override
public Void call(StorageAccount storageAccount) {
String containerName = vhdContainerName;
if (containerName == null) {
containerName = "vhds";
}
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
vhdContainerName = null;
creatableStorageAccountKeys.clear();
existingStorageAccountsToAssociate.clear();
return null;
}
});
} else {
String containerName = this.vhdContainerName;
if (containerName == null) {
for (String containerUrl : storageProfile.osDisk().vhdContainers()) {
containerName = containerUrl.substring(containerUrl.lastIndexOf("/") + 1);
break;
}
}
if (containerName == null) {
containerName = "vhds";
}
for (String storageAccountKey : this.creatableStorageAccountKeys) {
StorageAccount storageAccount = (StorageAccount) createdResource(storageAccountKey);
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
}
for (StorageAccount storageAccount : this.existingStorageAccountsToAssociate) {
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
}
this.vhdContainerName = null;
this.creatableStorageAccountKeys.clear();
this.existingStorageAccountsToAssociate.clear();
return Observable.just(null);
}
}
private void setPrimaryIpConfigurationSubnet() {
if (isInUpdateMode()) {
return;
}
VirtualMachineScaleSetIPConfigurationInner ipConfig = this.primaryNicDefaultIPConfiguration();
ipConfig.withSubnet(new ApiEntityReference().withId(this.existingPrimaryNetworkSubnetNameToAssociate));
this.existingPrimaryNetworkSubnetNameToAssociate = null;
}
private void setPrimaryIpConfigurationBackendsAndInboundNatPools() {
if (isInCreateMode()) {
return;
}
try {
this.loadCurrentPrimaryLoadBalancersIfAvailable();
} catch (IOException ioException) {
throw new RuntimeException(ioException);
}
VirtualMachineScaleSetIPConfigurationInner primaryIpConfig = primaryNicDefaultIPConfiguration();
if (this.primaryInternetFacingLoadBalancer != null) {
removeBackendsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToRemoveOnUpdate.toArray(new String[0]));
associateBackEndsToIpConfiguration(primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0]));
removeInboundNatPoolsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0]));
associateInboundNATPoolsToIpConfiguration(primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
if (this.primaryInternalLoadBalancer != null) {
removeBackendsFromIpConfiguration(this.primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToRemoveOnUpdate.toArray(new String[0]));
associateBackEndsToIpConfiguration(primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0]));
removeInboundNatPoolsFromIpConfiguration(this.primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0]));
associateInboundNATPoolsToIpConfiguration(primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
if (this.removePrimaryInternetFacingLoadBalancerOnUpdate) {
if (this.primaryInternetFacingLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, primaryIpConfig);
}
}
if (this.removePrimaryInternalLoadBalancerOnUpdate) {
if (this.primaryInternalLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, primaryIpConfig);
}
}
if (this.primaryInternetFacingLoadBalancerToAttachOnUpdate != null) {
if (this.primaryInternetFacingLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, primaryIpConfig);
}
associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
if (!this.primaryInternetFacingLBBackendsToAddOnUpdate.isEmpty()) {
removeAllBackendAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0]));
}
if (!this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.isEmpty()) {
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
}
if (this.primaryInternalLoadBalancerToAttachOnUpdate != null) {
if (this.primaryInternalLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, primaryIpConfig);
}
associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
if (!this.primaryInternalLBBackendsToAddOnUpdate.isEmpty()) {
removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0]));
}
if (!this.primaryInternalLBInboundNatPoolsToAddOnUpdate.isEmpty()) {
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
}
this.removePrimaryInternetFacingLoadBalancerOnUpdate = false;
this.removePrimaryInternalLoadBalancerOnUpdate = false;
this.primaryInternetFacingLoadBalancerToAttachOnUpdate = null;
this.primaryInternalLoadBalancerToAttachOnUpdate = null;
this.primaryInternetFacingLBBackendsToRemoveOnUpdate.clear();
this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.clear();
this.primaryInternalLBBackendsToRemoveOnUpdate.clear();
this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.clear();
this.primaryInternetFacingLBBackendsToAddOnUpdate.clear();
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.clear();
this.primaryInternalLBBackendsToAddOnUpdate.clear();
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.clear();
}
private void clearCachedProperties() {
this.primaryInternetFacingLoadBalancer = null;
this.primaryInternalLoadBalancer = null;
}
private void loadCurrentPrimaryLoadBalancersIfAvailable() throws IOException {
if (this.primaryInternetFacingLoadBalancer != null && this.primaryInternalLoadBalancer != null) {
return;
}
String firstLoadBalancerId = null;
VirtualMachineScaleSetIPConfigurationInner ipConfig = primaryNicDefaultIPConfiguration();
if (!ipConfig.loadBalancerBackendAddressPools().isEmpty()) {
firstLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(ipConfig.loadBalancerBackendAddressPools().get(0).id());
}
if (firstLoadBalancerId == null && !ipConfig.loadBalancerInboundNatPools().isEmpty()) {
firstLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(ipConfig.loadBalancerInboundNatPools().get(0).id());
}
if (firstLoadBalancerId == null) {
return;
}
LoadBalancer loadBalancer1 = this.networkManager
.loadBalancers()
.getById(firstLoadBalancerId);
if (loadBalancer1.publicIPAddressIds() != null && loadBalancer1.publicIPAddressIds().size() > 0) {
this.primaryInternetFacingLoadBalancer = loadBalancer1;
} else {
this.primaryInternalLoadBalancer = loadBalancer1;
}
String secondLoadBalancerId = null;
for (SubResource subResource: ipConfig.loadBalancerBackendAddressPools()) {
if (!subResource.id().toLowerCase().startsWith(firstLoadBalancerId.toLowerCase())) {
secondLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(subResource.id());
break;
}
}
if (secondLoadBalancerId == null) {
for (SubResource subResource: ipConfig.loadBalancerInboundNatPools()) {
if (!subResource.id().toLowerCase().startsWith(firstLoadBalancerId.toLowerCase())) {
secondLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(subResource.id());
break;
}
}
}
if (secondLoadBalancerId == null) {
return;
}
LoadBalancer loadBalancer2 = this.networkManager
.loadBalancers()
.getById(secondLoadBalancerId);
if (loadBalancer2.publicIPAddressIds() != null && loadBalancer2.publicIPAddressIds().size() > 0) {
this.primaryInternetFacingLoadBalancer = loadBalancer2;
} else {
this.primaryInternalLoadBalancer = loadBalancer2;
}
}
private VirtualMachineScaleSetIPConfigurationInner primaryNicDefaultIPConfiguration() {
List<VirtualMachineScaleSetNetworkConfigurationInner> nicConfigurations = this.inner()
.virtualMachineProfile()
.networkProfile()
.networkInterfaceConfigurations();
for (VirtualMachineScaleSetNetworkConfigurationInner nicConfiguration : nicConfigurations) {
if (nicConfiguration.primary()) {
if (nicConfiguration.ipConfigurations().size() > 0) {
VirtualMachineScaleSetIPConfigurationInner ipConfig = nicConfiguration.ipConfigurations().get(0);
if (ipConfig.loadBalancerBackendAddressPools() == null) {
ipConfig.withLoadBalancerBackendAddressPools(new ArrayList<SubResource>());
}
if (ipConfig.loadBalancerInboundNatPools() == null) {
ipConfig.withLoadBalancerInboundNatPools(new ArrayList<SubResource>());
}
return ipConfig;
}
}
}
throw new RuntimeException("Could not find the primary nic configuration or an IP configuration in it");
}
private static void associateBackEndsToIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... backendNames) {
List<SubResource> backendSubResourcesToAssociate = new ArrayList<>();
for (String backendName : backendNames) {
String backendPoolId = mergePath(loadBalancerId, "backendAddressPools", backendName);
boolean found = false;
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendPoolId)) {
found = true;
break;
}
}
if (!found) {
backendSubResourcesToAssociate.add(new SubResource().withId(backendPoolId));
}
}
for (SubResource backendSubResource : backendSubResourcesToAssociate) {
ipConfig.loadBalancerBackendAddressPools().add(backendSubResource);
}
}
private static void associateInboundNATPoolsToIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... inboundNatPools) {
List<SubResource> inboundNatPoolSubResourcesToAssociate = new ArrayList<>();
for (String inboundNatPool : inboundNatPools) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", inboundNatPool);
boolean found = false;
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
found = true;
break;
}
}
if (!found) {
inboundNatPoolSubResourcesToAssociate.add(new SubResource().withId(inboundNatPoolId));
}
}
for (SubResource backendSubResource : inboundNatPoolSubResourcesToAssociate) {
ipConfig.loadBalancerInboundNatPools().add(backendSubResource);
}
}
private static Map<String, LoadBalancerBackend> getBackendsAssociatedWithIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
String loadBalancerId = loadBalancer.id();
Map<String, LoadBalancerBackend> attachedBackends = new HashMap<>();
Map<String, LoadBalancerBackend> lbBackends = loadBalancer.backends();
for (LoadBalancerBackend lbBackend : lbBackends.values()) {
String backendId = mergePath(loadBalancerId, "backendAddressPools", lbBackend.name());
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendId)) {
attachedBackends.put(lbBackend.name(), lbBackend);
}
}
}
return attachedBackends;
}
private static Map<String, LoadBalancerInboundNatPool> getInboundNatPoolsAssociatedWithIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
String loadBalancerId = loadBalancer.id();
Map<String, LoadBalancerInboundNatPool> attachedInboundNatPools = new HashMap<>();
Map<String, LoadBalancerInboundNatPool> lbInboundNatPools = loadBalancer.inboundNatPools();
for (LoadBalancerInboundNatPool lbInboundNatPool : lbInboundNatPools.values()) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", lbInboundNatPool.name());
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
attachedInboundNatPools.put(lbInboundNatPool.name(), lbInboundNatPool);
}
}
}
return attachedInboundNatPools;
}
private static void associateLoadBalancerToIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
Collection<LoadBalancerBackend> backends = loadBalancer.backends().values();
String[] backendNames = new String[backends.size()];
int i = 0;
for (LoadBalancerBackend backend : backends) {
backendNames[i] = backend.name();
i++;
}
associateBackEndsToIpConfiguration(loadBalancer.id(),
ipConfig,
backendNames);
Collection<LoadBalancerInboundNatPool> inboundNatPools = loadBalancer.inboundNatPools().values();
String[] natPoolNames = new String[inboundNatPools.size()];
i = 0;
for (LoadBalancerInboundNatPool inboundNatPool : inboundNatPools) {
natPoolNames[i] = inboundNatPool.name();
i++;
}
associateInboundNATPoolsToIpConfiguration(loadBalancer.id(),
ipConfig,
natPoolNames);
}
private static void removeLoadBalancerAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
removeAllBackendAssociationFromIpConfiguration(loadBalancer, ipConfig);
removeAllInboundNatPoolAssociationFromIpConfiguration(loadBalancer, ipConfig);
}
private static void removeAllBackendAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
List<SubResource> toRemove = new ArrayList<>();
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().toLowerCase().startsWith(loadBalancer.id().toLowerCase() + "/")) {
toRemove.add(subResource);
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerBackendAddressPools().remove(subResource);
}
}
private static void removeAllInboundNatPoolAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
List<SubResource> toRemove = new ArrayList<>();
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().toLowerCase().startsWith(loadBalancer.id().toLowerCase() + "/")) {
toRemove.add(subResource);
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerInboundNatPools().remove(subResource);
}
}
private static void removeBackendsFromIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... backendNames) {
List<SubResource> toRemove = new ArrayList<>();
for (String backendName : backendNames) {
String backendPoolId = mergePath(loadBalancerId, "backendAddressPools", backendName);
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendPoolId)) {
toRemove.add(subResource);
break;
}
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerBackendAddressPools().remove(subResource);
}
}
private static void removeInboundNatPoolsFromIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... inboundNatPoolNames) {
List<SubResource> toRemove = new ArrayList<>();
for (String natPoolName : inboundNatPoolNames) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", natPoolName);
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
toRemove.add(subResource);
break;
}
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerInboundNatPools().remove(subResource);
}
}
private static <T> void addToList(List<T> list, T...items) {
for (T item : items) {
list.add(item);
}
}
private static String mergePath(String... segments) {
StringBuilder builder = new StringBuilder();
for (String segment : segments) {
while (segment.length() > 1 && segment.endsWith("/")) {
segment = segment.substring(0, segment.length() - 1);
}
if (segment.length() > 0) {
builder.append(segment);
builder.append("/");
}
}
String merged = builder.toString();
if (merged.endsWith("/")) {
merged = merged.substring(0, merged.length() - 1);
}
return merged;
}
protected VirtualMachineScaleSetImpl withUnmanagedDataDisk(VirtualMachineScaleSetUnmanagedDataDiskImpl unmanagedDisk) {
if (this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks() == null) {
this.inner()
.virtualMachineProfile()
.storageProfile()
.withDataDisks(new ArrayList<VirtualMachineScaleSetDataDisk>());
}
List<VirtualMachineScaleSetDataDisk> dataDisks = this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks();
dataDisks.add(unmanagedDisk.inner());
return this;
}
/**
* Checks whether the OS disk is based on an image (image from PIR or custom image [captured, bringYourOwnFeature]).
*
* @param osDisk the osDisk value in the storage profile
* @return true if the OS disk is configured to use image from PIR or custom image
*/
private boolean isOSDiskFromImage(VirtualMachineScaleSetOSDisk osDisk) {
return osDisk.createOption() == DiskCreateOptionTypes.FROM_IMAGE;
}
/**
* Checks whether the OS disk is based on a CustomImage.
* <p>
* A custom image is represented by {@link com.microsoft.azure.management.compute.VirtualMachineCustomImage}.
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to be based on custom image.
*/
private boolean isOsDiskFromCustomImage(VirtualMachineScaleSetStorageProfile storageProfile) {
ImageReferenceInner imageReference = storageProfile.imageReference();
return isOSDiskFromImage(storageProfile.osDisk())
&& imageReference != null
&& imageReference.id() != null;
}
/**
* Checks whether the OS disk is based on an platform image (image in PIR).
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to be based on platform image.
*/
private boolean isOSDiskFromPlatformImage(VirtualMachineScaleSetStorageProfile storageProfile) {
ImageReferenceInner imageReference = storageProfile.imageReference();
return isOSDiskFromImage(storageProfile.osDisk())
&& imageReference != null
&& imageReference.publisher() != null
&& imageReference.offer() != null
&& imageReference.sku() != null
&& imageReference.version() != null;
}
/**
* Checks whether the OS disk is based on a stored image ('captured' or 'bring your own feature').
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to use custom image ('captured' or 'bring your own feature')
*/
private boolean isOSDiskFromStoredImage(VirtualMachineScaleSetStorageProfile storageProfile) {
VirtualMachineScaleSetOSDisk osDisk = storageProfile.osDisk();
return isOSDiskFromImage(osDisk)
&& osDisk.image() != null
&& osDisk.image().uri() != null;
}
/* TODO Unused
private void throwIfManagedDiskEnabled(String message) {
if (this.isManagedDiskEnabled()) {
throw new UnsupportedOperationException(message);
}
}*/
private void throwIfManagedDiskDisabled(String message) {
if (!this.isManagedDiskEnabled()) {
throw new UnsupportedOperationException(message);
}
}
/**
* Class to manage Data Disk collection.
*/
private class ManagedDataDiskCollection {
private final List<VirtualMachineScaleSetDataDisk> implicitDisksToAssociate = new ArrayList<>();
private final List<Integer> diskLunsToRemove = new ArrayList<>();
private final List<VirtualMachineScaleSetDataDisk> newDisksFromImage = new ArrayList<>();
private final VirtualMachineScaleSetImpl vmss;
private CachingTypes defaultCachingType;
private StorageAccountTypes defaultStorageAccountType;
ManagedDataDiskCollection(VirtualMachineScaleSetImpl vmss) {
this.vmss = vmss;
}
void setDefaultCachingType(CachingTypes cachingType) {
this.defaultCachingType = cachingType;
}
void setDefaultStorageAccountType(StorageAccountTypes defaultStorageAccountType) {
this.defaultStorageAccountType = defaultStorageAccountType;
}
void setDataDisksDefaults() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
if (isPending()) {
if (storageProfile.dataDisks() == null) {
storageProfile.withDataDisks(new ArrayList<VirtualMachineScaleSetDataDisk>());
}
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
final List<Integer> usedLuns = new ArrayList<>();
// Get all used luns
//
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
for (VirtualMachineScaleSetDataDisk dataDisk : this.implicitDisksToAssociate) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
for (VirtualMachineScaleSetDataDisk dataDisk : this.newDisksFromImage) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
// Func to get the next available lun
//
Func0<Integer> nextLun = new Func0<Integer>() {
@Override
public Integer call() {
Integer lun = 0;
while (usedLuns.contains(lun)) {
lun++;
}
usedLuns.add(lun);
return lun;
}
};
setImplicitDataDisks(nextLun);
setImageBasedDataDisks();
removeDataDisks();
}
if (storageProfile.dataDisks() != null
&& storageProfile.dataDisks().size() == 0) {
if (vmss.isInCreateMode()) {
// If there is no data disks at all, then setting it to null rather than [] is necessary.
// This is for take advantage of CRP's implicit creation of the data disks if the image has
// more than one data disk image(s).
//
storageProfile.withDataDisks(null);
}
}
this.clear();
}
private void clear() {
implicitDisksToAssociate.clear();
diskLunsToRemove.clear();
newDisksFromImage.clear();
}
private boolean isPending() {
return implicitDisksToAssociate.size() > 0
|| diskLunsToRemove.size() > 0
|| newDisksFromImage.size() > 0;
}
private void setImplicitDataDisks(Func0<Integer> nextLun) {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (VirtualMachineScaleSetDataDisk dataDisk : this.implicitDisksToAssociate) {
dataDisk.withCreateOption(DiskCreateOptionTypes.EMPTY);
if (dataDisk.lun() == -1) {
dataDisk.withLun(nextLun.call());
}
if (dataDisk.managedDisk() == null) {
dataDisk.withManagedDisk(new VirtualMachineScaleSetManagedDiskParameters());
}
if (dataDisk.caching() == null) {
dataDisk.withCaching(getDefaultCachingType());
}
if (dataDisk.managedDisk().storageAccountType() == null) {
dataDisk.managedDisk().withStorageAccountType(getDefaultStorageAccountType());
}
dataDisk.withName(null);
dataDisks.add(dataDisk);
}
}
private void setImageBasedDataDisks() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (VirtualMachineScaleSetDataDisk dataDisk : this.newDisksFromImage) {
dataDisk.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
// Don't set default storage account type for the disk, either user has to specify it explicitly or let
// CRP pick it from the image
dataDisk.withName(null);
dataDisks.add(dataDisk);
}
}
private void removeDataDisks() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (Integer lun : this.diskLunsToRemove) {
int indexToRemove = 0;
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() == lun) {
dataDisks.remove(indexToRemove);
break;
}
indexToRemove++;
}
}
}
private CachingTypes getDefaultCachingType() {
if (defaultCachingType == null) {
return CachingTypes.READ_WRITE;
}
return defaultCachingType;
}
private StorageAccountTypes getDefaultStorageAccountType() {
if (defaultStorageAccountType == null) {
return StorageAccountTypes.STANDARD_LRS;
}
return defaultStorageAccountType;
}
}
}
|
azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineScaleSetImpl.java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.compute.implementation;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.compute.ApiEntityReference;
import com.microsoft.azure.management.compute.CachingTypes;
import com.microsoft.azure.management.compute.DiskCreateOptionTypes;
import com.microsoft.azure.management.compute.ImageReference;
import com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage;
import com.microsoft.azure.management.compute.KnownWindowsVirtualMachineImage;
import com.microsoft.azure.management.compute.LinuxConfiguration;
import com.microsoft.azure.management.compute.OperatingSystemTypes;
import com.microsoft.azure.management.compute.SshConfiguration;
import com.microsoft.azure.management.compute.SshPublicKey;
import com.microsoft.azure.management.compute.StorageAccountTypes;
import com.microsoft.azure.management.compute.UpgradeMode;
import com.microsoft.azure.management.compute.UpgradePolicy;
import com.microsoft.azure.management.compute.VirtualHardDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSet;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetDataDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetExtension;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetExtensionProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetManagedDiskParameters;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetNetworkProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetOSDisk;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetOSProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetSku;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetSkuTypes;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetStorageProfile;
import com.microsoft.azure.management.compute.VirtualMachineScaleSetVMs;
import com.microsoft.azure.management.compute.WinRMConfiguration;
import com.microsoft.azure.management.compute.WinRMListener;
import com.microsoft.azure.management.compute.WindowsConfiguration;
import com.microsoft.azure.management.network.LoadBalancerBackend;
import com.microsoft.azure.management.network.LoadBalancerFrontend;
import com.microsoft.azure.management.network.LoadBalancerInboundNatPool;
import com.microsoft.azure.management.network.LoadBalancer;
import com.microsoft.azure.management.network.Network;
import com.microsoft.azure.management.network.VirtualMachineScaleSetNetworkInterface;
import com.microsoft.azure.management.network.implementation.NetworkManager;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils;
import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.GroupableParentResourceImpl;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter;
import com.microsoft.azure.management.resources.fluentcore.utils.ResourceNamer;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.azure.management.resources.fluentcore.utils.Utils;
import com.microsoft.azure.management.storage.StorageAccount;
import com.microsoft.azure.management.storage.implementation.StorageManager;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import rx.Completable;
import rx.Observable;
import rx.functions.Func0;
import rx.functions.Func1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of VirtualMachineScaleSet.
*/
@LangDefinition
public class VirtualMachineScaleSetImpl
extends GroupableParentResourceImpl<
VirtualMachineScaleSet,
VirtualMachineScaleSetInner,
VirtualMachineScaleSetImpl,
ComputeManager>
implements
VirtualMachineScaleSet,
VirtualMachineScaleSet.DefinitionManagedOrUnmanaged,
VirtualMachineScaleSet.DefinitionManaged,
VirtualMachineScaleSet.DefinitionUnmanaged,
VirtualMachineScaleSet.Update {
// Clients
private final StorageManager storageManager;
private final NetworkManager networkManager;
// used to generate unique name for any dependency resources
private final ResourceNamer namer;
private boolean isMarketplaceLinuxImage = false;
// name of an existing subnet in the primary network to use
private String existingPrimaryNetworkSubnetNameToAssociate;
// unique key of a creatable storage accounts to be used for virtual machines child resources that
// requires storage [OS disk]
private List<String> creatableStorageAccountKeys = new ArrayList<>();
// reference to an existing storage account to be used for virtual machines child resources that
// requires storage [OS disk]
private List<StorageAccount> existingStorageAccountsToAssociate = new ArrayList<>();
// Name of the container in the storage account to use to store the disks
private String vhdContainerName;
// the child resource extensions
private Map<String, VirtualMachineScaleSetExtension> extensions;
// reference to the primary and internal Internet facing load balancer
private LoadBalancer primaryInternetFacingLoadBalancer;
private LoadBalancer primaryInternalLoadBalancer;
// Load balancer specific variables used during update
private boolean removePrimaryInternetFacingLoadBalancerOnUpdate;
private boolean removePrimaryInternalLoadBalancerOnUpdate;
private LoadBalancer primaryInternetFacingLoadBalancerToAttachOnUpdate;
private LoadBalancer primaryInternalLoadBalancerToAttachOnUpdate;
private List<String> primaryInternetFacingLBBackendsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBBackendsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBInboundNatPoolsToRemoveOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBBackendsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternetFacingLBInboundNatPoolsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBBackendsToAddOnUpdate = new ArrayList<>();
private List<String> primaryInternalLBInboundNatPoolsToAddOnUpdate = new ArrayList<>();
// The paged converter for virtual machine scale set sku
private PagedListConverter<VirtualMachineScaleSetSkuInner, VirtualMachineScaleSetSku> skuConverter;
// Flag indicates native disk is selected for OS and Data disks
private boolean isUnmanagedDiskSelected;
// To track the managed data disks
private final ManagedDataDiskCollection managedDataDisks;
VirtualMachineScaleSetImpl(
String name,
VirtualMachineScaleSetInner innerModel,
final ComputeManager computeManager,
final StorageManager storageManager,
final NetworkManager networkManager) {
super(name, innerModel, computeManager);
this.storageManager = storageManager;
this.networkManager = networkManager;
this.namer = SdkContext.getResourceNamerFactory().createResourceNamer(this.name());
this.skuConverter = new PagedListConverter<VirtualMachineScaleSetSkuInner, VirtualMachineScaleSetSku>() {
@Override
public VirtualMachineScaleSetSku typeConvert(VirtualMachineScaleSetSkuInner inner) {
return new VirtualMachineScaleSetSkuImpl(inner);
}
};
this.managedDataDisks = new ManagedDataDiskCollection(this);
}
@Override
protected void initializeChildrenFromInner() {
this.extensions = new HashMap<>();
if (this.inner().virtualMachineProfile().extensionProfile() != null) {
if (this.inner().virtualMachineProfile().extensionProfile().extensions() != null) {
for (VirtualMachineScaleSetExtensionInner inner : this.inner().virtualMachineProfile().extensionProfile().extensions()) {
this.extensions.put(inner.name(), new VirtualMachineScaleSetExtensionImpl(inner, this));
}
}
}
}
@Override
public VirtualMachineScaleSetVMs virtualMachines() {
return new VirtualMachineScaleSetVMsImpl(this, this.manager().inner().virtualMachineScaleSetVMs(), this.myManager);
}
@Override
public PagedList<VirtualMachineScaleSetSku> listAvailableSkus() {
return this.skuConverter.convert(this.manager().inner().virtualMachineScaleSets().listSkus(this.resourceGroupName(), this.name()));
}
@Override
public void deallocate() {
this.deallocateAsync().await();
}
@Override
public Completable deallocateAsync() {
Observable<OperationStatusResponseInner> d = this.manager().inner().virtualMachineScaleSets().deallocateAsync(this.resourceGroupName(), this.name());
Observable<VirtualMachineScaleSet> r = this.refreshAsync();
return Observable.concat(d, r).toCompletable();
}
@Override
public ServiceFuture<Void> deallocateAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.deallocateAsync().<Void>toObservable(), callback);
}
@Override
public void powerOff() {
this.powerOffAsync().await();
}
@Override
public Completable powerOffAsync() {
return this.manager().inner().virtualMachineScaleSets().powerOffAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> powerOffAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.powerOffAsync().<Void>toObservable(), callback);
}
@Override
public void restart() {
this.restartAsync().await();
}
@Override
public Completable restartAsync() {
return this.manager().inner().virtualMachineScaleSets().restartAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> restartAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.restartAsync().<Void>toObservable(), callback);
}
@Override
public void start() {
this.startAsync().await();
}
@Override
public Completable startAsync() {
return this.manager().inner().virtualMachineScaleSets().startAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> startAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.startAsync().<Void>toObservable(), callback);
}
@Override
public void reimage() {
this.reimageAsync().await();
}
@Override
public Completable reimageAsync() {
return this.manager().inner().virtualMachineScaleSets().reimageAsync(this.resourceGroupName(), this.name()).toCompletable();
}
@Override
public ServiceFuture<Void> reimageAsync(ServiceCallback<Void> callback) {
return ServiceFuture.fromBody(this.reimageAsync().<Void>toObservable(), callback);
}
@Override
public String computerNamePrefix() {
return this.inner().virtualMachineProfile().osProfile().computerNamePrefix();
}
@Override
public OperatingSystemTypes osType() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().osType();
}
@Override
public CachingTypes osDiskCachingType() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().caching();
}
@Override
public String osDiskName() {
return this.inner().virtualMachineProfile().storageProfile().osDisk().name();
}
@Override
public UpgradeMode upgradeModel() {
// upgradePolicy is a required property so no null check
return this.inner().upgradePolicy().mode();
}
@Override
public boolean overProvisionEnabled() {
return this.inner().overprovision();
}
@Override
public VirtualMachineScaleSetSkuTypes sku() {
return VirtualMachineScaleSetSkuTypes.fromSku(this.inner().sku());
}
@Override
public long capacity() {
return Utils.toPrimitiveLong(this.inner().sku().capacity());
}
@Override
public Network getPrimaryNetwork() throws IOException {
String subnetId = primaryNicDefaultIPConfiguration().subnet().id();
String virtualNetworkId = ResourceUtils.parentResourceIdFromResourceId(subnetId);
return this.networkManager
.networks()
.getById(virtualNetworkId);
}
@Override
public LoadBalancer getPrimaryInternetFacingLoadBalancer() throws IOException {
if (this.primaryInternetFacingLoadBalancer == null) {
loadCurrentPrimaryLoadBalancersIfAvailable();
}
return this.primaryInternetFacingLoadBalancer;
}
@Override
public Map<String, LoadBalancerBackend> listPrimaryInternetFacingLoadBalancerBackends() throws IOException {
if (this.getPrimaryInternetFacingLoadBalancer() != null) {
return getBackendsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public Map<String, LoadBalancerInboundNatPool> listPrimaryInternetFacingLoadBalancerInboundNatPools() throws IOException {
if (this.getPrimaryInternetFacingLoadBalancer() != null) {
return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternetFacingLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public LoadBalancer getPrimaryInternalLoadBalancer() throws IOException {
if (this.primaryInternalLoadBalancer == null) {
loadCurrentPrimaryLoadBalancersIfAvailable();
}
return this.primaryInternalLoadBalancer;
}
@Override
public Map<String, LoadBalancerBackend> listPrimaryInternalLoadBalancerBackends() throws IOException {
if (this.getPrimaryInternalLoadBalancer() != null) {
return getBackendsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public Map<String, LoadBalancerInboundNatPool> listPrimaryInternalLoadBalancerInboundNatPools() throws IOException {
if (this.getPrimaryInternalLoadBalancer() != null) {
return getInboundNatPoolsAssociatedWithIpConfiguration(this.primaryInternalLoadBalancer,
primaryNicDefaultIPConfiguration());
}
return new HashMap<>();
}
@Override
public List<String> primaryPublicIPAddressIds() throws IOException {
LoadBalancer loadBalancer = this.getPrimaryInternetFacingLoadBalancer();
if (loadBalancer != null) {
return loadBalancer.publicIPAddressIds();
}
return new ArrayList<>();
}
@Override
public List<String> vhdContainers() {
if (this.storageProfile() != null
&& this.storageProfile().osDisk() != null
&& this.storageProfile().osDisk().vhdContainers() != null) {
return this.storageProfile().osDisk().vhdContainers();
}
return new ArrayList<>();
}
@Override
public VirtualMachineScaleSetStorageProfile storageProfile() {
return this.inner().virtualMachineProfile().storageProfile();
}
@Override
public VirtualMachineScaleSetNetworkProfile networkProfile() {
return this.inner().virtualMachineProfile().networkProfile();
}
@Override
public Map<String, VirtualMachineScaleSetExtension> extensions() {
return Collections.unmodifiableMap(this.extensions);
}
@Override
public VirtualMachineScaleSetNetworkInterface getNetworkInterfaceByInstanceId(String instanceId, String name) {
return this.networkManager.networkInterfaces().getByVirtualMachineScaleSetInstanceId(this.resourceGroupName(),
this.name(),
instanceId,
name);
}
@Override
public PagedList<VirtualMachineScaleSetNetworkInterface> listNetworkInterfaces() {
return this.networkManager.networkInterfaces()
.listByVirtualMachineScaleSet(this.resourceGroupName(), this.name());
}
@Override
public PagedList<VirtualMachineScaleSetNetworkInterface> listNetworkInterfacesByInstanceId(String virtualMachineInstanceId) {
return this.networkManager.networkInterfaces()
.listByVirtualMachineScaleSetInstanceId(this.resourceGroupName(),
this.name(),
virtualMachineInstanceId);
}
// Fluent setters
@Override
public VirtualMachineScaleSetImpl withSku(VirtualMachineScaleSetSkuTypes skuType) {
this.inner()
.withSku(skuType.sku());
return this;
}
@Override
public VirtualMachineScaleSetImpl withSku(VirtualMachineScaleSetSku sku) {
return this.withSku(sku.skuType());
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryNetworkSubnet(Network network, String subnetName) {
this.existingPrimaryNetworkSubnetNameToAssociate = mergePath(network.id(), "subnets", subnetName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryInternetFacingLoadBalancer(LoadBalancer loadBalancer) {
if (loadBalancer.publicIPAddressIds().isEmpty()) {
throw new IllegalArgumentException("Parameter loadBalancer must be an Internet facing load balancer");
}
if (isInCreateMode()) {
this.primaryInternetFacingLoadBalancer = loadBalancer;
associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancer,
this.primaryNicDefaultIPConfiguration());
} else {
this.primaryInternetFacingLoadBalancerToAttachOnUpdate = loadBalancer;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerBackends(String... backendNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllBackendAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, defaultPrimaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
defaultPrimaryIpConfig,
backendNames);
} else {
addToList(this.primaryInternetFacingLBBackendsToAddOnUpdate, backendNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternetFacingLoadBalancerInboundNatPools(String... natPoolNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer,
defaultPrimaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
defaultPrimaryIpConfig,
natPoolNames);
} else {
addToList(this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate, natPoolNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingPrimaryInternalLoadBalancer(LoadBalancer loadBalancer) {
if (!loadBalancer.publicIPAddressIds().isEmpty()) {
throw new IllegalArgumentException("Parameter loadBalancer must be an internal load balancer");
}
String lbNetworkId = null;
for (LoadBalancerFrontend frontEnd : loadBalancer.frontends().values()) {
if (frontEnd.inner().subnet().id() != null) {
lbNetworkId = ResourceUtils.parentResourceIdFromResourceId(frontEnd.inner().subnet().id());
}
}
if (isInCreateMode()) {
String vmNICNetworkId = ResourceUtils.parentResourceIdFromResourceId(this.existingPrimaryNetworkSubnetNameToAssociate);
// Azure has a really wired BUG that - it throws exception when vnet of VMSS and LB are not same
// (code: NetworkInterfaceAndInternalLoadBalancerMustUseSameVnet) but at the same time Azure update
// the VMSS's network section to refer this invalid internal LB. This makes VMSS un-usable and portal
// will show a error above VMSS profile page.
//
if (!vmNICNetworkId.equalsIgnoreCase(lbNetworkId)) {
throw new IllegalArgumentException("Virtual network associated with scale set virtual machines"
+ " and internal load balancer must be same. "
+ "'" + vmNICNetworkId + "'"
+ "'" + lbNetworkId);
}
this.primaryInternalLoadBalancer = loadBalancer;
associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancer,
this.primaryNicDefaultIPConfiguration());
} else {
String vmNicVnetId = ResourceUtils.parentResourceIdFromResourceId(primaryNicDefaultIPConfiguration()
.subnet()
.id());
if (!vmNicVnetId.equalsIgnoreCase(lbNetworkId)) {
throw new IllegalArgumentException("Virtual network associated with scale set virtual machines"
+ " and internal load balancer must be same. "
+ "'" + vmNicVnetId + "'"
+ "'" + lbNetworkId);
}
this.primaryInternalLoadBalancerToAttachOnUpdate = loadBalancer;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerBackends(String... backendNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = primaryNicDefaultIPConfiguration();
removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancer,
defaultPrimaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancer.id(),
defaultPrimaryIpConfig,
backendNames);
} else {
addToList(this.primaryInternalLBBackendsToAddOnUpdate, backendNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withPrimaryInternalLoadBalancerInboundNatPools(String... natPoolNames) {
if (this.isInCreateMode()) {
VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIpConfig = this.primaryNicDefaultIPConfiguration();
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternalLoadBalancer,
defaultPrimaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancer.id(),
defaultPrimaryIpConfig,
natPoolNames);
} else {
addToList(this.primaryInternalLBInboundNatPoolsToAddOnUpdate, natPoolNames);
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancer() {
if (this.isInUpdateMode()) {
this.removePrimaryInternalLoadBalancerOnUpdate = true;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancer() {
if (this.isInUpdateMode()) {
this.removePrimaryInternetFacingLoadBalancerOnUpdate = true;
}
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancerBackends(String ...backendNames) {
addToList(this.primaryInternetFacingLBBackendsToRemoveOnUpdate, backendNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancerBackends(String ...backendNames) {
addToList(this.primaryInternalLBBackendsToRemoveOnUpdate, backendNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternetFacingLoadBalancerNatPools(String ...natPoolNames) {
addToList(this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate, natPoolNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutPrimaryInternalLoadBalancerNatPools(String ...natPoolNames) {
addToList(this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate, natPoolNames);
return this;
}
@Override
public VirtualMachineScaleSetImpl withPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage) {
return withSpecificWindowsImageVersion(knownImage.imageReference());
}
@Override
public VirtualMachineScaleSetImpl withLatestWindowsImage(String publisher, String offer, String sku) {
ImageReference imageReference = new ImageReference()
.withPublisher(publisher)
.withOffer(offer)
.withSku(sku)
.withVersion("latest");
return withSpecificWindowsImageVersion(imageReference);
}
@Override
public VirtualMachineScaleSetImpl withSpecificWindowsImageVersion(ImageReference imageReference) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReference.inner());
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withWindowsCustomImage(String customImageId) {
ImageReferenceInner imageReferenceInner = new ImageReferenceInner();
imageReferenceInner.withId(customImageId);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReferenceInner);
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withStoredWindowsImage(String imageUrl) {
VirtualHardDisk userImageVhd = new VirtualHardDisk();
userImageVhd.withUri(imageUrl);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withImage(userImageVhd);
// For platform image osType will be null, azure will pick it from the image metadata.
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withOsType(OperatingSystemTypes.WINDOWS);
this.inner()
.virtualMachineProfile()
.osProfile().withWindowsConfiguration(new WindowsConfiguration());
// sets defaults for "Stored(Custom)Image" or "VM(Platform)Image"
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withPopularLinuxImage(KnownLinuxVirtualMachineImage knownImage) {
return withSpecificLinuxImageVersion(knownImage.imageReference());
}
@Override
public VirtualMachineScaleSetImpl withLatestLinuxImage(String publisher, String offer, String sku) {
ImageReference imageReference = new ImageReference()
.withPublisher(publisher)
.withOffer(offer)
.withSku(sku)
.withVersion("latest");
return withSpecificLinuxImageVersion(imageReference);
}
@Override
public VirtualMachineScaleSetImpl withSpecificLinuxImageVersion(ImageReference imageReference) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReference.inner());
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
this.isMarketplaceLinuxImage = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withLinuxCustomImage(String customImageId) {
ImageReferenceInner imageReferenceInner = new ImageReferenceInner();
imageReferenceInner.withId(customImageId);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().withImageReference(imageReferenceInner);
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
this.isMarketplaceLinuxImage = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withStoredLinuxImage(String imageUrl) {
VirtualHardDisk userImageVhd = new VirtualHardDisk();
userImageVhd.withUri(imageUrl);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withImage(userImageVhd);
// For platform image osType will be null, azure will pick it from the image metadata.
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withOsType(OperatingSystemTypes.LINUX);
this.inner()
.virtualMachineProfile()
.osProfile().withLinuxConfiguration(new LinuxConfiguration());
return this;
}
@Override
public VirtualMachineScaleSetImpl withAdminUsername(String adminUserName) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminUsername(adminUserName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withRootUsername(String adminUserName) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminUsername(adminUserName);
return this;
}
@Override
public VirtualMachineScaleSetImpl withAdminPassword(String password) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminPassword(password);
return this;
}
@Override
public VirtualMachineScaleSetImpl withRootPassword(String password) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withAdminPassword(password);
return this;
}
@Override
public VirtualMachineScaleSetImpl withSsh(String publicKeyData) {
VirtualMachineScaleSetOSProfile osProfile = this.inner()
.virtualMachineProfile()
.osProfile();
if (osProfile.linuxConfiguration().ssh() == null) {
SshConfiguration sshConfiguration = new SshConfiguration();
sshConfiguration.withPublicKeys(new ArrayList<SshPublicKey>());
osProfile.linuxConfiguration().withSsh(sshConfiguration);
}
SshPublicKey sshPublicKey = new SshPublicKey();
sshPublicKey.withKeyData(publicKeyData);
sshPublicKey.withPath("/home/" + osProfile.adminUsername() + "/.ssh/authorized_keys");
osProfile.linuxConfiguration().ssh().publicKeys().add(sshPublicKey);
return this;
}
@Override
public VirtualMachineScaleSetImpl withVMAgent() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutVMAgent() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withProvisionVMAgent(false);
return this;
}
@Override
public VirtualMachineScaleSetImpl withAutoUpdate() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(true);
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutAutoUpdate() {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withEnableAutomaticUpdates(false);
return this;
}
@Override
public VirtualMachineScaleSetImpl withTimeZone(String timeZone) {
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withTimeZone(timeZone);
return this;
}
@Override
public VirtualMachineScaleSetImpl withWinRM(WinRMListener listener) {
if (this.inner().virtualMachineProfile().osProfile().windowsConfiguration().winRM() == null) {
WinRMConfiguration winRMConfiguration = new WinRMConfiguration();
this.inner()
.virtualMachineProfile()
.osProfile().windowsConfiguration().withWinRM(winRMConfiguration);
}
this.inner()
.virtualMachineProfile()
.osProfile()
.windowsConfiguration()
.winRM()
.listeners()
.add(listener);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskCaching(CachingTypes cachingType) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withCaching(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskName(String name) {
this.inner()
.virtualMachineProfile()
.storageProfile().osDisk().withName(name);
return this;
}
@Override
public VirtualMachineScaleSetImpl withComputerNamePrefix(String namePrefix) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withComputerNamePrefix(namePrefix);
return this;
}
@Override
public VirtualMachineScaleSetImpl withUpgradeMode(UpgradeMode upgradeMode) {
this.inner()
.upgradePolicy()
.withMode(upgradeMode);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOverProvision(boolean enabled) {
this.inner()
.withOverprovision(enabled);
return this;
}
@Override
public VirtualMachineScaleSetImpl withOverProvisioning() {
return this.withOverProvision(true);
}
@Override
public VirtualMachineScaleSetImpl withoutOverProvisioning() {
return this.withOverProvision(false);
}
@Override
public VirtualMachineScaleSetImpl withCapacity(int capacity) {
this.inner()
.sku().withCapacity(new Long(capacity));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewStorageAccount(String name) {
StorageAccount.DefinitionStages.WithGroup definitionWithGroup = this.storageManager
.storageAccounts()
.define(name)
.withRegion(this.regionName());
Creatable<StorageAccount> definitionAfterGroup;
if (this.creatableGroup != null) {
definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
} else {
definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
}
return withNewStorageAccount(definitionAfterGroup);
}
@Override
public VirtualMachineScaleSetImpl withNewStorageAccount(Creatable<StorageAccount> creatable) {
this.creatableStorageAccountKeys.add(creatable.key());
this.addCreatableDependency(creatable);
return this;
}
@Override
public VirtualMachineScaleSetImpl withExistingStorageAccount(StorageAccount storageAccount) {
this.existingStorageAccountsToAssociate.add(storageAccount);
return this;
}
@Override
public VirtualMachineScaleSetImpl withCustomData(String base64EncodedCustomData) {
this.inner()
.virtualMachineProfile()
.osProfile()
.withCustomData(base64EncodedCustomData);
return this;
}
@Override
public VirtualMachineScaleSetExtensionImpl defineNewExtension(String name) {
return new VirtualMachineScaleSetExtensionImpl(new VirtualMachineScaleSetExtensionInner().withName(name), this);
}
protected VirtualMachineScaleSetImpl withExtension(VirtualMachineScaleSetExtensionImpl extension) {
this.extensions.put(extension.name(), extension);
return this;
}
@Override
public VirtualMachineScaleSetExtensionImpl updateExtension(String name) {
return (VirtualMachineScaleSetExtensionImpl) this.extensions.get(name);
}
@Override
public VirtualMachineScaleSetImpl withoutExtension(String name) {
if (this.extensions.containsKey(name)) {
this.extensions.remove(name);
}
return this;
}
@Override
public boolean isManagedDiskEnabled() {
VirtualMachineScaleSetStorageProfile storageProfile = this.inner().virtualMachineProfile().storageProfile();
if (isOsDiskFromCustomImage(storageProfile)) {
return true;
}
if (isOSDiskFromStoredImage(storageProfile)) {
return false;
}
if (isOSDiskFromPlatformImage(storageProfile)) {
if (this.isUnmanagedDiskSelected) {
return false;
}
}
if (isInCreateMode()) {
return true;
} else {
List<String> vhdContainers = storageProfile
.osDisk()
.vhdContainers();
return vhdContainers == null || vhdContainers.size() == 0;
}
}
@Override
public VirtualMachineScaleSetImpl withUnmanagedDisks() {
this.isUnmanagedDiskSelected = true;
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(-1)
.withDiskSizeGB(sizeInGB));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB,
int lun,
CachingTypes cachingType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(lun)
.withDiskSizeGB(sizeInGB)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDisk(int sizeInGB,
int lun,
CachingTypes cachingType,
StorageAccountTypes storageAccountType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_BOTH_UNMANAGED_AND_MANAGED_DISK_NOT_ALLOWED);
VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters();
managedDiskParameters.withStorageAccountType(storageAccountType);
this.managedDataDisks.implicitDisksToAssociate.add(new VirtualMachineScaleSetDataDisk()
.withLun(lun)
.withDiskSizeGB(sizeInGB)
.withCaching(cachingType)
.withManagedDisk(managedDiskParameters));
return this;
}
@Override
public VirtualMachineScaleSetImpl withoutDataDisk(int lun) {
if (!isManagedDiskEnabled()) {
return this;
}
this.managedDataDisks.diskLunsToRemove.add(lun);
return this;
}
/* TODO: Broken by change in Azure API behavior
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, CachingTypes cachingType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskUpdated(int lun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) {
throwIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_NO_MANAGED_DISK_TO_UPDATE);
VirtualMachineScaleSetDataDisk dataDisk = getDataDiskInner(lun);
if (dataDisk == null) {
throw new RuntimeException(String.format("A data disk with lun '%d' not found", lun));
}
dataDisk
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType)
.managedDisk()
.withStorageAccountType(storageAccountType);
return this;
}
private VirtualMachineScaleSetDataDisk getDataDiskInner(int lun) {
VirtualMachineScaleSetStorageProfile storageProfile = this
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile
.dataDisks();
if (dataDisks == null) {
return null;
}
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() == lun) {
return dataDisk;
}
}
return null;
}
*/
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun) {
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun,
int newSizeInGB,
CachingTypes cachingType) {
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun)
.withDiskSizeGB(newSizeInGB)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withNewDataDiskFromImage(int imageLun,
int newSizeInGB,
CachingTypes cachingType,
StorageAccountTypes storageAccountType) {
VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters();
managedDiskParameters.withStorageAccountType(storageAccountType);
this.managedDataDisks.newDisksFromImage.add(new VirtualMachineScaleSetDataDisk()
.withLun(imageLun)
.withDiskSizeGB(newSizeInGB)
.withManagedDisk(managedDiskParameters)
.withCaching(cachingType));
return this;
}
@Override
public VirtualMachineScaleSetImpl withOSDiskStorageAccountType(StorageAccountTypes accountType) {
this.managedDataDisks.setDefaultStorageAccountType(accountType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskDefaultCachingType(CachingTypes cachingType) {
this.managedDataDisks.setDefaultCachingType(cachingType);
return this;
}
@Override
public VirtualMachineScaleSetImpl withDataDiskDefaultStorageAccountType(StorageAccountTypes storageAccountType) {
this.managedDataDisks.setDefaultStorageAccountType(storageAccountType);
return this;
}
// Create Update specific methods
//
@Override
protected void beforeCreating() {
if (this.extensions.size() > 0) {
this.inner()
.virtualMachineProfile()
.withExtensionProfile(new VirtualMachineScaleSetExtensionProfile())
.extensionProfile()
.withExtensions(innersFromWrappers(this.extensions.values()));
}
}
@Override
protected Observable<VirtualMachineScaleSetInner> createInner() {
if (isInCreateMode()) {
this.setOSProfileDefaults();
this.setOSDiskDefault();
}
this.setPrimaryIpConfigurationSubnet();
this.setPrimaryIpConfigurationBackendsAndInboundNatPools();
if (isManagedDiskEnabled()) {
this.managedDataDisks.setDataDisksDefaults();
} else {
List<VirtualMachineScaleSetDataDisk> dataDisks = this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks();
VirtualMachineScaleSetUnmanagedDataDiskImpl.setDataDisksDefaults(dataDisks, this.name());
}
final VirtualMachineScaleSetsInner client = this.manager().inner().virtualMachineScaleSets();
return this.handleOSDiskContainersAsync()
.flatMap(new Func1<Void, Observable<VirtualMachineScaleSetInner>>() {
@Override
public Observable<VirtualMachineScaleSetInner> call(Void aVoid) {
return client.createOrUpdateAsync(resourceGroupName(), name(), inner());
}
});
}
@Override
protected void afterCreating() {
this.clearCachedProperties();
this.initializeChildrenFromInner();
}
@Override
public Observable<VirtualMachineScaleSet> refreshAsync() {
return super.refreshAsync().map(new Func1<VirtualMachineScaleSet, VirtualMachineScaleSet>() {
@Override
public VirtualMachineScaleSet call(VirtualMachineScaleSet virtualMachineScaleSet) {
VirtualMachineScaleSetImpl impl = (VirtualMachineScaleSetImpl) virtualMachineScaleSet;
impl.clearCachedProperties();
impl.initializeChildrenFromInner();
return impl;
}
});
}
@Override
protected Observable<VirtualMachineScaleSetInner> getInnerAsync() {
return this.manager().inner().virtualMachineScaleSets().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
// Helpers
//
private boolean isInUpdateMode() {
return !this.isInCreateMode();
}
private void setOSProfileDefaults() {
if (isInUpdateMode()) {
return;
}
if (this.inner().sku().capacity() == null) {
this.withCapacity(2);
}
if (this.inner().upgradePolicy() == null
|| this.inner().upgradePolicy().mode() == null) {
this.inner()
.withUpgradePolicy(new UpgradePolicy()
.withMode(UpgradeMode.AUTOMATIC));
}
VirtualMachineScaleSetOSProfile osProfile = this.inner()
.virtualMachineProfile()
.osProfile();
VirtualMachineScaleSetOSDisk osDisk = this.inner().virtualMachineProfile().storageProfile().osDisk();
if (isOSDiskFromImage(osDisk)) {
// ODDisk CreateOption: FROM_IMAGE
//
if (this.osType() == OperatingSystemTypes.LINUX || this.isMarketplaceLinuxImage) {
if (osProfile.linuxConfiguration() == null) {
osProfile.withLinuxConfiguration(new LinuxConfiguration());
}
osProfile
.linuxConfiguration()
.withDisablePasswordAuthentication(osProfile.adminPassword() == null);
}
if (this.computerNamePrefix() == null) {
// VM name cannot contain only numeric values and cannot exceed 15 chars
if (this.name().matches("[0-9]+")) {
withComputerNamePrefix(this.namer.randomName("vmss-vm", 12));
} else if (this.name().length() <= 12) {
withComputerNamePrefix(this.name() + "-vm");
} else {
withComputerNamePrefix(this.namer.randomName("vmss-vm", 12));
}
}
} else {
// NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS]
this.inner()
.virtualMachineProfile()
.withOsProfile(null);
}
}
private void setOSDiskDefault() {
if (isInUpdateMode()) {
return;
}
VirtualMachineScaleSetStorageProfile storageProfile = this.inner().virtualMachineProfile().storageProfile();
VirtualMachineScaleSetOSDisk osDisk = storageProfile.osDisk();
if (isOSDiskFromImage(osDisk)) {
// ODDisk CreateOption: FROM_IMAGE
//
if (isManagedDiskEnabled()) {
// Note:
// Managed disk
// Supported: PlatformImage and CustomImage
// UnSupported: StoredImage
//
if (osDisk.managedDisk() == null) {
osDisk.withManagedDisk(new VirtualMachineScaleSetManagedDiskParameters());
}
if (osDisk.managedDisk().storageAccountType() == null) {
osDisk.managedDisk()
.withStorageAccountType(StorageAccountTypes.STANDARD_LRS);
}
osDisk.withVhdContainers(null);
// We won't set osDisk.name() explicitly for managed disk, if it is null CRP generates unique
// name for the disk resource within the resource group.
} else {
// Note:
// Native (un-managed) disk
// Supported: PlatformImage and StoredImage
// UnSupported: CustomImage
//
osDisk.withManagedDisk(null);
if (osDisk.name() == null) {
withOSDiskName(this.name() + "-os-disk");
}
}
} else {
// NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS]
}
if (this.osDiskCachingType() == null) {
withOSDiskCaching(CachingTypes.READ_WRITE);
}
}
private Observable<Void> handleOSDiskContainersAsync() {
final VirtualMachineScaleSetStorageProfile storageProfile = inner()
.virtualMachineProfile()
.storageProfile();
if (isManagedDiskEnabled()) {
storageProfile.osDisk()
.withVhdContainers(null);
return Observable.just(null);
}
if (isOSDiskFromStoredImage(storageProfile)) {
// There is a restriction currently that virtual machine's disk cannot be stored in multiple storage
// accounts if scale set is based on stored image. Remove this check once azure start supporting it.
//
storageProfile.osDisk()
.vhdContainers()
.clear();
return Observable.just(null);
}
if (this.isInCreateMode()
&& this.creatableStorageAccountKeys.isEmpty()
&& this.existingStorageAccountsToAssociate.isEmpty()) {
// If storage account(s) are not explicitly asked to create then create one implicitly
//
return Utils.<StorageAccount>rootResource(this.storageManager.storageAccounts()
.define(this.namer.randomName("stg", 24).replace("-", ""))
.withRegion(this.regionName())
.withExistingResourceGroup(this.resourceGroupName())
.createAsync())
.map(new Func1<StorageAccount, Void>() {
@Override
public Void call(StorageAccount storageAccount) {
String containerName = vhdContainerName;
if (containerName == null) {
containerName = "vhds";
}
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
vhdContainerName = null;
creatableStorageAccountKeys.clear();
existingStorageAccountsToAssociate.clear();
return null;
}
});
} else {
String containerName = this.vhdContainerName;
if (containerName == null) {
for (String containerUrl : storageProfile.osDisk().vhdContainers()) {
containerName = containerUrl.substring(containerUrl.lastIndexOf("/") + 1);
break;
}
}
if (containerName == null) {
containerName = "vhds";
}
for (String storageAccountKey : this.creatableStorageAccountKeys) {
StorageAccount storageAccount = (StorageAccount) createdResource(storageAccountKey);
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
}
for (StorageAccount storageAccount : this.existingStorageAccountsToAssociate) {
storageProfile.osDisk()
.vhdContainers()
.add(mergePath(storageAccount.endPoints().primary().blob(), containerName));
}
this.vhdContainerName = null;
this.creatableStorageAccountKeys.clear();
this.existingStorageAccountsToAssociate.clear();
return Observable.just(null);
}
}
private void setPrimaryIpConfigurationSubnet() {
if (isInUpdateMode()) {
return;
}
VirtualMachineScaleSetIPConfigurationInner ipConfig = this.primaryNicDefaultIPConfiguration();
ipConfig.withSubnet(new ApiEntityReference().withId(this.existingPrimaryNetworkSubnetNameToAssociate));
this.existingPrimaryNetworkSubnetNameToAssociate = null;
}
private void setPrimaryIpConfigurationBackendsAndInboundNatPools() {
if (isInCreateMode()) {
return;
}
try {
this.loadCurrentPrimaryLoadBalancersIfAvailable();
} catch (IOException ioException) {
throw new RuntimeException(ioException);
}
VirtualMachineScaleSetIPConfigurationInner primaryIpConfig = primaryNicDefaultIPConfiguration();
if (this.primaryInternetFacingLoadBalancer != null) {
removeBackendsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToRemoveOnUpdate.toArray(new String[0]));
associateBackEndsToIpConfiguration(primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0]));
removeInboundNatPoolsFromIpConfiguration(this.primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0]));
associateInboundNATPoolsToIpConfiguration(primaryInternetFacingLoadBalancer.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
if (this.primaryInternalLoadBalancer != null) {
removeBackendsFromIpConfiguration(this.primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToRemoveOnUpdate.toArray(new String[0]));
associateBackEndsToIpConfiguration(primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0]));
removeInboundNatPoolsFromIpConfiguration(this.primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.toArray(new String[0]));
associateInboundNATPoolsToIpConfiguration(primaryInternalLoadBalancer.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
if (this.removePrimaryInternetFacingLoadBalancerOnUpdate) {
if (this.primaryInternetFacingLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, primaryIpConfig);
}
}
if (this.removePrimaryInternalLoadBalancerOnUpdate) {
if (this.primaryInternalLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, primaryIpConfig);
}
}
if (this.primaryInternetFacingLoadBalancerToAttachOnUpdate != null) {
if (this.primaryInternetFacingLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancer, primaryIpConfig);
}
associateLoadBalancerToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
if (!this.primaryInternetFacingLBBackendsToAddOnUpdate.isEmpty()) {
removeAllBackendAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternetFacingLBBackendsToAddOnUpdate.toArray(new String[0]));
}
if (!this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.isEmpty()) {
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
}
if (this.primaryInternalLoadBalancerToAttachOnUpdate != null) {
if (this.primaryInternalLoadBalancer != null) {
removeLoadBalancerAssociationFromIpConfiguration(this.primaryInternalLoadBalancer, primaryIpConfig);
}
associateLoadBalancerToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
if (!this.primaryInternalLBBackendsToAddOnUpdate.isEmpty()) {
removeAllBackendAssociationFromIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateBackEndsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternalLBBackendsToAddOnUpdate.toArray(new String[0]));
}
if (!this.primaryInternalLBInboundNatPoolsToAddOnUpdate.isEmpty()) {
removeAllInboundNatPoolAssociationFromIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIpConfig);
associateInboundNATPoolsToIpConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.id(),
primaryIpConfig,
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.toArray(new String[0]));
}
}
this.removePrimaryInternetFacingLoadBalancerOnUpdate = false;
this.removePrimaryInternalLoadBalancerOnUpdate = false;
this.primaryInternetFacingLoadBalancerToAttachOnUpdate = null;
this.primaryInternalLoadBalancerToAttachOnUpdate = null;
this.primaryInternetFacingLBBackendsToRemoveOnUpdate.clear();
this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.clear();
this.primaryInternalLBBackendsToRemoveOnUpdate.clear();
this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.clear();
this.primaryInternetFacingLBBackendsToAddOnUpdate.clear();
this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.clear();
this.primaryInternalLBBackendsToAddOnUpdate.clear();
this.primaryInternalLBInboundNatPoolsToAddOnUpdate.clear();
}
private void clearCachedProperties() {
this.primaryInternetFacingLoadBalancer = null;
this.primaryInternalLoadBalancer = null;
}
private void loadCurrentPrimaryLoadBalancersIfAvailable() throws IOException {
if (this.primaryInternetFacingLoadBalancer != null && this.primaryInternalLoadBalancer != null) {
return;
}
String firstLoadBalancerId = null;
VirtualMachineScaleSetIPConfigurationInner ipConfig = primaryNicDefaultIPConfiguration();
if (!ipConfig.loadBalancerBackendAddressPools().isEmpty()) {
firstLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(ipConfig.loadBalancerBackendAddressPools().get(0).id());
}
if (firstLoadBalancerId == null && !ipConfig.loadBalancerInboundNatPools().isEmpty()) {
firstLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(ipConfig.loadBalancerInboundNatPools().get(0).id());
}
if (firstLoadBalancerId == null) {
return;
}
LoadBalancer loadBalancer1 = this.networkManager
.loadBalancers()
.getById(firstLoadBalancerId);
if (loadBalancer1.publicIPAddressIds() != null && loadBalancer1.publicIPAddressIds().size() > 0) {
this.primaryInternetFacingLoadBalancer = loadBalancer1;
} else {
this.primaryInternalLoadBalancer = loadBalancer1;
}
String secondLoadBalancerId = null;
for (SubResource subResource: ipConfig.loadBalancerBackendAddressPools()) {
if (!subResource.id().toLowerCase().startsWith(firstLoadBalancerId.toLowerCase())) {
secondLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(subResource.id());
break;
}
}
if (secondLoadBalancerId == null) {
for (SubResource subResource: ipConfig.loadBalancerInboundNatPools()) {
if (!subResource.id().toLowerCase().startsWith(firstLoadBalancerId.toLowerCase())) {
secondLoadBalancerId = ResourceUtils
.parentResourceIdFromResourceId(subResource.id());
break;
}
}
}
if (secondLoadBalancerId == null) {
return;
}
LoadBalancer loadBalancer2 = this.networkManager
.loadBalancers()
.getById(secondLoadBalancerId);
if (loadBalancer2.publicIPAddressIds() != null && loadBalancer2.publicIPAddressIds().size() > 0) {
this.primaryInternetFacingLoadBalancer = loadBalancer2;
} else {
this.primaryInternalLoadBalancer = loadBalancer2;
}
}
private VirtualMachineScaleSetIPConfigurationInner primaryNicDefaultIPConfiguration() {
List<VirtualMachineScaleSetNetworkConfigurationInner> nicConfigurations = this.inner()
.virtualMachineProfile()
.networkProfile()
.networkInterfaceConfigurations();
for (VirtualMachineScaleSetNetworkConfigurationInner nicConfiguration : nicConfigurations) {
if (nicConfiguration.primary()) {
if (nicConfiguration.ipConfigurations().size() > 0) {
VirtualMachineScaleSetIPConfigurationInner ipConfig = nicConfiguration.ipConfigurations().get(0);
if (ipConfig.loadBalancerBackendAddressPools() == null) {
ipConfig.withLoadBalancerBackendAddressPools(new ArrayList<SubResource>());
}
if (ipConfig.loadBalancerInboundNatPools() == null) {
ipConfig.withLoadBalancerInboundNatPools(new ArrayList<SubResource>());
}
return ipConfig;
}
}
}
throw new RuntimeException("Could not find the primary nic configuration or an IP configuration in it");
}
private static void associateBackEndsToIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... backendNames) {
List<SubResource> backendSubResourcesToAssociate = new ArrayList<>();
for (String backendName : backendNames) {
String backendPoolId = mergePath(loadBalancerId, "backendAddressPools", backendName);
boolean found = false;
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendPoolId)) {
found = true;
break;
}
}
if (!found) {
backendSubResourcesToAssociate.add(new SubResource().withId(backendPoolId));
}
}
for (SubResource backendSubResource : backendSubResourcesToAssociate) {
ipConfig.loadBalancerBackendAddressPools().add(backendSubResource);
}
}
private static void associateInboundNATPoolsToIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... inboundNatPools) {
List<SubResource> inboundNatPoolSubResourcesToAssociate = new ArrayList<>();
for (String inboundNatPool : inboundNatPools) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", inboundNatPool);
boolean found = false;
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
found = true;
break;
}
}
if (!found) {
inboundNatPoolSubResourcesToAssociate.add(new SubResource().withId(inboundNatPoolId));
}
}
for (SubResource backendSubResource : inboundNatPoolSubResourcesToAssociate) {
ipConfig.loadBalancerInboundNatPools().add(backendSubResource);
}
}
private static Map<String, LoadBalancerBackend> getBackendsAssociatedWithIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
String loadBalancerId = loadBalancer.id();
Map<String, LoadBalancerBackend> attachedBackends = new HashMap<>();
Map<String, LoadBalancerBackend> lbBackends = loadBalancer.backends();
for (LoadBalancerBackend lbBackend : lbBackends.values()) {
String backendId = mergePath(loadBalancerId, "backendAddressPools", lbBackend.name());
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendId)) {
attachedBackends.put(lbBackend.name(), lbBackend);
}
}
}
return attachedBackends;
}
private static Map<String, LoadBalancerInboundNatPool> getInboundNatPoolsAssociatedWithIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
String loadBalancerId = loadBalancer.id();
Map<String, LoadBalancerInboundNatPool> attachedInboundNatPools = new HashMap<>();
Map<String, LoadBalancerInboundNatPool> lbInboundNatPools = loadBalancer.inboundNatPools();
for (LoadBalancerInboundNatPool lbInboundNatPool : lbInboundNatPools.values()) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", lbInboundNatPool.name());
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
attachedInboundNatPools.put(lbInboundNatPool.name(), lbInboundNatPool);
}
}
}
return attachedInboundNatPools;
}
private static void associateLoadBalancerToIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
Collection<LoadBalancerBackend> backends = loadBalancer.backends().values();
String[] backendNames = new String[backends.size()];
int i = 0;
for (LoadBalancerBackend backend : backends) {
backendNames[i] = backend.name();
i++;
}
associateBackEndsToIpConfiguration(loadBalancer.id(),
ipConfig,
backendNames);
Collection<LoadBalancerInboundNatPool> inboundNatPools = loadBalancer.inboundNatPools().values();
String[] natPoolNames = new String[inboundNatPools.size()];
i = 0;
for (LoadBalancerInboundNatPool inboundNatPool : inboundNatPools) {
natPoolNames[i] = inboundNatPool.name();
i++;
}
associateInboundNATPoolsToIpConfiguration(loadBalancer.id(),
ipConfig,
natPoolNames);
}
private static void removeLoadBalancerAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
removeAllBackendAssociationFromIpConfiguration(loadBalancer, ipConfig);
removeAllInboundNatPoolAssociationFromIpConfiguration(loadBalancer, ipConfig);
}
private static void removeAllBackendAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
List<SubResource> toRemove = new ArrayList<>();
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().toLowerCase().startsWith(loadBalancer.id().toLowerCase() + "/")) {
toRemove.add(subResource);
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerBackendAddressPools().remove(subResource);
}
}
private static void removeAllInboundNatPoolAssociationFromIpConfiguration(LoadBalancer loadBalancer,
VirtualMachineScaleSetIPConfigurationInner ipConfig) {
List<SubResource> toRemove = new ArrayList<>();
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().toLowerCase().startsWith(loadBalancer.id().toLowerCase() + "/")) {
toRemove.add(subResource);
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerInboundNatPools().remove(subResource);
}
}
private static void removeBackendsFromIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... backendNames) {
List<SubResource> toRemove = new ArrayList<>();
for (String backendName : backendNames) {
String backendPoolId = mergePath(loadBalancerId, "backendAddressPools", backendName);
for (SubResource subResource : ipConfig.loadBalancerBackendAddressPools()) {
if (subResource.id().equalsIgnoreCase(backendPoolId)) {
toRemove.add(subResource);
break;
}
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerBackendAddressPools().remove(subResource);
}
}
private static void removeInboundNatPoolsFromIpConfiguration(String loadBalancerId,
VirtualMachineScaleSetIPConfigurationInner ipConfig,
String... inboundNatPoolNames) {
List<SubResource> toRemove = new ArrayList<>();
for (String natPoolName : inboundNatPoolNames) {
String inboundNatPoolId = mergePath(loadBalancerId, "inboundNatPools", natPoolName);
for (SubResource subResource : ipConfig.loadBalancerInboundNatPools()) {
if (subResource.id().equalsIgnoreCase(inboundNatPoolId)) {
toRemove.add(subResource);
break;
}
}
}
for (SubResource subResource : toRemove) {
ipConfig.loadBalancerInboundNatPools().remove(subResource);
}
}
private static <T> void addToList(List<T> list, T...items) {
for (T item : items) {
list.add(item);
}
}
private static String mergePath(String... segments) {
StringBuilder builder = new StringBuilder();
for (String segment : segments) {
while (segment.length() > 1 && segment.endsWith("/")) {
segment = segment.substring(0, segment.length() - 1);
}
if (segment.length() > 0) {
builder.append(segment);
builder.append("/");
}
}
String merged = builder.toString();
if (merged.endsWith("/")) {
merged = merged.substring(0, merged.length() - 1);
}
return merged;
}
protected VirtualMachineScaleSetImpl withUnmanagedDataDisk(VirtualMachineScaleSetUnmanagedDataDiskImpl unmanagedDisk) {
if (this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks() == null) {
this.inner()
.virtualMachineProfile()
.storageProfile()
.withDataDisks(new ArrayList<VirtualMachineScaleSetDataDisk>());
}
List<VirtualMachineScaleSetDataDisk> dataDisks = this.inner()
.virtualMachineProfile()
.storageProfile()
.dataDisks();
dataDisks.add(unmanagedDisk.inner());
return this;
}
/**
* Checks whether the OS disk is based on an image (image from PIR or custom image [captured, bringYourOwnFeature]).
*
* @param osDisk the osDisk value in the storage profile
* @return true if the OS disk is configured to use image from PIR or custom image
*/
private boolean isOSDiskFromImage(VirtualMachineScaleSetOSDisk osDisk) {
return osDisk.createOption() == DiskCreateOptionTypes.FROM_IMAGE;
}
/**
* Checks whether the OS disk is based on a CustomImage.
* <p>
* A custom image is represented by {@link com.microsoft.azure.management.compute.VirtualMachineCustomImage}.
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to be based on custom image.
*/
private boolean isOsDiskFromCustomImage(VirtualMachineScaleSetStorageProfile storageProfile) {
ImageReferenceInner imageReference = storageProfile.imageReference();
return isOSDiskFromImage(storageProfile.osDisk())
&& imageReference != null
&& imageReference.id() != null;
}
/**
* Checks whether the OS disk is based on an platform image (image in PIR).
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to be based on platform image.
*/
private boolean isOSDiskFromPlatformImage(VirtualMachineScaleSetStorageProfile storageProfile) {
ImageReferenceInner imageReference = storageProfile.imageReference();
return isOSDiskFromImage(storageProfile.osDisk())
&& imageReference != null
&& imageReference.publisher() != null
&& imageReference.offer() != null
&& imageReference.sku() != null
&& imageReference.version() != null;
}
/**
* Checks whether the OS disk is based on a stored image ('captured' or 'bring your own feature').
*
* @param storageProfile the storage profile
* @return true if the OS disk is configured to use custom image ('captured' or 'bring your own feature')
*/
private boolean isOSDiskFromStoredImage(VirtualMachineScaleSetStorageProfile storageProfile) {
VirtualMachineScaleSetOSDisk osDisk = storageProfile.osDisk();
return isOSDiskFromImage(osDisk)
&& osDisk.image() != null
&& osDisk.image().uri() != null;
}
/* TODO Unused
private void throwIfManagedDiskEnabled(String message) {
if (this.isManagedDiskEnabled()) {
throw new UnsupportedOperationException(message);
}
}*/
private void throwIfManagedDiskDisabled(String message) {
if (!this.isManagedDiskEnabled()) {
throw new UnsupportedOperationException(message);
}
}
/**
* Class to manage Data Disk collection.
*/
private class ManagedDataDiskCollection {
private final List<VirtualMachineScaleSetDataDisk> implicitDisksToAssociate = new ArrayList<>();
private final List<Integer> diskLunsToRemove = new ArrayList<>();
private final List<VirtualMachineScaleSetDataDisk> newDisksFromImage = new ArrayList<>();
private final VirtualMachineScaleSetImpl vmss;
private CachingTypes defaultCachingType;
private StorageAccountTypes defaultStorageAccountType;
ManagedDataDiskCollection(VirtualMachineScaleSetImpl vmss) {
this.vmss = vmss;
}
void setDefaultCachingType(CachingTypes cachingType) {
this.defaultCachingType = cachingType;
}
void setDefaultStorageAccountType(StorageAccountTypes defaultStorageAccountType) {
this.defaultStorageAccountType = defaultStorageAccountType;
}
void setDataDisksDefaults() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
if (isPending()) {
if (storageProfile.dataDisks() == null) {
storageProfile.withDataDisks(new ArrayList<VirtualMachineScaleSetDataDisk>());
}
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
final List<Integer> usedLuns = new ArrayList<>();
// Get all used luns
//
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
for (VirtualMachineScaleSetDataDisk dataDisk : this.implicitDisksToAssociate) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
for (VirtualMachineScaleSetDataDisk dataDisk : this.newDisksFromImage) {
if (dataDisk.lun() != -1) {
usedLuns.add(dataDisk.lun());
}
}
// Func to get the next available lun
//
Func0<Integer> nextLun = new Func0<Integer>() {
@Override
public Integer call() {
Integer lun = 0;
while (usedLuns.contains(lun)) {
lun++;
}
usedLuns.add(lun);
return lun;
}
};
setImplicitDataDisks(nextLun);
setImageBasedDataDisks();
removeDataDisks();
}
if (storageProfile.dataDisks() != null
&& storageProfile.dataDisks().size() == 0) {
if (vmss.isInCreateMode()) {
// If there is no data disks at all, then setting it to null rather than [] is necessary.
// This is for take advantage of CRP's implicit creation of the data disks if the image has
// more than one data disk image(s).
//
storageProfile.withDataDisks(null);
}
}
this.clear();
}
private void clear() {
implicitDisksToAssociate.clear();
diskLunsToRemove.clear();
newDisksFromImage.clear();
}
private boolean isPending() {
return implicitDisksToAssociate.size() > 0
|| diskLunsToRemove.size() > 0
|| newDisksFromImage.size() > 0;
}
private void setImplicitDataDisks(Func0<Integer> nextLun) {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (VirtualMachineScaleSetDataDisk dataDisk : this.implicitDisksToAssociate) {
dataDisk.withCreateOption(DiskCreateOptionTypes.EMPTY);
if (dataDisk.lun() == -1) {
dataDisk.withLun(nextLun.call());
}
if (dataDisk.managedDisk() == null) {
dataDisk.withManagedDisk(new VirtualMachineScaleSetManagedDiskParameters());
}
if (dataDisk.caching() == null) {
dataDisk.withCaching(getDefaultCachingType());
}
if (dataDisk.managedDisk().storageAccountType() == null) {
dataDisk.managedDisk().withStorageAccountType(getDefaultStorageAccountType());
}
dataDisk.withName(null);
dataDisks.add(dataDisk);
}
}
private void setImageBasedDataDisks() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (VirtualMachineScaleSetDataDisk dataDisk : this.newDisksFromImage) {
dataDisk.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
// Don't set default storage account type for the disk, either user has to specify it explicitly or let
// CRP pick it from the image
dataDisk.withName(null);
dataDisks.add(dataDisk);
}
}
private void removeDataDisks() {
VirtualMachineScaleSetStorageProfile storageProfile = this.vmss
.inner()
.virtualMachineProfile()
.storageProfile();
List<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile.dataDisks();
for (Integer lun : this.diskLunsToRemove) {
int indexToRemove = 0;
for (VirtualMachineScaleSetDataDisk dataDisk : dataDisks) {
if (dataDisk.lun() == lun) {
dataDisks.remove(indexToRemove);
break;
}
indexToRemove++;
}
}
}
private CachingTypes getDefaultCachingType() {
if (defaultCachingType == null) {
return CachingTypes.READ_WRITE;
}
return defaultCachingType;
}
private StorageAccountTypes getDefaultStorageAccountType() {
if (defaultStorageAccountType == null) {
return StorageAccountTypes.STANDARD_LRS;
}
return defaultStorageAccountType;
}
}
}
|
fixing NPE in VMSS.withUpgradeMode
|
azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineScaleSetImpl.java
|
fixing NPE in VMSS.withUpgradeMode
|
|
Java
|
mit
|
error: pathspec 'demo/nudge4j/DemoN4J.java' did not match any file(s) known to git
|
7f11c04318b05c8fd2da9632dcfac562bf35601b
| 1
|
lorenzoongithub/nudge4j
|
package nudge4j;
/**
*
* This is a stand alone program that you can just run as is.
* It requires JAVA 8 and it has no dependencies.
*
**/
public class DemoN4J {
public static void main(String args[]) {
System.out.println("Demo N4J");
//
// below is the code copied from
// https://lorenzoongithub.github.io/nudge4j/
//
// The latest code snippet is always available here:
// https://lorenzoongithub.github.io/nudge4j/dist/n4j.snippet.java
//
// Always that check you are running the latest code by visiting the project
// https://github.com/lorenzoongithub/nudge4j
//
//
// nudge4j:begin
(new java.util.function.Consumer<Object[]>() { public void accept(Object args[]) {
try {
javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("JavaScript");
engine.put("args", args);
Class<?> HttpHandler= Class.forName("com.sun.net.httpserver.HttpHandler");
java.lang.reflect.Method
getRequestURI = Class.forName("com.sun.net.httpserver.HttpExchange").getMethod("getRequestURI"),
getResponseHeaders = Class.forName("com.sun.net.httpserver.HttpExchange").getMethod("getResponseHeaders"),
set = Class.forName("com.sun.net.httpserver.Headers"). getMethod("set", String.class,String.class),
sendResponseHeaders = Class.forName("com.sun.net.httpserver.HttpExchange").getMethod("sendResponseHeaders",int.class,long.class),
getResponseBody = Class.forName("com.sun.net.httpserver.HttpExchange").getMethod("getResponseBody"),
getQuery = Class.forName("java.net.URI"). getMethod("getQuery"),
create = Class.forName("com.sun.net.httpserver.HttpServer"). getMethod("create", java.net.InetSocketAddress.class, int.class),
createContext = Class.forName("com.sun.net.httpserver.HttpServer"). getMethod("createContext", String.class, HttpHandler),
setExecutor = Class.forName("com.sun.net.httpserver.HttpServer"). getMethod("setExecutor", java.util.concurrent.Executor.class),
start = Class.forName("com.sun.net.httpserver.HttpServer"). getMethod("start");
Object server = create.invoke(null, new java.net.InetSocketAddress((int)args[0]), 0);
createContext.invoke(server, "/", java.lang.reflect.Proxy.newProxyInstance(
HttpHandler.getClassLoader(),
new Class[] { HttpHandler },
new java.lang.reflect.InvocationHandler() {
private java.nio.charset.Charset UTF8 = java.nio.charset.Charset.forName("UTF-8");
private byte data[] = new byte[200000];
private java.util.function.Function<Object,String> stringify = (oj) -> {
return "\""+(""+oj).replace("\\", "\\\\").replace("\n", "\\n").replace("\b", "\\b").
replace("\t", "\\t").replace("\r", "\\r").replace("\f", "\\f").
replace("\"", "\\\"") +"\"";
};
private void send(Object httpExchange,byte array[],int max, String contentType) throws Exception {
set.invoke(getResponseHeaders.invoke(httpExchange), "Content-Type",contentType);
sendResponseHeaders.invoke(httpExchange, 200, max);
java.io.OutputStream os = (java.io.OutputStream) getResponseBody.invoke(httpExchange);
os.write(array,0, max);
os.close();
}
public synchronized Object invoke(Object pxy, java.lang.reflect.Method mthd, Object[] args) throws Throwable {
Object httpExchange = args[0];
String uri = getRequestURI.invoke(httpExchange).toString();
if (uri.startsWith("/js")) {
String query = (String) getQuery.invoke(getRequestURI.invoke(httpExchange));
String id = '"'+query.substring(0, 10)+'"';
String code = query.substring(11);
Object result = null;
try {
result = engine.eval(code);
} catch (Exception e) {
final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
e.printStackTrace(new java.io.PrintStream(baos));
byte array[] = ("n4j.on("+id+","+stringify.apply(baos)+",null)").getBytes(UTF8);
send(httpExchange,array,array.length,"application/javascript");
return null;
}
byte[] array = ("n4j.on("+id+",null,"+stringify.apply(result)+")").getBytes(UTF8);
send(httpExchange,array,array.length,"application/javascript");
return null;
}
String url = "https://lorenzoongithub.github.io/nudge4j/proxy"+uri;
java.net.HttpURLConnection con = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode != 200) {
sendResponseHeaders.invoke(httpExchange,responseCode,-1);
return null;
}
java.io.InputStream is = con.getInputStream();
int count = 0;
while (true) {
int b = is.read();
if (b == -1) break;
data[count++] = (byte) b;
}
is.close();
send(httpExchange,data, count, (
(uri.endsWith(".ico")) ? "image/x-icon" :
(uri.endsWith(".css")) ? "text/css" :
(uri.endsWith(".png")) ? "image/png" :
(uri.endsWith(".js")) ? "application/javascript" :
"text/html"));
return null;
}
}
));
setExecutor.invoke(server, new Object[] { null });
start.invoke(server);
System.out.println("nudge4j serving on port:"+args[0]);
} catch (Exception e) {
throw new InternalError(e);
}
}}).accept( new Object[] { 5050 });
// nudge4j:end
}
}
|
demo/nudge4j/DemoN4J.java
|
code for a minimal demo
|
demo/nudge4j/DemoN4J.java
|
code for a minimal demo
|
|
Java
|
mit
|
error: pathspec 'Java/CodingBat/lastChars.java' did not match any file(s) known to git
|
5d0a65a001c27810f747686f3f74286c670c5a7a
| 1
|
dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey
|
// http://codingbat.com/prob/p138183
public String lastChars(String a, String b) {
if (a.length() == 0 && b.length() == 0) {
return "@@";
}
else if (a.length() == 0) {
return "@" + b.substring(b.length()-1, b.length());
}
else if (b.length() == 0) {
return a.substring(0, 1) + "@";
}
else {
return a.substring(0, 1) + b.substring(b.length()-1, b.length());
}
}
|
Java/CodingBat/lastChars.java
|
Create lastChars.java
|
Java/CodingBat/lastChars.java
|
Create lastChars.java
|
|
Java
|
mit
|
error: pathspec 'src/examples/ConfigAssure.java' did not match any file(s) known to git
|
ef1ceb30a33e872afeeb13613ae86429cff23711
| 1
|
drayside/kodkod,drayside/kodkod,drayside/kodkod,drayside/kodkod,drayside/kodkod
|
/**
*
*/
package examples;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.Relation;
import kodkod.ast.Variable;
import kodkod.engine.Evaluator;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.config.Options;
import kodkod.engine.satlab.SATFactory;
import kodkod.instance.Bounds;
import kodkod.instance.Instance;
import kodkod.instance.Tuple;
import kodkod.instance.TupleFactory;
import kodkod.instance.TupleSet;
import kodkod.instance.Universe;
import kodkod.util.nodes.Nodes;
/**
* Pure Kodkod encoding of the new test case for ConfigAssure.
* @author Emina Torlak
*/
public final class ConfigAssure {
private final Relation port, addr, mask, subnet;
/**
* Constructs a new instance of ConfigAssure.
*/
public ConfigAssure() {
this.port = Relation.unary("port");
this.addr = Relation.binary("addr");
this.mask = Relation.binary("mask");
this.subnet = Relation.binary("subnet");
}
/**
* Returns the netID of the given port.
* @return netID of the given port
*/
Expression netid(Expression p) {
return addr(p).intersection(mask(p));
}
/**
* Returns the ip address of the given port.
* @return ip address of the given port
*/
Expression addr(Expression p) { return p.join(addr); }
/**
* Returns the mask of the given port.
* @return mask of the given port
*/
Expression mask(Expression p) { return p.join(mask); }
/**
* Returns the subnet of the given port.
* @return subnet of the given port
*/
Expression subnet(Expression p) { return p.join(subnet); }
/**
* Returns the requirements.
* @return requirements
*/
public Formula requirements () {
final Variable p1 = Variable.unary("p1"), p2 = Variable.unary("p2");
// no two ports have the same address: all disj p1, p2: Port | p1.addr != p2.addr
final Formula f0 = p1.eq(p2).not().implies(addr(p1).eq(addr(p2)).not()).forAll(p1.oneOf(port).and(p2.oneOf(port)));
// two ports on the same subnet have the same netid: all p1, p2: Port | p1.subnet = p2.subnet => p1.netid = p2.netid
final Formula f1 = subnet(p1).eq(subnet(p2)).implies(netid(p1).eq(netid(p2))).forAll(p1.oneOf(port).and(p2.oneOf(port)));
// net ids don't overlap: all disj p1, p2: Port | bitwise-and (p1.netid, p2.netid) = 0
final Formula f2 = p1.eq(p2).not().implies(netid(p1).intersection(netid(p2)).no()).forAll(p1.oneOf(port).and(p2.oneOf(port)));
// all addresses are in the range 121.96.0.0 to 121.96.255.255: all p: Port | 121.96.0.0 <= p.addr <= 121.96.255.255
final IntExpression p1bits = addr(p1).sum();
final Formula f3 = IntConstant.constant(2036334592).lte(p1bits).and(p1bits.lte(IntConstant.constant(2036400127))).forAll(p1.oneOf(port));
return Nodes.and(f0, f1, f2, f3);
}
/**
* Returns the universe from the given ipAddresses file.
* @throws IOException
*/
private Universe universe(String ipAddresses) throws IOException {
final BufferedReader reader = new BufferedReader(new FileReader(new File(ipAddresses)));
final List<Object> atoms = new ArrayList<Object>();
final Pattern p = Pattern.compile("ipAddress\\((.+), (.+), \\S+, \\S+\\)\\.");
String line = "";
final Matcher m = p.matcher(line);
for(line = reader.readLine(); line != null && m.reset(line).matches(); line = reader.readLine()) {
atoms.add(m.group(1) + "-" + m.group(2));
}
// add the integers
for(int i = 0; i < 32; i++) {
atoms.add(Integer.valueOf(1<<i));
}
return new Universe(atoms);
}
/**
* Returns the bounds corresponding to the given ip address and subnet files.
* @return bounds corresponding to the given ip address and subnet files.
*/
public Bounds bounds(String ipAddresses, String subnets) {
try {
final Universe universe = universe(ipAddresses);
final Bounds bounds = new Bounds(universe);
final TupleFactory factory = universe.factory();
for(int i = 0; i < 32; i++) {
bounds.boundExactly(1<<i, factory.setOf(Integer.valueOf(1<<i)));
}
bounds.boundExactly(port, factory.range(factory.tuple(universe.atom(0)), factory.tuple(universe.atom(universe.size()-32))));
BufferedReader reader = new BufferedReader(new FileReader(new File(ipAddresses)));
String line = "";
// first parse the ipAddresses file and populate the upper and lower bounds of the addr and mask relations
final TupleSet lAddr = factory.noneOf(2), uAddr = factory.noneOf(2);
final TupleSet lMask = factory.noneOf(2), uMask = factory.noneOf(2);
// example: ipAddress('IOS_00096', 'FastEthernet0/0', 2036387617, 8).
final Pattern p0 = Pattern.compile("ipAddress\\((.+), (.+), (\\S+), (\\S+)\\)\\.");
final Pattern p1 = Pattern.compile("\\d+");
final Matcher m0 = p0.matcher(line), m1 = p1.matcher(line);
for(line = reader.readLine(); line != null && m0.reset(line).matches(); line = reader.readLine()) {
final String portName = m0.group(1) + "-" + m0.group(2);
if (m1.reset(m0.group(3)).matches()) { // address is constant
final int pAddr = Integer.parseInt(m0.group(3));
for(int i = 0 ; i < 32; i++) {
if ((pAddr & (1<<i)) != 0) {
final Tuple tuple = factory.tuple(portName, Integer.valueOf(1<<i));
lAddr.add(tuple);
uAddr.add(tuple);
}
}
} else {
for(int i = 0 ; i < 32; i++) {
uAddr.add(factory.tuple(portName, Integer.valueOf(1<<i)));
}
}
if (m1.reset(m0.group(4)).matches()) { // mask is constant
final int pMask = Integer.parseInt(m0.group(4));
for(int i = 0 ; i < 32; i++) {
if ((pMask & (1<<i)) != 0) {
final Tuple tuple = factory.tuple(portName, Integer.valueOf(1<<i));
lMask.add(tuple);
uMask.add(tuple);
}
}
} else {
for(int i = 0 ; i < 32; i++) {
uMask.add(factory.tuple(portName, Integer.valueOf(1<<i)));
}
}
}
bounds.bound(addr, lAddr, uAddr);
bounds.bound(mask, lMask, uMask);
// then parse the subnets file and populate the exact bound for the subnet relation
final TupleSet bsubnet = factory.noneOf(2);
reader = new BufferedReader(new FileReader(new File(subnets)));
// example: subnet(['IOS_00022'-'Vlan172', 'IOS_00023'-'Vlan172']).
final Pattern p2 = Pattern.compile("subnet\\(\\[(.+)(?:, (.+))*\\]\\)\\.");
final Matcher m2 = p2.matcher(line);
int n = 1;
for(line = reader.readLine(); line != null && m2.reset(line).matches(); line = reader.readLine()) {
for(int i = 1, groups = m2.groupCount(); i < groups; i++) {
final String portName = m2.group(i);
for(int j = 0 ; j < 32; i++) {
if ((n & (1<<j)) != 0) {
bsubnet.add(factory.tuple(portName, Integer.valueOf(1<<j)));
}
}
}
n++;
}
bounds.boundExactly(subnet, bsubnet);
return bounds;
} catch (IOException e) {
e.printStackTrace();
usage();
}
return null;
}
/**
* Displays an instance obtained with the given options.
* @requires inst != null and opt != null
*/
private final void display(Instance inst, Options opt) {
final Universe univ = inst.universe();
final Evaluator eval = new Evaluator(inst, opt);
final TupleFactory factory = univ.factory();
final Relation[] ports = new Relation[univ.size()-31];
for(int i = 0; i < ports.length; i++) {
ports[i] = Relation.unary(univ.atom(i).toString());
inst.add(ports[i], factory.setOf(ports[i].name()));
}
for(Relation p : ports) {
System.out.print(p);
System.out.print(": addr=" + eval.evaluate(addr(p).sum()));
System.out.print(", mask=" + eval.evaluate(mask(p).sum()));
System.out.print(", netid=" + eval.evaluate(netid(p).sum()));
System.out.println(", subnet=" + eval.evaluate(subnet(p).sum()) + ".");
}
}
private static void usage() {
System.out.println("java examples.ConfigAssure <ipAddresses file> <subnets file>");
System.exit(1);
}
/**
* Usage: java examples.ConfigAssure <ipAddresses file> <subnets file>
*/
public static void main(String[] args) {
if (args.length < 2) usage();
final ConfigAssure ca = new ConfigAssure();
final Solver solver = new Solver();
solver.options().setBitwidth(32);
solver.options().setSolver(SATFactory.MiniSat);
final Solution sol = solver.solve(ca.requirements(), ca.bounds(args[0], args[1]));
if (sol.instance() != null) {
System.out.println(sol.stats());
ca.display(sol.instance(), solver.options());
} else {
System.out.println(sol);
}
}
}
|
src/examples/ConfigAssure.java
|
*** empty log message ***
|
src/examples/ConfigAssure.java
|
*** empty log message ***
|
|
Java
|
mit
|
error: pathspec 'src/com/haxademic/render/TunnelTorus.java' did not match any file(s) known to git
|
9e7ccae2b44ca3086290646d7c24c950dce6852f
| 1
|
cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic
|
package com.haxademic.render;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.app.config.AppSettings;
import com.haxademic.core.app.config.Config;
import com.haxademic.core.debug.DebugView;
import com.haxademic.core.draw.context.PG;
import com.haxademic.core.draw.filters.pshader.CubicLensDistortionFilter;
import com.haxademic.core.draw.filters.pshader.FeedbackRadialFilter;
import com.haxademic.core.draw.filters.pshader.GrainFilter;
import com.haxademic.core.draw.filters.pshader.RepeatFilter;
import com.haxademic.core.draw.filters.pshader.VignetteFilter;
import com.haxademic.core.draw.shapes.PShapeUtil;
import com.haxademic.core.draw.shapes.Shapes;
import com.haxademic.core.draw.shapes.pshader.MeshDeformAndTextureFilter;
import com.haxademic.core.hardware.mouse.Mouse;
import com.haxademic.core.media.DemoAssets;
import com.haxademic.core.render.FrameLoop;
import processing.core.PGraphics;
import processing.core.PShape;
public class TunnelTorus
extends PAppletHax {
public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
int FRAMES = 60 * 30;
protected PShape shape;
protected float torusRadius;
protected PGraphics texture;
protected void config() {
Config.setAppSize(1024, 1024);
Config.setProperty(AppSettings.LOOP_FRAMES, FRAMES);
Config.setProperty(AppSettings.RENDERING_MOVIE, false);
Config.setProperty(AppSettings.RENDERING_MOVIE_START_FRAME, 1 + FRAMES);
Config.setProperty(AppSettings.RENDERING_MOVIE_STOP_FRAME, 1 + FRAMES * 2);
}
protected void firstFrame() {
// build texture
texture = PG.newPG(2048, 1024);
PG.setTextureRepeat(texture, true);
DebugView.setTexture("texture", texture);
// create torus w/quads
torusRadius = p.width * 2;
// shape = Shapes.createTorus(torusRadius, torusRadius/20, 360, 200, texture);
shape = Shapes.createTorus(torusRadius, torusRadius/20, 180, 24, null);
// get triangulaed version if desired
shape = shape.getTessellation();
// shape.setTexture(texture);
// rotate up front for ease of later fancy rotation
PShapeUtil.meshRotateOnAxis(shape, P.HALF_PI, P.X);
}
protected void drawApp() {
background(0);
// update texture
texture.beginDraw();
texture.background(0);
texture.noStroke();
// for (float i = -64 + (FrameLoop.progress() * 64f * 20)%64; i < texture.width + 32; i+=16) {
for (float i = 0; i < texture.width; i+=16) {
texture.fill(255);
texture.rect(i, 0, 8, texture.height);
}
texture.endDraw();
RepeatFilter.instance(p).setOffset(FrameLoop.progress() * -0.1f, 0);
// RepeatFilter.instance(p).applyTo(texture);
FeedbackRadialFilter.instance(p).setMultY(0);
FeedbackRadialFilter.instance(p).setAmp(0.05f);
// FeedbackRadialFilter.instance(p).applyTo(texture);
// MirrorQuadFilter.instance(p).applyTo(texture);
// ImageUtil.copyImage(DemoAssets.textureNebula(), texture);
PG.setCenterScreen(p.g);
p.g.translate(0, 0, Mouse.xNorm * -3000);
// PG.basicCameraFromMouse(p.g);
// PG.setBetterLights(p.g);
// p.lights();
// p.ambient(255);
// p.ambientLight(75, 75, 75);
// basic rotation
// p.translate(torusRadius, 0, torusRadius/2);
// p.rotateX(P.HALF_PI);
// p.rotateZ(FrameLoop.count(-0.01f));
// fancier rotating rotation
float curRads = -1f * FrameLoop.progressRads();
p.translate(torusRadius * P.cos(curRads), torusRadius * P.sin(curRads), torusRadius/2);
// p.rotateX(-curRads);
p.rotateZ(curRads);
p.rotateY(-curRads);
// draw torus
shape.disableStyle();
p.fill(0);
// p.noFill();
p.stroke(0, 255, 0);
p.strokeWeight(2);
// p.noStroke();
// deform mesh
MeshDeformAndTextureFilter.instance(p).setDisplacementMap(DemoAssets.textureNebula());
MeshDeformAndTextureFilter.instance(p).setDisplaceAmp(0.01f);
MeshDeformAndTextureFilter.instance(p).setSheetMode(false);
// MeshDeformAndTextureFilter.instance(p).applyTo(p);
// draw mesh
// p.shape(shape);
PShapeUtil.drawTriangles(p.g, shape, null, 1);
p.resetShader();
// postprocessing
VignetteFilter.instance(p).setDarkness(0.75f);
VignetteFilter.instance(p).setSpread(0.2f);
VignetteFilter.instance(p).applyTo(p.g);
GrainFilter.instance(p).setTime(p.frameCount * 0.02f);
GrainFilter.instance(p).setCrossfade(0.02f);
// GrainFilter.instance(p).applyTo(p.g);
CubicLensDistortionFilter.instance(p).setAmplitude(-2f);
// CubicLensDistortionFilter.instance(p).applyTo(p.g);
}
}
|
src/com/haxademic/render/TunnelTorus.java
|
Create TunnelTorus.java
|
src/com/haxademic/render/TunnelTorus.java
|
Create TunnelTorus.java
|
|
Java
|
mit
|
error: pathspec 'src/linenux/controller/TaskController.java' did not match any file(s) known to git
|
5dba2014f2b8b9889e20af23497bbee6b6e7bcae
| 1
|
CS2103AUG2016-W11-C1/main
|
package linenux.controller;
class TaskController {
}
|
src/linenux/controller/TaskController.java
|
Add empty Task Controller
|
src/linenux/controller/TaskController.java
|
Add empty Task Controller
|
|
Java
|
mit
|
error: pathspec 'src/main/java/org/blub/domain/Description.java' did not match any file(s) known to git
|
199d9a7f3b4caf710589e6b7aeebb5f3396341d3
| 1
|
neo8ba8dms/neo_ba_dms,neo8ba8dms/neo_ba_dms,neo8ba8dms/neo_ba_dms
|
package org.blub.domain;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
/*
Does this get a separate node in neo4J? --> yes
Needs a Relationship to classes that use it.
Naming scheme: "relFrom<using class>ToDescription"
*/
@NodeEntity
public class Description {
@GraphId Long graphId;
private String textual_description;
private Description_enumeration_type type_of;
private String language_code;
public Long getGraphId() {
return graphId;
}
public void setGraphId(Long graphId) {
this.graphId = graphId;
}
public String getTextual_description() {
return textual_description;
}
public void setTextual_description(String textual_description) {
this.textual_description = textual_description;
}
public Description_enumeration_type getType_of() {
return type_of;
}
public void setType_of(Description_enumeration_type type_of) {
this.type_of = type_of;
}
public String getLanguage_code() {
return language_code;
}
public void setLanguage_code(String language_code) {
this.language_code = language_code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Description that = (Description) o;
return graphId != null ? graphId.equals(that.graphId) : that.graphId == null;
}
@Override
public int hashCode() {
return graphId != null ? graphId.hashCode() : 0;
}
}
|
src/main/java/org/blub/domain/Description.java
|
created Description class/entity
|
src/main/java/org/blub/domain/Description.java
|
created Description class/entity
|
|
Java
|
mit
|
error: pathspec 'src/test/java/contest/question3/AnswerTest.java' did not match any file(s) known to git
|
9eb252f13172a33ac5a30b34dc0d9c616f07ab61
| 1
|
sjitech/contest01
|
package contest.question3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by wang on 2015/04/13.
*/
public class AnswerTest {
protected static Logger log = LoggerFactory.getLogger(Answer.class);
}
|
src/test/java/contest/question3/AnswerTest.java
|
temp commit for question 3
|
src/test/java/contest/question3/AnswerTest.java
|
temp commit for question 3
|
|
Java
|
mit
|
error: pathspec 'src/net/dimensions/solar/event/EventException.java' did not match any file(s) known to git
|
25091b5b8b42668a50f8c38c00407106c7bd6371
| 1
|
Dimensions/Solar
|
package net.dimensions.solar.event;
public class EventException extends Exception{
public EventException(String message) {
super(message);
}
public EventException(Throwable cause) {
super(cause);
}
public EventException(String message, Throwable cause) {
super(message, cause);
}
}
|
src/net/dimensions/solar/event/EventException.java
|
Exception for events
|
src/net/dimensions/solar/event/EventException.java
|
Exception for events
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/amee/base/validation/ValidationHelper.java' did not match any file(s) known to git
|
f0b80fe48b44955ed04b32c3d78f4b3723bac8c9
| 1
|
OpenAMEE/amee.platform.api
|
package com.amee.base.validation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import java.util.Map;
public abstract class ValidationHelper {
private final Log log = LogFactory.getLog(getClass());
private DataBinder dataBinder;
public ValidationHelper() {
super();
}
/**
* Validates the supplied form.
*
* @param values to validate
* @return true if form is valid, otherwise false
*/
public boolean isValid(Map<String, String> values) {
log.debug("isValid()");
dataBinder = createDataBinder();
prepareDataBinder(dataBinder);
beforeBind(values);
dataBinder.bind(createPropertyValues(values));
Errors errors = getErrors();
if (!errors.hasErrors()) {
ValidationUtils.invokeValidator(getValidator(), dataBinder.getTarget(), errors);
if (!errors.hasErrors()) {
log.debug("isValid() - No validation errors.");
return true;
}
} else {
log.debug("isValid() - Has binding errors.");
}
log.debug("isValid() - Has validation errors.");
return false;
}
/**
* Prepare the DataBinder before it is used for validation. Default implementation updates the DataBinder
* allowedFields and calls registerCustomEditors with the DataBinder.
*
* @param dataBinder to be prepared
*/
protected void prepareDataBinder(DataBinder dataBinder) {
dataBinder.setAllowedFields(getAllowedFields());
registerCustomEditors(dataBinder);
}
/**
* Hook for registering custom PropertyEditors into the DataBinder. Default implementation does
* nothing. Extending classes should override this method to supply required PropertyEditors to
* the DataBinder.
*
* @param dataBinder to set editors on
*/
protected void registerCustomEditors(DataBinder dataBinder) {
// do nothing
}
protected DataBinder createDataBinder() {
return new DataBinder(getTarget(), getName());
}
/**
* Hook for pre-processing the Form before binding happens.
*
* @param values to be validated
*/
protected void beforeBind(Map<String, String> values) {
// do nothing
}
/**
* Renames all parameters in the Form that match oldName to newName. Useful for re-implementations of beforeBind.
*
* @param values to consider for renaming
* @param oldName old name for value
* @param newName new name for value
*/
protected void renameValue(Map<String, String> values, String oldName, String newName) {
String value = values.remove(oldName);
if (value != null) {
values.put(newName, value);
}
}
protected PropertyValues createPropertyValues(Map<String, String> values) {
return new MutablePropertyValues(values);
}
protected Validator getValidator() {
throw new UnsupportedOperationException();
}
public DataBinder getDataBinder() {
return dataBinder;
}
public Errors getErrors() {
return dataBinder.getBindingResult();
}
public Object getTarget() {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public String[] getAllowedFields() {
return new String[]{};
}
}
|
src/main/java/com/amee/base/validation/ValidationHelper.java
|
First draft for PL-373.
|
src/main/java/com/amee/base/validation/ValidationHelper.java
|
First draft for PL-373.
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/matthewhatcher/vpnguard/PluginMessages.java' did not match any file(s) known to git
|
7fb4520d4c584f3e6fdcab9416bef4de20f5e843
| 1
|
MatthewSH/spigot-VPNGuard
|
package com.matthewhatcher.vpnguard;
import org.bukkit.ChatColor;
public class PluginMessages
{
public static String DEFAULT_KICK_MESSAGE = "Sorry, but your IP (%ip) seems to be a VPN and you were kicked. Please turn it off and try again.";
public static String PREFIX = ChatColor.WHITE + "[" +
ChatColor.GOLD + "VPN Guard" +
ChatColor.WHITE + "] ";
public static String PREFIX_NOCOLOR = "[VPN Guard] ";
public static String NO_PERMISSION = PREFIX + "Sorry, but you do not have permission to run that command.";
public static String INVALID_COMMAND = PREFIX + "I don't recognize that command.";
public static String[] HELP_MESSAGE_COMMANDS = {
"/vpng refresh | Force refreshes the cache.",
"/vpng reload | Reloads the plugin configuration"
};
public static String COMMAND_REFRESH = PREFIX + "Refreshing cache...";
public static String COMMAND_REFRESH_COMPLETED = PREFIX + "Cache has been refreshed.";
public static String COMMAND_RELOAD = PREFIX + "Reloading config...";
public static String COMMAND_RELOAD_COMPLETED = PREFIX + "Configuration has been reloaded.";
public static String CONSOLE_BLOCKEDLOGIN = PREFIX_NOCOLOR + "";
public static String CONSOLE_COMMAND_PURGE = PREFIX_NOCOLOR + "Okay then, clearing the cache file.";
public static String CONSOLE_COMMAND_PURGE_COMPLETED = PREFIX_NOCOLOR + "Cache file has been emptied, may God help you.";
}
|
src/main/java/com/matthewhatcher/vpnguard/PluginMessages.java
|
Adding messages! :notebook:
We all need messages. So here they are!
|
src/main/java/com/matthewhatcher/vpnguard/PluginMessages.java
|
Adding messages! :notebook:
|
|
Java
|
mit
|
error: pathspec 'src/main/java/interpres/language/definitions/core/IntegerToString.java' did not match any file(s) known to git
|
a71f68263639eb1f14abe2264b29a7c5aedce67d
| 1
|
thomasbrus/interpres
|
package interpres.language.definitions.core;
import java.util.List;
import java.util.ArrayList;
import interpres.ast.Symbol;
import interpres.ast.AST;
import interpres.language.definitions.Definition;
import interpres.language.values.Lambda;
import interpres.language.values.Integer;
import interpres.language.values.String;
public class IntegerToString extends Definition {
public IntegerToString() {
super("core.integer-to-string", new Lambda((definitionTable, arguments) -> {
Integer integerValue = (Integer) arguments.get(0).evaluate(definitionTable);
return new String(integerValue.getValue().toString());
}), 0);
}
}
|
src/main/java/interpres/language/definitions/core/IntegerToString.java
|
Added core.integer-to-string
|
src/main/java/interpres/language/definitions/core/IntegerToString.java
|
Added core.integer-to-string
|
|
Java
|
mit
|
error: pathspec 'src/test/java/com/twilio/ivrrecording/servlet/extension/ConnectServletTest.java' did not match any file(s) known to git
|
660b3a095d3c86a5cbedfca528b6986660d7f256
| 1
|
TwilioDevEd/ivr-recording-servlets,TwilioDevEd/ivr-recording-servlets
|
package com.twilio.ivrrecording.servlet.extension;
import com.twilio.ivrrecording.models.Agent;
import com.twilio.ivrrecording.repositories.AgentRepository;
import com.twilio.ivrrecording.servlet.BaseTwilioServletTest;
import com.twilio.ivrrecording.servlet.menu.ShowServlet;
import org.hamcrest.CoreMatchers;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
public class ConnectServletTest extends BaseTwilioServletTest {
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
AgentRepository agentRepository;
@Before
public void setUp() throws IOException {
MockitoAnnotations.initMocks(this);
}
@Test
public void postMethod_WhenAnAgentIsFound_ThenRespondsByDialingTheAgentsPhoneNumber()
throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(output);
String number = "+12025550142";
when(agentRepository.findByExtension(anyString())).thenReturn(new Agent(1, "Brodo", number));
when(request.getParameter("Digits")).thenReturn("2");
when(response.getWriter()).thenReturn(printWriter);
ConnectServlet servlet = new ConnectServlet(agentRepository);
servlet.doPost(request, response);
printWriter.flush();
String content = new String(output.toByteArray(), "UTF-8");
Document document = getDocument(content);
assertThatContentTypeIsXML(response);
assertThat(getAttributeValue(document, "Dial/Number", "url"), is(equalTo("/agents/screen-call")));
assertThat(getElement(document, "Dial/Number").getValue(), is(equalTo(number)));
}
}
|
src/test/java/com/twilio/ivrrecording/servlet/extension/ConnectServletTest.java
|
Add Connect Servlets, tests and some code refactoring
|
src/test/java/com/twilio/ivrrecording/servlet/extension/ConnectServletTest.java
|
Add Connect Servlets, tests and some code refactoring
|
|
Java
|
mit
|
error: pathspec 'java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java' did not match any file(s) known to git
|
499c422de6c20543f17c02064e7468caa85ee9d6
| 1
|
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
|
package org.broadinstitute.sting.playground.fourbasecaller;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileFilter;
import java.util.Vector;
import java.lang.Math;
import org.broadinstitute.sting.playground.illumina.FirecrestFileParser;
import org.broadinstitute.sting.playground.illumina.FourIntensity;
import cern.colt.matrix.linalg.Algebra;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleFactory1D;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileWriter;
import net.sf.samtools.SAMFileWriterFactory;
import net.sf.samtools.SAMRecord;
import edu.mit.broad.picard.illumina.BustardFileParser;
import edu.mit.broad.picard.illumina.BustardReadData;
import edu.mit.broad.picard.illumina.BustardFileParser_1_1;
public class FourBaseRecaller {
public static void main(String[] argv) {
// Parse args
File FIRECREST_DIR = new File(argv[0]);
int LANE = Integer.valueOf(argv[1]);
File SAM_OUT = new File(argv[2]);
int CYCLE_START = Integer.valueOf(argv[3]);
int CYCLE_STOP = Integer.valueOf(argv[4]);
boolean isPaired = Boolean.valueOf(argv[5]);
int readLength = (CYCLE_STOP - CYCLE_START);
File BUSTARD_DIR = getBustardDirectory(FIRECREST_DIR);
int limit = 1000000;
NucleotideChannelMeans[] cmeans = new NucleotideChannelMeans[readLength];
NucleotideChannelCovariances[] ccov = new NucleotideChannelCovariances[readLength];
for (int i = 0; i < readLength; i++) {
cmeans[i] = new NucleotideChannelMeans();
ccov[i] = new NucleotideChannelCovariances();
}
// Loop through bustard data and compute signal means
FirecrestFileParser ffp1 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP);
BustardFileParser_1_1 bfp1 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS");
for (int queryid = 0; queryid < limit && ffp1.hasNext(); queryid++) {
if (queryid % (limit/10) == 0) {
System.err.println("Processed " + queryid + " reads for means.");
}
FourIntensity[] intensities = ffp1.next().getIntensities();
String rsq = (CYCLE_START == 0) ? bfp1.next().getFirstReadSequence() : bfp1.next().getSecondReadSequence();
for (int cycle = 0; cycle < intensities.length; cycle++) {
FourIntensity sig = intensities[cycle];
if (rsq.charAt(cycle) == 'A') { cmeans[cycle].add(Nucleotide.A, sig); }
else if (rsq.charAt(cycle) == 'C') { cmeans[cycle].add(Nucleotide.C, sig); }
else if (rsq.charAt(cycle) == 'G') { cmeans[cycle].add(Nucleotide.G, sig); }
else if (rsq.charAt(cycle) == 'T') { cmeans[cycle].add(Nucleotide.T, sig); }
}
}
// Go through the data again and compute signal covariances
FirecrestFileParser ffp2 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP);
BustardFileParser_1_1 bfp2 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS");
for (int queryid = 0; queryid < limit && ffp2.hasNext(); queryid++) {
if (queryid % (limit/10) == 0) {
System.err.println("Processed " + queryid + " reads for covariances.");
}
FourIntensity[] intensities = ffp2.next().getIntensities();
String rsq = (CYCLE_START == 0) ? bfp2.next().getFirstReadSequence() : bfp2.next().getSecondReadSequence();
for (int cycle = 0; cycle < intensities.length; cycle++) {
FourIntensity sig = intensities[cycle];
NucleotideChannelMeans mus = cmeans[cycle];
if (rsq.charAt(cycle) == 'A') { ccov[cycle].add(Nucleotide.A, sig, mus); }
else if (rsq.charAt(cycle) == 'C') { ccov[cycle].add(Nucleotide.C, sig, mus); }
else if (rsq.charAt(cycle) == 'G') { ccov[cycle].add(Nucleotide.G, sig, mus); }
else if (rsq.charAt(cycle) == 'T') { ccov[cycle].add(Nucleotide.T, sig, mus); }
}
}
// Now compute probabilities for the bases
Algebra alg = new Algebra();
for (int cycle = 0; cycle < readLength; cycle++) {
ccov[cycle].invert();
}
FirecrestFileParser ffp3 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP);
SAMFileHeader sfh = new SAMFileHeader();
SAMFileWriter sfw = new SAMFileWriterFactory().makeSAMOrBAMWriter(sfh, false, SAM_OUT);
for (int queryid = 0; ffp3.hasNext(); queryid++) {
if (queryid % limit == 0) {
System.err.println("Basecalled " + queryid + " reads.");
}
FourIntensity[] intensities = ffp3.next().getIntensities();
byte[] asciiseq = new byte[intensities.length];
byte[] bestqual = new byte[intensities.length];
byte[] nextbestqual = new byte[intensities.length];
for (int cycle = 0; cycle < intensities.length; cycle++) {
FourIntensity fi = intensities[cycle];
double[] likes = new double[4];
double total = 0.0;
for (Nucleotide nuc : Nucleotide.values()) {
double norm = Math.sqrt(alg.det(ccov[cycle].channelCovariances(nuc)))/Math.pow(2.0*Math.PI, 2.0);
DoubleMatrix1D sub = subtract(fi, cmeans[cycle].channelMeans(nuc));
DoubleMatrix1D Ax = alg.mult(ccov[cycle].channelCovariances(nuc), sub);
double exparg = -0.5*alg.mult(sub, Ax);
likes[nuc.ordinal()] = norm*Math.exp(exparg);
total += likes[nuc.ordinal()];
}
Nucleotide call1 = Nucleotide.A;
double prob1 = likes[0]/total;
for (int i = 1; i < 4; i++) {
if (likes[i]/total > prob1) {
prob1 = likes[i]/total;
switch (i) {
case 1: call1 = Nucleotide.C; break;
case 2: call1 = Nucleotide.G; break;
case 3: call1 = Nucleotide.T; break;
}
}
}
Nucleotide call2 = Nucleotide.A;
double prob2 = 0.0;
for (int i = 0; i < 4; i++) {
if (i != call1.ordinal() && likes[i]/total > prob2 && likes[i]/total < prob1) {
prob2 = likes[i]/total;
switch (i) {
case 0: call2 = Nucleotide.A; break;
case 1: call2 = Nucleotide.C; break;
case 2: call2 = Nucleotide.G; break;
case 3: call2 = Nucleotide.T; break;
}
}
}
asciiseq[cycle] = (byte) call1.asChar();
bestqual[cycle] = toPhredScore(prob1);
nextbestqual[cycle] = toCompressedQuality(call2, prob2);
}
SAMRecord sr = new SAMRecord(sfh);
sr.setReadName(Integer.toString(queryid));
sr.setReadUmappedFlag(true);
sr.setReadBases(asciiseq);
sr.setBaseQualities(bestqual);
sr.setAttribute("SQ", nextbestqual);
sfw.addAlignment(sr);
queryid++;
}
sfw.close();
System.err.println("Done.");
}
private static byte toPhredScore(double prob) {
byte qual = (1.0 - prob < 0.00001) ? 40 : (byte) (-10*Math.log10(1.0 - prob));
//System.out.println("prob=" + prob + " qual=" + qual);
return (qual > 40) ? 40 : qual;
}
private static DoubleMatrix1D subtract(FourIntensity a, FourIntensity b) {
DoubleMatrix1D sub = (DoubleFactory1D.dense).make(4);
for (int i = 0; i < 4; i++) {
sub.set(i, a.getChannelIntensity(i) - b.getChannelIntensity(i));
}
return sub;
}
private static byte toCompressedQuality(Nucleotide base, double prob) {
byte compressedQual = (byte) base.ordinal();
byte cprob = (byte) (100.0*prob);
byte qualmask = (byte) 252;
compressedQual += ((cprob << 2) & qualmask);
return compressedQual;
}
private static NucleotideSequence toNucleotideSequence(FourIntensity[] intensities) {
NucleotideSequence ns = new NucleotideSequence(intensities.length);
for (int cycle = 0; cycle < intensities.length; cycle++) {
int brightestChannel = intensities[cycle].brightestChannel();
Nucleotide nt = Nucleotide.A;
switch (brightestChannel) {
case 0: nt = Nucleotide.A; break;
case 1: nt = Nucleotide.C; break;
case 2: nt = Nucleotide.G; break;
case 3: nt = Nucleotide.T; break;
}
ns.set(cycle, nt);
}
return ns;
}
private static File getBustardDirectory(File firecrestDir) {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
return (file.isDirectory() && file.getName().contains("Bustard"));
}
};
File[] bustardDirs = firecrestDir.listFiles(filter);
return bustardDirs[0];
}
}
|
java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java
|
A version of the four-base caller that computes the probability distribution over base call space by initializing off the Bustard calls rather than the ICs.
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@173 348d0f76-0448-11de-a6fe-93d51630548a
|
java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java
|
A version of the four-base caller that computes the probability distribution over base call space by initializing off the Bustard calls rather than the ICs.
|
|
Java
|
epl-1.0
|
error: pathspec 'org.eclipse.sisu.plexus.tests/src/org/eclipse/sisu/plexus/DefaultValuesTest.java' did not match any file(s) known to git
|
b3c6c7edc253c2a373d408aafbf36433f9ede732
| 1
|
eclipse/sisu.plexus,mcculls/sisu.plexus,eclipse/sisu.plexus,mcculls/sisu.plexus,mcculls/sisu.plexus
|
/*******************************************************************************
* Copyright (c) 2010, 2015 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stuart McCulloch (Sonatype, Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.sisu.plexus;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.codehaus.plexus.component.configurator.BasicComponentConfigurator;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
public class DefaultValuesTest
extends TestCase
{
public void testDefaultBasicValue()
throws ComponentConfigurationException
{
final ComponentWithInt componentWithString = new ComponentWithInt();
final PlexusConfiguration config = new XmlPlexusConfiguration( "config" );
final PlexusConfiguration target = new XmlPlexusConfiguration( "target" );
target.setAttribute( "default-value", "TEST" );
config.addChild( target );
new BasicComponentConfigurator().configureComponent( componentWithString, config, null );
assertEquals( "TEST", componentWithString.target );
target.setValue( "OVERRIDE" );
new BasicComponentConfigurator().configureComponent( componentWithString, config, null );
assertEquals( "OVERRIDE", componentWithString.target );
}
public void testDefaultCollection()
throws ComponentConfigurationException
{
final ComponentWithArray componentWithArray = new ComponentWithArray();
final ComponentWithList componentWithList = new ComponentWithList();
final PlexusConfiguration config = new XmlPlexusConfiguration( "config" );
final PlexusConfiguration target = new XmlPlexusConfiguration( "target" );
target.setAttribute( "default-value", "one,two,three" );
config.addChild( target );
new BasicComponentConfigurator().configureComponent( componentWithArray, config, null );
assertTrue( Arrays.equals( new String[] { "one", "two", "three" }, componentWithArray.target ) );
new BasicComponentConfigurator().configureComponent( componentWithList, config, null );
assertEquals( Arrays.asList( "one", "two", "three" ), componentWithList.target );
final PlexusConfiguration element = new XmlPlexusConfiguration( "element" );
element.setValue( "OVERRIDE" );
target.addChild( element );
new BasicComponentConfigurator().configureComponent( componentWithArray, config, null );
assertTrue( Arrays.equals( new String[] { "OVERRIDE" }, componentWithArray.target ) );
new BasicComponentConfigurator().configureComponent( componentWithList, config, null );
assertEquals( Arrays.asList( "OVERRIDE" ), componentWithList.target );
}
static class ComponentWithInt
{
String target;
}
static class ComponentWithArray
{
String[] target;
}
static class ComponentWithList
{
List<String> target;
}
}
|
org.eclipse.sisu.plexus.tests/src/org/eclipse/sisu/plexus/DefaultValuesTest.java
|
Bug 470781: test default values can be overridden
|
org.eclipse.sisu.plexus.tests/src/org/eclipse/sisu/plexus/DefaultValuesTest.java
|
Bug 470781: test default values can be overridden
|
|
Java
|
agpl-3.0
|
error: pathspec 'webapp/lib/src/test/java/com/github/podd/resources/test/DeleteArtifactResourceImplTest.java' did not match any file(s) known to git
|
5a3783ea3bb57363cee35e44c166f011111ed97b
| 1
|
podd/podd-redesign,podd/podd-redesign,podd/podd-redesign,podd/podd-redesign
|
/**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.resources.test;
import org.junit.Assert;
import org.junit.Test;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Status;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import com.github.ansell.restletutils.test.RestletTestUtils;
import com.github.podd.api.test.TestConstants;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.PoddWebConstants;
/**
* @author kutila
*
*/
public class DeleteArtifactResourceImplTest extends AbstractResourceImplTest
{
@Test
public void testDeleteArtifactBasicRdf() throws Exception
{
// prepare: add an artifact
final InferredOWLOntologyID artifactID =
this.loadTestArtifact(TestConstants.TEST_ARTIFACT_20130206, MediaType.APPLICATION_RDF_TURTLE);
final ClientResource deleteArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_DELETE));
deleteArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactID
.getOntologyIRI().toString());
deleteArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, artifactID
.getVersionIRI().toString());
RestletTestUtils.doTestAuthenticatedRequest(deleteArtifactClientResource, Method.DELETE, null,
MediaType.APPLICATION_RDF_XML, Status.SUCCESS_NO_CONTENT, this.testWithAdminPrivileges);
// verify: try to retrieve deleted artifact
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactID
.getOntologyIRI().toString());
try
{
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.APPLICATION_RDF_XML, Status.CLIENT_ERROR_NOT_FOUND, this.testWithAdminPrivileges);
Assert.fail("Should have failed with a NOT_FOUND error");
}
catch(ResourceException e)
{
Assert.assertNotNull(e);
}
}
}
|
webapp/lib/src/test/java/com/github/podd/resources/test/DeleteArtifactResourceImplTest.java
|
add restlet resource test for delete artifact
|
webapp/lib/src/test/java/com/github/podd/resources/test/DeleteArtifactResourceImplTest.java
|
add restlet resource test for delete artifact
|
|
Java
|
lgpl-2.1
|
error: pathspec 'intermine/objectstore/test/src/org/intermine/sql/OracleConnectionTest.java' did not match any file(s) known to git
|
0096811b94ebc53caa6ea8f45d20c8a4ba18ecb3
| 1
|
JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,elsiklab/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,zebrafishmine/intermine,JoeCarlson/intermine,drhee/toxoMine,elsiklab/intermine,justincc/intermine,justincc/intermine,drhee/toxoMine,elsiklab/intermine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,kimrutherford/intermine,tomck/intermine,joshkh/intermine,kimrutherford/intermine,joshkh/intermine,justincc/intermine,joshkh/intermine,JoeCarlson/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,tomck/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,tomck/intermine,JoeCarlson/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,zebrafishmine/intermine
|
package org.intermine.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* class to test a connection to oracle
*/
public class OracleConnectionTest {
private static final String INSTANCE = "db.sgd";
private static Properties props = new Properties();
private static final String TEST_QUERY = "select feature_name from feature";
/**
* set up the connection to the database using properties specified in setUpProps()
* run the sample query
*/
public static void testConnection() {
setUpProps();
Database database = null;
try {
database = new Database(props);
} catch (Exception e) {
throw new RuntimeException("Failed to initialise " + INSTANCE, e);
}
Connection conn = null;
try {
conn = database.getConnection();
runQuery(conn);
} catch (SQLException e) {
throw new RuntimeException("couldn't load properties:", e);
}
}
/**
* load the properties directly.
*
* note that the beginning of the properties (eg. db.sgd) are stripped off.
*
* see org.intermine.sql.DatabaseFactory
*
* When the database is created, the starting instance is removed:
*
* database = new Database(PropertiesUtil.stripStart(instance, props));
*/
private static void setUpProps() {
props = new Properties();
props.put("datasource.class", "oracle.jdbc.pool.OracleDataSource");
props.put("datasource.serverName", "oracle.flymine.org");
props.put("datasource.databaseName", "XE");
props.put("datasource.user", "");
props.put("datasource.password", "");
props.put("datasource.maxConnections", "10");
props.put("platform", "Oracle");
props.put("driver", "org.oracle.jdbc.OracleDriver");
props.put("datasource.driverType", "thin");
props.put("datasource.portNumber", "1521");
}
/**
* test the driver by calling the class directly
* pass the connection string to the driver manager, test the connection by running a query
*/
public static void testDriver() {
Connection conn = null;
try {
// register the driver directly
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
} catch (SQLException e) {
System.out.println("oops:" + e.getMessage());
}
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.flymine.org:1521:XE", "bud", "bud");
runQuery(conn);
} catch (SQLException e) {
throw new RuntimeException("oops:", e);
}
}
/**
* test the connection to the database by running a sample query and outputting the first column of results
* @param conn connection to the database
*/
private static void runQuery(Connection conn) {
Statement stmt = null;
ResultSet rset = null;
try {
stmt = conn.createStatement();
// execute query
rset = stmt.executeQuery(TEST_QUERY);
System.out.println("running query ....");
// loop through results
while (rset.next()) {
System.out.println(rset.getString(1));
}
// done!
System.out.println("query done!");
// clean up
rset.close();
rset = null;
stmt.close();
stmt = null;
conn.close();
conn = null;
} catch (SQLException e) {
throw new RuntimeException("oops", e);
}
}
public static void main(String[] args) {
testDriver();
// testConnection();
}
}
|
intermine/objectstore/test/src/org/intermine/sql/OracleConnectionTest.java
|
test oracle connection.
|
intermine/objectstore/test/src/org/intermine/sql/OracleConnectionTest.java
|
test oracle connection.
|
|
Java
|
unlicense
|
error: pathspec 'src/Test.java' did not match any file(s) known to git
|
6b1c3fd89ff0393fb3c5021a784b31cd23438109
| 1
|
samirsikander/tdd-part1
|
public class Test {
}
|
src/Test.java
|
Testing commit
|
src/Test.java
|
Testing commit
|
|
Java
|
apache-2.0
|
ef018c0385452635fed17e880d802fa30e623e10
| 0
|
epiphany27/SeriesGuide,UweTrottmann/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide,0359xiaodong/SeriesGuide,hoanganhx86/SeriesGuide,artemnikitin/SeriesGuide
|
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.getglueapi.GetGlue;
import com.battlelancer.seriesguide.getglueapi.PrepareRequestTokenActivity;
import com.battlelancer.seriesguide.provider.SeriesContract.Episodes;
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.seriesguide.ui.ShowInfoActivity;
import com.jakewharton.apibuilder.ApiException;
import com.jakewharton.trakt.ServiceManager;
import com.jakewharton.trakt.TraktException;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.enumerations.Rating;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.SupportActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
public class ShareUtils {
public static final String KEY_GETGLUE_COMMENT = "com.battlelancer.seriesguide.getglue.comment";
public static final String KEY_GETGLUE_IMDBID = "com.battlelancer.seriesguide.getglue.imdbid";
protected static final String TAG = "ShareUtils";
public enum ShareMethod {
CHECKIN_GETGLUE(0, R.string.menu_checkin_getglue, R.drawable.ic_getglue),
CHECKIN_TRAKT(1, R.string.menu_checkin_trakt, R.drawable.ic_trakt),
MARKSEEN_TRAKT(2, R.string.menu_markseen_trakt, R.drawable.ic_trakt_seen),
RATE_TRAKT(3, R.string.menu_rate_trakt, R.drawable.trakt_love_large),
OTHER_SERVICES(4, R.string.menu_share_others, R.drawable.ic_action_share);
ShareMethod(int index, int titleRes, int drawableRes) {
this.index = index;
this.titleRes = titleRes;
this.drawableRes = drawableRes;
}
public int index;
public int titleRes;
public int drawableRes;
}
/**
* Share an episode via the given {@link ShareMethod}.
*
* @param activity
* @param shareData - a {@link Bundle} including all
* {@link ShareUtils.ShareItems}
* @param shareMethod the {@link ShareMethod} to use
*/
public static void onShareEpisode(SupportActivity activity, Bundle shareData,
ShareMethod shareMethod) {
final FragmentManager fm = activity.getSupportFragmentManager();
final String imdbId = shareData.getString(ShareUtils.ShareItems.IMDBID);
final String sharestring = shareData.getString(ShareUtils.ShareItems.SHARESTRING);
// save used share method, so we can use it later for the quick share
// button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.asActivity());
prefs.edit().putInt(SeriesGuidePreferences.KEY_LAST_USED_SHARE_METHOD, shareMethod.index)
.commit();
switch (shareMethod) {
case CHECKIN_GETGLUE: {
// GetGlue check in
if (imdbId.length() != 0) {
showGetGlueDialog(fm, shareData);
} else {
Toast.makeText(activity.asActivity(),
activity.getString(R.string.checkin_impossible), Toast.LENGTH_LONG)
.show();
}
break;
}
case CHECKIN_TRAKT: {
// trakt check in
// DialogFragment.show() will take care of
// adding the fragment
// in a transaction. We also want to remove
// any currently showing
// dialog, so make our own transaction and
// take care of that here.
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
ProgressDialog newFragment = ProgressDialog.newInstance();
// start the trakt check in task, add the
// dialog as listener
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.CHECKIN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData, newFragment).execute();
newFragment.show(ft, "progress-dialog");
break;
}
case MARKSEEN_TRAKT: {
// trakt mark as seen
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.SEEN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData).execute();
break;
}
case RATE_TRAKT: {
// trakt rate
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.RATE_EPISODE.index());
TraktRateDialogFragment newFragment = TraktRateDialogFragment
.newInstance(shareData);
FragmentTransaction ft = fm.beginTransaction();
newFragment.show(ft, "traktratedialog");
break;
}
case OTHER_SERVICES: {
// Android apps
String text = sharestring;
if (imdbId.length() != 0) {
text += " " + ShowInfoActivity.IMDB_TITLE_URL + imdbId;
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(i,
activity.getString(R.string.share_episode)));
break;
}
}
}
public static void showGetGlueDialog(FragmentManager manager, Bundle shareData) {
// Create and show the dialog.
GetGlueDialogFragment newFragment = GetGlueDialogFragment.newInstance(shareData);
FragmentTransaction ft = manager.beginTransaction();
newFragment.show(ft, "getgluedialog");
}
public static class GetGlueDialogFragment extends DialogFragment {
public static GetGlueDialogFragment newInstance(Bundle shareData) {
GetGlueDialogFragment f = new GetGlueDialogFragment();
f.setArguments(shareData);
return f;
}
private EditText input;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String episodestring = getArguments().getString(ShareItems.EPISODESTRING);
final String imdbId = getArguments().getString(ShareItems.IMDBID);
input = new EditText(getActivity());
input.setMinLines(3);
input.setGravity(Gravity.TOP);
input.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(140)
});
if (savedInstanceState != null) {
input.setText(savedInstanceState.getString("inputtext"));
} else {
input.setText(episodestring);
}
return new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.comment))
.setView(input)
.setPositiveButton(R.string.checkin, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onGetGlueCheckIn(getActivity(), input.getText().toString(), imdbId);
}
}).setNegativeButton(android.R.string.cancel, null).create();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("inputtext", input.getText().toString());
}
}
public static void onGetGlueCheckIn(final Activity activity, final String comment,
final String imdbId) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
if (GetGlue.isAuthenticated(prefs)) {
new Thread(new Runnable() {
public void run() {
try {
GetGlue.checkIn(prefs, imdbId, comment, activity);
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity,
activity.getString(R.string.checkinsuccess),
Toast.LENGTH_SHORT).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Success", 0);
} catch (final Exception e) {
Log.e(TAG, "GetGlue Check-In failed");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
activity,
activity.getString(R.string.checkinfailed) + " - "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Failed", 0);
}
}
}).start();
} else {
Intent i = new Intent(activity, PrepareRequestTokenActivity.class);
i.putExtra(ShareUtils.KEY_GETGLUE_IMDBID, imdbId);
i.putExtra(ShareUtils.KEY_GETGLUE_COMMENT, comment);
activity.startActivity(i);
}
}
public interface ShareItems {
String SEASON = "season";
String IMDBID = "imdbId";
String SHARESTRING = "sharestring";
String EPISODESTRING = "episodestring";
String EPISODE = "episode";
String TVDBID = "tvdbid";
String RATING = "rating";
String TRAKTACTION = "traktaction";
}
public static String onCreateShareString(Context context, final Cursor episode) {
String season = episode.getString(episode.getColumnIndexOrThrow(Episodes.SEASON));
String number = episode.getString(episode.getColumnIndexOrThrow(Episodes.NUMBER));
String title = episode.getString(episode.getColumnIndexOrThrow(Episodes.TITLE));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return Utils.getNextEpisodeString(prefs, season, number, title);
}
public static void onAddCalendarEvent(Context context, String title, String description,
long airtime, String runtime) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", title);
intent.putExtra("description", description);
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
Calendar cal = Utils.getAirtimeCalendar(airtime, prefs);
long startTime = cal.getTimeInMillis();
long endTime = startTime + Long.valueOf(runtime) * DateUtils.MINUTE_IN_MILLIS;
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", endTime);
context.startActivity(intent);
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Success", 0);
} catch (Exception e) {
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Failed", 0);
Toast.makeText(context, context.getString(R.string.addtocalendar_failed),
Toast.LENGTH_SHORT).show();
}
}
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public enum TraktAction {
SEEN_EPISODE(0), RATE_EPISODE(1), CHECKIN_EPISODE(2);
final private int mIndex;
private TraktAction(int index) {
mIndex = index;
}
public int index() {
return mIndex;
}
}
public interface TraktStatus {
String SUCCESS = "success";
String FAILURE = "failure";
}
public static class TraktTask extends AsyncTask<Void, Void, Response> {
private final Context mContext;
private final FragmentManager mManager;
private final Bundle mTraktData;
private OnTaskFinishedListener mListener;
public interface OnTaskFinishedListener {
public void onTaskFinished();
}
/**
* Do the specified TraktAction. traktData should include all required
* parameters.
*
* @param context
* @param manager
* @param traktData
* @param action
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData) {
mContext = context;
mManager = manager;
mTraktData = traktData;
}
/**
* Specify a listener which will be notified once any activity context
* dependent work is completed.
*
* @param context
* @param manager
* @param traktData
* @param listener
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData,
OnTaskFinishedListener listener) {
this(context, manager, traktData);
mListener = listener;
}
@Override
protected Response doInBackground(Void... params) {
if (!isTraktCredentialsValid(mContext)) {
// return null, so onPostExecute displays a credentials dialog
// which later calls us again.
return null;
}
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(mContext, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = mContext.getString(R.string.trakt_decryptfail);
return r;
}
// get some values
final int tvdbid = mTraktData.getInt(ShareItems.TVDBID);
final int season = mTraktData.getInt(ShareItems.SEASON);
final int episode = mTraktData.getInt(ShareItems.EPISODE);
final TraktAction action = TraktAction.values()[mTraktData
.getInt(ShareItems.TRAKTACTION)];
// last chance to abort (return value thrown away)
if (isCancelled()) {
return null;
}
try {
Response r = null;
switch (action) {
case CHECKIN_EPISODE: {
r = manager.showService().checkin(tvdbid).season(season).episode(episode)
.fire();
break;
}
case SEEN_EPISODE: {
manager.showService().episodeSeen(tvdbid).episode(season, episode).fire();
r = new Response();
r.status = TraktStatus.SUCCESS;
r.message = mContext.getString(R.string.trakt_seen);
break;
}
case RATE_EPISODE: {
final Rating rating = Rating.fromValue(mTraktData
.getString(ShareItems.RATING));
r = manager.rateService().episode(tvdbid).season(season).episode(episode)
.rating(rating).fire();
break;
}
}
return r;
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
}
@Override
protected void onPostExecute(Response r) {
if (r != null) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(mContext,
mContext.getString(R.string.trakt_success) + ": " + r.message,
Toast.LENGTH_SHORT).show();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
if (r.wait != 0) {
// looks like a check in is in progress
TraktCancelCheckinDialogFragment newFragment = TraktCancelCheckinDialogFragment
.newInstance(mTraktData, r.wait);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "cancel-checkin-dialog");
} else {
// well, something went wrong
Toast.makeText(mContext,
mContext.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
} else {
// credentials are invalid
TraktCredentialsDialogFragment newFragment = TraktCredentialsDialogFragment
.newInstance(mTraktData);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "traktdialog");
}
// tell a potential listener that our work is done
if (mListener != null) {
mListener.onTaskFinished();
}
}
}
public static class TraktCredentialsDialogFragment extends DialogFragment {
private boolean isForwardingGivenTask;
public static TraktCredentialsDialogFragment newInstance(Bundle traktData) {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.setArguments(traktData);
f.isForwardingGivenTask = true;
return f;
}
public static TraktCredentialsDialogFragment newInstance() {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.isForwardingGivenTask = false;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null);
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
((EditText) layout.findViewById(R.id.username)).setText(username);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(layout);
builder.setTitle("trakt.tv");
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
((CheckBox) layout.findViewById(R.id.checkNewAccount))
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
builder.setPositiveButton(R.string.save, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String username = ((EditText) layout.findViewById(R.id.username))
.getText().toString();
final String passwordHash = ShareUtils.toSHA1(((EditText) layout
.findViewById(R.id.password)).getText().toString().getBytes());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout
.findViewById(R.id.checkNewAccount)).isChecked();
AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
// SHA of any password is always non-empty
if (username.length() == 0) {
return null;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final ServiceManager manager = new ServiceManager();
manager.setApiKey(getResources().getString(R.string.trakt_apikey));
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService()
.create(username, passwordHash, email).fire();
} else {
// validate existing account
response = manager.accountService().test().fire();
}
} catch (TraktException te) {
response = te.getResponse();
} catch (ApiException ae) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
if (response != null) {
String passwordEncr;
// try to encrypt the password before storing it
try {
passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
} catch (Exception e) {
passwordEncr = "";
}
// prepare writing credentials to settings
Editor editor = prefs.edit();
editor.putString(SeriesGuidePreferences.KEY_TRAKTUSER, username)
.putString(SeriesGuidePreferences.KEY_TRAKTPWD,
passwordEncr);
if (response.getStatus().equalsIgnoreCase("success")
&& passwordEncr.length() != 0 && editor.commit()) {
// all went through
Toast.makeText(context,
response.getStatus() + ": " + response.getMessage(),
Toast.LENGTH_SHORT).show();
// set new auth data for service manager
try {
Utils.getServiceManagerWithAuth(context, true);
} catch (Exception e) {
// we don't care
}
} else {
Toast.makeText(context,
response.getStatus() + ": " + response.getError(),
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context,
context.getString(R.string.trakt_generalerror),
Toast.LENGTH_LONG).show();
}
if (isForwardingGivenTask) {
// relaunch the trakt task which called us
new TraktTask(context, fm, args).execute();
}
}
};
accountValidatorTask.execute();
}
});
builder.setNegativeButton(R.string.dontsave, null);
return builder.create();
}
}
public static class TraktCancelCheckinDialogFragment extends DialogFragment {
private int mWait;
public static TraktCancelCheckinDialogFragment newInstance(Bundle traktData, int wait) {
TraktCancelCheckinDialogFragment f = new TraktCancelCheckinDialogFragment();
f.setArguments(traktData);
f.mWait = wait;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(context.getString(R.string.traktcheckin_inprogress,
DateUtils.formatElapsedTime(mWait)));
builder.setPositiveButton(R.string.traktcheckin_cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AsyncTask<String, Void, Response> cancelCheckinTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(context, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.trakt_decryptfail);
return r;
}
Response response;
try {
response = manager.showService().cancelCheckin().fire();
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
return response;
}
@Override
protected void onPostExecute(Response r) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(
context,
context.getString(R.string.trakt_success) + ": "
+ r.message, Toast.LENGTH_SHORT).show();
// relaunch the trakt task which called us to
// try the check in again
new TraktTask(context, fm, args).execute();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
// well, something went wrong
Toast.makeText(context,
context.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
};
cancelCheckinTask.execute();
}
});
builder.setNegativeButton(R.string.traktcheckin_wait, null);
return builder.create();
}
}
public static class TraktRateDialogFragment extends DialogFragment {
public static TraktRateDialogFragment newInstance(Bundle traktData) {
TraktRateDialogFragment f = new TraktRateDialogFragment();
f.setArguments(traktData);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity();
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_rate_dialog, null);
final Button totallyNinja = (Button) layout.findViewById(R.id.totallyninja);
final Button weakSauce = (Button) layout.findViewById(R.id.weaksauce);
totallyNinja.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Love;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
weakSauce.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Hate;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
builder = new AlertDialog.Builder(context);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
}
public static class ProgressDialog extends DialogFragment implements
TraktTask.OnTaskFinishedListener {
public static ProgressDialog newInstance() {
ProgressDialog f = new ProgressDialog();
f.setCancelable(false);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.progress_dialog, container, false);
return v;
}
@Override
public void onTaskFinished() {
if (isVisible()) {
dismiss();
}
}
}
public static boolean isTraktCredentialsValid(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, "");
return (!username.equalsIgnoreCase("") && !password.equalsIgnoreCase(""));
}
}
|
SeriesGuide/src/com/battlelancer/seriesguide/util/ShareUtils.java
|
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.getglueapi.GetGlue;
import com.battlelancer.seriesguide.getglueapi.PrepareRequestTokenActivity;
import com.battlelancer.seriesguide.provider.SeriesContract.Episodes;
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.seriesguide.ui.ShowInfoActivity;
import com.jakewharton.apibuilder.ApiException;
import com.jakewharton.trakt.ServiceManager;
import com.jakewharton.trakt.TraktException;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.enumerations.Rating;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.SupportActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
public class ShareUtils {
public static final String KEY_GETGLUE_COMMENT = "com.battlelancer.seriesguide.getglue.comment";
public static final String KEY_GETGLUE_IMDBID = "com.battlelancer.seriesguide.getglue.imdbid";
protected static final String TAG = "ShareUtils";
public enum ShareMethod {
CHECKIN_GETGLUE(0, R.string.menu_checkin_getglue, R.drawable.ic_getglue),
CHECKIN_TRAKT(1, R.string.menu_checkin_trakt, R.drawable.ic_trakt),
MARKSEEN_TRAKT(2, R.string.menu_markseen_trakt, R.drawable.ic_trakt_seen),
RATE_TRAKT(3, R.string.menu_rate_trakt, R.drawable.trakt_love_large),
OTHER_SERVICES(4, R.string.menu_share_others, R.drawable.ic_action_share);
ShareMethod(int index, int titleRes, int drawableRes) {
this.index = index;
this.titleRes = titleRes;
this.drawableRes = drawableRes;
}
public int index;
public int titleRes;
public int drawableRes;
}
/**
* Share an episode via the given {@link ShareMethod}.
*
* @param activity
* @param shareData - a {@link Bundle} including all
* {@link ShareUtils.ShareItems}
* @param shareMethod the {@link ShareMethod} to use
*/
public static void onShareEpisode(SupportActivity activity, Bundle shareData,
ShareMethod shareMethod) {
final FragmentManager fm = activity.getSupportFragmentManager();
final String imdbId = shareData.getString(ShareUtils.ShareItems.IMDBID);
final String sharestring = shareData.getString(ShareUtils.ShareItems.SHARESTRING);
// save used share method, so we can use it later for the quick share
// button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.asActivity());
prefs.edit().putInt(SeriesGuidePreferences.KEY_LAST_USED_SHARE_METHOD, shareMethod.index)
.commit();
switch (shareMethod) {
case CHECKIN_GETGLUE: {
// GetGlue check in
if (imdbId.length() != 0) {
showGetGlueDialog(fm, shareData);
} else {
Toast.makeText(activity.asActivity(),
activity.getString(R.string.checkin_impossible), Toast.LENGTH_LONG)
.show();
}
break;
}
case CHECKIN_TRAKT: {
// trakt check in
// DialogFragment.show() will take care of
// adding the fragment
// in a transaction. We also want to remove
// any currently showing
// dialog, so make our own transaction and
// take care of that here.
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
ProgressDialog newFragment = ProgressDialog.newInstance();
// start the trakt check in task, add the
// dialog as listener
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.CHECKIN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData, newFragment).execute();
newFragment.show(ft, "progress-dialog");
break;
}
case MARKSEEN_TRAKT: {
// trakt mark as seen
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.SEEN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData).execute();
break;
}
case RATE_TRAKT: {
// trakt rate
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.RATE_EPISODE.index());
TraktRateDialogFragment newFragment = TraktRateDialogFragment
.newInstance(shareData);
FragmentTransaction ft = fm.beginTransaction();
newFragment.show(ft, "traktratedialog");
break;
}
case OTHER_SERVICES: {
// Android apps
String text = sharestring;
if (imdbId.length() != 0) {
text += " " + ShowInfoActivity.IMDB_TITLE_URL + imdbId;
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(i,
activity.getString(R.string.share_episode)));
break;
}
}
}
public static void showGetGlueDialog(FragmentManager manager, Bundle shareData) {
// Create and show the dialog.
GetGlueDialogFragment newFragment = GetGlueDialogFragment.newInstance(shareData);
FragmentTransaction ft = manager.beginTransaction();
newFragment.show(ft, "getgluedialog");
}
public static class GetGlueDialogFragment extends DialogFragment {
public static GetGlueDialogFragment newInstance(Bundle shareData) {
GetGlueDialogFragment f = new GetGlueDialogFragment();
f.setArguments(shareData);
return f;
}
private EditText input;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String episodestring = getArguments().getString(ShareItems.EPISODESTRING);
final String imdbId = getArguments().getString(ShareItems.IMDBID);
input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMinLines(3);
input.setGravity(Gravity.TOP);
input.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(140)
});
if (savedInstanceState != null) {
input.setText(savedInstanceState.getString("inputtext"));
} else {
input.setText(episodestring);
}
return new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.comment))
.setView(input)
.setPositiveButton(R.string.checkin, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onGetGlueCheckIn(getActivity(), input.getText().toString(), imdbId);
}
}).setNegativeButton(android.R.string.cancel, null).create();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("inputtext", input.getText().toString());
}
}
public static void onGetGlueCheckIn(final Activity activity, final String comment,
final String imdbId) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
if (GetGlue.isAuthenticated(prefs)) {
new Thread(new Runnable() {
public void run() {
try {
GetGlue.checkIn(prefs, imdbId, comment, activity);
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity,
activity.getString(R.string.checkinsuccess),
Toast.LENGTH_SHORT).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Success", 0);
} catch (final Exception e) {
Log.e(TAG, "GetGlue Check-In failed");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
activity,
activity.getString(R.string.checkinfailed) + " - "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Failed", 0);
}
}
}).start();
} else {
Intent i = new Intent(activity, PrepareRequestTokenActivity.class);
i.putExtra(ShareUtils.KEY_GETGLUE_IMDBID, imdbId);
i.putExtra(ShareUtils.KEY_GETGLUE_COMMENT, comment);
activity.startActivity(i);
}
}
public interface ShareItems {
String SEASON = "season";
String IMDBID = "imdbId";
String SHARESTRING = "sharestring";
String EPISODESTRING = "episodestring";
String EPISODE = "episode";
String TVDBID = "tvdbid";
String RATING = "rating";
String TRAKTACTION = "traktaction";
}
public static String onCreateShareString(Context context, final Cursor episode) {
String season = episode.getString(episode.getColumnIndexOrThrow(Episodes.SEASON));
String number = episode.getString(episode.getColumnIndexOrThrow(Episodes.NUMBER));
String title = episode.getString(episode.getColumnIndexOrThrow(Episodes.TITLE));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return Utils.getNextEpisodeString(prefs, season, number, title);
}
public static void onAddCalendarEvent(Context context, String title, String description,
long airtime, String runtime) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", title);
intent.putExtra("description", description);
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
Calendar cal = Utils.getAirtimeCalendar(airtime, prefs);
long startTime = cal.getTimeInMillis();
long endTime = startTime + Long.valueOf(runtime) * DateUtils.MINUTE_IN_MILLIS;
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", endTime);
context.startActivity(intent);
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Success", 0);
} catch (Exception e) {
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Failed", 0);
Toast.makeText(context, context.getString(R.string.addtocalendar_failed),
Toast.LENGTH_SHORT).show();
}
}
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public enum TraktAction {
SEEN_EPISODE(0), RATE_EPISODE(1), CHECKIN_EPISODE(2);
final private int mIndex;
private TraktAction(int index) {
mIndex = index;
}
public int index() {
return mIndex;
}
}
public interface TraktStatus {
String SUCCESS = "success";
String FAILURE = "failure";
}
public static class TraktTask extends AsyncTask<Void, Void, Response> {
private final Context mContext;
private final FragmentManager mManager;
private final Bundle mTraktData;
private OnTaskFinishedListener mListener;
public interface OnTaskFinishedListener {
public void onTaskFinished();
}
/**
* Do the specified TraktAction. traktData should include all required
* parameters.
*
* @param context
* @param manager
* @param traktData
* @param action
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData) {
mContext = context;
mManager = manager;
mTraktData = traktData;
}
/**
* Specify a listener which will be notified once any activity context
* dependent work is completed.
*
* @param context
* @param manager
* @param traktData
* @param listener
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData,
OnTaskFinishedListener listener) {
this(context, manager, traktData);
mListener = listener;
}
@Override
protected Response doInBackground(Void... params) {
if (!isTraktCredentialsValid(mContext)) {
// return null, so onPostExecute displays a credentials dialog
// which later calls us again.
return null;
}
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(mContext, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = mContext.getString(R.string.trakt_decryptfail);
return r;
}
// get some values
final int tvdbid = mTraktData.getInt(ShareItems.TVDBID);
final int season = mTraktData.getInt(ShareItems.SEASON);
final int episode = mTraktData.getInt(ShareItems.EPISODE);
final TraktAction action = TraktAction.values()[mTraktData
.getInt(ShareItems.TRAKTACTION)];
// last chance to abort (return value thrown away)
if (isCancelled()) {
return null;
}
try {
Response r = null;
switch (action) {
case CHECKIN_EPISODE: {
r = manager.showService().checkin(tvdbid).season(season).episode(episode)
.fire();
break;
}
case SEEN_EPISODE: {
manager.showService().episodeSeen(tvdbid).episode(season, episode).fire();
r = new Response();
r.status = TraktStatus.SUCCESS;
r.message = mContext.getString(R.string.trakt_seen);
break;
}
case RATE_EPISODE: {
final Rating rating = Rating.fromValue(mTraktData
.getString(ShareItems.RATING));
r = manager.rateService().episode(tvdbid).season(season).episode(episode)
.rating(rating).fire();
break;
}
}
return r;
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
}
@Override
protected void onPostExecute(Response r) {
if (r != null) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(mContext,
mContext.getString(R.string.trakt_success) + ": " + r.message,
Toast.LENGTH_SHORT).show();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
if (r.wait != 0) {
// looks like a check in is in progress
TraktCancelCheckinDialogFragment newFragment = TraktCancelCheckinDialogFragment
.newInstance(mTraktData, r.wait);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "cancel-checkin-dialog");
} else {
// well, something went wrong
Toast.makeText(mContext,
mContext.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
} else {
// credentials are invalid
TraktCredentialsDialogFragment newFragment = TraktCredentialsDialogFragment
.newInstance(mTraktData);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "traktdialog");
}
// tell a potential listener that our work is done
if (mListener != null) {
mListener.onTaskFinished();
}
}
}
public static class TraktCredentialsDialogFragment extends DialogFragment {
private boolean isForwardingGivenTask;
public static TraktCredentialsDialogFragment newInstance(Bundle traktData) {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.setArguments(traktData);
f.isForwardingGivenTask = true;
return f;
}
public static TraktCredentialsDialogFragment newInstance() {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.isForwardingGivenTask = false;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null);
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
((EditText) layout.findViewById(R.id.username)).setText(username);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(layout);
builder.setTitle("trakt.tv");
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
((CheckBox) layout.findViewById(R.id.checkNewAccount))
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
builder.setPositiveButton(R.string.save, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String username = ((EditText) layout.findViewById(R.id.username))
.getText().toString();
final String passwordHash = ShareUtils.toSHA1(((EditText) layout
.findViewById(R.id.password)).getText().toString().getBytes());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout
.findViewById(R.id.checkNewAccount)).isChecked();
AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
// SHA of any password is always non-empty
if (username.length() == 0) {
return null;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final ServiceManager manager = new ServiceManager();
manager.setApiKey(getResources().getString(R.string.trakt_apikey));
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService()
.create(username, passwordHash, email).fire();
} else {
// validate existing account
response = manager.accountService().test().fire();
}
} catch (TraktException te) {
response = te.getResponse();
} catch (ApiException ae) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
if (response != null) {
String passwordEncr;
// try to encrypt the password before storing it
try {
passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
} catch (Exception e) {
passwordEncr = "";
}
// prepare writing credentials to settings
Editor editor = prefs.edit();
editor.putString(SeriesGuidePreferences.KEY_TRAKTUSER, username)
.putString(SeriesGuidePreferences.KEY_TRAKTPWD,
passwordEncr);
if (response.getStatus().equalsIgnoreCase("success")
&& passwordEncr.length() != 0 && editor.commit()) {
// all went through
Toast.makeText(context,
response.getStatus() + ": " + response.getMessage(),
Toast.LENGTH_SHORT).show();
// set new auth data for service manager
try {
Utils.getServiceManagerWithAuth(context, true);
} catch (Exception e) {
// we don't care
}
} else {
Toast.makeText(context,
response.getStatus() + ": " + response.getError(),
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context,
context.getString(R.string.trakt_generalerror),
Toast.LENGTH_LONG).show();
}
if (isForwardingGivenTask) {
// relaunch the trakt task which called us
new TraktTask(context, fm, args).execute();
}
}
};
accountValidatorTask.execute();
}
});
builder.setNegativeButton(R.string.dontsave, null);
return builder.create();
}
}
public static class TraktCancelCheckinDialogFragment extends DialogFragment {
private int mWait;
public static TraktCancelCheckinDialogFragment newInstance(Bundle traktData, int wait) {
TraktCancelCheckinDialogFragment f = new TraktCancelCheckinDialogFragment();
f.setArguments(traktData);
f.mWait = wait;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(context.getString(R.string.traktcheckin_inprogress,
DateUtils.formatElapsedTime(mWait)));
builder.setPositiveButton(R.string.traktcheckin_cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AsyncTask<String, Void, Response> cancelCheckinTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(context, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.trakt_decryptfail);
return r;
}
Response response;
try {
response = manager.showService().cancelCheckin().fire();
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
return response;
}
@Override
protected void onPostExecute(Response r) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(
context,
context.getString(R.string.trakt_success) + ": "
+ r.message, Toast.LENGTH_SHORT).show();
// relaunch the trakt task which called us to
// try the check in again
new TraktTask(context, fm, args).execute();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
// well, something went wrong
Toast.makeText(context,
context.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
};
cancelCheckinTask.execute();
}
});
builder.setNegativeButton(R.string.traktcheckin_wait, null);
return builder.create();
}
}
public static class TraktRateDialogFragment extends DialogFragment {
public static TraktRateDialogFragment newInstance(Bundle traktData) {
TraktRateDialogFragment f = new TraktRateDialogFragment();
f.setArguments(traktData);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity();
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_rate_dialog, null);
final Button totallyNinja = (Button) layout.findViewById(R.id.totallyninja);
final Button weakSauce = (Button) layout.findViewById(R.id.weaksauce);
totallyNinja.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Love;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
weakSauce.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Hate;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
builder = new AlertDialog.Builder(context);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
}
public static class ProgressDialog extends DialogFragment implements
TraktTask.OnTaskFinishedListener {
public static ProgressDialog newInstance() {
ProgressDialog f = new ProgressDialog();
f.setCancelable(false);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.progress_dialog, container, false);
return v;
}
@Override
public void onTaskFinished() {
if (isVisible()) {
dismiss();
}
}
}
public static boolean isTraktCredentialsValid(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, "");
return (!username.equalsIgnoreCase("") && !password.equalsIgnoreCase(""));
}
}
|
Remove input type flag from GetGlue comment box. Restores multiline
support.
|
SeriesGuide/src/com/battlelancer/seriesguide/util/ShareUtils.java
|
Remove input type flag from GetGlue comment box. Restores multiline support.
|
|
Java
|
apache-2.0
|
029b02f14cc2f0216cc5fb4cccf820b4ca00cde8
| 0
|
semonte/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,semonte/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,dslomov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,caot/intellij-community,xfournet/intellij-community,ibinti/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,robovm/robovm-studio,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,ryano144/intellij-community,supersven/intellij-community,slisson/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,izonder/intellij-community,caot/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,adedayo/intellij-community,izonder/intellij-community,jexp/idea2,salguarnieri/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vladmm/intellij-community,retomerz/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,da1z/intellij-community,xfournet/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,vladmm/intellij-community,da1z/intellij-community,samthor/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,signed/intellij-community,consulo/consulo,hurricup/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ryano144/intellij-community,samthor/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,fnouama/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,ryano144/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,da1z/intellij-community,clumsy/intellij-community,fitermay/intellij-community,clumsy/intellij-community,jexp/idea2,kdwink/intellij-community,diorcety/intellij-community,petteyg/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,samthor/intellij-community,fitermay/intellij-community,dslomov/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,holmes/intellij-community,izonder/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,kool79/intellij-community,slisson/intellij-community,akosyakov/intellij-community,supersven/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,kdwink/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,blademainer/intellij-community,supersven/intellij-community,ernestp/consulo,pwoodworth/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,xfournet/intellij-community,dslomov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fnouama/intellij-community,da1z/intellij-community,ryano144/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,jexp/idea2,idea4bsd/idea4bsd,muntasirsyed/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,hurricup/intellij-community,kdwink/intellij-community,kdwink/intellij-community,slisson/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kool79/intellij-community,adedayo/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,ernestp/consulo,allotria/intellij-community,fnouama/intellij-community,da1z/intellij-community,vladmm/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,consulo/consulo,kool79/intellij-community,amith01994/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,kool79/intellij-community,supersven/intellij-community,signed/intellij-community,slisson/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,allotria/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,asedunov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,consulo/consulo,tmpgit/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,jexp/idea2,holmes/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,kool79/intellij-community,allotria/intellij-community,FHannes/intellij-community,apixandru/intellij-community,holmes/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,samthor/intellij-community,retomerz/intellij-community,kool79/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,blademainer/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,blademainer/intellij-community,fnouama/intellij-community,hurricup/intellij-community,supersven/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,caot/intellij-community,FHannes/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,slisson/intellij-community,asedunov/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,caot/intellij-community,FHannes/intellij-community,semonte/intellij-community,fitermay/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ernestp/consulo,da1z/intellij-community,jexp/idea2,MER-GROUP/intellij-community,fitermay/intellij-community,izonder/intellij-community,hurricup/intellij-community,fitermay/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,apixandru/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,caot/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,allotria/intellij-community,joewalnes/idea-community,hurricup/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,petteyg/intellij-community,signed/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,xfournet/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,caot/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,gnuhub/intellij-community,semonte/intellij-community,allotria/intellij-community,fitermay/intellij-community,xfournet/intellij-community,kdwink/intellij-community,izonder/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ryano144/intellij-community,holmes/intellij-community,ryano144/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,holmes/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,supersven/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,retomerz/intellij-community,FHannes/intellij-community,kool79/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,signed/intellij-community,fitermay/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,blademainer/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,allotria/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,jexp/idea2,semonte/intellij-community,izonder/intellij-community,gnuhub/intellij-community,allotria/intellij-community,jexp/idea2,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,caot/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,clumsy/intellij-community,clumsy/intellij-community,supersven/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,da1z/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,signed/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,robovm/robovm-studio,semonte/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,petteyg/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,signed/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,robovm/robovm-studio,clumsy/intellij-community,diorcety/intellij-community,ernestp/consulo,joewalnes/idea-community,fengbaicanhe/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,apixandru/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,kool79/intellij-community,consulo/consulo,robovm/robovm-studio,retomerz/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,holmes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,izonder/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,supersven/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,da1z/intellij-community,petteyg/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,petteyg/intellij-community,consulo/consulo,ryano144/intellij-community,signed/intellij-community,consulo/consulo,Lekanich/intellij-community,allotria/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kdwink/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,jexp/idea2,Lekanich/intellij-community,nicolargo/intellij-community,slisson/intellij-community,da1z/intellij-community,slisson/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,samthor/intellij-community,amith01994/intellij-community,supersven/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,samthor/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community
|
/*
* @author max
*/
package com.intellij.psi.impl.source;
import com.intellij.lang.ASTNode;
import com.intellij.lang.StdLanguages;
import com.intellij.lexer.JavaLexer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiManager;
import com.intellij.psi.StubBuilder;
import com.intellij.psi.impl.java.stubs.PsiJavaFileStub;
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl;
import com.intellij.psi.impl.source.parsing.FileTextParsing;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.io.StringRef;
import java.io.IOException;
public class JavaFileElementType extends IStubFileElementType<PsiJavaFileStub> {
public static final int STUB_VERSION = 3;
public JavaFileElementType() {
super("java.FILE", StdLanguages.JAVA);
}
public StubBuilder getBuilder() {
return new JavaFileStubBuilder();
}
public int getStubVersion() {
return STUB_VERSION;
}
@Override
public boolean shouldBuildStubFor(final VirtualFile file) {
final VirtualFile dir = file.getParent();
return dir == null || dir.getUserData(LanguageLevel.KEY) != null;
}
public ASTNode parseContents(ASTNode chameleon) {
FileElement node = (FileElement)chameleon;
final CharSequence seq = node.getChars();
final PsiManager manager = node.getManager();
final JavaLexer lexer = new JavaLexer(PsiUtil.getLanguageLevel(node.getPsi()));
return FileTextParsing.parseFileText(manager, lexer, seq, 0, seq.length(), node.getCharTable());
}
public String getExternalId() {
return "java.FILE";
}
public void serialize(final PsiJavaFileStub stub, final StubOutputStream dataStream)
throws IOException {
dataStream.writeBoolean(stub.isCompiled());
dataStream.writeName(stub.getPackageName());
}
public PsiJavaFileStub deserialize(final StubInputStream dataStream, final StubElement parentStub) throws IOException {
boolean compiled = dataStream.readBoolean();
StringRef packName = dataStream.readName();
return new PsiJavaFileStubImpl(packName, compiled);
}
public void indexStub(final PsiJavaFileStub stub, final IndexSink sink) {
}
}
|
java/java-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java
|
/*
* @author max
*/
package com.intellij.psi.impl.source;
import com.intellij.lang.ASTNode;
import com.intellij.lang.StdLanguages;
import com.intellij.lexer.JavaLexer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiManager;
import com.intellij.psi.StubBuilder;
import com.intellij.psi.impl.java.stubs.PsiJavaFileStub;
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl;
import com.intellij.psi.impl.source.parsing.FileTextParsing;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.psi.tree.IStubFileElementType;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.io.StringRef;
import java.io.IOException;
public class JavaFileElementType extends IStubFileElementType<PsiJavaFileStub> {
public static final int STUB_VERSION = 2;
public JavaFileElementType() {
super("java.FILE", StdLanguages.JAVA);
}
public StubBuilder getBuilder() {
return new JavaFileStubBuilder();
}
public int getStubVersion() {
return STUB_VERSION;
}
@Override
public boolean shouldBuildStubFor(final VirtualFile file) {
final VirtualFile dir = file.getParent();
return dir == null || dir.getUserData(LanguageLevel.KEY) != null;
}
public ASTNode parseContents(ASTNode chameleon) {
FileElement node = (FileElement)chameleon;
final CharSequence seq = node.getChars();
final PsiManager manager = node.getManager();
final JavaLexer lexer = new JavaLexer(PsiUtil.getLanguageLevel(node.getPsi()));
return FileTextParsing.parseFileText(manager, lexer, seq, 0, seq.length(), node.getCharTable());
}
public String getExternalId() {
return "java.FILE";
}
public void serialize(final PsiJavaFileStub stub, final StubOutputStream dataStream)
throws IOException {
dataStream.writeBoolean(stub.isCompiled());
dataStream.writeName(stub.getPackageName());
}
public PsiJavaFileStub deserialize(final StubInputStream dataStream, final StubElement parentStub) throws IOException {
boolean compiled = dataStream.readBoolean();
StringRef packName = dataStream.readName();
return new PsiJavaFileStubImpl(packName, compiled);
}
public void indexStub(final PsiJavaFileStub stub, final IndexSink sink) {
}
}
|
update Java stub version to ensure that cls parameter names are picked up
|
java/java-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java
|
update Java stub version to ensure that cls parameter names are picked up
|
|
Java
|
apache-2.0
|
8baae4a6bee6bffa25f9fe02ccbaf18a63f27b6b
| 0
|
philipz/pinpoint,shuvigoss/pinpoint,chenguoxi1985/pinpoint,emeroad/pinpoint,shuvigoss/pinpoint,cijung/pinpoint,nstopkimsk/pinpoint,majinkai/pinpoint,eBaoTech/pinpoint,InfomediaLtd/pinpoint,koo-taejin/pinpoint,KimTaehee/pinpoint,nstopkimsk/pinpoint,breadval/pinpoint,naver/pinpoint,chenguoxi1985/pinpoint,barneykim/pinpoint,lioolli/pinpoint,denzelsN/pinpoint,majinkai/pinpoint,minwoo-jung/pinpoint,tsyma/pinpoint,InfomediaLtd/pinpoint,krishnakanthpps/pinpoint,lioolli/pinpoint,eBaoTech/pinpoint,koo-taejin/pinpoint,majinkai/pinpoint,gspandy/pinpoint,KimTaehee/pinpoint,sbcoba/pinpoint,sjmittal/pinpoint,Skkeem/pinpoint,Allive1/pinpoint,koo-taejin/pinpoint,andyspan/pinpoint,shuvigoss/pinpoint,sjmittal/pinpoint,minwoo-jung/pinpoint,cit-lab/pinpoint,jiaqifeng/pinpoint,carpedm20/pinpoint,gspandy/pinpoint,andyspan/pinpoint,citywander/pinpoint,nstopkimsk/pinpoint,krishnakanthpps/pinpoint,minwoo-jung/pinpoint,KRDeNaT/pinpoint,citywander/pinpoint,eBaoTech/pinpoint,minwoo-jung/pinpoint,87439247/pinpoint,minwoo-jung/pinpoint,jaehong-kim/pinpoint,denzelsN/pinpoint,breadval/pinpoint,shuvigoss/pinpoint,87439247/pinpoint,nstopkimsk/pinpoint,wziyong/pinpoint,koo-taejin/pinpoint,carpedm20/pinpoint,philipz/pinpoint,krishnakanthpps/pinpoint,hcapitaine/pinpoint,sbcoba/pinpoint,Allive1/pinpoint,barneykim/pinpoint,InfomediaLtd/pinpoint,87439247/pinpoint,PerfGeeks/pinpoint,carpedm20/pinpoint,hcapitaine/pinpoint,wziyong/pinpoint,shuvigoss/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,andyspan/pinpoint,jiaqifeng/pinpoint,Skkeem/pinpoint,barneykim/pinpoint,naver/pinpoint,carpedm20/pinpoint,jiaqifeng/pinpoint,suraj-raturi/pinpoint,sbcoba/pinpoint,breadval/pinpoint,chenguoxi1985/pinpoint,carpedm20/pinpoint,barneykim/pinpoint,andyspan/pinpoint,Xylus/pinpoint,emeroad/pinpoint,emeroad/pinpoint,philipz/pinpoint,cit-lab/pinpoint,Xylus/pinpoint,suraj-raturi/pinpoint,krishnakanthpps/pinpoint,coupang/pinpoint,KRDeNaT/pinpoint,koo-taejin/pinpoint,cijung/pinpoint,masonmei/pinpoint,barneykim/pinpoint,jaehong-kim/pinpoint,sjmittal/pinpoint,KRDeNaT/pinpoint,breadval/pinpoint,cijung/pinpoint,breadval/pinpoint,lioolli/pinpoint,Allive1/pinpoint,KimTaehee/pinpoint,dawidmalina/pinpoint,Allive1/pinpoint,wziyong/pinpoint,chenguoxi1985/pinpoint,masonmei/pinpoint,emeroad/pinpoint,hcapitaine/pinpoint,PerfGeeks/pinpoint,Xylus/pinpoint,suraj-raturi/pinpoint,masonmei/pinpoint,gspandy/pinpoint,Xylus/pinpoint,cijung/pinpoint,suraj-raturi/pinpoint,majinkai/pinpoint,naver/pinpoint,citywander/pinpoint,87439247/pinpoint,jiaqifeng/pinpoint,naver/pinpoint,KRDeNaT/pinpoint,cit-lab/pinpoint,shuvigoss/pinpoint,suraj-raturi/pinpoint,jiaqifeng/pinpoint,breadval/pinpoint,hcapitaine/pinpoint,jaehong-kim/pinpoint,emeroad/pinpoint,sbcoba/pinpoint,denzelsN/pinpoint,lioolli/pinpoint,masonmei/pinpoint,denzelsN/pinpoint,dawidmalina/pinpoint,cijung/pinpoint,tsyma/pinpoint,citywander/pinpoint,wziyong/pinpoint,jaehong-kim/pinpoint,masonmei/pinpoint,denzelsN/pinpoint,sjmittal/pinpoint,masonmei/pinpoint,chenguoxi1985/pinpoint,sjmittal/pinpoint,gspandy/pinpoint,Xylus/pinpoint,Xylus/pinpoint,lioolli/pinpoint,KimTaehee/pinpoint,sbcoba/pinpoint,InfomediaLtd/pinpoint,nstopkimsk/pinpoint,andyspan/pinpoint,jiaqifeng/pinpoint,KimTaehee/pinpoint,Xylus/pinpoint,denzelsN/pinpoint,sbcoba/pinpoint,citywander/pinpoint,jaehong-kim/pinpoint,barneykim/pinpoint,KRDeNaT/pinpoint,InfomediaLtd/pinpoint,cit-lab/pinpoint,tsyma/pinpoint,barneykim/pinpoint,sjmittal/pinpoint,gspandy/pinpoint,emeroad/pinpoint,nstopkimsk/pinpoint,dawidmalina/pinpoint,Skkeem/pinpoint,krishnakanthpps/pinpoint,Skkeem/pinpoint,cijung/pinpoint,dawidmalina/pinpoint,eBaoTech/pinpoint,eBaoTech/pinpoint,krishnakanthpps/pinpoint,citywander/pinpoint,tsyma/pinpoint,PerfGeeks/pinpoint,InfomediaLtd/pinpoint,PerfGeeks/pinpoint,gspandy/pinpoint,cit-lab/pinpoint,philipz/pinpoint,chenguoxi1985/pinpoint,dawidmalina/pinpoint,hcapitaine/pinpoint,lioolli/pinpoint,coupang/pinpoint,coupang/pinpoint,87439247/pinpoint,philipz/pinpoint,tsyma/pinpoint,minwoo-jung/pinpoint,jaehong-kim/pinpoint,denzelsN/pinpoint,hcapitaine/pinpoint,KRDeNaT/pinpoint,majinkai/pinpoint,majinkai/pinpoint,KimTaehee/pinpoint,wziyong/pinpoint,philipz/pinpoint,tsyma/pinpoint,wziyong/pinpoint,PerfGeeks/pinpoint,dawidmalina/pinpoint,Skkeem/pinpoint,87439247/pinpoint,andyspan/pinpoint,naver/pinpoint,coupang/pinpoint,Allive1/pinpoint,Skkeem/pinpoint,koo-taejin/pinpoint,cit-lab/pinpoint,Allive1/pinpoint,PerfGeeks/pinpoint,coupang/pinpoint,suraj-raturi/pinpoint
|
package com.nhn.pinpoint.web.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.nhn.pinpoint.common.HistogramSchema;
import com.nhn.pinpoint.common.HistogramSlot;
import com.nhn.pinpoint.web.applicationmap.ApplicationMapBuilder;
import com.nhn.pinpoint.web.applicationmap.rawdata.LinkDataDuplexMap;
import com.nhn.pinpoint.web.applicationmap.rawdata.LinkDataMap;
import com.nhn.pinpoint.web.util.TimeWindow;
import com.nhn.pinpoint.web.util.TimeWindowOneMinuteSampler;
import com.nhn.pinpoint.web.dao.*;
import com.nhn.pinpoint.web.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import com.nhn.pinpoint.common.ServiceType;
import com.nhn.pinpoint.common.bo.SpanBo;
import com.nhn.pinpoint.common.bo.SpanEventBo;
import com.nhn.pinpoint.web.applicationmap.ApplicationMap;
import com.nhn.pinpoint.web.filter.Filter;
/**
* @author netspider
* @author emeroad
*/
@Service
public class FilteredMapServiceImpl implements FilteredMapService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private TraceDao traceDao;
@Autowired
private ApplicationTraceIndexDao applicationTraceIndexDao;
@Autowired
private AgentInfoService agentInfoService;
private static final Object V = new Object();
@Override
public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, Range range, int limit) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (range == null) {
throw new NullPointerException("range must not be null");
}
if (logger.isTraceEnabled()) {
logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, range);
}
return this.applicationTraceIndexDao.scanTraceIndex(applicationName, range, limit);
}
@Override
public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, SelectedScatterArea area, int limit) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (area == null) {
throw new NullPointerException("area must not be null");
}
if (logger.isTraceEnabled()) {
logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, area);
}
return this.applicationTraceIndexDao.scanTraceIndex(applicationName, area, limit);
}
@Override
@Deprecated
public LoadFactor linkStatistics(Range range, List<TransactionId> traceIdSet, Application sourceApplication, Application destinationApplication, Filter filter) {
if (sourceApplication == null) {
throw new NullPointerException("sourceApplication must not be null");
}
if (destinationApplication == null) {
throw new NullPointerException("destApplicationName must not be null");
}
if (filter == null) {
throw new NullPointerException("filter must not be null");
}
StopWatch watch = new StopWatch();
watch.start();
List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(traceIdSet);
List<SpanBo> filteredTransactionList = filterList(originalList, filter);
LoadFactor statistics = new LoadFactor(range);
// TODO fromToFilter처럼. node의 타입에 따른 처리 필요함.
// scan transaction list
for (SpanBo span : filteredTransactionList) {
if (sourceApplication.equals(span.getApplicationId(), span.getServiceType())) {
List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
if (spanEventBoList == null) {
continue;
}
// find dest elapsed time
for (SpanEventBo spanEventBo : spanEventBoList) {
if (destinationApplication.equals(spanEventBo.getDestinationId(), spanEventBo.getServiceType())) {
// find exception
boolean hasException = spanEventBo.hasException();
// add sample
// TODO : 실제값 대신 slot값을 넣어야 함.
statistics.addSample(span.getStartTime() + spanEventBo.getStartElapsed(), spanEventBo.getEndElapsed(), 1, hasException);
break;
}
}
}
}
watch.stop();
logger.info("Fetch link statistics elapsed. {}ms", watch.getLastTaskTimeMillis());
return statistics;
}
private List<SpanBo> filterList(List<List<SpanBo>> transactionList, Filter filter) {
final List<SpanBo> filteredResult = new ArrayList<SpanBo>();
for (List<SpanBo> transaction : transactionList) {
if (filter.include(transaction)) {
filteredResult.addAll(transaction);
}
}
return filteredResult;
}
private List<List<SpanBo>> filterList2(List<List<SpanBo>> transactionList, Filter filter) {
final List<List<SpanBo>> filteredResult = new ArrayList<List<SpanBo>>();
for (List<SpanBo> transaction : transactionList) {
if (filter.include(transaction)) {
filteredResult.add(transaction);
}
}
return filteredResult;
}
@Override
public ApplicationMap selectApplicationMap(TransactionId transactionId) {
if (transactionId == null) {
throw new NullPointerException("transactionId must not be null");
}
List<TransactionId> transactionIdList = new ArrayList<TransactionId>();
transactionIdList.add(transactionId);
// FIXME from,to -1 땜방임.
Range range = new Range(-1, -1);
return selectApplicationMap(transactionIdList, range, range, Filter.NONE);
}
/**
* filtered application map
*/
@Override
public ApplicationMap selectApplicationMap(List<TransactionId> transactionIdList, Range originalRange, Range scanRange, Filter filter) {
if (transactionIdList == null) {
throw new NullPointerException("transactionIdList must not be null");
}
if (filter == null) {
throw new NullPointerException("filter must not be null");
}
StopWatch watch = new StopWatch();
watch.start();
final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);
ApplicationMap map = createMap(originalRange, scanRange, filterList);
watch.stop();
logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());
return map;
}
private List<List<SpanBo>> selectFilteredSpan(List<TransactionId> transactionIdList, Filter filter) {
// 개별 객체를 각각 보고 재귀 내용을 삭제함.
// 향후 tree base로 충돌구간을 점검하여 없앨 경우 여기서 filter를 치면 안됨.
final Collection<TransactionId> recursiveFilterList = recursiveCallFilter(transactionIdList);
// FIXME 나중에 List<Span>을 순회하면서 실행할 process chain을 두는것도 괜찮을듯.
final List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(recursiveFilterList);
return filterList2(originalList, filter);
}
private ApplicationMap createMap(Range range, Range scanRange, List<List<SpanBo>> filterList) {
// Window의 설정은 따로 inject받던지 해야 될듯함.
final TimeWindow window = new TimeWindow(range, TimeWindowOneMinuteSampler.SAMPLER);
final LinkDataDuplexMap linkDataDuplexMap = new LinkDataDuplexMap();
final DotExtractor dotExtractor = new DotExtractor(scanRange);
final MapResponseHistogramSummary mapHistogramSummary = new MapResponseHistogramSummary(range);
/**
* 통계정보로 변환한다.
*/
for (List<SpanBo> transaction : filterList) {
final Map<Long, SpanBo> transactionSpanMap = checkDuplicatedSpanId(transaction);
for (SpanBo span : transaction) {
final Application parentApplication = createParentApplication(span, transactionSpanMap);
final Application spanApplication = new Application(span.getApplicationId(), span.getServiceType());
// SPAN의 respoinseTime의 통계를 저장한다.
recordSpanResponseTime(spanApplication, span, mapHistogramSummary, span.getCollectorAcceptTime());
// 사실상 여기서 걸리는것은 span의 serviceType이 잘못되었다고 할수 있음.
if (!spanApplication.getServiceType().isRecordStatistics() || spanApplication.getServiceType().isRpcClient()) {
logger.warn("invalid span application:{}", spanApplication);
continue;
}
final short slotTime = getHistogramSlotTime(span, spanApplication.getServiceType());
// link의 통계값에 collector acceptor time을 넣는것이 맞는것인지는 다시 생각해볼 필요가 있음.
// 통계값의 window의 time으로 전환해야함. 안그러면 slot이 맞지 않아 oom이 발생할수 있음.
long timestamp = window.refineTimestamp(span.getCollectorAcceptTime());
if (parentApplication.getServiceType() == ServiceType.USER) {
// 정방향 데이터
if (logger.isTraceEnabled()) {
logger.trace("span user:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
}
final LinkDataMap sourceLinkData = linkDataDuplexMap.getSourceLinkDataMap();
sourceLinkData.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
if (logger.isTraceEnabled()) {
logger.trace("span target user:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
}
// 역관계 데이터
final LinkDataMap targetLinkDataMap = linkDataDuplexMap.getTargetLinkDataMap();
targetLinkDataMap.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
} else {
// 역관계 데이터
if (logger.isTraceEnabled()) {
logger.trace("span target parent:{} {} -> span:{} {}", parentApplication, span.getAgentId(), spanApplication, span.getAgentId());
}
final LinkDataMap targetLinkDataMap = linkDataDuplexMap.getTargetLinkDataMap();
targetLinkDataMap.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
}
addNodeFromSpanEvent(span, window, linkDataDuplexMap, transactionSpanMap);
dotExtractor.addDot(span);
}
}
List<ApplicationScatterScanResult> applicationScatterScanResult = dotExtractor.getApplicationScatterScanResult();
ApplicationMapBuilder applicationMapBuilder = new ApplicationMapBuilder(range);
ApplicationMap map = applicationMapBuilder.build(linkDataDuplexMap, agentInfoService);
mapHistogramSummary.build();
map.appendResponseTime(mapHistogramSummary);
map.setApplicationScatterScanResult(applicationScatterScanResult);
return map;
}
private Map<Long, SpanBo> checkDuplicatedSpanId(List<SpanBo> transaction) {
final Map<Long, SpanBo> transactionSpanMap = new HashMap<Long, SpanBo>();
for (SpanBo span : transaction) {
final SpanBo old = transactionSpanMap.put(span.getSpanId(), span);
if (old != null) {
logger.warn("duplicated span found:{}", old);
}
}
return transactionSpanMap;
}
private void recordSpanResponseTime(Application application, SpanBo span, MapResponseHistogramSummary mapResponseHistogramSummary, long timeStamp) {
mapResponseHistogramSummary.addHistogram(application, span, timeStamp);
}
private void addNodeFromSpanEvent(SpanBo span, TimeWindow window, LinkDataDuplexMap linkDataDuplexMap, Map<Long, SpanBo> transactionSpanMap) {
/**
* span event의 statistics추가.
*/
final List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
if (CollectionUtils.isEmpty(spanEventBoList)) {
return;
}
final Application srcApplication = new Application(span.getApplicationId(), span.getServiceType());
LinkDataMap sourceLinkDataMap = linkDataDuplexMap.getSourceLinkDataMap();
for (SpanEventBo spanEvent : spanEventBoList) {
ServiceType destServiceType = spanEvent.getServiceType();
if (!destServiceType.isRecordStatistics()) {
// internal 메소드
continue;
}
// rpc client이면서 acceptor가 없으면 unknown으로 변환시킨다.
// 내가 아는 next spanid를 spanid로 가진 span이 있으면 acceptor가 존재하는 셈.
// acceptor check로직
if (destServiceType.isRpcClient()) {
if (!transactionSpanMap.containsKey(spanEvent.getNextSpanId())) {
destServiceType = ServiceType.UNKNOWN;
}
}
final String dest = spanEvent.getDestinationId();
final Application destApplication = new Application(dest, destServiceType);
final short slotTime = getHistogramSlotTime(spanEvent, destServiceType);
// FIXME
final long spanEventTimeStamp = window.refineTimestamp(span.getStartTime() + spanEvent.getStartElapsed());
if (logger.isTraceEnabled()) {
logger.trace("spanEvent src:{} {} -> dest:{} {}", srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint());
}
sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint(), spanEventTimeStamp, slotTime, 1);
}
}
private Application createParentApplication(SpanBo span, Map<Long, SpanBo> transactionSpanMap) {
final SpanBo parentSpan = transactionSpanMap.get(span.getParentSpanId());
if (span.isRoot() || parentSpan == null) {
String applicationName = span.getApplicationId();
ServiceType serviceType = ServiceType.USER;
return new Application(applicationName, serviceType);
} else {
String parentApplicationName = parentSpan.getApplicationId();
ServiceType serviceType = parentSpan.getServiceType();
return new Application(parentApplicationName, serviceType);
}
}
private short getHistogramSlotTime(SpanEventBo spanEvent, ServiceType serviceType) {
return getHistogramSlotTime(spanEvent.hasException(), spanEvent.getEndElapsed(), serviceType);
}
private short getHistogramSlotTime(SpanBo span, ServiceType serviceType) {
boolean allException = span.getErrCode() != 0;
return getHistogramSlotTime(allException, span.getElapsed(), serviceType);
}
private short getHistogramSlotTime(boolean hasException, int elapsedTime, ServiceType serviceType) {
if (hasException) {
return serviceType.getHistogramSchema().getErrorSlot().getSlotTime();
} else {
final HistogramSchema schema = serviceType.getHistogramSchema();
final HistogramSlot histogramSlot = schema.findHistogramSlot(elapsedTime);
return histogramSlot.getSlotTime();
}
}
private Collection<TransactionId> recursiveCallFilter(List<TransactionId> transactionIdList) {
if (transactionIdList == null) {
throw new NullPointerException("transactionIdList must not be null");
}
List<TransactionId> crashKey = new ArrayList<TransactionId>();
Map<TransactionId, Object> filterMap = new LinkedHashMap<TransactionId, Object>(transactionIdList.size());
for (TransactionId transactionId : transactionIdList) {
Object old = filterMap.put(transactionId, V);
if (old != null) {
crashKey.add(transactionId);
}
}
if (crashKey.size() != 0) {
Set<TransactionId> filteredTrasnactionId = filterMap.keySet();
logger.info("transactionId crash found. original:{} filter:{} crashKey:{}", transactionIdList.size(), filteredTrasnactionId.size(), crashKey);
return filteredTrasnactionId;
}
return transactionIdList;
}
}
|
src/main/java/com/nhn/pinpoint/web/service/FilteredMapServiceImpl.java
|
package com.nhn.pinpoint.web.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.nhn.pinpoint.common.HistogramSchema;
import com.nhn.pinpoint.common.HistogramSlot;
import com.nhn.pinpoint.web.applicationmap.ApplicationMapBuilder;
import com.nhn.pinpoint.web.applicationmap.rawdata.LinkDataDuplexMap;
import com.nhn.pinpoint.web.applicationmap.rawdata.LinkDataMap;
import com.nhn.pinpoint.web.util.TimeWindow;
import com.nhn.pinpoint.web.util.TimeWindowOneMinuteSampler;
import com.nhn.pinpoint.web.dao.*;
import com.nhn.pinpoint.web.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import com.nhn.pinpoint.common.ServiceType;
import com.nhn.pinpoint.common.bo.SpanBo;
import com.nhn.pinpoint.common.bo.SpanEventBo;
import com.nhn.pinpoint.web.applicationmap.ApplicationMap;
import com.nhn.pinpoint.web.filter.Filter;
/**
* @author netspider
* @author emeroad
*/
@Service
public class FilteredMapServiceImpl implements FilteredMapService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private TraceDao traceDao;
@Autowired
private ApplicationTraceIndexDao applicationTraceIndexDao;
@Autowired
private AgentInfoService agentInfoService;
private static final Object V = new Object();
@Override
public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, Range range, int limit) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (range == null) {
throw new NullPointerException("range must not be null");
}
if (logger.isTraceEnabled()) {
logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, range);
}
return this.applicationTraceIndexDao.scanTraceIndex(applicationName, range, limit);
}
@Override
public LimitedScanResult<List<TransactionId>> selectTraceIdsFromApplicationTraceIndex(String applicationName, SelectedScatterArea area, int limit) {
if (applicationName == null) {
throw new NullPointerException("applicationName must not be null");
}
if (area == null) {
throw new NullPointerException("area must not be null");
}
if (logger.isTraceEnabled()) {
logger.trace("scan(selectTraceIdsFromApplicationTraceIndex) {}, {}", applicationName, area);
}
return this.applicationTraceIndexDao.scanTraceIndex(applicationName, area, limit);
}
@Override
@Deprecated
public LoadFactor linkStatistics(Range range, List<TransactionId> traceIdSet, Application sourceApplication, Application destinationApplication, Filter filter) {
if (sourceApplication == null) {
throw new NullPointerException("sourceApplication must not be null");
}
if (destinationApplication == null) {
throw new NullPointerException("destApplicationName must not be null");
}
if (filter == null) {
throw new NullPointerException("filter must not be null");
}
StopWatch watch = new StopWatch();
watch.start();
List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(traceIdSet);
List<SpanBo> filteredTransactionList = filterList(originalList, filter);
LoadFactor statistics = new LoadFactor(range);
// TODO fromToFilter처럼. node의 타입에 따른 처리 필요함.
// scan transaction list
for (SpanBo span : filteredTransactionList) {
if (sourceApplication.equals(span.getApplicationId(), span.getServiceType())) {
List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
if (spanEventBoList == null) {
continue;
}
// find dest elapsed time
for (SpanEventBo spanEventBo : spanEventBoList) {
if (destinationApplication.equals(spanEventBo.getDestinationId(), spanEventBo.getServiceType())) {
// find exception
boolean hasException = spanEventBo.hasException();
// add sample
// TODO : 실제값 대신 slot값을 넣어야 함.
statistics.addSample(span.getStartTime() + spanEventBo.getStartElapsed(), spanEventBo.getEndElapsed(), 1, hasException);
break;
}
}
}
}
watch.stop();
logger.info("Fetch link statistics elapsed. {}ms", watch.getLastTaskTimeMillis());
return statistics;
}
private List<SpanBo> filterList(List<List<SpanBo>> transactionList, Filter filter) {
final List<SpanBo> filteredResult = new ArrayList<SpanBo>();
for (List<SpanBo> transaction : transactionList) {
if (filter.include(transaction)) {
filteredResult.addAll(transaction);
}
}
return filteredResult;
}
private List<List<SpanBo>> filterList2(List<List<SpanBo>> transactionList, Filter filter) {
final List<List<SpanBo>> filteredResult = new ArrayList<List<SpanBo>>();
for (List<SpanBo> transaction : transactionList) {
if (filter.include(transaction)) {
filteredResult.add(transaction);
}
}
return filteredResult;
}
@Override
public ApplicationMap selectApplicationMap(TransactionId transactionId) {
if (transactionId == null) {
throw new NullPointerException("transactionId must not be null");
}
List<TransactionId> transactionIdList = new ArrayList<TransactionId>();
transactionIdList.add(transactionId);
// FIXME from,to -1 땜방임.
Range range = new Range(-1, -1);
return selectApplicationMap(transactionIdList, range, range, Filter.NONE);
}
/**
* filtered application map
*/
@Override
public ApplicationMap selectApplicationMap(List<TransactionId> transactionIdList, Range originalRange, Range scanRange, Filter filter) {
if (transactionIdList == null) {
throw new NullPointerException("transactionIdList must not be null");
}
if (filter == null) {
throw new NullPointerException("filter must not be null");
}
StopWatch watch = new StopWatch();
watch.start();
final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);
ApplicationMap map = createMap(originalRange, scanRange, filterList);
watch.stop();
logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());
return map;
}
private List<List<SpanBo>> selectFilteredSpan(List<TransactionId> transactionIdList, Filter filter) {
// 개별 객체를 각각 보고 재귀 내용을 삭제함.
// 향후 tree base로 충돌구간을 점검하여 없앨 경우 여기서 filter를 치면 안됨.
final Collection<TransactionId> recursiveFilterList = recursiveCallFilter(transactionIdList);
// FIXME 나중에 List<Span>을 순회하면서 실행할 process chain을 두는것도 괜찮을듯.
final List<List<SpanBo>> originalList = this.traceDao.selectAllSpans(recursiveFilterList);
return filterList2(originalList, filter);
}
private ApplicationMap createMap(Range range, Range scanRange, List<List<SpanBo>> filterList) {
// Window의 설정은 따로 inject받던지 해야 될듯함.
final TimeWindow window = new TimeWindow(range, TimeWindowOneMinuteSampler.SAMPLER);
final LinkDataDuplexMap linkDataDuplexMap = new LinkDataDuplexMap();
// final LinkDataMap sourceLinkDataMap = new LinkDataMap();
final LinkDataMap targetLinkDataMap = linkDataDuplexMap.getTargetLinkDataMap();
final DotExtractor dotExtractor = new DotExtractor(scanRange);
final MapResponseHistogramSummary mapHistogramSummary = new MapResponseHistogramSummary(range);
/**
* 통계정보로 변환한다.
*/
for (List<SpanBo> transaction : filterList) {
final Map<Long, SpanBo> transactionSpanMap = checkDuplicatedSpanId(transaction);
for (SpanBo span : transaction) {
final Application parentApplication = createParentApplication(span, transactionSpanMap);
final Application spanApplication = new Application(span.getApplicationId(), span.getServiceType());
// SPAN의 respoinseTime의 통계를 저장한다.
recordSpanResponseTime(spanApplication, span, mapHistogramSummary, span.getCollectorAcceptTime());
// 사실상 여기서 걸리는것은 span의 serviceType이 잘못되었다고 할수 있음.
if (!spanApplication.getServiceType().isRecordStatistics() || spanApplication.getServiceType().isRpcClient()) {
logger.warn("invalid span application:{}", spanApplication);
continue;
}
final short slotTime = getHistogramSlotTime(span, spanApplication.getServiceType());
// link의 통계값에 collector acceptor time을 넣는것이 맞는것인지는 다시 생각해볼 필요가 있음.
// 통계값의 window의 time으로 전환해야함. 안그러면 slot이 맞지 않아 oom이 발생할수 있음.
long timestamp = window.refineTimestamp(span.getCollectorAcceptTime());
if (parentApplication.getServiceType() == ServiceType.USER) {
LinkDataMap sourceLinkData = linkDataDuplexMap.getSourceLinkDataMap();
sourceLinkData.addLinkData(parentApplication, span.getAgentId(), spanApplication, span.getAgentId(), timestamp, slotTime, 1);
// targetLinkDataMap.addLinkData(spanApplication, span.getAgentId(), parentApplication, span.getAgentId(), timestamp, slotTime, 1);
} else {
targetLinkDataMap.addLinkData(spanApplication, span.getAgentId(), parentApplication, span.getAgentId(), timestamp, slotTime, 1);
}
addNodeFromSpanEvent(span, window, linkDataDuplexMap, transactionSpanMap);
dotExtractor.addDot(span);
}
}
List<ApplicationScatterScanResult> applicationScatterScanResult = dotExtractor.getApplicationScatterScanResult();
ApplicationMapBuilder applicationMapBuilder = new ApplicationMapBuilder(range);
ApplicationMap map = applicationMapBuilder.build(linkDataDuplexMap, agentInfoService);
mapHistogramSummary.build();
map.appendResponseTime(mapHistogramSummary);
map.setApplicationScatterScanResult(applicationScatterScanResult);
return map;
}
private Map<Long, SpanBo> checkDuplicatedSpanId(List<SpanBo> transaction) {
final Map<Long, SpanBo> transactionSpanMap = new HashMap<Long, SpanBo>();
for (SpanBo span : transaction) {
final SpanBo old = transactionSpanMap.put(span.getSpanId(), span);
if (old != null) {
logger.warn("duplicated span found:{}", old);
}
}
return transactionSpanMap;
}
private void recordSpanResponseTime(Application application, SpanBo span, MapResponseHistogramSummary mapResponseHistogramSummary, long timeStamp) {
mapResponseHistogramSummary.addHistogram(application, span, timeStamp);
}
private void addNodeFromSpanEvent(SpanBo span, TimeWindow window, LinkDataDuplexMap linkDataDuplexMap, Map<Long, SpanBo> transactionSpanMap) {
/**
* span event의 statistics추가.
*/
final List<SpanEventBo> spanEventBoList = span.getSpanEventBoList();
if (CollectionUtils.isEmpty(spanEventBoList)) {
return;
}
final Application srcApplication = new Application(span.getApplicationId(), span.getServiceType());
LinkDataMap sourceLinkDataMap = linkDataDuplexMap.getSourceLinkDataMap();
for (SpanEventBo spanEvent : spanEventBoList) {
ServiceType destServiceType = spanEvent.getServiceType();
if (!destServiceType.isRecordStatistics()) {
// internal 메소드
continue;
}
// rpc client이면서 acceptor가 없으면 unknown으로 변환시킨다.
// 내가 아는 next spanid를 spanid로 가진 span이 있으면 acceptor가 존재하는 셈.
// acceptor check로직
if (destServiceType.isRpcClient()) {
if (!transactionSpanMap.containsKey(spanEvent.getNextSpanId())) {
destServiceType = ServiceType.UNKNOWN;
}
}
final String dest = spanEvent.getDestinationId();
final Application destApplication = new Application(dest, destServiceType);
final short slotTime = getHistogramSlotTime(spanEvent, destServiceType);
// FIXME
final long spanEventTimeStamp = window.refineTimestamp(span.getStartTime() + spanEvent.getStartElapsed());
sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint(), spanEventTimeStamp, slotTime, 1);
}
}
private Application createParentApplication(SpanBo span, Map<Long, SpanBo> transactionSpanMap) {
final SpanBo parentSpan = transactionSpanMap.get(span.getParentSpanId());
if (span.isRoot() || parentSpan == null) {
String applicationName = span.getApplicationId();
ServiceType serviceType = ServiceType.USER;
return new Application(applicationName, serviceType);
} else {
String parentApplicationName = parentSpan.getApplicationId();
ServiceType serviceType = parentSpan.getServiceType();
return new Application(parentApplicationName, serviceType);
}
}
private short getHistogramSlotTime(SpanEventBo spanEvent, ServiceType serviceType) {
return getHistogramSlotTime(spanEvent.hasException(), spanEvent.getEndElapsed(), serviceType);
}
private short getHistogramSlotTime(SpanBo span, ServiceType serviceType) {
boolean allException = span.getErrCode() != 0;
return getHistogramSlotTime(allException, span.getElapsed(), serviceType);
}
private short getHistogramSlotTime(boolean hasException, int elapsedTime, ServiceType serviceType) {
if (hasException) {
return serviceType.getHistogramSchema().getErrorSlot().getSlotTime();
} else {
final HistogramSchema schema = serviceType.getHistogramSchema();
final HistogramSlot histogramSlot = schema.findHistogramSlot(elapsedTime);
return histogramSlot.getSlotTime();
}
}
private Collection<TransactionId> recursiveCallFilter(List<TransactionId> transactionIdList) {
if (transactionIdList == null) {
throw new NullPointerException("transactionIdList must not be null");
}
List<TransactionId> crashKey = new ArrayList<TransactionId>();
Map<TransactionId, Object> filterMap = new LinkedHashMap<TransactionId, Object>(transactionIdList.size());
for (TransactionId transactionId : transactionIdList) {
Object old = filterMap.put(transactionId, V);
if (old != null) {
crashKey.add(transactionId);
}
}
if (crashKey.size() != 0) {
Set<TransactionId> filteredTrasnactionId = filterMap.keySet();
logger.info("transactionId crash found. original:{} filter:{} crashKey:{}", transactionIdList.size(), filteredTrasnactionId.size(), crashKey);
return filteredTrasnactionId;
}
return transactionIdList;
}
}
|
[강운덕] [WEB-96] filter를 통한 map 구성시 target데이터 생성 부분 수정.
git-svn-id: 7358e302d50fd4045a689b8bedf0763179db032e@3607 84d0f5b1-2673-498c-a247-62c4ff18d310
|
src/main/java/com/nhn/pinpoint/web/service/FilteredMapServiceImpl.java
|
[강운덕] [WEB-96] filter를 통한 map 구성시 target데이터 생성 부분 수정.
|
|
Java
|
apache-2.0
|
eaff87286289a0f0b2386776d713ec3f3e3808f6
| 0
|
clumsy/intellij-community,samthor/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,izonder/intellij-community,kool79/intellij-community,petteyg/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,supersven/intellij-community,apixandru/intellij-community,fitermay/intellij-community,petteyg/intellij-community,izonder/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fnouama/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ibinti/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ryano144/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,caot/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,slisson/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,da1z/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,slisson/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ryano144/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,signed/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,allotria/intellij-community,wreckJ/intellij-community,izonder/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,semonte/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,retomerz/intellij-community,blademainer/intellij-community,izonder/intellij-community,samthor/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ryano144/intellij-community,caot/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,holmes/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ryano144/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,apixandru/intellij-community,vladmm/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,holmes/intellij-community,caot/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,kool79/intellij-community,hurricup/intellij-community,petteyg/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,allotria/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,signed/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,izonder/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,amith01994/intellij-community,clumsy/intellij-community,apixandru/intellij-community,signed/intellij-community,samthor/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,vladmm/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,holmes/intellij-community,apixandru/intellij-community,robovm/robovm-studio,hurricup/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ibinti/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,caot/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,supersven/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,semonte/intellij-community,fitermay/intellij-community,dslomov/intellij-community,semonte/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,semonte/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,samthor/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,kool79/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,ibinti/intellij-community,semonte/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,kdwink/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,allotria/intellij-community,FHannes/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,izonder/intellij-community,samthor/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,FHannes/intellij-community,da1z/intellij-community,petteyg/intellij-community,ibinti/intellij-community,supersven/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,semonte/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,semonte/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,xfournet/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,holmes/intellij-community,samthor/intellij-community,fitermay/intellij-community,ryano144/intellij-community,supersven/intellij-community,signed/intellij-community,signed/intellij-community,slisson/intellij-community,holmes/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,caot/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,supersven/intellij-community,izonder/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,slisson/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,caot/intellij-community,holmes/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,caot/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,clumsy/intellij-community,amith01994/intellij-community,supersven/intellij-community,nicolargo/intellij-community,caot/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,izonder/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,izonder/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,kool79/intellij-community,da1z/intellij-community,kool79/intellij-community,xfournet/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,signed/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,samthor/intellij-community,kdwink/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,holmes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,fitermay/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,amith01994/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,petteyg/intellij-community,caot/intellij-community,slisson/intellij-community,FHannes/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,signed/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,dslomov/intellij-community,slisson/intellij-community,clumsy/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,kool79/intellij-community,robovm/robovm-studio,kdwink/intellij-community
|
package com.jetbrains.python;
import com.intellij.lang.parameterInfo.CreateParameterInfoContext;
import com.intellij.lang.parameterInfo.ParameterInfoHandler;
import com.intellij.lang.parameterInfo.ParameterInfoUIContextEx;
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.python.fixtures.LightMarkedTestCase;
import com.jetbrains.python.psi.PyArgumentList;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
/**
* Tests parameter info available via ^P at call sites.
* <br/>User: dcheryasov
* Date: Jul 14, 2009 3:42:44 AM
*/
public class PyParameterInfoTest extends LightMarkedTestCase {
@Override
protected String getTestDataPath() {
return PythonTestUtil.getTestDataPath()+ "/paramInfo/";
}
public void testSimpleFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()-3).assertNotFound(); // ^P before arglist gives nothing
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+2).check("a,b,c", new String[]{"c"}); // one too far after arg2, and we came to arg3
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,c", new String[]{"c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,c", new String[]{"c"});
feignCtrlP(arg3.getTextOffset()-1).check("a,b,c", new String[]{"c"}); // space before arg goes to that arg
feignCtrlP(arg3.getTextOffset()+2).assertNotFound(); // ^P on a ")" gives nothing
}
public void testStarredFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,*c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,*c", new String[]{"a,"});
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,*c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,*c", new String[]{"b,"});
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,*c", new String[]{"*c"});
PsiElement arg4 = marks.get("<arg4>");
feignCtrlP(arg4.getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg4.getTextOffset()+1).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg4.getTextOffset()+2).assertNotFound();
}
public void testKwdFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,**c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,**c", new String[]{"a,"});
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,**c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,**c", new String[]{"b,"});
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,**c", new String[]{"**c"});
PsiElement arg4 = marks.get("<arg4>");
feignCtrlP(arg4.getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(arg4.getTextOffset()+1).check("a,b,**c", new String[]{"**c"});
}
public void testKwdOutOfOrder() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,**c", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,**c", new String[]{"a,"});
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,**c", new String[]{"**c"});
}
public void testStarArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testKwdArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testKwdArgOutOfOrder() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"b,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"a,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"a,","c"});
}
public void testStarredAndKwdFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 6);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,*c,**d", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,*c,**d", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,*c,**d", new String[]{"*c,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,b,*c,**d", new String[]{"*c,"});
feignCtrlP(marks.get("<arg5>").getTextOffset()).check("a,b,*c,**d", new String[]{"**d"});
feignCtrlP(marks.get("<arg6>").getTextOffset()).check("a,b,*c,**d", new String[]{"**d"});
}
public void testNestedArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,c),d", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,(b,c),d", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,(b,c),d", new String[]{"c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,c),d", new String[]{"d"});
feignCtrlP(marks.get("<arg2>").getTextOffset()-2).check("a,(b,c),d", new String[]{}); // before nested tuple: no arg matches
}
public void testDoubleNestedArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 5);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"c,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"d"});
feignCtrlP(marks.get("<arg5>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"e"});
}
public void testNestedMultiArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,c),d", new String[]{"a,"});
feignCtrlP(marks.get("<arg23>").getTextOffset()).check("a,(b,c),d", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,c),d", new String[]{"d"});
}
public void testStarredParam() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg23>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testStarredParamAndArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,*c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,*c", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,b,*c", new String[]{"*c"});
}
public void testSimpleMethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a", new String[]{"a"}, new String[]{"self,"});
}
public void testSimpleClassFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a", new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a", new String[]{"a"});
}
public void testReassignedFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
public void testReassignedInstanceMethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b,c", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b,c", new String[]{"b,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("self,a,b,c", new String[]{"c"}, new String[]{"self,"});
}
public void testReassignedClassInit() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testInheritedClassInit() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testRedefinedNewConstructorCall() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("cls,a,b", new String[]{"a,"}, new String[]{"cls,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("cls,a,b", new String[]{"b"}, new String[]{"cls,"});
}
public void testRedefinedNewDirectCall() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("cls,a,b", new String[]{"cls,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("cls,a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("cls,a,b", new String[]{"b"});
}
public void testIgnoreNewInOldStyleClass() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,one", new String[]{"one"}, new String[]{"self,"});
}
public void testBoundMethodSimple() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testBoundMethodReassigned() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testConstructorFactory() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg>").getTextOffset()).check("self,color", new String[]{"color"}, new String[]{"self,"});
}
public void testBoundMethodStatic() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
public void testSimpleLambda() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x", new String[]{"x"});
}
public void testReassignedLambda() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x,y", new String[]{"x,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("x,y", new String[]{"y"});
}
public void testLambdaVariousArgs() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"x,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"y=1,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"*args,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"**kwargs"});
}
public void testTupleAndNamedArg1() throws Exception {
// PY-1268
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg_c>").getTextOffset()).check("a,b,c", new String[]{"c"});
feignCtrlP(marks.get("<arg_star>").getTextOffset()).check("a,b,c", new String[]{"a,", "b,"});
}
public void testTupleAndNamedArg2() throws Exception {
// PY-1268
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg_star>").getTextOffset()).check("a,b,c", new String[]{"a,", "b,"});
feignCtrlP(marks.get("<arg_c>").getTextOffset()).check("a,b,c", new String[]{"c"});
}
public void testTupleArgPlainParam() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg>").getTextOffset()).check("a,b,c", new String[]{"b,"});
}
public void testStaticmethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
/**
* Imitates pressing of Ctrl+P; fails if results are not as expected.
* @param offset offset of 'cursor' where ^P is pressed.
* @return a {@link Collector} with collected hint info.
* @throws Exception if it fails
*/
private Collector feignCtrlP(int offset) throws Exception {
Collector collector = new Collector(myFixture.getProject(), myFixture.getFile(), offset);
PyParameterInfoHandler handler = new PyParameterInfoHandler();
collector.setParameterOwner(handler.findElementForParameterInfo(collector)); // finds arglist, sets items to show
if (collector.getParameterOwner() != null) {
assertEquals("Collected one analysis result", 1, collector.myItems.length);
handler.updateParameterInfo((PyArgumentList)collector.getParameterOwner(), collector); // moves offset to correct parameter
handler.updateUI((PyArgumentList.AnalysisResult)collector.getItemsToShow()[0], collector); // sets hint text and flags
}
return collector;
}
/**
* Imitates the normal UI contexts to the extent we use it. Collects highlighting.
*/
private static class Collector implements ParameterInfoUIContextEx, CreateParameterInfoContext, UpdateParameterInfoContext {
private final PsiFile myFile;
private final int myOffset;
private int myIndex;
private Object[] myItems;
private final Project myProject;
private final Editor myEditor;
private PyArgumentList myParamOwner;
private String[] myTexts;
private EnumSet<Flag>[] myFlags;
private Collector(Project project, PsiFile file, int offset) {
myProject = project;
myEditor = null;
myFile = file;
myOffset = offset;
}
@Override
public void setupUIComponentPresentation(String[] texts, EnumSet<Flag>[] flags, Color background) {
assert texts.length == flags.length;
myTexts = texts;
myFlags = flags;
}
@Override
public void setupUIComponentPresentation(String text, int highlightStartOffset, int highlightEndOffset, boolean isDisabled,
boolean strikeout, boolean isDisabledBeforeHighlight, Color background) {
// nothing, we don't use it
}
@Override
public boolean isUIComponentEnabled() {
return true;
}
@Override
public boolean isUIComponentEnabled(int index) {
return true;
}
@Override
public void setUIComponentEnabled(boolean enabled) { }
@Override
public void setUIComponentEnabled(int index, boolean b) { }
@Override
public int getCurrentParameterIndex() {
return myIndex;
}
@Override
public void removeHint() { }
@Override
public void setParameterOwner(PsiElement o) {
assertTrue("Found element is a python arglist", o == null || o instanceof PyArgumentList);
myParamOwner = (PyArgumentList)o;
}
@Override
public PsiElement getParameterOwner() {
return myParamOwner;
}
@Override
public void setHighlightedParameter(Object parameter) {
// nothing, we don't use it
}
@Override
public void setCurrentParameter(int index) {
myIndex = index;
}
@Override
public Color getDefaultParameterColor() {
return java.awt.Color.BLACK;
}
@Override
public Object[] getItemsToShow() {
return myItems;
}
@Override
public void setItemsToShow(Object[] items) {
myItems = items;
}
@Override
public void showHint(PsiElement element, int offset, ParameterInfoHandler handler) { }
@Override
public int getParameterListStart() {
return 0; // we don't use it
}
@Override
public Object[] getObjectsToView() {
return null; // we don't use it
}
@Override
public PsiElement getHighlightedElement() {
return null; // we don't use it
}
@Override
public void setHighlightedElement(PsiElement elements) {
// nothing, we don't use it
}
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myFile;
}
@Override
public int getOffset() {
return myOffset;
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
/**
* Checks if hint data look as expected.
* @param text expected text of the hint, without formatting
* @param highlighted expected highlighted substrings of hint
* @param disabled expected disabled substrings of hint
*/
public void check(String text, String[] highlighted, String[] disabled) {
assertEquals("Signature", text, StringUtil.join(myTexts, ""));
StringBuilder wrongs = new StringBuilder();
// see if highlighted matches
Set<String> highlight_set = new HashSet<String>();
ContainerUtil.addAll(highlight_set, highlighted);
for (int i = 0; i < myTexts.length; i += 1) {
if (myFlags[i].contains(Flag.HIGHLIGHT) && !highlight_set.contains(myTexts[i])) {
wrongs.append("Highlighted unexpected '").append(myTexts[i]).append("'. ");
}
}
for (int i = 0; i < myTexts.length; i += 1) {
if (!myFlags[i].contains(Flag.HIGHLIGHT) && highlight_set.contains(myTexts[i])) {
wrongs.append("Not highlighted expected '").append(myTexts[i]).append("'. ");
}
}
// see if disabled matches
Set<String> disabled_set = new HashSet<String>();
ContainerUtil.addAll(disabled_set, disabled);
for (int i = 0; i < myTexts.length; i += 1) {
if (myFlags[i].contains(Flag.DISABLE) && !disabled_set.contains(myTexts[i])) {
wrongs.append("Highlighted a disabled '").append(myTexts[i]).append("'. ");
}
}
for (int i = 0; i < myTexts.length; i += 1) {
if (!myFlags[i].contains(Flag.DISABLE) && disabled_set.contains(myTexts[i])) {
wrongs.append("Not disabled expected '").append(myTexts[i]).append("'. ");
}
}
//
if (wrongs.length() > 0) fail(wrongs.toString());
}
public void check(String text, String[] highlighted) {
check(text, highlighted, ArrayUtil.EMPTY_STRING_ARRAY);
}
public void assertNotFound() {
assertNull(myParamOwner);
}
}
}
|
python/testSrc/com/jetbrains/python/PyParameterInfoTest.java
|
package com.jetbrains.python;
import com.intellij.lang.parameterInfo.CreateParameterInfoContext;
import com.intellij.lang.parameterInfo.ParameterInfoHandler;
import com.intellij.lang.parameterInfo.ParameterInfoUIContextEx;
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.python.fixtures.LightMarkedTestCase;
import com.jetbrains.python.psi.PyArgumentList;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
/**
* Tests parameter info available via ^P at call sites.
* <br/>User: dcheryasov
* Date: Jul 14, 2009 3:42:44 AM
*/
public class PyParameterInfoTest extends LightMarkedTestCase {
@Override
protected String getTestDataPath() {
return PythonTestUtil.getTestDataPath()+ "/paramInfo/";
}
public void testSimpleFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()-3).assertNotFound(); // ^P before arglist gives nothing
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+2).check("a,b,c", new String[]{"c"}); // one too far after arg2, and we came to arg3
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,c", new String[]{"c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,c", new String[]{"c"});
feignCtrlP(arg3.getTextOffset()-1).check("a,b,c", new String[]{"c"}); // space before arg goes to that arg
feignCtrlP(arg3.getTextOffset()+2).assertNotFound(); // ^P on a ")" gives nothing
}
public void testStarredFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,*c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,*c", new String[]{"a,"});
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,*c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,*c", new String[]{"b,"});
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,*c", new String[]{"*c"});
PsiElement arg4 = marks.get("<arg4>");
feignCtrlP(arg4.getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg4.getTextOffset()+1).check("a,b,*c", new String[]{"*c"});
feignCtrlP(arg4.getTextOffset()+2).assertNotFound();
}
public void testKwdFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
PsiElement arg1 = marks.get("<arg1>");
feignCtrlP(arg1.getTextOffset()).check("a,b,**c", new String[]{"a,"});
feignCtrlP(arg1.getTextOffset()+1).check("a,b,**c", new String[]{"a,"});
PsiElement arg2 = marks.get("<arg2>");
feignCtrlP(arg2.getTextOffset()).check("a,b,**c", new String[]{"b,"});
feignCtrlP(arg2.getTextOffset()+1).check("a,b,**c", new String[]{"b,"});
PsiElement arg3 = marks.get("<arg3>");
feignCtrlP(arg3.getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(arg3.getTextOffset()+1).check("a,b,**c", new String[]{"**c"});
PsiElement arg4 = marks.get("<arg4>");
feignCtrlP(arg4.getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(arg4.getTextOffset()+1).check("a,b,**c", new String[]{"**c"});
}
public void testKwdOutOfOrder() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,**c", new String[]{"**c"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,**c", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,**c", new String[]{"a,"});
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,**c", new String[]{"**c"});
}
public void testStarArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testKwdArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testKwdArgOutOfOrder() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"b,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,c", new String[]{"a,","c"});
feignCtrlP(marks.get("<arg2a>").getTextOffset()).check("a,b,c", new String[]{"a,","c"});
}
public void testStarredAndKwdFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 6);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,*c,**d", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,*c,**d", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,*c,**d", new String[]{"*c,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,b,*c,**d", new String[]{"*c,"});
feignCtrlP(marks.get("<arg5>").getTextOffset()).check("a,b,*c,**d", new String[]{"**d"});
feignCtrlP(marks.get("<arg6>").getTextOffset()).check("a,b,*c,**d", new String[]{"**d"});
}
public void testNestedArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,c),d", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,(b,c),d", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,(b,c),d", new String[]{"c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,c),d", new String[]{"d"});
feignCtrlP(marks.get("<arg2>").getTextOffset()-2).check("a,(b,c),d", new String[]{}); // before nested tuple: no arg matches
}
public void testDoubleNestedArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 5);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"c,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"d"});
feignCtrlP(marks.get("<arg5>").getTextOffset()).check("a,(b,(c,d)),e", new String[]{"e"});
}
public void testNestedMultiArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,(b,c),d", new String[]{"a,"});
feignCtrlP(marks.get("<arg23>").getTextOffset()).check("a,(b,c),d", new String[]{"b,","c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,(b,c),d", new String[]{"d"});
}
public void testStarredParam() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,c", new String[]{"a,"});
feignCtrlP(marks.get("<arg23>").getTextOffset()).check("a,b,c", new String[]{"b,","c"});
}
public void testStarredParamAndArg() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b,*c", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b,*c", new String[]{"b,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("a,b,*c", new String[]{"*c"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("a,b,*c", new String[]{"*c"});
}
public void testSimpleMethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a", new String[]{"a"}, new String[]{"self,"});
}
public void testSimpleClassFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a", new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a", new String[]{"a"});
}
public void testReassignedFunction() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
public void testReassignedInstanceMethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b,c", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b,c", new String[]{"b,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("self,a,b,c", new String[]{"c"}, new String[]{"self,"});
}
public void testReassignedClassInit() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testInheritedClassInit() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testRedefinedNewConstructorCall() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("cls,a,b", new String[]{"a,"}, new String[]{"cls,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("cls,a,b", new String[]{"b"}, new String[]{"cls,"});
}
public void testRedefinedNewDirectCall() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 3);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("cls,a,b", new String[]{"cls,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("cls,a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("cls,a,b", new String[]{"b"});
}
public void testIgnoreNewInOldStyleClass() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,one", new String[]{"one"}, new String[]{"self,"});
}
public void testBoundMethodSimple() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testBoundMethodReassigned() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("self,a,b", new String[]{"a,"}, new String[]{"self,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("self,a,b", new String[]{"b"}, new String[]{"self,"});
}
public void testConstructorFactory() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg>").getTextOffset()).check("self,color", new String[]{"color"}, new String[]{"self,"});
}
public void testBoundMethodStatic() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
public void testSimpleLambda() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 1);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x", new String[]{"x"});
}
public void testReassignedLambda() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x,y", new String[]{"x,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("x,y", new String[]{"y"});
}
public void testLambdaVariousArgs() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 4);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"x,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"y=1,"});
feignCtrlP(marks.get("<arg3>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"*args,"});
feignCtrlP(marks.get("<arg4>").getTextOffset()).check("x,y=1,*args,**kwargs", new String[]{"**kwargs"});
}
public void testTupleAndNamedArg1() throws Exception {
// PY-1268
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg_c>").getTextOffset()).check("a,b,c", new String[]{"c"});
feignCtrlP(marks.get("<arg_star>").getTextOffset()).check("a,b,c", new String[]{"a,", "b,"});
}
public void testTupleAndNamedArg2() throws Exception {
// PY-1268
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg_star>").getTextOffset()).check("a,b,c", new String[]{"a,", "b,"});
feignCtrlP(marks.get("<arg_c>").getTextOffset()).check("a,b,c", new String[]{"c"});
}
public void testStaticmethod() throws Exception {
Map<String, PsiElement> marks = loadTest();
assertEquals("Test data sanity", marks.size(), 2);
feignCtrlP(marks.get("<arg1>").getTextOffset()).check("a,b", new String[]{"a,"});
feignCtrlP(marks.get("<arg2>").getTextOffset()).check("a,b", new String[]{"b"});
}
/**
* Imitates pressing of Ctrl+P; fails if results are not as expected.
* @param offset offset of 'cursor' where ^P is pressed.
* @return a {@link Collector} with collected hint info.
* @throws Exception if it fails
*/
private Collector feignCtrlP(int offset) throws Exception {
Collector collector = new Collector(myFixture.getProject(), myFixture.getFile(), offset);
PyParameterInfoHandler handler = new PyParameterInfoHandler();
collector.setParameterOwner(handler.findElementForParameterInfo(collector)); // finds arglist, sets items to show
if (collector.getParameterOwner() != null) {
assertEquals("Collected one analysis result", 1, collector.myItems.length);
handler.updateParameterInfo((PyArgumentList)collector.getParameterOwner(), collector); // moves offset to correct parameter
handler.updateUI((PyArgumentList.AnalysisResult)collector.getItemsToShow()[0], collector); // sets hint text and flags
}
return collector;
}
/**
* Imitates the normal UI contexts to the extent we use it. Collects highlighting.
*/
private static class Collector implements ParameterInfoUIContextEx, CreateParameterInfoContext, UpdateParameterInfoContext {
private final PsiFile myFile;
private final int myOffset;
private int myIndex;
private Object[] myItems;
private final Project myProject;
private final Editor myEditor;
private PyArgumentList myParamOwner;
private String[] myTexts;
private EnumSet<Flag>[] myFlags;
private Collector(Project project, PsiFile file, int offset) {
myProject = project;
myEditor = null;
myFile = file;
myOffset = offset;
}
@Override
public void setupUIComponentPresentation(String[] texts, EnumSet<Flag>[] flags, Color background) {
assert texts.length == flags.length;
myTexts = texts;
myFlags = flags;
}
@Override
public void setupUIComponentPresentation(String text, int highlightStartOffset, int highlightEndOffset, boolean isDisabled,
boolean strikeout, boolean isDisabledBeforeHighlight, Color background) {
// nothing, we don't use it
}
@Override
public boolean isUIComponentEnabled() {
return true;
}
@Override
public boolean isUIComponentEnabled(int index) {
return true;
}
@Override
public void setUIComponentEnabled(boolean enabled) { }
@Override
public void setUIComponentEnabled(int index, boolean b) { }
@Override
public int getCurrentParameterIndex() {
return myIndex;
}
@Override
public void removeHint() { }
@Override
public void setParameterOwner(PsiElement o) {
assertTrue("Found element is a python arglist", o == null || o instanceof PyArgumentList);
myParamOwner = (PyArgumentList)o;
}
@Override
public PsiElement getParameterOwner() {
return myParamOwner;
}
@Override
public void setHighlightedParameter(Object parameter) {
// nothing, we don't use it
}
@Override
public void setCurrentParameter(int index) {
myIndex = index;
}
@Override
public Color getDefaultParameterColor() {
return java.awt.Color.BLACK;
}
@Override
public Object[] getItemsToShow() {
return myItems;
}
@Override
public void setItemsToShow(Object[] items) {
myItems = items;
}
@Override
public void showHint(PsiElement element, int offset, ParameterInfoHandler handler) { }
@Override
public int getParameterListStart() {
return 0; // we don't use it
}
@Override
public Object[] getObjectsToView() {
return null; // we don't use it
}
@Override
public PsiElement getHighlightedElement() {
return null; // we don't use it
}
@Override
public void setHighlightedElement(PsiElement elements) {
// nothing, we don't use it
}
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myFile;
}
@Override
public int getOffset() {
return myOffset;
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
/**
* Checks if hint data look as expected.
* @param text expected text of the hint, without formatting
* @param highlighted expected highlighted substrings of hint
* @param disabled expected disabled substrings of hint
*/
public void check(String text, String[] highlighted, String[] disabled) {
assertEquals("Signature", text, StringUtil.join(myTexts, ""));
StringBuilder wrongs = new StringBuilder();
// see if highlighted matches
Set<String> highlight_set = new HashSet<String>();
ContainerUtil.addAll(highlight_set, highlighted);
for (int i = 0; i < myTexts.length; i += 1) {
if (myFlags[i].contains(Flag.HIGHLIGHT) && !highlight_set.contains(myTexts[i])) {
wrongs.append("Highlighted unexpected '").append(myTexts[i]).append("'. ");
}
}
for (int i = 0; i < myTexts.length; i += 1) {
if (!myFlags[i].contains(Flag.HIGHLIGHT) && highlight_set.contains(myTexts[i])) {
wrongs.append("Not highlighted expected '").append(myTexts[i]).append("'. ");
}
}
// see if disabled matches
Set<String> disabled_set = new HashSet<String>();
ContainerUtil.addAll(disabled_set, disabled);
for (int i = 0; i < myTexts.length; i += 1) {
if (myFlags[i].contains(Flag.DISABLE) && !disabled_set.contains(myTexts[i])) {
wrongs.append("Highlighted a disabled '").append(myTexts[i]).append("'. ");
}
}
for (int i = 0; i < myTexts.length; i += 1) {
if (!myFlags[i].contains(Flag.DISABLE) && disabled_set.contains(myTexts[i])) {
wrongs.append("Not disabled expected '").append(myTexts[i]).append("'. ");
}
}
//
if (wrongs.length() > 0) fail(wrongs.toString());
}
public void check(String text, String[] highlighted) {
check(text, highlighted, ArrayUtil.EMPTY_STRING_ARRAY);
}
public void assertNotFound() {
assertNull(myParamOwner);
}
}
}
|
Missing added test.
|
python/testSrc/com/jetbrains/python/PyParameterInfoTest.java
|
Missing added test.
|
|
Java
|
apache-2.0
|
94adb3a0a3454da872673db846723e06e9c5aac4
| 0
|
blademainer/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,fitermay/intellij-community,clumsy/intellij-community,fnouama/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,asedunov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,samthor/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,diorcety/intellij-community,ernestp/consulo,diorcety/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,signed/intellij-community,signed/intellij-community,kool79/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,da1z/intellij-community,slisson/intellij-community,petteyg/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,apixandru/intellij-community,kool79/intellij-community,consulo/consulo,kdwink/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,petteyg/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,caot/intellij-community,jagguli/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,FHannes/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,adedayo/intellij-community,orekyuu/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ernestp/consulo,slisson/intellij-community,da1z/intellij-community,apixandru/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,clumsy/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,petteyg/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,amith01994/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,signed/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,consulo/consulo,ol-loginov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,signed/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,supersven/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,signed/intellij-community,supersven/intellij-community,izonder/intellij-community,ryano144/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,xfournet/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,allotria/intellij-community,suncycheng/intellij-community,kool79/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,holmes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,signed/intellij-community,vvv1559/intellij-community,slisson/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,supersven/intellij-community,vvv1559/intellij-community,semonte/intellij-community,nicolargo/intellij-community,semonte/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,signed/intellij-community,adedayo/intellij-community,izonder/intellij-community,ryano144/intellij-community,slisson/intellij-community,allotria/intellij-community,da1z/intellij-community,nicolargo/intellij-community,supersven/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,izonder/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,samthor/intellij-community,retomerz/intellij-community,caot/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,retomerz/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,signed/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,da1z/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,kool79/intellij-community,FHannes/intellij-community,vladmm/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,supersven/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,izonder/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,consulo/consulo,caot/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,samthor/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,robovm/robovm-studio,supersven/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,vladmm/intellij-community,FHannes/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,signed/intellij-community,kool79/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,clumsy/intellij-community,caot/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,samthor/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,nicolargo/intellij-community,ernestp/consulo,fnouama/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,caot/intellij-community,kdwink/intellij-community,xfournet/intellij-community,allotria/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,signed/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,slisson/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,vladmm/intellij-community,ibinti/intellij-community,allotria/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,fitermay/intellij-community,izonder/intellij-community,caot/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ahb0327/intellij-community,allotria/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,amith01994/intellij-community,asedunov/intellij-community,da1z/intellij-community,clumsy/intellij-community,fitermay/intellij-community,fitermay/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,caot/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,signed/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,alphafoobar/intellij-community,ernestp/consulo,clumsy/intellij-community,blademainer/intellij-community,supersven/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,consulo/consulo,amith01994/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,robovm/robovm-studio,kdwink/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,holmes/intellij-community,ernestp/consulo,samthor/intellij-community,dslomov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,asedunov/intellij-community,holmes/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,petteyg/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ibinti/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,hurricup/intellij-community,fnouama/intellij-community,izonder/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,supersven/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,retomerz/intellij-community,fnouama/intellij-community,diorcety/intellij-community,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,allotria/intellij-community,kdwink/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,holmes/intellij-community,amith01994/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,da1z/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,holmes/intellij-community,clumsy/intellij-community,da1z/intellij-community,allotria/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,Distrotech/intellij-community,izonder/intellij-community,gnuhub/intellij-community,samthor/intellij-community,izonder/intellij-community,retomerz/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,adedayo/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,apixandru/intellij-community,dslomov/intellij-community,supersven/intellij-community,adedayo/intellij-community,dslomov/intellij-community,adedayo/intellij-community,blademainer/intellij-community,semonte/intellij-community,tmpgit/intellij-community,da1z/intellij-community,signed/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,caot/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,caot/intellij-community,vladmm/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,wreckJ/intellij-community,caot/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,holmes/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,apixandru/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,kool79/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.completion.CodeCompletionFeatures;
import com.intellij.codeInsight.completion.CompletionLookupArranger;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.completion.impl.CamelHumpMatcher;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.*;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.ui.UISettings;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.RangeMarkerEx;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.ListScrollingUtil;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.plaf.beg.BegPopupMenuBorder;
import com.intellij.util.Alarm;
import com.intellij.util.CollectConsumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.AsyncProcessIcon;
import com.intellij.util.ui.ButtonlessScrollBarUI;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
public class LookupImpl extends LightweightHint implements LookupEx, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.impl.LookupImpl");
private static final int MAX_PREFERRED_COUNT = 5;
private static final LookupItem EMPTY_LOOKUP_ITEM = LookupItem.fromString("preselect");
private static final int LOOKUP_HEIGHT = Integer.getInteger("idea.lookup.height", 11).intValue();
private static final Icon relevanceSortIcon = IconLoader.getIcon("/ide/lookupRelevance.png");
private static final Icon lexiSortIcon = IconLoader.getIcon("/ide/lookupAlphanumeric.png");
private final Project myProject;
private final Editor myEditor;
private int myPreferredItemsCount;
private String myInitialPrefix;
private LookupArranger myCustomArranger;
private boolean myStableStart;
private RangeMarker myLookupStartMarker;
private final JList myList = new JBList(new DefaultListModel());
private final LookupCellRenderer myCellRenderer;
private Boolean myPositionedAbove = null;
final ArrayList<LookupListener> myListeners = new ArrayList<LookupListener>();
private long myStampShown = 0;
private boolean myShown = false;
private boolean myDisposed = false;
private boolean myHidden = false;
private LookupElement myPreselectedItem = EMPTY_LOOKUP_ITEM;
private final List<LookupElement> myFrozenItems = new ArrayList<LookupElement>();
private String mySelectionInvariant = null;
private boolean mySelectionTouched;
private boolean myFocused = true;
private String myAdditionalPrefix = "";
private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
private final JPanel myIconPanel = new JPanel(new BorderLayout());
private volatile boolean myCalculating;
private final Advertiser myAdComponent;
private volatile String myAdText;
private volatile int myLookupTextWidth = 50;
private boolean myReused;
private boolean myChangeGuard;
private LookupModel myModel = new LookupModel();
@SuppressWarnings("unchecked") private final Map<LookupElement, PrefixMatcher> myMatchers = new ConcurrentHashMap<LookupElement, PrefixMatcher>(TObjectHashingStrategy.IDENTITY);
private LookupHint myElementHint = null;
private Alarm myHintAlarm = new Alarm();
private JLabel mySortingLabel = new JLabel();
private final JScrollPane myScrollPane;
private final LookupLayeredPane myLayeredPane = new LookupLayeredPane();
private JButton myScrollBarIncreaseButton;
private boolean myStartCompletionWhenNothingMatches;
public LookupImpl(Project project, Editor editor, @NotNull LookupArranger arranger){
super(new JPanel(new BorderLayout()));
setForceShowAsPopup(true);
setCancelOnClickOutside(false);
setResizable(true);
myProject = project;
myEditor = editor;
myIconPanel.setVisible(false);
myCellRenderer = new LookupCellRenderer(this);
myList.setCellRenderer(myCellRenderer);
myList.setFocusable(false);
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR);
myScrollBarIncreaseButton = new JButton();
myScrollBarIncreaseButton.setFocusable(false);
myScrollBarIncreaseButton.setRequestFocusEnabled(false);
myScrollPane = new JBScrollPane(myList);
myScrollPane.setViewportBorder(new EmptyBorder(0, 0, 0, 0));
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
myScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(13, -1));
myScrollPane.getVerticalScrollBar().setUI(new ButtonlessScrollBarUI() {
@Override
protected JButton createIncreaseButton(int orientation) {
return myScrollBarIncreaseButton;
}
});
getComponent().add(myLayeredPane, BorderLayout.CENTER);
myLayeredPane.mainPanel.add(myScrollPane, BorderLayout.CENTER);
myScrollPane.setBorder(null);
myAdComponent = new Advertiser();
JComponent adComponent = myAdComponent.getAdComponent();
adComponent.setBorder(new EmptyBorder(0, 1, 1, 2 + relevanceSortIcon.getIconWidth()));
myLayeredPane.mainPanel.add(adComponent, BorderLayout.SOUTH);
getComponent().setBorder(new BegPopupMenuBorder());
myIconPanel.setBackground(Color.LIGHT_GRAY);
myIconPanel.add(myProcessIcon);
updateLookupStart(0);
final ListModel model = myList.getModel();
addEmptyItem((DefaultListModel)model);
updateListHeight(model);
setArranger(arranger);
addListeners();
mySortingLabel.setBorder(new LineBorder(Color.LIGHT_GRAY));
mySortingLabel.setOpaque(true);
mySortingLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = !UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
updateSorting();
}
});
updateSorting();
}
private void updateSorting() {
final boolean lexi = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
mySortingLabel.setIcon(lexi ? lexiSortIcon : relevanceSortIcon);
mySortingLabel.setToolTipText(lexi ? "Click to sort variants by relevance" : "Click to sort variants alphabetically");
myModel.setArranger(getActualArranger());
resort();
}
public void setArranger(LookupArranger arranger) {
myCustomArranger = arranger;
myModel.setArranger(getActualArranger());
}
@Override
public boolean isFocused() {
return myFocused;
}
public void setFocused(boolean focused) {
myFocused = focused;
}
public boolean isCalculating() {
return myCalculating;
}
public void setCalculating(final boolean calculating) {
myCalculating = calculating;
myIconPanel.setVisible(calculating);
if (calculating) {
myProcessIcon.resume();
} else {
myProcessIcon.suspend();
}
}
public int getPreferredItemsCount() {
return myPreferredItemsCount;
}
public void markSelectionTouched() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
mySelectionTouched = true;
myPreselectedItem = null;
}
@TestOnly
public void setSelectionTouched(boolean selectionTouched) {
mySelectionTouched = selectionTouched;
}
public void resort() {
myFrozenItems.clear();
myPreselectedItem = EMPTY_LOOKUP_ITEM;
synchronized (myList) {
((DefaultListModel)myList.getModel()).clear();
}
final List<LookupElement> items = myModel.getItems();
myModel.clearItems();
for (final LookupElement item : items) {
addItem(item, itemMatcher(item));
}
refreshUi(true);
}
public void addItem(LookupElement item, PrefixMatcher matcher) {
myMatchers.put(item, matcher);
myModel.addItem(item);
updateLookupWidth(item);
}
public void updateLookupWidth(LookupElement item) {
final LookupElementPresentation presentation = renderItemApproximately(item);
int maxWidth = myCellRenderer.updateMaximumWidth(presentation);
myLookupTextWidth = Math.max(maxWidth, myLookupTextWidth);
myModel.setItemPresentation(item, presentation);
}
public Collection<LookupElementAction> getActionsFor(LookupElement element) {
final CollectConsumer<LookupElementAction> consumer = new CollectConsumer<LookupElementAction>();
for (LookupActionProvider provider : LookupActionProvider.EP_NAME.getExtensions()) {
provider.fillActions(element, this, consumer);
}
return consumer.getResult();
}
public JList getList() {
return myList;
}
public List<LookupElement> getItems() {
final ArrayList<LookupElement> result = new ArrayList<LookupElement>();
final Object[] objects;
synchronized (myList) {
objects = ((DefaultListModel)myList.getModel()).toArray();
}
for (final Object object : objects) {
if (!(object instanceof EmptyLookupItem)) {
result.add((LookupElement) object);
}
}
return result;
}
public void setAdvertisementText(@Nullable String text) {
myAdText = text;
if (StringUtil.isNotEmpty(text)) {
addAdvertisement(ObjectUtils.assertNotNull(text));
}
}
public String getAdvertisementText() {
return myAdText;
}
public String getAdditionalPrefix() {
return myAdditionalPrefix;
}
void appendPrefix(char c) {
checkValid();
myAdditionalPrefix += c;
myInitialPrefix = null;
myFrozenItems.clear();
refreshUi(false);
ensureSelectionVisible();
}
//todo closing such a lookup still cancels the live template, it shouldn't
public void setStartCompletionWhenNothingMatches(boolean startCompletionWhenNothingMatches) {
myStartCompletionWhenNothingMatches = startCompletionWhenNothingMatches;
}
public boolean isStartCompletionWhenNothingMatches() {
return myStartCompletionWhenNothingMatches;
}
public void ensureSelectionVisible() {
if (!isSelectionVisible()) {
ListScrollingUtil.ensureIndexIsVisible(myList, myList.getSelectedIndex(), 1);
}
}
boolean truncatePrefix(boolean preserveSelection) {
final int len = myAdditionalPrefix.length();
if (len == 0) return false;
if (preserveSelection) {
markSelectionTouched();
}
myAdditionalPrefix = myAdditionalPrefix.substring(0, len - 1);
myInitialPrefix = null;
myFrozenItems.clear();
if (!myReused) {
refreshUi(false);
ensureSelectionVisible();
}
return true;
}
private void updateList() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
checkValid();
final Pair<List<LookupElement>,Iterable<List<LookupElement>>> snapshot = myModel.getModelSnapshot();
final LinkedHashSet<LookupElement> items = matchingItems(snapshot);
checkMinPrefixLengthChanges(items);
boolean hasPreselected = !mySelectionTouched && items.contains(myPreselectedItem);
LookupElement oldSelected = mySelectionTouched ? (LookupElement)myList.getSelectedValue() : null;
String oldInvariant = mySelectionInvariant;
LinkedHashSet<LookupElement> model = new LinkedHashSet<LookupElement>();
model.addAll(getPrefixItems(items, true));
model.addAll(getPrefixItems(items, false));
myFrozenItems.retainAll(items);
model.addAll(myFrozenItems);
if (!isAlphaSorted()) {
addMostRelevantItems(model, snapshot.second);
if (hasPreselected) {
model.add(myPreselectedItem);
}
}
myPreferredItemsCount = model.size();
myFrozenItems.clear();
if (myShown) {
myFrozenItems.addAll(model);
}
if (isAlphaSorted()) {
model.addAll(items);
} else if (limitRelevance()) {
model.addAll(addRemainingItemsLexicographically(model, items));
} else {
for (List<LookupElement> group : snapshot.second) {
for (LookupElement element : group) {
if (prefixMatches(element)) {
model.add(element);
}
}
}
}
DefaultListModel listModel = (DefaultListModel)myList.getModel();
synchronized (myList) {
listModel.clear();
if (!model.isEmpty()) {
for (LookupElement element : model) {
listModel.addElement(element);
}
}
else {
addEmptyItem(listModel);
}
}
updateListHeight(listModel);
if (!model.isEmpty()) {
myList.setFixedCellWidth(Math.max(myLookupTextWidth + myCellRenderer.getIconIndent(), myAdComponent.getAdComponent().getPreferredSize().width));
LookupElement first = model.iterator().next();
if (isFocused() && (!(isExactPrefixItem(first, true) || isExactPrefixItem(first, false)) || mySelectionTouched)) {
restoreSelection(oldSelected, hasPreselected, oldInvariant, snapshot.second);
}
else {
myList.setSelectedIndex(0);
}
}
}
private boolean isSelectionVisible() {
return myList.getFirstVisibleIndex() <= myList.getSelectedIndex() && myList.getSelectedIndex() <= myList.getLastVisibleIndex();
}
private LinkedHashSet<LookupElement> matchingItems(Pair<List<LookupElement>, Iterable<List<LookupElement>>> snapshot) {
final LinkedHashSet<LookupElement> items = new LinkedHashSet<LookupElement>();
for (LookupElement element : snapshot.first) {
if (prefixMatches(element)) {
items.add(element);
}
}
return items;
}
private boolean checkReused() {
if (myReused) {
myAdditionalPrefix = "";
myFrozenItems.clear();
myModel.collectGarbage();
myReused = false;
return true;
}
return false;
}
private void checkMinPrefixLengthChanges(Collection<LookupElement> items) {
if (myStableStart) return;
if (!myCalculating && !items.isEmpty()) {
myStableStart = true;
}
int minPrefixLength = items.isEmpty() ? 0 : Integer.MAX_VALUE;
for (final LookupElement item : items) {
minPrefixLength = Math.min(itemMatcher(item).getPrefix().length(), minPrefixLength);
}
updateLookupStart(minPrefixLength);
}
private void restoreSelection(@Nullable LookupElement oldSelected, boolean choosePreselectedItem, @Nullable String oldInvariant, Iterable<List<LookupElement>> groups) {
if (oldSelected != null) {
if (oldSelected.isValid()) {
myList.setSelectedValue(oldSelected, false);
if (myList.getSelectedValue() == oldSelected) {
return;
}
}
if (oldInvariant != null) {
for (LookupElement element : getItems()) {
if (oldInvariant.equals(myModel.getItemPresentationInvariant(element))) {
myList.setSelectedValue(element, false);
if (myList.getSelectedValue() == element) {
return;
}
}
}
}
}
if (choosePreselectedItem) {
myList.setSelectedValue(myPreselectedItem, false);
} else {
myList.setSelectedIndex(doSelectMostPreferableItem(getItems(), groups));
}
if (myPreselectedItem != null && myShown) {
myPreselectedItem = getCurrentItem();
}
}
private void updateListHeight(ListModel model) {
myList.setFixedCellHeight(myCellRenderer.getListCellRendererComponent(myList, model.getElementAt(0), 0, false, false).getPreferredSize().height);
myList.setVisibleRowCount(Math.min(model.getSize(), LOOKUP_HEIGHT));
}
private void addEmptyItem(DefaultListModel model) {
LookupItem<String> item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions"));
myMatchers.put(item, new CamelHumpMatcher(""));
if (!myCalculating) {
myList.setFixedCellWidth(Math.max(myCellRenderer.updateMaximumWidth(renderItemApproximately(item)), myLookupTextWidth));
}
model.addElement(item);
}
private static LookupElementPresentation renderItemApproximately(LookupElement item) {
final LookupElementPresentation p = new LookupElementPresentation();
item.renderElement(p);
return p;
}
private static List<LookupElement> addRemainingItemsLexicographically(Set<LookupElement> firstItems, Collection<LookupElement> allItems) {
List<LookupElement> model = new ArrayList<LookupElement>();
for (LookupElement item : allItems) {
if (!firstItems.contains(item)) {
model.add(item);
}
}
return model;
}
private void addMostRelevantItems(final Set<LookupElement> model, final Iterable<List<LookupElement>> sortedItems) {
if (model.size() > MAX_PREFERRED_COUNT) return;
for (final List<LookupElement> elements : sortedItems) {
final List<LookupElement> suitable = new SmartList<LookupElement>();
for (final LookupElement item : elements) {
if (!model.contains(item) && prefixMatches(item)) {
suitable.add(item);
}
}
if (model.size() + suitable.size() > MAX_PREFERRED_COUNT) break;
model.addAll(suitable);
}
}
public static boolean limitRelevance() {
return ApplicationManager.getApplication().isUnitTestMode() || Registry.is("limited.relevance.sorting.in.completion");
}
public boolean isFrozen(@NotNull LookupElement element) {
return myFrozenItems.contains(element);
}
private List<LookupElement> getPrefixItems(final Collection<LookupElement> elements, final boolean caseSensitive) {
List<LookupElement> better = new ArrayList<LookupElement>();
for (LookupElement element : elements) {
if (isExactPrefixItem(element, caseSensitive)) {
better.add(element);
}
}
final LookupArranger arranger = getActualArranger();
final Comparator<LookupElement> itemComparator = arranger.getItemComparator();
if (itemComparator != null) {
Collections.sort(better, itemComparator);
}
return myModel.classifyByRelevance(better);
}
@NotNull
@Override
public String itemPattern(LookupElement element) {
return itemMatcher(element).getPrefix() + myAdditionalPrefix;
}
private LookupArranger getActualArranger() {
return myCustomArranger;
}
private boolean isAlphaSorted() {
return isCompletion() && UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
}
private boolean isExactPrefixItem(LookupElement item, final boolean caseSensitive) {
final String pattern = itemPattern(item);
final Set<String> strings = item.getAllLookupStrings();
if (strings.contains(pattern)) {
return caseSensitive; //to not add the same elements twice to the model, as sensitive and then as insensitive
}
if (caseSensitive) {
return false;
}
for (String s : strings) {
if (s.equalsIgnoreCase(pattern)) {
return true;
}
}
return false;
}
private boolean prefixMatches(final LookupElement item) {
PrefixMatcher matcher = itemMatcher(item);
if (myAdditionalPrefix.length() > 0) {
matcher = matcher.cloneWithPrefix(itemPattern(item));
}
return matcher.prefixMatches(item);
}
@Override
@NotNull
public PrefixMatcher itemMatcher(LookupElement item) {
PrefixMatcher matcher = myMatchers.get(item);
if (matcher == null) {
throw new AssertionError("Item not in lookup: item=" + item + "; lookup items=" + getItems());
}
return matcher;
}
/**
* @return point in layered pane coordinate system.
*/
private Point calculatePosition() {
Dimension dim = getComponent().getPreferredSize();
int lookupStart = getLookupStart();
if (lookupStart < 0 || lookupStart > myEditor.getDocument().getTextLength()) {
LOG.error(lookupStart + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" +
getPsiElement());
}
LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart);
Point location = myEditor.logicalPositionToXY(pos);
location.y += myEditor.getLineHeight();
location.x -= myCellRenderer.getIconIndent() + getComponent().getInsets().left;
SwingUtilities.convertPointToScreen(location, myEditor.getContentComponent());
final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(location);
if (!isPositionedAboveCaret()) {
int shiftLow = screenRectangle.height - (location.y + dim.height);
myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height;
}
if (isPositionedAboveCaret()) {
location.y -= dim.height + myEditor.getLineHeight();
if (pos.line == 0) {
location.y += 1;
//otherwise the lookup won't intersect with the editor and every editor's resize (e.g. after typing in console) will close the lookup
}
}
if (!screenRectangle.contains(location)) {
location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
}
final JRootPane rootPane = myEditor.getComponent().getRootPane();
if (rootPane == null) {
LOG.error(myEditor.isDisposed() + "; shown=" + myShown + "; disposed=" + myDisposed + "; editorShowing=" + myEditor.getContentComponent().isShowing());
}
SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
return location;
}
public void finishLookup(final char completionChar) {
finishLookup(completionChar, (LookupElement)myList.getSelectedValue());
}
public void finishLookup(char completionChar, @Nullable final LookupElement item) {
doHide(false, true);
if (item == null ||
item instanceof EmptyLookupItem ||
item.getObject() instanceof DeferredUserLookupValue &&
item.as(LookupItem.CLASS_CONDITION_KEY) != null &&
!((DeferredUserLookupValue)item.getObject()).handleUserSelection(item.as(LookupItem.CLASS_CONDITION_KEY), myProject)) {
fireItemSelected(null, completionChar);
return;
}
final PsiFile file = getPsiFile();
if (file != null && !WriteCommandAction.ensureFilesWritable(myProject, Arrays.asList(file))) {
fireItemSelected(null, completionChar);
return;
}
final String prefix = itemPattern(item);
boolean plainMatch = ContainerUtil.or(item.getAllLookupStrings(), new Condition<String>() {
@Override
public boolean value(String s) {
return StringUtil.startsWithIgnoreCase(s, prefix);
}
});
if (!plainMatch) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CAMEL_HUMPS);
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
insertLookupString(item, prefix);
}
});
fireItemSelected(item, completionChar);
}
private void insertLookupString(LookupElement item, final String prefix) {
PrefixMatcher matcher = itemMatcher(item);
String lookupString = item.getLookupString();
if (!item.isCaseSensitive() && matcher.prefixMatches(item) && StringUtil.startsWithIgnoreCase(lookupString, prefix)) {
lookupString = handleCaseInsensitiveVariant(prefix, lookupString);
}
EditorModificationUtil.deleteSelectedText(myEditor);
final int caretOffset = myEditor.getCaretModel().getOffset();
int lookupStart = caretOffset - prefix.length();
int len = myEditor.getDocument().getTextLength();
LOG.assertTrue(lookupStart >= 0 && lookupStart <= len, "ls: " + lookupStart + " caret: " + caretOffset + " prefix:" + prefix + " doc: " + len);
LOG.assertTrue(caretOffset >= 0 && caretOffset <= len, "co: " + caretOffset + " doc: " + len);
myEditor.getDocument().replaceString(lookupStart, caretOffset, lookupString);
int offset = lookupStart + lookupString.length();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
}
private static String handleCaseInsensitiveVariant(final String prefix, @NotNull final String lookupString) {
final int length = prefix.length();
if (length == 0) return lookupString;
boolean isAllLower = true;
boolean isAllUpper = true;
boolean sameCase = true;
for (int i = 0; i < length && (isAllLower || isAllUpper || sameCase); i++) {
final char c = prefix.charAt(i);
isAllLower = isAllLower && Character.isLowerCase(c);
isAllUpper = isAllUpper && Character.isUpperCase(c);
sameCase = sameCase && Character.isLowerCase(c) == Character.isLowerCase(lookupString.charAt(i));
}
if (sameCase) return lookupString;
if (isAllLower) return lookupString.toLowerCase();
if (isAllUpper) return lookupString.toUpperCase();
return lookupString;
}
public int getLookupStart() {
LOG.assertTrue(myLookupStartMarker.isValid());
return myLookupStartMarker.getStartOffset();
}
public void performGuardedChange(Runnable change) {
checkValid();
assert myLookupStartMarker.isValid();
assert !myChangeGuard;
myChangeGuard = true;
RangeMarkerEx marker = (RangeMarkerEx) myEditor.getDocument().createRangeMarker(myLookupStartMarker.getStartOffset(), myLookupStartMarker.getEndOffset());
marker.trackInvalidation(true);
try {
change.run();
}
finally {
marker.trackInvalidation(false);
myChangeGuard = false;
}
checkValid();
LOG.assertTrue(myLookupStartMarker.isValid(), "invalid lookup start");
LOG.assertTrue(marker.isValid(), "invalid marker");
marker.dispose();
if (isVisible()) {
updateLookupBounds();
}
checkValid();
}
@Override
public boolean vetoesHiding() {
return myChangeGuard || myDisposed;
}
public boolean isShown() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
return myShown;
}
public boolean showLookup() {
ApplicationManager.getApplication().assertIsDispatchThread();
checkValid();
LOG.assertTrue(!myShown);
myShown = true;
myStampShown = System.currentTimeMillis();
if (ApplicationManager.getApplication().isUnitTestMode()) return true;
myAdComponent.showRandomText();
getComponent().setBorder(null);
updateScrollbarVisibility();
Point p = calculatePosition();
HintManagerImpl.getInstanceImpl().showEditorHint(this, myEditor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false,
HintManagerImpl.createHintHint(myEditor, p, this, HintManager.UNDER).setAwtTooltip(false));
if (!isVisible()) return false;
LOG.assertTrue(myList.isShowing(), "!showing, disposed=" + myDisposed);
return true;
}
public boolean mayBeNoticed() {
return myStampShown > 0 && System.currentTimeMillis() - myStampShown > 300;
}
private void addListeners() {
myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
if (!myChangeGuard) {
hide();
}
}
}, this);
final CaretListener caretListener = new CaretListener() {
public void caretPositionChanged(CaretEvent e) {
if (!myChangeGuard) {
hide();
}
}
};
final SelectionListener selectionListener = new SelectionListener() {
public void selectionChanged(final SelectionEvent e) {
if (!myChangeGuard) {
hide();
}
}
};
final EditorMouseListener mouseListener = new EditorMouseAdapter() {
public void mouseClicked(EditorMouseEvent e){
e.consume();
hide();
}
};
myEditor.getCaretModel().addCaretListener(caretListener);
myEditor.getSelectionModel().addSelectionListener(selectionListener);
myEditor.addEditorMouseListener(mouseListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myEditor.getCaretModel().removeCaretListener(caretListener);
myEditor.getSelectionModel().removeSelectionListener(selectionListener);
myEditor.removeEditorMouseListener(mouseListener);
}
});
myList.addListSelectionListener(new ListSelectionListener() {
private LookupElement oldItem = null;
public void valueChanged(ListSelectionEvent e){
myHintAlarm.cancelAllRequests();
final LookupElement item = getCurrentItem();
if (oldItem != item) {
mySelectionInvariant = item == null ? null : myModel.getItemPresentationInvariant(item);
fireCurrentItemChanged(item);
}
if (item != null) {
updateHint(item);
}
oldItem = item;
}
});
myList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
setFocused(true);
markSelectionTouched();
if (e.getClickCount() == 2){
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
finishLookup(NORMAL_SELECT_CHAR);
}
}, "", null);
}
}
});
}
private void updateHint(@NotNull final LookupElement item) {
checkValid();
if (myElementHint != null) {
myLayeredPane.remove(myElementHint);
myElementHint = null;
final JRootPane rootPane = getComponent().getRootPane();
if (rootPane != null) {
rootPane.revalidate();
rootPane.repaint();
}
}
if (!isFocused()) {
return;
}
final Collection<LookupElementAction> actions = getActionsFor(item);
if (!actions.isEmpty()) {
myHintAlarm.addRequest(new Runnable() {
@Override
public void run() {
assert !myDisposed;
myElementHint = new LookupHint();
myLayeredPane.add(myElementHint, 20, 0);
myLayeredPane.layoutHint();
}
}, 500);
}
}
private int updateLookupStart(int myMinPrefixLength) {
int offset = myEditor.getSelectionModel().hasSelection()
? myEditor.getSelectionModel().getSelectionStart()
: myEditor.getCaretModel().getOffset();
int start = Math.max(offset - myMinPrefixLength - myAdditionalPrefix.length(), 0);
if (myLookupStartMarker != null) {
if (myLookupStartMarker.isValid() && myLookupStartMarker.getStartOffset() == start && myLookupStartMarker.getEndOffset() == start) {
return start;
}
myLookupStartMarker.dispose();
}
myLookupStartMarker = myEditor.getDocument().createRangeMarker(start, start);
myLookupStartMarker.setGreedyToLeft(true);
return start;
}
@Nullable
public LookupElement getCurrentItem(){
LookupElement item = (LookupElement)myList.getSelectedValue();
return item instanceof EmptyLookupItem ? null : item;
}
public void setCurrentItem(LookupElement item){
markSelectionTouched();
myList.setSelectedValue(item, false);
}
public void addLookupListener(LookupListener listener){
myListeners.add(listener);
}
public void removeLookupListener(LookupListener listener){
myListeners.remove(listener);
}
public Rectangle getCurrentItemBounds(){
int index = myList.getSelectedIndex();
if (index < 0) {
LOG.error("No selected element, size=" + myList.getModel().getSize() + "; items" + getItems());
}
Rectangle itmBounds = myList.getCellBounds(index, index);
if (itmBounds == null){
LOG.error("No bounds for " + index + "; size=" + myList.getModel().getSize());
return null;
}
Point layeredPanePoint=SwingUtilities.convertPoint(myList,itmBounds.x,itmBounds.y,getComponent());
itmBounds.x = layeredPanePoint.x;
itmBounds.y = layeredPanePoint.y;
return itmBounds;
}
public void fireItemSelected(@Nullable final LookupElement item, char completionChar){
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
if (item != null) {
getActualArranger().itemSelected(item, this);
}
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item, completionChar);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
try {
listener.itemSelected(event);
}
catch (Throwable e) {
LOG.error(e);
}
}
}
}
private void fireLookupCanceled(final boolean explicitly) {
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, explicitly);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
try {
listener.lookupCanceled(event);
}
catch (Throwable e) {
LOG.error(e);
}
}
}
}
private void fireCurrentItemChanged(LookupElement item){
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item, (char)0);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
listener.currentItemChanged(event);
}
}
}
public boolean fillInCommonPrefix(boolean explicitlyInvoked) {
if (explicitlyInvoked) {
setFocused(true);
}
if (explicitlyInvoked && myCalculating) return false;
if (!explicitlyInvoked && mySelectionTouched) return false;
ListModel listModel = myList.getModel();
if (listModel.getSize() <= 1) return false;
if (listModel.getSize() == 0) return false;
final LookupElement firstItem = (LookupElement)listModel.getElementAt(0);
if (listModel.getSize() == 1 && firstItem instanceof EmptyLookupItem) return false;
final PrefixMatcher firstItemMatcher = itemMatcher(firstItem);
final String oldPrefix = firstItemMatcher.getPrefix();
final String presentPrefix = oldPrefix + myAdditionalPrefix;
String commonPrefix = firstItem.getLookupString();
for (int i = 1; i < listModel.getSize(); i++) {
LookupElement item = (LookupElement)listModel.getElementAt(i);
if (!oldPrefix.equals(itemMatcher(item).getPrefix())) return false;
final String lookupString = item.getLookupString();
final int length = Math.min(commonPrefix.length(), lookupString.length());
if (length < commonPrefix.length()) {
commonPrefix = commonPrefix.substring(0, length);
}
for (int j = 0; j < length; j++) {
if (commonPrefix.charAt(j) != lookupString.charAt(j)) {
commonPrefix = lookupString.substring(0, j);
break;
}
}
if (commonPrefix.length() == 0 || commonPrefix.length() < presentPrefix.length()) {
return false;
}
}
if (commonPrefix.equals(presentPrefix)) {
return false;
}
for (int i = 0; i < listModel.getSize(); i++) {
LookupElement item = (LookupElement)listModel.getElementAt(i);
if (!itemMatcher(item).cloneWithPrefix(commonPrefix).prefixMatches(item)) {
return false;
}
}
if (myAdditionalPrefix.length() == 0 && myInitialPrefix == null && !explicitlyInvoked) {
myInitialPrefix = presentPrefix;
}
else {
myInitialPrefix = null;
}
replacePrefix(presentPrefix, commonPrefix);
return true;
}
public void replacePrefix(final String presentPrefix, final String newPrefix) {
performGuardedChange(new Runnable() {
public void run() {
EditorModificationUtil.deleteSelectedText(myEditor);
int offset = myEditor.getCaretModel().getOffset();
final int start = offset - presentPrefix.length();
myEditor.getDocument().replaceString(start, offset, newPrefix);
Map<LookupElement, PrefixMatcher> newItems = myModel.retainMatchingItems(newPrefix, LookupImpl.this);
myMatchers.clear();
myMatchers.putAll(newItems);
myAdditionalPrefix = "";
myEditor.getCaretModel().moveToOffset(start + newPrefix.length());
}
});
refreshUi(true);
}
@Nullable
public PsiFile getPsiFile() {
return PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
}
public boolean isCompletion() {
return myCustomArranger instanceof CompletionLookupArranger;
}
public PsiElement getPsiElement() {
PsiFile file = getPsiFile();
if (file == null) return null;
int offset = getLookupStart();
if (offset > 0) return file.findElementAt(offset - 1);
return file.findElementAt(0);
}
public Editor getEditor() {
return myEditor;
}
@TestOnly
public void setPositionedAbove(boolean positionedAbove) {
myPositionedAbove = positionedAbove;
}
public boolean isPositionedAboveCaret(){
return myPositionedAbove != null && myPositionedAbove.booleanValue();
}
public boolean isSelectionTouched() {
return mySelectionTouched;
}
public void hide(){
hideLookup(true);
}
public void hideLookup(boolean explicitly) {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myDisposed) return;
doHide(true, explicitly);
}
private void doHide(final boolean fireCanceled, final boolean explicitly) {
if (myChangeGuard) {
LOG.error("Disposing under a change guard");
}
if (myDisposed) {
LOG.error(disposeTrace);
}
else {
myHidden = true;
try {
super.hide();
Disposer.dispose(this);
assert myDisposed;
}
catch (Throwable e) {
LOG.error(e);
}
}
if (fireCanceled) {
fireLookupCanceled(explicitly);
}
}
public void restorePrefix() {
if (myInitialPrefix != null) {
myEditor.getDocument().replaceString(getLookupStart(), myEditor.getCaretModel().getOffset(), myInitialPrefix);
}
}
private static String staticDisposeTrace = null;
private String disposeTrace = null;
public static String getLastLookupDisposeTrace() {
return staticDisposeTrace;
}
public void dispose() {
assert ApplicationManager.getApplication().isDispatchThread();
assert myHidden;
if (myDisposed) {
LOG.error(disposeTrace);
return;
}
Disposer.dispose(myProcessIcon);
Disposer.dispose(myHintAlarm);
myDisposed = true;
disposeTrace = DebugUtil.currentStackTrace();
//noinspection AssignmentToStaticFieldFromInstanceMethod
staticDisposeTrace = disposeTrace;
}
private int doSelectMostPreferableItem(List<LookupElement> items, Iterable<List<LookupElement>> groups) {
if (items.isEmpty()) {
return -1;
}
if (items.size() == 1) {
return 0;
}
for (int i = 0; i < items.size(); i++) {
LookupElement item = items.get(i);
if (isExactPrefixItem(item, true)) {
return i;
}
}
final int index = getActualArranger().suggestPreselectedItem(items, groups);
assert index >= 0 && index < items.size();
return index;
}
public void refreshUi(boolean mayCheckReused) {
final boolean reused = mayCheckReused && checkReused();
boolean selectionVisible = isSelectionVisible();
updateList();
if (isVisible()) {
LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode());
if (myEditor.getComponent().getRootPane() == null) {
LOG.error("Null root pane");
}
updateScrollbarVisibility();
updateLookupBounds();
if (reused || selectionVisible) {
ensureSelectionVisible();
}
}
}
private void updateLookupBounds() {
HintManagerImpl.adjustEditorHintPosition(this, myEditor, calculatePosition());
}
private void updateScrollbarVisibility() {
boolean showSorting = isCompletion() && getList().getModel().getSize() >= 3;
mySortingLabel.setVisible(showSorting);
myScrollPane.setVerticalScrollBarPolicy(showSorting ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
}
@TestOnly
public LookupArranger getArranger() {
return getActualArranger();
}
public void markReused() {
myReused = true;
myModel.clearItems();
myAdComponent.clearAdvertisements();
myPreselectedItem = null;
}
public void addAdvertisement(@NotNull String text) {
myAdComponent.addAdvertisement(text);
}
public boolean isLookupDisposed() {
return myDisposed;
}
public void checkValid() {
if (myDisposed) {
throw new AssertionError("Disposed at: " + disposeTrace);
}
}
@Override
public void showItemPopup(JBPopup hint) {
final Rectangle bounds = getCurrentItemBounds();
hint.show(new RelativePoint(getComponent(), new Point(bounds.x + bounds.width, bounds.y)));
}
@Override
public boolean showElementActions() {
if (!isVisible()) return false;
final LookupElement element = getCurrentItem();
if (element == null) {
return false;
}
final Collection<LookupElementAction> actions = getActionsFor(element);
if (actions.isEmpty()) {
return false;
}
showItemPopup(JBPopupFactory.getInstance().createListPopup(new LookupActionsStep(actions, this, element)));
return true;
}
private class LookupLayeredPane extends JLayeredPane {
final JPanel mainPanel = new JPanel(new BorderLayout());
private LookupLayeredPane() {
add(mainPanel, 0, 0);
add(myIconPanel, 42, 0);
add(mySortingLabel, 10, 0);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
mainPanel.setSize(getSize());
mainPanel.validate();
layoutStatusIcons();
layoutHint();
revalidate();
repaint();
}
});
}
private void layoutStatusIcons() {
int adHeight = myAdComponent.getAdComponent().getPreferredSize().height;
Dimension buttonSize = adHeight > 0 ? new Dimension(0, 0) : new Dimension(relevanceSortIcon.getIconWidth(), relevanceSortIcon.getIconHeight());
myScrollBarIncreaseButton.setPreferredSize(buttonSize);
myScrollBarIncreaseButton.setMinimumSize(buttonSize);
myScrollBarIncreaseButton.setMaximumSize(buttonSize);
myScrollPane.getVerticalScrollBar().revalidate();
myScrollPane.getVerticalScrollBar().repaint();
final Dimension iconSize = myProcessIcon.getPreferredSize();
myIconPanel.setBounds(getWidth() - iconSize.width, 0, iconSize.width, iconSize.height);
final Dimension sortSize = mySortingLabel.getPreferredSize();
final Point sbLocation = SwingUtilities.convertPoint(myScrollPane.getVerticalScrollBar(), 0, 0, myLayeredPane);
final int sortHeight = Math.max(adHeight, mySortingLabel.getPreferredSize().height);
mySortingLabel.setBounds(sbLocation.x, getHeight() - sortHeight, sortSize.width, sortHeight);
}
void layoutHint() {
if (myElementHint != null) {
final Rectangle bounds = getCurrentItemBounds();
myElementHint.setSize(myElementHint.getPreferredSize());
myElementHint.setLocation(new Point(bounds.x + bounds.width - myElementHint.getWidth(), bounds.y));
}
}
@Override
public Dimension getPreferredSize() {
return mainPanel.getPreferredSize();
}
}
private class LookupHint extends JLabel {
private final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(4, 4, 4, 4);
private final Border ACTIVE_BORDER = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK, 1), BorderFactory.createEmptyBorder(3, 3, 3, 3));
private LookupHint() {
setOpaque(false);
setBorder(INACTIVE_BORDER);
setIcon(IconLoader.findIcon("/actions/intentionBulb.png"));
String acceleratorsText = KeymapUtil.getFirstKeyboardShortcutText(
ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS));
if (acceleratorsText.length() > 0) {
setToolTipText(CodeInsightBundle.message("lightbulb.tooltip", acceleratorsText));
}
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
setBorder(ACTIVE_BORDER);
}
@Override
public void mouseExited(MouseEvent e) {
setBorder(INACTIVE_BORDER);
}
@Override
public void mousePressed(MouseEvent e) {
if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
showElementActions();
}
}
});
}
}
public LinkedHashMap<LookupElement,StringBuilder> getRelevanceStrings() {
return myModel.getRelevanceStrings();
}
}
|
platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.completion.CodeCompletionFeatures;
import com.intellij.codeInsight.completion.CompletionLookupArranger;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.completion.impl.CamelHumpMatcher;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.*;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.ui.UISettings;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.RangeMarkerEx;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.ListScrollingUtil;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.plaf.beg.BegPopupMenuBorder;
import com.intellij.util.Alarm;
import com.intellij.util.CollectConsumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.AsyncProcessIcon;
import com.intellij.util.ui.ButtonlessScrollBarUI;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
public class LookupImpl extends LightweightHint implements LookupEx, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.impl.LookupImpl");
private static final int MAX_PREFERRED_COUNT = 5;
private static final LookupItem EMPTY_LOOKUP_ITEM = LookupItem.fromString("preselect");
private static final int LOOKUP_HEIGHT = Integer.getInteger("idea.lookup.height", 11).intValue();
private static final Icon relevanceSortIcon = IconLoader.getIcon("/ide/lookupRelevance.png");
private static final Icon lexiSortIcon = IconLoader.getIcon("/ide/lookupAlphanumeric.png");
private final Project myProject;
private final Editor myEditor;
private int myPreferredItemsCount;
private String myInitialPrefix;
private LookupArranger myCustomArranger;
private boolean myStableStart;
private RangeMarker myLookupStartMarker;
private final JList myList = new JBList(new DefaultListModel());
private final LookupCellRenderer myCellRenderer;
private Boolean myPositionedAbove = null;
final ArrayList<LookupListener> myListeners = new ArrayList<LookupListener>();
private long myStampShown = 0;
private boolean myShown = false;
private boolean myDisposed = false;
private boolean myHidden = false;
private LookupElement myPreselectedItem = EMPTY_LOOKUP_ITEM;
private final List<LookupElement> myFrozenItems = new ArrayList<LookupElement>();
private String mySelectionInvariant = null;
private boolean mySelectionTouched;
private boolean myFocused = true;
private String myAdditionalPrefix = "";
private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
private final JPanel myIconPanel = new JPanel(new BorderLayout());
private volatile boolean myCalculating;
private final Advertiser myAdComponent;
private volatile String myAdText;
private volatile int myLookupTextWidth = 50;
private boolean myReused;
private boolean myChangeGuard;
private LookupModel myModel = new LookupModel();
@SuppressWarnings("unchecked") private final Map<LookupElement, PrefixMatcher> myMatchers = new ConcurrentHashMap<LookupElement, PrefixMatcher>(TObjectHashingStrategy.IDENTITY);
private LookupHint myElementHint = null;
private Alarm myHintAlarm = new Alarm();
private JLabel mySortingLabel = new JLabel();
private final JScrollPane myScrollPane;
private final LookupLayeredPane myLayeredPane = new LookupLayeredPane();
private JButton myScrollBarIncreaseButton;
private boolean myStartCompletionWhenNothingMatches;
public LookupImpl(Project project, Editor editor, @NotNull LookupArranger arranger){
super(new JPanel(new BorderLayout()));
setForceShowAsPopup(true);
setCancelOnClickOutside(false);
myProject = project;
myEditor = editor;
myIconPanel.setVisible(false);
myCellRenderer = new LookupCellRenderer(this);
myList.setCellRenderer(myCellRenderer);
myList.setFocusable(false);
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR);
myScrollBarIncreaseButton = new JButton();
myScrollBarIncreaseButton.setFocusable(false);
myScrollBarIncreaseButton.setRequestFocusEnabled(false);
myScrollPane = new JBScrollPane(myList);
myScrollPane.setViewportBorder(new EmptyBorder(0, 0, 0, 0));
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
myScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(13, -1));
myScrollPane.getVerticalScrollBar().setUI(new ButtonlessScrollBarUI() {
@Override
protected JButton createIncreaseButton(int orientation) {
return myScrollBarIncreaseButton;
}
});
getComponent().add(myLayeredPane, BorderLayout.CENTER);
myLayeredPane.mainPanel.add(myScrollPane, BorderLayout.NORTH);
myScrollPane.setBorder(null);
myAdComponent = new Advertiser();
JComponent adComponent = myAdComponent.getAdComponent();
adComponent.setBorder(new EmptyBorder(0, 1, 1, 2 + relevanceSortIcon.getIconWidth()));
myLayeredPane.mainPanel.add(adComponent, BorderLayout.SOUTH);
getComponent().setBorder(new BegPopupMenuBorder());
myIconPanel.setBackground(Color.LIGHT_GRAY);
myIconPanel.add(myProcessIcon);
updateLookupStart(0);
final ListModel model = myList.getModel();
addEmptyItem((DefaultListModel)model);
updateListHeight(model);
setArranger(arranger);
addListeners();
mySortingLabel.setBorder(new LineBorder(Color.LIGHT_GRAY));
mySortingLabel.setOpaque(true);
mySortingLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = !UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
updateSorting();
}
});
updateSorting();
}
private void updateSorting() {
final boolean lexi = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
mySortingLabel.setIcon(lexi ? lexiSortIcon : relevanceSortIcon);
mySortingLabel.setToolTipText(lexi ? "Click to sort variants by relevance" : "Click to sort variants alphabetically");
myModel.setArranger(getActualArranger());
resort();
}
public void setArranger(LookupArranger arranger) {
myCustomArranger = arranger;
myModel.setArranger(getActualArranger());
}
@Override
public boolean isFocused() {
return myFocused;
}
public void setFocused(boolean focused) {
myFocused = focused;
}
public boolean isCalculating() {
return myCalculating;
}
public void setCalculating(final boolean calculating) {
myCalculating = calculating;
myIconPanel.setVisible(calculating);
if (calculating) {
myProcessIcon.resume();
} else {
myProcessIcon.suspend();
}
}
public int getPreferredItemsCount() {
return myPreferredItemsCount;
}
public void markSelectionTouched() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
mySelectionTouched = true;
myPreselectedItem = null;
}
@TestOnly
public void setSelectionTouched(boolean selectionTouched) {
mySelectionTouched = selectionTouched;
}
public void resort() {
myFrozenItems.clear();
myPreselectedItem = EMPTY_LOOKUP_ITEM;
synchronized (myList) {
((DefaultListModel)myList.getModel()).clear();
}
final List<LookupElement> items = myModel.getItems();
myModel.clearItems();
for (final LookupElement item : items) {
addItem(item, itemMatcher(item));
}
refreshUi(true);
}
public void addItem(LookupElement item, PrefixMatcher matcher) {
myMatchers.put(item, matcher);
myModel.addItem(item);
updateLookupWidth(item);
}
public void updateLookupWidth(LookupElement item) {
final LookupElementPresentation presentation = renderItemApproximately(item);
int maxWidth = myCellRenderer.updateMaximumWidth(presentation);
myLookupTextWidth = Math.max(maxWidth, myLookupTextWidth);
myModel.setItemPresentation(item, presentation);
}
public Collection<LookupElementAction> getActionsFor(LookupElement element) {
final CollectConsumer<LookupElementAction> consumer = new CollectConsumer<LookupElementAction>();
for (LookupActionProvider provider : LookupActionProvider.EP_NAME.getExtensions()) {
provider.fillActions(element, this, consumer);
}
return consumer.getResult();
}
public JList getList() {
return myList;
}
public List<LookupElement> getItems() {
final ArrayList<LookupElement> result = new ArrayList<LookupElement>();
final Object[] objects;
synchronized (myList) {
objects = ((DefaultListModel)myList.getModel()).toArray();
}
for (final Object object : objects) {
if (!(object instanceof EmptyLookupItem)) {
result.add((LookupElement) object);
}
}
return result;
}
public void setAdvertisementText(@Nullable String text) {
myAdText = text;
if (StringUtil.isNotEmpty(text)) {
addAdvertisement(ObjectUtils.assertNotNull(text));
}
}
public String getAdvertisementText() {
return myAdText;
}
public String getAdditionalPrefix() {
return myAdditionalPrefix;
}
void appendPrefix(char c) {
checkValid();
myAdditionalPrefix += c;
myInitialPrefix = null;
myFrozenItems.clear();
refreshUi(false);
ensureSelectionVisible();
}
//todo closing such a lookup still cancels the live template, it shouldn't
public void setStartCompletionWhenNothingMatches(boolean startCompletionWhenNothingMatches) {
myStartCompletionWhenNothingMatches = startCompletionWhenNothingMatches;
}
public boolean isStartCompletionWhenNothingMatches() {
return myStartCompletionWhenNothingMatches;
}
public void ensureSelectionVisible() {
if (!isSelectionVisible()) {
ListScrollingUtil.ensureIndexIsVisible(myList, myList.getSelectedIndex(), 1);
}
}
boolean truncatePrefix(boolean preserveSelection) {
final int len = myAdditionalPrefix.length();
if (len == 0) return false;
if (preserveSelection) {
markSelectionTouched();
}
myAdditionalPrefix = myAdditionalPrefix.substring(0, len - 1);
myInitialPrefix = null;
myFrozenItems.clear();
if (!myReused) {
refreshUi(false);
ensureSelectionVisible();
}
return true;
}
private void updateList() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
checkValid();
final Pair<List<LookupElement>,Iterable<List<LookupElement>>> snapshot = myModel.getModelSnapshot();
final LinkedHashSet<LookupElement> items = matchingItems(snapshot);
checkMinPrefixLengthChanges(items);
boolean hasPreselected = !mySelectionTouched && items.contains(myPreselectedItem);
LookupElement oldSelected = mySelectionTouched ? (LookupElement)myList.getSelectedValue() : null;
String oldInvariant = mySelectionInvariant;
LinkedHashSet<LookupElement> model = new LinkedHashSet<LookupElement>();
model.addAll(getPrefixItems(items, true));
model.addAll(getPrefixItems(items, false));
myFrozenItems.retainAll(items);
model.addAll(myFrozenItems);
if (!isAlphaSorted()) {
addMostRelevantItems(model, snapshot.second);
if (hasPreselected) {
model.add(myPreselectedItem);
}
}
myPreferredItemsCount = model.size();
myFrozenItems.clear();
if (myShown) {
myFrozenItems.addAll(model);
}
if (isAlphaSorted()) {
model.addAll(items);
} else if (limitRelevance()) {
model.addAll(addRemainingItemsLexicographically(model, items));
} else {
for (List<LookupElement> group : snapshot.second) {
for (LookupElement element : group) {
if (prefixMatches(element)) {
model.add(element);
}
}
}
}
DefaultListModel listModel = (DefaultListModel)myList.getModel();
synchronized (myList) {
listModel.clear();
if (!model.isEmpty()) {
for (LookupElement element : model) {
listModel.addElement(element);
}
}
else {
addEmptyItem(listModel);
}
}
updateListHeight(listModel);
if (!model.isEmpty()) {
myList.setFixedCellWidth(Math.max(myLookupTextWidth + myCellRenderer.getIconIndent(), myAdComponent.getAdComponent().getPreferredSize().width));
LookupElement first = model.iterator().next();
if (isFocused() && (!(isExactPrefixItem(first, true) || isExactPrefixItem(first, false)) || mySelectionTouched)) {
restoreSelection(oldSelected, hasPreselected, oldInvariant, snapshot.second);
}
else {
myList.setSelectedIndex(0);
}
}
}
private boolean isSelectionVisible() {
return myList.getFirstVisibleIndex() <= myList.getSelectedIndex() && myList.getSelectedIndex() <= myList.getLastVisibleIndex();
}
private LinkedHashSet<LookupElement> matchingItems(Pair<List<LookupElement>, Iterable<List<LookupElement>>> snapshot) {
final LinkedHashSet<LookupElement> items = new LinkedHashSet<LookupElement>();
for (LookupElement element : snapshot.first) {
if (prefixMatches(element)) {
items.add(element);
}
}
return items;
}
private boolean checkReused() {
if (myReused) {
myAdditionalPrefix = "";
myFrozenItems.clear();
myModel.collectGarbage();
myReused = false;
return true;
}
return false;
}
private void checkMinPrefixLengthChanges(Collection<LookupElement> items) {
if (myStableStart) return;
if (!myCalculating && !items.isEmpty()) {
myStableStart = true;
}
int minPrefixLength = items.isEmpty() ? 0 : Integer.MAX_VALUE;
for (final LookupElement item : items) {
minPrefixLength = Math.min(itemMatcher(item).getPrefix().length(), minPrefixLength);
}
updateLookupStart(minPrefixLength);
}
private void restoreSelection(@Nullable LookupElement oldSelected, boolean choosePreselectedItem, @Nullable String oldInvariant, Iterable<List<LookupElement>> groups) {
if (oldSelected != null) {
if (oldSelected.isValid()) {
myList.setSelectedValue(oldSelected, false);
if (myList.getSelectedValue() == oldSelected) {
return;
}
}
if (oldInvariant != null) {
for (LookupElement element : getItems()) {
if (oldInvariant.equals(myModel.getItemPresentationInvariant(element))) {
myList.setSelectedValue(element, false);
if (myList.getSelectedValue() == element) {
return;
}
}
}
}
}
if (choosePreselectedItem) {
myList.setSelectedValue(myPreselectedItem, false);
} else {
myList.setSelectedIndex(doSelectMostPreferableItem(getItems(), groups));
}
if (myPreselectedItem != null && myShown) {
myPreselectedItem = getCurrentItem();
}
}
private void updateListHeight(ListModel model) {
myList.setFixedCellHeight(myCellRenderer.getListCellRendererComponent(myList, model.getElementAt(0), 0, false, false).getPreferredSize().height);
myList.setVisibleRowCount(Math.min(model.getSize(), LOOKUP_HEIGHT));
}
private void addEmptyItem(DefaultListModel model) {
LookupItem<String> item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions"));
myMatchers.put(item, new CamelHumpMatcher(""));
if (!myCalculating) {
myList.setFixedCellWidth(Math.max(myCellRenderer.updateMaximumWidth(renderItemApproximately(item)), myLookupTextWidth));
}
model.addElement(item);
}
private static LookupElementPresentation renderItemApproximately(LookupElement item) {
final LookupElementPresentation p = new LookupElementPresentation();
item.renderElement(p);
return p;
}
private static List<LookupElement> addRemainingItemsLexicographically(Set<LookupElement> firstItems, Collection<LookupElement> allItems) {
List<LookupElement> model = new ArrayList<LookupElement>();
for (LookupElement item : allItems) {
if (!firstItems.contains(item)) {
model.add(item);
}
}
return model;
}
private void addMostRelevantItems(final Set<LookupElement> model, final Iterable<List<LookupElement>> sortedItems) {
if (model.size() > MAX_PREFERRED_COUNT) return;
for (final List<LookupElement> elements : sortedItems) {
final List<LookupElement> suitable = new SmartList<LookupElement>();
for (final LookupElement item : elements) {
if (!model.contains(item) && prefixMatches(item)) {
suitable.add(item);
}
}
if (model.size() + suitable.size() > MAX_PREFERRED_COUNT) break;
model.addAll(suitable);
}
}
public static boolean limitRelevance() {
return ApplicationManager.getApplication().isUnitTestMode() || Registry.is("limited.relevance.sorting.in.completion");
}
public boolean isFrozen(@NotNull LookupElement element) {
return myFrozenItems.contains(element);
}
private List<LookupElement> getPrefixItems(final Collection<LookupElement> elements, final boolean caseSensitive) {
List<LookupElement> better = new ArrayList<LookupElement>();
for (LookupElement element : elements) {
if (isExactPrefixItem(element, caseSensitive)) {
better.add(element);
}
}
final LookupArranger arranger = getActualArranger();
final Comparator<LookupElement> itemComparator = arranger.getItemComparator();
if (itemComparator != null) {
Collections.sort(better, itemComparator);
}
return myModel.classifyByRelevance(better);
}
@NotNull
@Override
public String itemPattern(LookupElement element) {
return itemMatcher(element).getPrefix() + myAdditionalPrefix;
}
private LookupArranger getActualArranger() {
return myCustomArranger;
}
private boolean isAlphaSorted() {
return isCompletion() && UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
}
private boolean isExactPrefixItem(LookupElement item, final boolean caseSensitive) {
final String pattern = itemPattern(item);
final Set<String> strings = item.getAllLookupStrings();
if (strings.contains(pattern)) {
return caseSensitive; //to not add the same elements twice to the model, as sensitive and then as insensitive
}
if (caseSensitive) {
return false;
}
for (String s : strings) {
if (s.equalsIgnoreCase(pattern)) {
return true;
}
}
return false;
}
private boolean prefixMatches(final LookupElement item) {
PrefixMatcher matcher = itemMatcher(item);
if (myAdditionalPrefix.length() > 0) {
matcher = matcher.cloneWithPrefix(itemPattern(item));
}
return matcher.prefixMatches(item);
}
@Override
@NotNull
public PrefixMatcher itemMatcher(LookupElement item) {
PrefixMatcher matcher = myMatchers.get(item);
if (matcher == null) {
throw new AssertionError("Item not in lookup: item=" + item + "; lookup items=" + getItems());
}
return matcher;
}
/**
* @return point in layered pane coordinate system.
*/
private Point calculatePosition() {
Dimension dim = getComponent().getPreferredSize();
int lookupStart = getLookupStart();
if (lookupStart < 0 || lookupStart > myEditor.getDocument().getTextLength()) {
LOG.error(lookupStart + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" +
getPsiElement());
}
LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart);
Point location = myEditor.logicalPositionToXY(pos);
location.y += myEditor.getLineHeight();
location.x -= myCellRenderer.getIconIndent() + getComponent().getInsets().left;
SwingUtilities.convertPointToScreen(location, myEditor.getContentComponent());
final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(location);
if (!isPositionedAboveCaret()) {
int shiftLow = screenRectangle.height - (location.y + dim.height);
myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height;
}
if (isPositionedAboveCaret()) {
location.y -= dim.height + myEditor.getLineHeight();
if (pos.line == 0) {
location.y += 1;
//otherwise the lookup won't intersect with the editor and every editor's resize (e.g. after typing in console) will close the lookup
}
}
if (!screenRectangle.contains(location)) {
location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
}
final JRootPane rootPane = myEditor.getComponent().getRootPane();
if (rootPane == null) {
LOG.error(myEditor.isDisposed() + "; shown=" + myShown + "; disposed=" + myDisposed + "; editorShowing=" + myEditor.getContentComponent().isShowing());
}
SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
return location;
}
public void finishLookup(final char completionChar) {
finishLookup(completionChar, (LookupElement)myList.getSelectedValue());
}
public void finishLookup(char completionChar, @Nullable final LookupElement item) {
doHide(false, true);
if (item == null ||
item instanceof EmptyLookupItem ||
item.getObject() instanceof DeferredUserLookupValue &&
item.as(LookupItem.CLASS_CONDITION_KEY) != null &&
!((DeferredUserLookupValue)item.getObject()).handleUserSelection(item.as(LookupItem.CLASS_CONDITION_KEY), myProject)) {
fireItemSelected(null, completionChar);
return;
}
final PsiFile file = getPsiFile();
if (file != null && !WriteCommandAction.ensureFilesWritable(myProject, Arrays.asList(file))) {
fireItemSelected(null, completionChar);
return;
}
final String prefix = itemPattern(item);
boolean plainMatch = ContainerUtil.or(item.getAllLookupStrings(), new Condition<String>() {
@Override
public boolean value(String s) {
return StringUtil.startsWithIgnoreCase(s, prefix);
}
});
if (!plainMatch) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CAMEL_HUMPS);
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
insertLookupString(item, prefix);
}
});
fireItemSelected(item, completionChar);
}
private void insertLookupString(LookupElement item, final String prefix) {
PrefixMatcher matcher = itemMatcher(item);
String lookupString = item.getLookupString();
if (!item.isCaseSensitive() && matcher.prefixMatches(item) && StringUtil.startsWithIgnoreCase(lookupString, prefix)) {
lookupString = handleCaseInsensitiveVariant(prefix, lookupString);
}
EditorModificationUtil.deleteSelectedText(myEditor);
final int caretOffset = myEditor.getCaretModel().getOffset();
int lookupStart = caretOffset - prefix.length();
int len = myEditor.getDocument().getTextLength();
LOG.assertTrue(lookupStart >= 0 && lookupStart <= len, "ls: " + lookupStart + " caret: " + caretOffset + " prefix:" + prefix + " doc: " + len);
LOG.assertTrue(caretOffset >= 0 && caretOffset <= len, "co: " + caretOffset + " doc: " + len);
myEditor.getDocument().replaceString(lookupStart, caretOffset, lookupString);
int offset = lookupStart + lookupString.length();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
}
private static String handleCaseInsensitiveVariant(final String prefix, @NotNull final String lookupString) {
final int length = prefix.length();
if (length == 0) return lookupString;
boolean isAllLower = true;
boolean isAllUpper = true;
boolean sameCase = true;
for (int i = 0; i < length && (isAllLower || isAllUpper || sameCase); i++) {
final char c = prefix.charAt(i);
isAllLower = isAllLower && Character.isLowerCase(c);
isAllUpper = isAllUpper && Character.isUpperCase(c);
sameCase = sameCase && Character.isLowerCase(c) == Character.isLowerCase(lookupString.charAt(i));
}
if (sameCase) return lookupString;
if (isAllLower) return lookupString.toLowerCase();
if (isAllUpper) return lookupString.toUpperCase();
return lookupString;
}
public int getLookupStart() {
LOG.assertTrue(myLookupStartMarker.isValid());
return myLookupStartMarker.getStartOffset();
}
public void performGuardedChange(Runnable change) {
checkValid();
assert myLookupStartMarker.isValid();
assert !myChangeGuard;
myChangeGuard = true;
RangeMarkerEx marker = (RangeMarkerEx) myEditor.getDocument().createRangeMarker(myLookupStartMarker.getStartOffset(), myLookupStartMarker.getEndOffset());
marker.trackInvalidation(true);
try {
change.run();
}
finally {
marker.trackInvalidation(false);
myChangeGuard = false;
}
checkValid();
LOG.assertTrue(myLookupStartMarker.isValid(), "invalid lookup start");
LOG.assertTrue(marker.isValid(), "invalid marker");
marker.dispose();
if (isVisible()) {
updateLookupBounds();
}
checkValid();
}
@Override
public boolean vetoesHiding() {
return myChangeGuard || myDisposed;
}
public boolean isShown() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
return myShown;
}
public boolean showLookup() {
ApplicationManager.getApplication().assertIsDispatchThread();
checkValid();
LOG.assertTrue(!myShown);
myShown = true;
myStampShown = System.currentTimeMillis();
if (ApplicationManager.getApplication().isUnitTestMode()) return true;
myAdComponent.showRandomText();
getComponent().setBorder(null);
updateScrollbarVisibility();
Point p = calculatePosition();
HintManagerImpl.getInstanceImpl().showEditorHint(this, myEditor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false,
HintManagerImpl.createHintHint(myEditor, p, this, HintManager.UNDER).setAwtTooltip(false));
if (!isVisible()) return false;
LOG.assertTrue(myList.isShowing(), "!showing, disposed=" + myDisposed);
return true;
}
public boolean mayBeNoticed() {
return myStampShown > 0 && System.currentTimeMillis() - myStampShown > 300;
}
private void addListeners() {
myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
if (!myChangeGuard) {
hide();
}
}
}, this);
final CaretListener caretListener = new CaretListener() {
public void caretPositionChanged(CaretEvent e) {
if (!myChangeGuard) {
hide();
}
}
};
final SelectionListener selectionListener = new SelectionListener() {
public void selectionChanged(final SelectionEvent e) {
if (!myChangeGuard) {
hide();
}
}
};
final EditorMouseListener mouseListener = new EditorMouseAdapter() {
public void mouseClicked(EditorMouseEvent e){
e.consume();
hide();
}
};
myEditor.getCaretModel().addCaretListener(caretListener);
myEditor.getSelectionModel().addSelectionListener(selectionListener);
myEditor.addEditorMouseListener(mouseListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myEditor.getCaretModel().removeCaretListener(caretListener);
myEditor.getSelectionModel().removeSelectionListener(selectionListener);
myEditor.removeEditorMouseListener(mouseListener);
}
});
myList.addListSelectionListener(new ListSelectionListener() {
private LookupElement oldItem = null;
public void valueChanged(ListSelectionEvent e){
myHintAlarm.cancelAllRequests();
final LookupElement item = getCurrentItem();
if (oldItem != item) {
mySelectionInvariant = item == null ? null : myModel.getItemPresentationInvariant(item);
fireCurrentItemChanged(item);
}
if (item != null) {
updateHint(item);
}
oldItem = item;
}
});
myList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
setFocused(true);
markSelectionTouched();
if (e.getClickCount() == 2){
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
finishLookup(NORMAL_SELECT_CHAR);
}
}, "", null);
}
}
});
}
private void updateHint(@NotNull final LookupElement item) {
checkValid();
if (myElementHint != null) {
myLayeredPane.remove(myElementHint);
myElementHint = null;
final JRootPane rootPane = getComponent().getRootPane();
if (rootPane != null) {
rootPane.revalidate();
rootPane.repaint();
}
}
if (!isFocused()) {
return;
}
final Collection<LookupElementAction> actions = getActionsFor(item);
if (!actions.isEmpty()) {
myHintAlarm.addRequest(new Runnable() {
@Override
public void run() {
assert !myDisposed;
myElementHint = new LookupHint();
myLayeredPane.add(myElementHint, 20, 0);
myLayeredPane.layoutHint();
}
}, 500);
}
}
private int updateLookupStart(int myMinPrefixLength) {
int offset = myEditor.getSelectionModel().hasSelection()
? myEditor.getSelectionModel().getSelectionStart()
: myEditor.getCaretModel().getOffset();
int start = Math.max(offset - myMinPrefixLength - myAdditionalPrefix.length(), 0);
if (myLookupStartMarker != null) {
if (myLookupStartMarker.isValid() && myLookupStartMarker.getStartOffset() == start && myLookupStartMarker.getEndOffset() == start) {
return start;
}
myLookupStartMarker.dispose();
}
myLookupStartMarker = myEditor.getDocument().createRangeMarker(start, start);
myLookupStartMarker.setGreedyToLeft(true);
return start;
}
@Nullable
public LookupElement getCurrentItem(){
LookupElement item = (LookupElement)myList.getSelectedValue();
return item instanceof EmptyLookupItem ? null : item;
}
public void setCurrentItem(LookupElement item){
markSelectionTouched();
myList.setSelectedValue(item, false);
}
public void addLookupListener(LookupListener listener){
myListeners.add(listener);
}
public void removeLookupListener(LookupListener listener){
myListeners.remove(listener);
}
public Rectangle getCurrentItemBounds(){
int index = myList.getSelectedIndex();
if (index < 0) {
LOG.error("No selected element, size=" + myList.getModel().getSize() + "; items" + getItems());
}
Rectangle itmBounds = myList.getCellBounds(index, index);
if (itmBounds == null){
LOG.error("No bounds for " + index + "; size=" + myList.getModel().getSize());
return null;
}
Point layeredPanePoint=SwingUtilities.convertPoint(myList,itmBounds.x,itmBounds.y,getComponent());
itmBounds.x = layeredPanePoint.x;
itmBounds.y = layeredPanePoint.y;
return itmBounds;
}
public void fireItemSelected(@Nullable final LookupElement item, char completionChar){
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
if (item != null) {
getActualArranger().itemSelected(item, this);
}
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item, completionChar);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
try {
listener.itemSelected(event);
}
catch (Throwable e) {
LOG.error(e);
}
}
}
}
private void fireLookupCanceled(final boolean explicitly) {
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, explicitly);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
try {
listener.lookupCanceled(event);
}
catch (Throwable e) {
LOG.error(e);
}
}
}
}
private void fireCurrentItemChanged(LookupElement item){
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item, (char)0);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
listener.currentItemChanged(event);
}
}
}
public boolean fillInCommonPrefix(boolean explicitlyInvoked) {
if (explicitlyInvoked) {
setFocused(true);
}
if (explicitlyInvoked && myCalculating) return false;
if (!explicitlyInvoked && mySelectionTouched) return false;
ListModel listModel = myList.getModel();
if (listModel.getSize() <= 1) return false;
if (listModel.getSize() == 0) return false;
final LookupElement firstItem = (LookupElement)listModel.getElementAt(0);
if (listModel.getSize() == 1 && firstItem instanceof EmptyLookupItem) return false;
final PrefixMatcher firstItemMatcher = itemMatcher(firstItem);
final String oldPrefix = firstItemMatcher.getPrefix();
final String presentPrefix = oldPrefix + myAdditionalPrefix;
String commonPrefix = firstItem.getLookupString();
for (int i = 1; i < listModel.getSize(); i++) {
LookupElement item = (LookupElement)listModel.getElementAt(i);
if (!oldPrefix.equals(itemMatcher(item).getPrefix())) return false;
final String lookupString = item.getLookupString();
final int length = Math.min(commonPrefix.length(), lookupString.length());
if (length < commonPrefix.length()) {
commonPrefix = commonPrefix.substring(0, length);
}
for (int j = 0; j < length; j++) {
if (commonPrefix.charAt(j) != lookupString.charAt(j)) {
commonPrefix = lookupString.substring(0, j);
break;
}
}
if (commonPrefix.length() == 0 || commonPrefix.length() < presentPrefix.length()) {
return false;
}
}
if (commonPrefix.equals(presentPrefix)) {
return false;
}
for (int i = 0; i < listModel.getSize(); i++) {
LookupElement item = (LookupElement)listModel.getElementAt(i);
if (!itemMatcher(item).cloneWithPrefix(commonPrefix).prefixMatches(item)) {
return false;
}
}
if (myAdditionalPrefix.length() == 0 && myInitialPrefix == null && !explicitlyInvoked) {
myInitialPrefix = presentPrefix;
}
else {
myInitialPrefix = null;
}
replacePrefix(presentPrefix, commonPrefix);
return true;
}
public void replacePrefix(final String presentPrefix, final String newPrefix) {
performGuardedChange(new Runnable() {
public void run() {
EditorModificationUtil.deleteSelectedText(myEditor);
int offset = myEditor.getCaretModel().getOffset();
final int start = offset - presentPrefix.length();
myEditor.getDocument().replaceString(start, offset, newPrefix);
Map<LookupElement, PrefixMatcher> newItems = myModel.retainMatchingItems(newPrefix, LookupImpl.this);
myMatchers.clear();
myMatchers.putAll(newItems);
myAdditionalPrefix = "";
myEditor.getCaretModel().moveToOffset(start + newPrefix.length());
}
});
refreshUi(true);
}
@Nullable
public PsiFile getPsiFile() {
return PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
}
public boolean isCompletion() {
return myCustomArranger instanceof CompletionLookupArranger;
}
public PsiElement getPsiElement() {
PsiFile file = getPsiFile();
if (file == null) return null;
int offset = getLookupStart();
if (offset > 0) return file.findElementAt(offset - 1);
return file.findElementAt(0);
}
public Editor getEditor() {
return myEditor;
}
@TestOnly
public void setPositionedAbove(boolean positionedAbove) {
myPositionedAbove = positionedAbove;
}
public boolean isPositionedAboveCaret(){
return myPositionedAbove != null && myPositionedAbove.booleanValue();
}
public boolean isSelectionTouched() {
return mySelectionTouched;
}
public void hide(){
hideLookup(true);
}
public void hideLookup(boolean explicitly) {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myDisposed) return;
doHide(true, explicitly);
}
private void doHide(final boolean fireCanceled, final boolean explicitly) {
if (myChangeGuard) {
LOG.error("Disposing under a change guard");
}
if (myDisposed) {
LOG.error(disposeTrace);
}
else {
myHidden = true;
try {
super.hide();
Disposer.dispose(this);
assert myDisposed;
}
catch (Throwable e) {
LOG.error(e);
}
}
if (fireCanceled) {
fireLookupCanceled(explicitly);
}
}
public void restorePrefix() {
if (myInitialPrefix != null) {
myEditor.getDocument().replaceString(getLookupStart(), myEditor.getCaretModel().getOffset(), myInitialPrefix);
}
}
private static String staticDisposeTrace = null;
private String disposeTrace = null;
public static String getLastLookupDisposeTrace() {
return staticDisposeTrace;
}
public void dispose() {
assert ApplicationManager.getApplication().isDispatchThread();
assert myHidden;
if (myDisposed) {
LOG.error(disposeTrace);
return;
}
Disposer.dispose(myProcessIcon);
Disposer.dispose(myHintAlarm);
myDisposed = true;
disposeTrace = DebugUtil.currentStackTrace();
//noinspection AssignmentToStaticFieldFromInstanceMethod
staticDisposeTrace = disposeTrace;
}
private int doSelectMostPreferableItem(List<LookupElement> items, Iterable<List<LookupElement>> groups) {
if (items.isEmpty()) {
return -1;
}
if (items.size() == 1) {
return 0;
}
for (int i = 0; i < items.size(); i++) {
LookupElement item = items.get(i);
if (isExactPrefixItem(item, true)) {
return i;
}
}
final int index = getActualArranger().suggestPreselectedItem(items, groups);
assert index >= 0 && index < items.size();
return index;
}
public void refreshUi(boolean mayCheckReused) {
final boolean reused = mayCheckReused && checkReused();
boolean selectionVisible = isSelectionVisible();
updateList();
if (isVisible()) {
LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode());
if (myEditor.getComponent().getRootPane() == null) {
LOG.error("Null root pane");
}
updateScrollbarVisibility();
updateLookupBounds();
if (reused || selectionVisible) {
ensureSelectionVisible();
}
}
}
private void updateLookupBounds() {
HintManagerImpl.adjustEditorHintPosition(this, myEditor, calculatePosition());
}
private void updateScrollbarVisibility() {
boolean showSorting = isCompletion() && getList().getModel().getSize() >= 3;
mySortingLabel.setVisible(showSorting);
myScrollPane.setVerticalScrollBarPolicy(showSorting ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
}
@TestOnly
public LookupArranger getArranger() {
return getActualArranger();
}
public void markReused() {
myReused = true;
myModel.clearItems();
myAdComponent.clearAdvertisements();
myPreselectedItem = null;
}
public void addAdvertisement(@NotNull String text) {
myAdComponent.addAdvertisement(text);
}
public boolean isLookupDisposed() {
return myDisposed;
}
public void checkValid() {
if (myDisposed) {
throw new AssertionError("Disposed at: " + disposeTrace);
}
}
@Override
public void showItemPopup(JBPopup hint) {
final Rectangle bounds = getCurrentItemBounds();
hint.show(new RelativePoint(getComponent(), new Point(bounds.x + bounds.width, bounds.y)));
}
@Override
public boolean showElementActions() {
if (!isVisible()) return false;
final LookupElement element = getCurrentItem();
if (element == null) {
return false;
}
final Collection<LookupElementAction> actions = getActionsFor(element);
if (actions.isEmpty()) {
return false;
}
showItemPopup(JBPopupFactory.getInstance().createListPopup(new LookupActionsStep(actions, this, element)));
return true;
}
private class LookupLayeredPane extends JLayeredPane {
final JPanel mainPanel = new JPanel(new BorderLayout());
private LookupLayeredPane() {
add(mainPanel, 0, 0);
add(myIconPanel, 42, 0);
add(mySortingLabel, 10, 0);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
mainPanel.setSize(getSize());
layoutStatusIcons();
layoutHint();
revalidate();
repaint();
}
});
}
private void layoutStatusIcons() {
final Dimension iconSize = myProcessIcon.getPreferredSize();
myIconPanel.setBounds(getWidth() - iconSize.width, 0, iconSize.width, iconSize.height);
final Dimension sortSize = mySortingLabel.getPreferredSize();
final Point sbLocation = SwingUtilities.convertPoint(myScrollPane.getVerticalScrollBar(), 0, 0, myLayeredPane);
int adHeight = myAdComponent.getAdComponent().getPreferredSize().height;
final int sortHeight = Math.max(adHeight, mySortingLabel.getPreferredSize().height);
mySortingLabel.setBounds(sbLocation.x, getHeight() - sortHeight, sortSize.width, sortHeight);
Dimension buttonSize = adHeight > 0 ? new Dimension(0, 0) : new Dimension(relevanceSortIcon.getIconWidth(), relevanceSortIcon.getIconHeight());
myScrollBarIncreaseButton.setPreferredSize(buttonSize);
myScrollBarIncreaseButton.setMinimumSize(buttonSize);
myScrollBarIncreaseButton.setMaximumSize(buttonSize);
myScrollPane.getVerticalScrollBar().revalidate();
myScrollPane.getVerticalScrollBar().repaint();
}
void layoutHint() {
if (myElementHint != null) {
final Rectangle bounds = getCurrentItemBounds();
myElementHint.setSize(myElementHint.getPreferredSize());
myElementHint.setLocation(new Point(bounds.x + bounds.width - myElementHint.getWidth(), bounds.y));
}
}
@Override
public Dimension getPreferredSize() {
return mainPanel.getPreferredSize();
}
}
private class LookupHint extends JLabel {
private final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(4, 4, 4, 4);
private final Border ACTIVE_BORDER = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK, 1), BorderFactory.createEmptyBorder(3, 3, 3, 3));
private LookupHint() {
setOpaque(false);
setBorder(INACTIVE_BORDER);
setIcon(IconLoader.findIcon("/actions/intentionBulb.png"));
String acceleratorsText = KeymapUtil.getFirstKeyboardShortcutText(
ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS));
if (acceleratorsText.length() > 0) {
setToolTipText(CodeInsightBundle.message("lightbulb.tooltip", acceleratorsText));
}
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
setBorder(ACTIVE_BORDER);
}
@Override
public void mouseExited(MouseEvent e) {
setBorder(INACTIVE_BORDER);
}
@Override
public void mousePressed(MouseEvent e) {
if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
showElementActions();
}
}
});
}
}
public LinkedHashMap<LookupElement,StringBuilder> getRelevanceStrings() {
return myModel.getRelevanceStrings();
}
}
|
resizeable lookup (IDEA-74401)
|
platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
|
resizeable lookup (IDEA-74401)
|
|
Java
|
apache-2.0
|
66b516116d9388ec60ae8b9cf871ef7c581a3c23
| 0
|
SylvesterAbreu/sling,anchela/sling,awadheshv/sling,trekawek/sling,nleite/sling,nleite/sling,mmanski/sling,mcdan/sling,SylvesterAbreu/sling,sdmcraft/sling,Nimco/sling,JEBailey/sling,ist-dresden/sling,sdmcraft/sling,mikibrv/sling,mmanski/sling,sdmcraft/sling,Nimco/sling,awadheshv/sling,mcdan/sling,headwirecom/sling,sdmcraft/sling,wimsymons/sling,cleliameneghin/sling,awadheshv/sling,tmaret/sling,ffromm/sling,JEBailey/sling,roele/sling,Sivaramvt/sling,mmanski/sling,tteofili/sling,ieb/sling,headwirecom/sling,awadheshv/sling,dulvac/sling,cleliameneghin/sling,ffromm/sling,dulvac/sling,ffromm/sling,gutsy/sling,klcodanr/sling,ffromm/sling,wimsymons/sling,codders/k2-sling-fork,roele/sling,tteofili/sling,roele/sling,mcdan/sling,labertasch/sling,nleite/sling,gutsy/sling,cleliameneghin/sling,labertasch/sling,tmaret/sling,tyge68/sling,tyge68/sling,cleliameneghin/sling,anchela/sling,tteofili/sling,trekawek/sling,gutsy/sling,roele/sling,SylvesterAbreu/sling,headwirecom/sling,ffromm/sling,tteofili/sling,gutsy/sling,anchela/sling,ieb/sling,JEBailey/sling,sdmcraft/sling,Sivaramvt/sling,mmanski/sling,nleite/sling,klcodanr/sling,Nimco/sling,dulvac/sling,dulvac/sling,mcdan/sling,Nimco/sling,vladbailescu/sling,wimsymons/sling,Nimco/sling,ieb/sling,mikibrv/sling,vladbailescu/sling,vladbailescu/sling,ieb/sling,tmaret/sling,ist-dresden/sling,nleite/sling,ieb/sling,codders/k2-sling-fork,mcdan/sling,plutext/sling,SylvesterAbreu/sling,ist-dresden/sling,mikibrv/sling,dulvac/sling,ist-dresden/sling,anchela/sling,Sivaramvt/sling,mikibrv/sling,JEBailey/sling,cleliameneghin/sling,gutsy/sling,wimsymons/sling,tmaret/sling,awadheshv/sling,tyge68/sling,tyge68/sling,klcodanr/sling,ffromm/sling,tteofili/sling,sdmcraft/sling,anchela/sling,mmanski/sling,plutext/sling,Sivaramvt/sling,klcodanr/sling,trekawek/sling,ieb/sling,labertasch/sling,klcodanr/sling,plutext/sling,Sivaramvt/sling,headwirecom/sling,Sivaramvt/sling,trekawek/sling,trekawek/sling,mikibrv/sling,ist-dresden/sling,tyge68/sling,vladbailescu/sling,mmanski/sling,labertasch/sling,labertasch/sling,SylvesterAbreu/sling,Nimco/sling,tyge68/sling,plutext/sling,wimsymons/sling,nleite/sling,tmaret/sling,trekawek/sling,JEBailey/sling,headwirecom/sling,dulvac/sling,gutsy/sling,tteofili/sling,awadheshv/sling,plutext/sling,codders/k2-sling-fork,klcodanr/sling,plutext/sling,SylvesterAbreu/sling,mikibrv/sling,roele/sling,wimsymons/sling,mcdan/sling,vladbailescu/sling
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.api;
/**
* The <code>SlingConstants</code> interface provides some symbolic constants
* for well known constant strings in Sling. Even though these constants will
* never change, it is recommended that applications refer to the symbolic
* constants instead of code the strings themselves.
*/
public class SlingConstants {
/**
* The namespace prefix used throughout Sling (value is "sling").
* <p>
* The actual use depends on the environment. For example a
* {@link org.apache.sling.api.resource.ResourceResolver} using a JCR
* repository may name Sling node types and items using namespaces mapped to
* this prefix. A JSP tag library for Sling may use this prefix as the
* namespace prefix for its tags.
*/
public static final String NAMESPACE_PREFIX = "sling";
/**
* The namespace URI prefix to be used by Sling projects to define
* namespaces (value is "http://sling.apache.org/").
* <p>
* The actual namespace URI depends on the environment. For example a
* {@link org.apache.sling.api.resource.ResourceResolver} using a JCR
* repository may define its namespace as
* <code><em>NAMESPACE_URI_ROOT + "jcr/sling/1.0"</em></code>. A JSP tag library for
* Sling may define its namespace as
* <code><em>NAMESPACE_URI_ROOT + "taglib/sling/1.0"</em></code>.
*/
public static final String NAMESPACE_URI_ROOT = "http://sling.apache.org/";
/**
* The name of the request attribute containing the <code>Servlet</code>
* which included the servlet currently being active (value is
* "org.apache.sling.api.include.servlet"). This attribute is
* <code>null</code> if the current servlet is the servlet handling the
* client request.
* <p>
* The type of the attribute value is <code>javax.servlet.Servlet</code>.
*/
public static final String ATTR_REQUEST_SERVLET = "org.apache.sling.api.include.servlet";
/**
* The name of the request attribute containing the <code>Resource</code>
* underlying the <code>Servlet</code> which included the servlet
* currently being active (value is
* "org.apache.sling.api.include.resource"). This attribute is
* <code>null</code> if the current servlet is the servlet handling the
* client request.
* <p>
* The type of the attribute value is
* <code>org.apache.sling.api.resource.Resource</code>.
*/
public static final String ATTR_REQUEST_CONTENT = "org.apache.sling.api.include.resource";
// ---------- Error handling -----------------------------------------------
/**
* The name of the request attribute containing the exception thrown causing
* the error handler to be called (value is
* "javax.servlet.error.exception"). This attribute is only available to
* error handling servlets and only if an exception has been thrown causing
* error handling.
* <p>
* The type of the attribute value is <code>java.lang.Throwable</code>.
*/
public static final String ERROR_EXCEPTION = "javax.servlet.error.exception";
/**
* The name of the request attribute containing the fully qualified class
* name of the exception thrown causing the error handler to be called
* (value is "javax.servlet.error.exception_type"). This attribute is only
* available to error handling servlets and only if an exception has been
* thrown causing error handling. This attribute is present for backwards
* compatibility only. Error handling servlet implementors are advised to
* use the {@link #ERROR_EXCEPTION Throwable} itself.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type";
/**
* The name of the request attribute containing the message of the error
* situation (value is "javax.servlet.error.message"). If an exception
* caused error handling, this is the exceptions message from
* <code>Throwable.getMessage()</code>. If error handling is caused by a
* call to one of the <code>SlingHttpServletResponse.sendError</code>
* methods, this attribute contains the optional message.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_MESSAGE = "javax.servlet.error.message";
/**
* The name of the request attribute containing the URL requested by the
* client during whose processing the error handling was caused (value is
* "javax.servlet.error.request_uri"). This property is retrieved calling
* the <code>SlingHttpServletRequest.getRequestURI()</code> method.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_REQUEST_URI = "javax.servlet.error.request_uri";
/**
* The name of the request attribute containing the name of the servlet
* which caused the error handling (value is
* "javax.servlet.error.servlet_name").
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_SERVLET_NAME = "javax.servlet.error.servlet_name";
/**
* The name of the request attribute containing the status code sent to the
* client (value is "javax.servlet.error.status_code"). Error handling
* servlets may set this status code on their response to the client or they
* may choose to set another status code. For example a handler for
* NOT_FOUND status (404) may opt to redirect to a new location and thus not
* set the 404 status but a MOVED_PERMANENTLY (301) status. If this
* attribute is not set and the error handler is not configured to set its
* own status code anyway, a default value of INTERNAL_SERVER_ERROR (500)
* should be sent.
* <p>
* The type of the attribute value is <code>java.lang.Integer</code>.
*/
public static final String ERROR_STATUS = "javax.servlet.error.status_code";
}
|
api/src/main/java/org/apache/sling/api/SlingConstants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.api;
/**
* The <code>SlingConstants</code> interface provides some symbolic constants
* for well known constant strings in Sling. Even though these constants will
* never change, it is recommended that applications refer to the symbolic
* constants instead of code the strings themselves.
*/
public class SlingConstants {
/**
* The namespace prefix used throughout Sling (value is "sling").
* <p>
* The actual use depends on the environment. For example a
* {@link org.apache.sling.api.resource.ResourceResolver} using a JCR
* repository may name Sling node types and items using namespaces mapped to
* this prefix. A JSP tag library for Sling may use this prefix as the
* namespace prefix for its tags.
*/
public static final String NAMESPACE_PREFIX = "sling";
/**
* The namespace URI prefix to be used by Sling projects to define
* namespaces (value is "http://sling.apache.org/").
* <p>
* The actual namespace URI depends on the environment. For example a
* {@link org.apache.sling.api.resource.ResourceResolver} using a JCR
* repository may define its namespace as
* <code><em>NAMESPACE_URI_ROOT + "jcr/sling/1.0"</em></code>. A JSP tag library for
* Sling may define its namespace as
* <code><em>NAMESPACE_URI_ROOT + "taglib/sling/1.0"</em></code>.
*/
public static final String NAMESPACE_URI_ROOT = "http://sling.apache.org/";
/**
* The name of the request attribute containing the <code>Servlet</code>
* which included the servlet currently being active (value is
* "org.apache.sling.api.include.servlet"). This attribute is
* <code>null</code> if the current servlet is the servlet handling the
* client request.
* <p>
* The type of the attribute value is <code>javax.servlet.Servlet</code>.
*/
public static final String ATTR_REQUEST_SERVLET = "org.apache.sling.api.include.servlet";
/**
* The name of the request attribute containing the <code>Resource</code>
* underlying the <code>Servlet</code> which included the servlet
* currently being active (value is
* "org.apache.sling.api.include.resource"). This attribute is
* <code>null</code> if the current servlet is the servlet handling the
* client request.
* <p>
* The type of the attribute value is
* <code>org.apache.sling.api.resource.Resource</code>.
*/
public static final String ATTR_REQUEST_CONTENT = "org.apache.sling.api.include.resource";
/**
* The name of the request attribute containing request context path if
* Sling (the Sling Servlet actually) is called by the servlet containing as
* a result of a standard Servlet request include (value is
* "javax.servlet.include.context_path"). Sling never sets this attribute.
* <p>
* The type of the attribute value is <code>java.lang.String</code>. This
* attribute corresponds to the
* <code>HttpServletRequest.getContextPath()</code>.
*/
public static final String INCLUDE_CONTEXT_PATH = "javax.servlet.include.context_path";
/**
* The name of the request attribute containing request path info if Sling
* (the Sling Servlet actually) is called by the servlet containing as a
* result of a standard Servlet request include (value is
* "javax.servlet.include.path_info"). Sling never sets this attribute.
* <p>
* The type of the attribute value is <code>java.lang.String</code>. This
* attribute corresponds to the
* <code>HttpServletRequest.getPathInfo()</code>.
*/
public static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
/**
* The name of the request attribute containing request query string if
* Sling (the Sling Servlet actually) is called by the servlet containing as
* a result of a standard Servlet request include (value is
* "javax.servlet.include.query_string"). Sling never sets this attribute.
* <p>
* The type of the attribute value is <code>java.lang.String</code>. This
* attribute corresponds to the
* <code>HttpServletRequest.getQueryString()</code>.
*/
public static final String INCLUDE_QUERY_STRING = "javax.servlet.include.query_string";
/**
* The name of the request attribute containing request uri if Sling (the
* Sling Servlet actually) is called by the servlet containing as a result
* of a standard Servlet request include (value is
* "javax.servlet.include.request_uri"). Sling never sets this attribute.
* <p>
* The type of the attribute value is <code>java.lang.String</code>. This
* attribute corresponds to the
* <code>HttpServletRequest.getRequestURI()</code>.
*/
public static final String INCLUDE_REQUEST_URI = "javax.servlet.include.request_uri";
/**
* The name of the request attribute containing servlet path if Sling (the
* Sling Servlet actually) is called by the servlet containing as a result
* of a standard Servlet request include (value is
* "javax.servlet.include.servlet_path"). Sling never sets this attribute.
* <p>
* The type of the attribute value is <code>java.lang.String</code>. This
* attribute corresponds to the
* <code>HttpServletRequest.getServletPath()</code>.
*/
public static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
// ---------- Error handling -----------------------------------------------
/**
* The name of the request attribute containing the exception thrown causing
* the error handler to be called (value is
* "javax.servlet.error.exception"). This attribute is only available to
* error handling servlets and only if an exception has been thrown causing
* error handling.
* <p>
* The type of the attribute value is <code>java.lang.Throwable</code>.
*/
public static final String ERROR_EXCEPTION = "javax.servlet.error.exception";
/**
* The name of the request attribute containing the fully qualified class
* name of the exception thrown causing the error handler to be called
* (value is "javax.servlet.error.exception_type"). This attribute is only
* available to error handling servlets and only if an exception has been
* thrown causing error handling. This attribute is present for backwards
* compatibility only. Error handling servlet implementors are advised to
* use the {@link #ERROR_EXCEPTION Throwable} itself.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type";
/**
* The name of the request attribute containing the message of the error
* situation (value is "javax.servlet.error.message"). If an exception
* caused error handling, this is the exceptions message from
* <code>Throwable.getMessage()</code>. If error handling is caused by a
* call to one of the <code>SlingHttpServletResponse.sendError</code>
* methods, this attribute contains the optional message.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_MESSAGE = "javax.servlet.error.message";
/**
* The name of the request attribute containing the URL requested by the
* client during whose processing the error handling was caused (value is
* "javax.servlet.error.request_uri"). This property is retrieved calling
* the <code>SlingHttpServletRequest.getRequestURI()</code> method.
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_REQUEST_URI = "javax.servlet.error.request_uri";
/**
* The name of the request attribute containing the name of the servlet
* which caused the error handling (value is
* "javax.servlet.error.servlet_name").
* <p>
* The type of the attribute value is <code>java.lang.String</code>.
*/
public static final String ERROR_SERVLET_NAME = "javax.servlet.error.servlet_name";
/**
* The name of the request attribute containing the status code sent to the
* client (value is "javax.servlet.error.status_code"). Error handling
* servlets may set this status code on their response to the client or they
* may choose to set another status code. For example a handler for
* NOT_FOUND status (404) may opt to redirect to a new location and thus not
* set the 404 status but a MOVED_PERMANENTLY (301) status. If this
* attribute is not set and the error handler is not configured to set its
* own status code anyway, a default value of INTERNAL_SERVER_ERROR (500)
* should be sent.
* <p>
* The type of the attribute value is <code>java.lang.Integer</code>.
*/
public static final String ERROR_STATUS = "javax.servlet.error.status_code";
}
|
SLING-104 Remove INCLUDE_* constants from SlingConstants as they are defined in the SlingRequestPaths class.
git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@597491 13f79535-47bb-0310-9956-ffa450edef68
|
api/src/main/java/org/apache/sling/api/SlingConstants.java
|
SLING-104 Remove INCLUDE_* constants from SlingConstants as they are defined in the SlingRequestPaths class.
|
|
Java
|
apache-2.0
|
9732e04c60fcaf7f9869024f7676a81af6f25359
| 0
|
leventov/druid,pjain1/druid,pjain1/druid,implydata/druid,druid-io/druid,deltaprojects/druid,pjain1/druid,Fokko/druid,Fokko/druid,michaelschiff/druid,druid-io/druid,mghosh4/druid,knoguchi/druid,mghosh4/druid,leventov/druid,mghosh4/druid,nishantmonu51/druid,jon-wei/druid,Fokko/druid,michaelschiff/druid,nishantmonu51/druid,mghosh4/druid,implydata/druid,deltaprojects/druid,nishantmonu51/druid,Fokko/druid,mghosh4/druid,monetate/druid,monetate/druid,implydata/druid,pjain1/druid,himanshug/druid,jon-wei/druid,leventov/druid,monetate/druid,druid-io/druid,nishantmonu51/druid,himanshug/druid,mghosh4/druid,jon-wei/druid,knoguchi/druid,leventov/druid,druid-io/druid,gianm/druid,monetate/druid,pjain1/druid,nishantmonu51/druid,jon-wei/druid,himanshug/druid,knoguchi/druid,michaelschiff/druid,michaelschiff/druid,himanshug/druid,Fokko/druid,jon-wei/druid,deltaprojects/druid,deltaprojects/druid,gianm/druid,gianm/druid,deltaprojects/druid,michaelschiff/druid,implydata/druid,gianm/druid,pjain1/druid,michaelschiff/druid,deltaprojects/druid,monetate/druid,jon-wei/druid,knoguchi/druid,druid-io/druid,gianm/druid,monetate/druid,implydata/druid,monetate/druid,gianm/druid,mghosh4/druid,jon-wei/druid,gianm/druid,himanshug/druid,pjain1/druid,Fokko/druid,knoguchi/druid,michaelschiff/druid,leventov/druid,Fokko/druid,implydata/druid,deltaprojects/druid,nishantmonu51/druid,nishantmonu51/druid
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.indexer.updater;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Supplier;
import org.apache.druid.metadata.MetadataStorageConnectorConfig;
import org.apache.druid.metadata.MetadataStorageTablesConfig;
import org.apache.druid.metadata.PasswordProvider;
import javax.validation.constraints.NotNull;
/**
*/
public class MetadataStorageUpdaterJobSpec implements Supplier<MetadataStorageConnectorConfig>
{
@JsonProperty("type")
@NotNull
public String type;
@JsonProperty("connectURI")
public String connectURI;
@JsonProperty("user")
public String user;
@JsonProperty("password")
private PasswordProvider passwordProvider;
@JsonProperty("segmentTable")
public String segmentTable;
public String getSegmentTable()
{
return segmentTable;
}
public String getType()
{
return type;
}
@Override
public MetadataStorageConnectorConfig get()
{
return new MetadataStorageConnectorConfig()
{
@Override
public String getConnectURI()
{
return connectURI;
}
@Override
public String getUser()
{
return user;
}
@Override
public String getPassword()
{
return passwordProvider == null ? null : passwordProvider.getPassword();
}
};
}
//Note: Currently it only supports configured segmentTable, other tables should be added if needed
//by the code using this
public MetadataStorageTablesConfig getMetadataStorageTablesConfig()
{
return new MetadataStorageTablesConfig(
null,
null,
null,
segmentTable,
null,
null,
null,
null,
null,
null,
null
);
}
}
|
indexing-hadoop/src/main/java/org/apache/druid/indexer/updater/MetadataStorageUpdaterJobSpec.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.indexer.updater;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Supplier;
import org.apache.druid.metadata.MetadataStorageConnectorConfig;
import org.apache.druid.metadata.MetadataStorageTablesConfig;
import org.apache.druid.metadata.PasswordProvider;
import javax.validation.constraints.NotNull;
/**
*/
public class MetadataStorageUpdaterJobSpec implements Supplier<MetadataStorageConnectorConfig>
{
@JsonProperty("type")
@NotNull
public String type;
@JsonProperty("connectURI")
public String connectURI;
@JsonProperty("user")
public String user;
@JsonProperty("password")
private PasswordProvider passwordProvider;
@JsonProperty("segmentTable")
public String segmentTable;
public String getSegmentTable()
{
return segmentTable;
}
public String getType()
{
return type;
}
@Override
public MetadataStorageConnectorConfig get()
{
return new MetadataStorageConnectorConfig()
{
@Override
public String getConnectURI()
{
return connectURI;
}
@Override
public String getUser()
{
return user;
}
@Override
public String getPassword()
{
return passwordProvider == null ? null : passwordProvider.getPassword();
}
};
}
//Note: Currently it only supports configured segmentTable, other tables should be added if needed
//by the code using this
public MetadataStorageTablesConfig getMetadataStorageTablesConfig()
{
return new MetadataStorageTablesConfig(
null,
null,
segmentTable,
null,
null,
null,
null,
null,
null,
null,
null
);
}
}
|
Pass in segmentTable correctly (#7492)
|
indexing-hadoop/src/main/java/org/apache/druid/indexer/updater/MetadataStorageUpdaterJobSpec.java
|
Pass in segmentTable correctly (#7492)
|
|
Java
|
apache-2.0
|
56f6c4bb2ff93e3af4538d3f8011a89716f292e3
| 0
|
lato333/guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,glyptodon/guacamole-client,softpymesJeffer/incubator-guacamole-client,glyptodon/guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,lato333/guacamole-client,lato333/guacamole-client,necouchman/incubator-guacamole-client,necouchman/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,esmailpour-hosein/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,lato333/guacamole-client,necouchman/incubator-guacamole-client
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.guacamole.auth.jdbc.tunnel;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.guacamole.GuacamoleClientTooManyException;
import org.apache.guacamole.auth.jdbc.connection.ModeledConnection;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleResourceConflictException;
import org.apache.guacamole.auth.jdbc.JDBCEnvironment;
import org.apache.guacamole.auth.jdbc.connectiongroup.ModeledConnectionGroup;
import org.apache.guacamole.auth.jdbc.user.RemoteAuthenticatedUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GuacamoleTunnelService implementation which restricts concurrency for each
* connection and group according to a maximum number of connections and
* maximum number of connections per user.
*/
@Singleton
public class RestrictedGuacamoleTunnelService
extends AbstractGuacamoleTunnelService {
/**
* Logger for this class.
*/
private static final Logger logger = LoggerFactory.getLogger(RestrictedGuacamoleTunnelService.class);
/**
* The environment of the Guacamole server.
*/
@Inject
private JDBCEnvironment environment;
/**
* Set of all currently-active user/connection pairs (seats).
*/
private final ConcurrentHashMultiset<Seat> activeSeats = ConcurrentHashMultiset.<Seat>create();
/**
* Set of all currently-active connections.
*/
private final ConcurrentHashMultiset<String> activeConnections = ConcurrentHashMultiset.<String>create();
/**
* Set of all currently-active user/connection group pairs (seats).
*/
private final ConcurrentHashMultiset<Seat> activeGroupSeats = ConcurrentHashMultiset.<Seat>create();
/**
* Set of all currently-active connection groups.
*/
private final ConcurrentHashMultiset<String> activeGroups = ConcurrentHashMultiset.<String>create();
/**
* The total number of active connections within this instance of
* Guacamole.
*/
private final AtomicInteger totalActiveConnections = new AtomicInteger(0);
/**
* Attempts to add a single instance of the given value to the given
* multiset without exceeding the specified maximum number of values. If
* the value cannot be added without exceeding the maximum, false is
* returned.
*
* @param <T>
* The type of values contained within the multiset.
*
* @param multiset
* The multiset to attempt to add a value to.
*
* @param value
* The value to attempt to add.
*
* @param max
* The maximum number of each distinct value that the given multiset
* should hold, or zero if no limit applies.
*
* @return
* true if the value was successfully added without exceeding the
* specified maximum, false if the value could not be added.
*/
private <T> boolean tryAdd(ConcurrentHashMultiset<T> multiset, T value, int max) {
// Repeatedly attempt to add a new value to the given multiset until we
// explicitly succeed or explicitly fail
while (true) {
// Get current number of values
int count = multiset.count(value);
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to add one more value
if (multiset.setCount(value, count, count+1))
return true;
// Try again if unsuccessful
}
}
/**
* Attempts to increment the given AtomicInteger without exceeding the
* specified maximum value. If the AtomicInteger cannot be incremented
* without exceeding the maximum, false is returned.
*
* @param counter
* The AtomicInteger to attempt to increment.
*
* @param max
* The maximum value that the given AtomicInteger should contain, or
* zero if no limit applies.
*
* @return
* true if the AtomicInteger was successfully incremented without
* exceeding the specified maximum, false if the AtomicInteger could
* not be incremented.
*/
private boolean tryIncrement(AtomicInteger counter, int max) {
// Repeatedly attempt to increment the given AtomicInteger until we
// explicitly succeed or explicitly fail
while (true) {
// Get current value
int count = counter.get();
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to increment
if (counter.compareAndSet(count, count+1))
return true;
// Try again if unsuccessful
}
}
@Override
protected ModeledConnection acquire(RemoteAuthenticatedUser user,
List<ModeledConnection> connections) throws GuacamoleException {
// Do not acquire connection unless within overall limits
if (!tryIncrement(totalActiveConnections, environment.getAbsoluteMaxConnections()))
throw new GuacamoleResourceConflictException("Cannot connect. Overall maximum connections reached.");
// Get username
String username = user.getIdentifier();
// Sort connections in ascending order of usage
ModeledConnection[] sortedConnections = connections.toArray(new ModeledConnection[connections.size()]);
Arrays.sort(sortedConnections, new Comparator<ModeledConnection>() {
@Override
public int compare(ModeledConnection a, ModeledConnection b) {
int weightA, weightB;
// Check if weight of a is null, assign 1 if it is.
if (a.getConnectionWeight() == null)
weightA = 1;
// If weight is less than 1, host will be disabled
// but for sorting we set it to 1 to avoid divide
// by 0.
else if (a.getConnectionWeight().intValue() < 1)
weightA = 1;
else
weightA = a.getConnectionWeight().intValue() + 1;
// Check if weight of b is null, assign 1 if it is.
if (b.getConnectionWeight() == null)
weightB = 1;
// If weight is less than 1, host will be disabled,
// but for sorting we set it to 1 to avoid divide
// by 0.
else if (b.getConnectionWeight().intValue() < 1)
weightB = 1;
else
weightB = b.getConnectionWeight().intValue() + 1;
int connsA = getActiveConnections(a).size() + 1;
int connsB = getActiveConnections(b).size() + 1;
return (connsA * 10000 / weightA) - (connsB * 10000 / weightB);
}
});
// Track whether acquire fails due to user-specific limits
boolean userSpecificFailure = true;
// Return the first unreserved connection
for (ModeledConnection connection : sortedConnections) {
// If connection weight is zero or negative, this host is disabled and should not be used.
if (connection.getConnectionWeight() != null && connection.getConnectionWeight().intValue() < 1) {
logger.warn("Weight for {} is non-null and < 1, connection will be skipped.", connection.getName());
continue;
}
// Attempt to aquire connection according to per-user limits
Seat seat = new Seat(username, connection.getIdentifier());
if (tryAdd(activeSeats, seat,
connection.getMaxConnectionsPerUser())) {
// Attempt to aquire connection according to overall limits
if (tryAdd(activeConnections, connection.getIdentifier(),
connection.getMaxConnections()))
return connection;
// Acquire failed - retry with next connection
activeSeats.remove(seat);
// Failure to acquire is not user-specific
userSpecificFailure = false;
}
}
// Acquire failed
totalActiveConnections.decrementAndGet();
// Too many connections by this user
if (userSpecificFailure)
throw new GuacamoleClientTooManyException("Cannot connect. Connection already in use by this user.");
// Too many connections, but not necessarily due purely to this user
else
throw new GuacamoleResourceConflictException("Cannot connect. This connection is in use.");
}
@Override
protected void release(RemoteAuthenticatedUser user, ModeledConnection connection) {
activeSeats.remove(new Seat(user.getIdentifier(), connection.getIdentifier()));
activeConnections.remove(connection.getIdentifier());
totalActiveConnections.decrementAndGet();
}
@Override
protected void acquire(RemoteAuthenticatedUser user,
ModeledConnectionGroup connectionGroup) throws GuacamoleException {
// Get username
String username = user.getIdentifier();
// Attempt to aquire connection group according to per-user limits
Seat seat = new Seat(username, connectionGroup.getIdentifier());
if (tryAdd(activeGroupSeats, seat,
connectionGroup.getMaxConnectionsPerUser())) {
// Attempt to aquire connection group according to overall limits
if (tryAdd(activeGroups, connectionGroup.getIdentifier(),
connectionGroup.getMaxConnections()))
return;
// Acquire failed
activeGroupSeats.remove(seat);
// Failure to acquire is not user-specific
throw new GuacamoleResourceConflictException("Cannot connect. This connection group is in use.");
}
// Already in use by this user
throw new GuacamoleClientTooManyException("Cannot connect. Connection group already in use by this user.");
}
@Override
protected void release(RemoteAuthenticatedUser user,
ModeledConnectionGroup connectionGroup) {
activeGroupSeats.remove(new Seat(user.getIdentifier(), connectionGroup.getIdentifier()));
activeGroups.remove(connectionGroup.getIdentifier());
}
}
|
extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/RestrictedGuacamoleTunnelService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.guacamole.auth.jdbc.tunnel;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.guacamole.GuacamoleClientTooManyException;
import org.apache.guacamole.auth.jdbc.connection.ModeledConnection;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleResourceConflictException;
import org.apache.guacamole.auth.jdbc.JDBCEnvironment;
import org.apache.guacamole.auth.jdbc.connectiongroup.ModeledConnectionGroup;
import org.apache.guacamole.auth.jdbc.user.RemoteAuthenticatedUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GuacamoleTunnelService implementation which restricts concurrency for each
* connection and group according to a maximum number of connections and
* maximum number of connections per user.
*/
@Singleton
public class RestrictedGuacamoleTunnelService
extends AbstractGuacamoleTunnelService {
/**
* The environment of the Guacamole server.
*/
@Inject
private JDBCEnvironment environment;
/**
* Set of all currently-active user/connection pairs (seats).
*/
private final ConcurrentHashMultiset<Seat> activeSeats = ConcurrentHashMultiset.<Seat>create();
/**
* Set of all currently-active connections.
*/
private final ConcurrentHashMultiset<String> activeConnections = ConcurrentHashMultiset.<String>create();
/**
* Set of all currently-active user/connection group pairs (seats).
*/
private final ConcurrentHashMultiset<Seat> activeGroupSeats = ConcurrentHashMultiset.<Seat>create();
/**
* Set of all currently-active connection groups.
*/
private final ConcurrentHashMultiset<String> activeGroups = ConcurrentHashMultiset.<String>create();
/**
* The total number of active connections within this instance of
* Guacamole.
*/
private final AtomicInteger totalActiveConnections = new AtomicInteger(0);
/**
* Attempts to add a single instance of the given value to the given
* multiset without exceeding the specified maximum number of values. If
* the value cannot be added without exceeding the maximum, false is
* returned.
*
* @param <T>
* The type of values contained within the multiset.
*
* @param multiset
* The multiset to attempt to add a value to.
*
* @param value
* The value to attempt to add.
*
* @param max
* The maximum number of each distinct value that the given multiset
* should hold, or zero if no limit applies.
*
* @return
* true if the value was successfully added without exceeding the
* specified maximum, false if the value could not be added.
*/
private <T> boolean tryAdd(ConcurrentHashMultiset<T> multiset, T value, int max) {
// Repeatedly attempt to add a new value to the given multiset until we
// explicitly succeed or explicitly fail
while (true) {
// Get current number of values
int count = multiset.count(value);
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to add one more value
if (multiset.setCount(value, count, count+1))
return true;
// Try again if unsuccessful
}
}
/**
* Attempts to increment the given AtomicInteger without exceeding the
* specified maximum value. If the AtomicInteger cannot be incremented
* without exceeding the maximum, false is returned.
*
* @param counter
* The AtomicInteger to attempt to increment.
*
* @param max
* The maximum value that the given AtomicInteger should contain, or
* zero if no limit applies.
*
* @return
* true if the AtomicInteger was successfully incremented without
* exceeding the specified maximum, false if the AtomicInteger could
* not be incremented.
*/
private boolean tryIncrement(AtomicInteger counter, int max) {
// Repeatedly attempt to increment the given AtomicInteger until we
// explicitly succeed or explicitly fail
while (true) {
// Get current value
int count = counter.get();
// Bail out if the maximum has already been reached
if (count >= max && max != 0)
return false;
// Attempt to increment
if (counter.compareAndSet(count, count+1))
return true;
// Try again if unsuccessful
}
}
@Override
protected ModeledConnection acquire(RemoteAuthenticatedUser user,
List<ModeledConnection> connections) throws GuacamoleException {
// Do not acquire connection unless within overall limits
if (!tryIncrement(totalActiveConnections, environment.getAbsoluteMaxConnections()))
throw new GuacamoleResourceConflictException("Cannot connect. Overall maximum connections reached.");
// Get username
String username = user.getIdentifier();
// Remove connections where weight < 0
Iterator<ModeledConnection> i = connections.iterator();
while(i.hasNext()) {
Integer weight = i.next().getConnectionWeight();
if (weight != null && weight.intValue() < 0)
i.remove();
}
// Sort connections in ascending order of usage
ModeledConnection[] sortedConnections = connections.toArray(new ModeledConnection[connections.size()]);
Arrays.sort(sortedConnections, new Comparator<ModeledConnection>() {
@Override
public int compare(ModeledConnection a, ModeledConnection b) {
int weightA, weightB;
// Check if weight of a is null, assign 1 if it is.
if (a.getConnectionWeight() == null)
weightA = 1;
else
weightA = a.getConnectionWeight().intValue() + 1;
// Check if weight of b is null, assign 1 if it is.
if (b.getConnectionWeight() == null)
weightB = 1;
else
weightB = b.getConnectionWeight().intValue() + 1;
int connsA = getActiveConnections(a).size() + 1;
int connsB = getActiveConnections(b).size() + 1;
return (connsA * 10000 / weightA) - (connsB * 10000 / weightB);
}
});
// Track whether acquire fails due to user-specific limits
boolean userSpecificFailure = true;
// Return the first unreserved connection
for (ModeledConnection connection : sortedConnections) {
// If connection weight is zero or negative, this host is disabled and should not be used.
if (connection.getConnectionWeight() < 1)
continue;
// Attempt to aquire connection according to per-user limits
Seat seat = new Seat(username, connection.getIdentifier());
if (tryAdd(activeSeats, seat,
connection.getMaxConnectionsPerUser())) {
// Attempt to aquire connection according to overall limits
if (tryAdd(activeConnections, connection.getIdentifier(),
connection.getMaxConnections()))
return connection;
// Acquire failed - retry with next connection
activeSeats.remove(seat);
// Failure to acquire is not user-specific
userSpecificFailure = false;
}
}
// Acquire failed
totalActiveConnections.decrementAndGet();
// Too many connections by this user
if (userSpecificFailure)
throw new GuacamoleClientTooManyException("Cannot connect. Connection already in use by this user.");
// Too many connections, but not necessarily due purely to this user
else
throw new GuacamoleResourceConflictException("Cannot connect. This connection is in use.");
}
@Override
protected void release(RemoteAuthenticatedUser user, ModeledConnection connection) {
activeSeats.remove(new Seat(user.getIdentifier(), connection.getIdentifier()));
activeConnections.remove(connection.getIdentifier());
totalActiveConnections.decrementAndGet();
}
@Override
protected void acquire(RemoteAuthenticatedUser user,
ModeledConnectionGroup connectionGroup) throws GuacamoleException {
// Get username
String username = user.getIdentifier();
// Attempt to aquire connection group according to per-user limits
Seat seat = new Seat(username, connectionGroup.getIdentifier());
if (tryAdd(activeGroupSeats, seat,
connectionGroup.getMaxConnectionsPerUser())) {
// Attempt to aquire connection group according to overall limits
if (tryAdd(activeGroups, connectionGroup.getIdentifier(),
connectionGroup.getMaxConnections()))
return;
// Acquire failed
activeGroupSeats.remove(seat);
// Failure to acquire is not user-specific
throw new GuacamoleResourceConflictException("Cannot connect. This connection group is in use.");
}
// Already in use by this user
throw new GuacamoleClientTooManyException("Cannot connect. Connection group already in use by this user.");
}
@Override
protected void release(RemoteAuthenticatedUser user,
ModeledConnectionGroup connectionGroup) {
activeGroupSeats.remove(new Seat(user.getIdentifier(), connectionGroup.getIdentifier()));
activeGroups.remove(connectionGroup.getIdentifier());
}
}
|
GUACAMOLE-102: Remove redundant iterations through connections.
|
extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/RestrictedGuacamoleTunnelService.java
|
GUACAMOLE-102: Remove redundant iterations through connections.
|
|
Java
|
apache-2.0
|
e0e28a81451cd09dce08a7bc949142ffd7185d98
| 0
|
mglukhikh/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,hurricup/intellij-community,hurricup/intellij-community,asedunov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,fitermay/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,signed/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,xfournet/intellij-community,semonte/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,ibinti/intellij-community,da1z/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,fitermay/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,fitermay/intellij-community,retomerz/intellij-community,FHannes/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,apixandru/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,fitermay/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,semonte/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ibinti/intellij-community,fitermay/intellij-community,allotria/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,suncycheng/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,allotria/intellij-community,apixandru/intellij-community,hurricup/intellij-community,apixandru/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,semonte/intellij-community,hurricup/intellij-community,retomerz/intellij-community,signed/intellij-community,semonte/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,hurricup/intellij-community,xfournet/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,signed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,signed/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.analysis;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.daemon.DaemonBundle;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.quickfix.*;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.codeInspection.LocalQuickFixOnPsiElementAsIntentionAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.*;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.ui.ColorUtil;
import com.intellij.util.containers.MostlySingularMultiMap;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Highlight method problems
*
* @author cdr
* Date: Aug 14, 2002
*/
public class HighlightMethodUtil {
private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance();
private static final String MISMATCH_COLOR = UIUtil.isUnderDarcula() ? "ff6464" : "red";
private HighlightMethodUtil() { }
static String createClashMethodMessage(PsiMethod method1, PsiMethod method2, boolean showContainingClasses) {
@NonNls String pattern = showContainingClasses ? "clash.methods.message.show.classes" : "clash.methods.message";
return JavaErrorMessages.message(pattern,
JavaHighlightUtil.formatMethod(method1),
JavaHighlightUtil.formatMethod(method2),
HighlightUtil.formatClass(method1.getContainingClass()),
HighlightUtil.formatClass(method2.getContainingClass()));
}
static HighlightInfo checkMethodWeakerPrivileges(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo,
@NotNull PsiFile containingFile) {
PsiMethod method = methodSignature.getMethod();
PsiModifierList modifierList = method.getModifierList();
if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) return null;
int accessLevel = PsiUtil.getAccessLevel(modifierList);
String accessModifier = PsiUtil.getAccessModifier(accessLevel);
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
if (method.hasModifierProperty(PsiModifier.ABSTRACT) && !MethodSignatureUtil.isSuperMethod(superMethod, method)) continue;
if (!PsiUtil.isAccessible(containingFile.getProject(), superMethod, method, null)) continue;
if (!includeRealPositionInfo && MethodSignatureUtil.isSuperMethod(superMethod, method)) continue;
HighlightInfo info = isWeaker(method, modifierList, accessModifier, accessLevel, superMethod, includeRealPositionInfo);
if (info != null) return info;
}
return null;
}
private static HighlightInfo isWeaker(final PsiMethod method, final PsiModifierList modifierList, final String accessModifier, final int accessLevel,
final PsiMethod superMethod,
final boolean includeRealPositionInfo) {
int superAccessLevel = PsiUtil.getAccessLevel(superMethod.getModifierList());
if (accessLevel < superAccessLevel) {
String description = JavaErrorMessages.message("weaker.privileges",
createClashMethodMessage(method, superMethod, true),
accessModifier,
PsiUtil.getAccessModifier(superAccessLevel));
TextRange textRange;
if (includeRealPositionInfo) {
if (modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
textRange = method.getNameIdentifier().getTextRange();
}
else {
PsiElement keyword = PsiUtil.findModifierInList(modifierList, accessModifier);
textRange = keyword.getTextRange();
}
}
else {
textRange = TextRange.EMPTY_RANGE;
}
HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(highlightInfo,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiUtil.getAccessModifier(superAccessLevel), true, false));
return highlightInfo;
}
return null;
}
static HighlightInfo checkMethodIncompatibleReturnType(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo) {
return checkMethodIncompatibleReturnType(methodSignature, superMethodSignatures, includeRealPositionInfo, null);
}
static HighlightInfo checkMethodIncompatibleReturnType(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo,
@Nullable TextRange textRange) {
PsiMethod method = methodSignature.getMethod();
PsiType returnType = methodSignature.getSubstitutor().substitute(method.getReturnType());
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
PsiType declaredReturnType = superMethod.getReturnType();
PsiType superReturnType = declaredReturnType;
if (superMethodSignature.isRaw()) superReturnType = TypeConversionUtil.erasure(declaredReturnType);
if (returnType == null || superReturnType == null || method == superMethod) continue;
PsiClass superClass = superMethod.getContainingClass();
if (superClass == null) continue;
TextRange toHighlight = textRange != null ? textRange
: includeRealPositionInfo ? method.getReturnTypeElement().getTextRange() : TextRange.EMPTY_RANGE;
HighlightInfo highlightInfo = checkSuperMethodSignature(superMethod, superMethodSignature, superReturnType, method, methodSignature,
returnType, JavaErrorMessages.message("incompatible.return.type"),
toHighlight, PsiUtil.getLanguageLevel(aClass));
if (highlightInfo != null) return highlightInfo;
}
return null;
}
private static HighlightInfo checkSuperMethodSignature(@NotNull PsiMethod superMethod,
@NotNull MethodSignatureBackedByPsiMethod superMethodSignature,
PsiType superReturnType,
@NotNull PsiMethod method,
@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull PsiType returnType,
@NotNull String detailMessage,
@NotNull TextRange range,
@NotNull LanguageLevel languageLevel) {
if (superReturnType == null) return null;
if ("clone".equals(method.getName())) {
final PsiClass containingClass = method.getContainingClass();
final PsiClass superContainingClass = superMethod.getContainingClass();
if (containingClass != null && superContainingClass != null && containingClass.isInterface() && !superContainingClass.isInterface()) {
return null;
}
}
PsiType substitutedSuperReturnType;
final boolean isJdk15 = languageLevel.isAtLeast(LanguageLevel.JDK_1_5);
if (isJdk15 && !superMethodSignature.isRaw() && superMethodSignature.equals(methodSignature)) { //see 8.4.5
PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature,
superMethodSignature);
substitutedSuperReturnType = unifyingSubstitutor == null
? superReturnType
: unifyingSubstitutor.substitute(superReturnType);
}
else {
substitutedSuperReturnType = TypeConversionUtil.erasure(superMethodSignature.getSubstitutor().substitute(superReturnType));
}
if (returnType.equals(substitutedSuperReturnType)) return null;
if (!(returnType instanceof PsiPrimitiveType) && substitutedSuperReturnType.getDeepComponentType() instanceof PsiClassType) {
if (isJdk15 && TypeConversionUtil.isAssignable(substitutedSuperReturnType, returnType)) {
return null;
}
}
return createIncompatibleReturnTypeMessage(method, superMethod, substitutedSuperReturnType, returnType, detailMessage, range);
}
private static HighlightInfo createIncompatibleReturnTypeMessage(@NotNull PsiMethod method,
@NotNull PsiMethod superMethod,
@NotNull PsiType substitutedSuperReturnType,
@NotNull PsiType returnType,
@NotNull String detailMessage,
@NotNull TextRange textRange) {
String description = MessageFormat.format("{0}; {1}", createClashMethodMessage(method, superMethod, true), detailMessage);
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(
description).create();
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createMethodReturnFix(method, substitutedSuperReturnType, false));
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createSuperMethodReturnFix(superMethod, returnType));
return errorResult;
}
static HighlightInfo checkMethodOverridesFinal(MethodSignatureBackedByPsiMethod methodSignature,
List<HierarchicalMethodSignature> superMethodSignatures) {
PsiMethod method = methodSignature.getMethod();
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
HighlightInfo info = checkSuperMethodIsFinal(method, superMethod);
if (info != null) return info;
}
return null;
}
private static HighlightInfo checkSuperMethodIsFinal(PsiMethod method, PsiMethod superMethod) {
// strange things happen when super method is from Object and method from interface
if (superMethod.hasModifierProperty(PsiModifier.FINAL)) {
String description = JavaErrorMessages.message("final.method.override",
JavaHighlightUtil.formatMethod(method),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superMethod.getContainingClass()));
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(superMethod, PsiModifier.FINAL, false, true));
return errorResult;
}
return null;
}
static HighlightInfo checkMethodIncompatibleThrows(MethodSignatureBackedByPsiMethod methodSignature,
List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo, PsiClass analyzedClass) {
PsiMethod method = methodSignature.getMethod();
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(aClass, analyzedClass, PsiSubstitutor.EMPTY);
PsiClassType[] exceptions = method.getThrowsList().getReferencedTypes();
PsiJavaCodeReferenceElement[] referenceElements;
List<PsiElement> exceptionContexts;
if (includeRealPositionInfo) {
exceptionContexts = new ArrayList<PsiElement>();
referenceElements = method.getThrowsList().getReferenceElements();
}
else {
exceptionContexts = null;
referenceElements = null;
}
List<PsiClassType> checkedExceptions = new ArrayList<PsiClassType>();
for (int i = 0; i < exceptions.length; i++) {
PsiClassType exception = exceptions[i];
if (!ExceptionUtil.isUncheckedException(exception)) {
checkedExceptions.add(exception);
if (includeRealPositionInfo && i < referenceElements.length) {
PsiJavaCodeReferenceElement exceptionRef = referenceElements[i];
exceptionContexts.add(exceptionRef);
}
}
}
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
int index = getExtraExceptionNum(methodSignature, superMethodSignature, checkedExceptions, superSubstitutor);
if (index != -1) {
if (aClass.isInterface()) {
final PsiClass superContainingClass = superMethod.getContainingClass();
if (superContainingClass != null && !superContainingClass.isInterface()) continue;
if (superContainingClass != null && !aClass.isInheritor(superContainingClass, true)) continue;
}
PsiClassType exception = checkedExceptions.get(index);
String description = JavaErrorMessages.message("overridden.method.does.not.throw",
createClashMethodMessage(method, superMethod, true),
JavaHighlightUtil.formatType(exception));
TextRange textRange;
if (includeRealPositionInfo) {
PsiElement exceptionContext = exceptionContexts.get(index);
textRange = exceptionContext.getTextRange();
}
else {
textRange = TextRange.EMPTY_RANGE;
}
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(errorResult, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(method, exception, false, false)));
QuickFixAction.registerQuickFixAction(errorResult, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(superMethod, exception, true, true)));
return errorResult;
}
}
return null;
}
// return number of exception which was not declared in super method or -1
private static int getExtraExceptionNum(final MethodSignature methodSignature,
final MethodSignatureBackedByPsiMethod superSignature,
List<PsiClassType> checkedExceptions, PsiSubstitutor substitutorForDerivedClass) {
PsiMethod superMethod = superSignature.getMethod();
PsiSubstitutor substitutorForMethod = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature, superSignature);
for (int i = 0; i < checkedExceptions.size(); i++) {
final PsiClassType checkedEx = checkedExceptions.get(i);
final PsiType substituted = substitutorForMethod != null ? substitutorForMethod.substitute(checkedEx) : TypeConversionUtil.erasure(checkedEx);
PsiType exception = substitutorForDerivedClass.substitute(substituted);
if (!isMethodThrows(superMethod, substitutorForMethod, exception, substitutorForDerivedClass)) {
return i;
}
}
return -1;
}
private static boolean isMethodThrows(PsiMethod method, @Nullable PsiSubstitutor substitutorForMethod, PsiType exception, PsiSubstitutor substitutorForDerivedClass) {
PsiClassType[] thrownExceptions = method.getThrowsList().getReferencedTypes();
for (PsiClassType thrownException1 : thrownExceptions) {
PsiType thrownException = substitutorForMethod != null ? substitutorForMethod.substitute(thrownException1) : TypeConversionUtil.erasure(thrownException1);
thrownException = substitutorForDerivedClass.substitute(thrownException);
if (TypeConversionUtil.isAssignable(thrownException, exception)) return true;
}
return false;
}
@Nullable
static HighlightInfo checkMethodCall(@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper,
@NotNull LanguageLevel languageLevel,
@NotNull JavaSdkVersion javaSdkVersion) {
PsiExpressionList list = methodCall.getArgumentList();
PsiReferenceExpression referenceToMethod = methodCall.getMethodExpression();
JavaResolveResult[] results = referenceToMethod.multiResolve(true);
JavaResolveResult resolveResult = results.length == 1 ? results[0] : JavaResolveResult.EMPTY;
PsiElement resolved = resolveResult.getElement();
boolean isDummy = isDummyConstructorCall(methodCall, resolveHelper, list, referenceToMethod);
if (isDummy) return null;
HighlightInfo highlightInfo;
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
if (resolved instanceof PsiMethod && resolveResult.isValidResult()) {
TextRange fixRange = getFixRange(methodCall);
highlightInfo = HighlightUtil.checkUnhandledExceptions(methodCall, fixRange);
if (highlightInfo == null) {
final String invalidCallMessage =
LambdaUtil.getInvalidQualifier4StaticInterfaceMethodMessage((PsiMethod)resolved, methodCall.getMethodExpression(), resolveResult.getCurrentFileResolveScope(), languageLevel);
if (invalidCallMessage != null) {
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).descriptionAndTooltip(invalidCallMessage).range(fixRange).create();
if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createIncreaseLanguageLevelFix(LanguageLevel.JDK_1_8));
}
} else {
highlightInfo = GenericsHighlightUtil.checkInferredIntersections(substitutor, fixRange);
}
if (highlightInfo == null) {
highlightInfo = checkVarargParameterErasureToBeAccessible((MethodCandidateInfo)resolveResult, methodCall);
}
if (highlightInfo == null && resolveResult instanceof MethodCandidateInfo) {
final String errorMessage = ((MethodCandidateInfo)resolveResult).getInferenceErrorMessage();
if (errorMessage != null) {
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).descriptionAndTooltip(errorMessage).range(fixRange).create();
if (highlightInfo != null) {
registerMethodCallIntentions(highlightInfo, methodCall, list, resolveHelper);
registerMethodReturnFixAction(highlightInfo, (MethodCandidateInfo)resolveResult, methodCall);
}
}
}
}
}
else {
PsiMethod resolvedMethod = null;
MethodCandidateInfo candidateInfo = null;
if (resolveResult instanceof MethodCandidateInfo) {
candidateInfo = (MethodCandidateInfo)resolveResult;
resolvedMethod = candidateInfo.getElement();
}
if (!resolveResult.isAccessible() || !resolveResult.isStaticsScopeCorrect()) {
highlightInfo = null;
}
else if (candidateInfo != null && !candidateInfo.isApplicable()) {
if (candidateInfo.isTypeArgumentsApplicable()) {
String methodName = HighlightMessageUtil.getSymbolName(resolved, substitutor);
PsiElement parent = resolved.getParent();
String containerName = parent == null ? "" : HighlightMessageUtil.getSymbolName(parent, substitutor);
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.method.arguments", methodName, containerName, argTypes);
final Ref<PsiElement> elementToHighlight = new Ref<PsiElement>(list);
String toolTip;
if (parent instanceof PsiClass && !ApplicationManager.getApplication().isUnitTestMode()) {
toolTip = buildOneLineMismatchDescription(list, candidateInfo, elementToHighlight);
if (toolTip == null) {
toolTip = createMismatchedArgumentsHtmlTooltip(candidateInfo, list);
}
}
else {
toolTip = description;
}
PsiElement element = elementToHighlight.get();
int navigationShift = element instanceof PsiExpressionList ? +1 : 0; // argument list starts with paren which there is no need to highlight
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element)
.description(description).escapedToolTip(toolTip).navigationShift(navigationShift).create();
if (highlightInfo != null) {
registerMethodCallIntentions(highlightInfo, methodCall, list, resolveHelper);
registerMethodReturnFixAction(highlightInfo, candidateInfo, methodCall);
}
}
else {
PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
PsiReferenceParameterList typeArgumentList = methodCall.getTypeArgumentList();
if (typeArgumentList.getTypeArguments().length == 0 && resolvedMethod.hasTypeParameters()) {
highlightInfo = GenericsHighlightUtil.checkInferredTypeArguments(resolvedMethod, methodCall, substitutor);
}
else {
highlightInfo = GenericsHighlightUtil.checkParameterizedReferenceTypeArguments(resolved, methodExpression, substitutor, javaSdkVersion);
}
}
}
else {
String description = JavaErrorMessages.message("method.call.expected");
highlightInfo =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCall).descriptionAndTooltip(description).create();
if (resolved instanceof PsiClass) {
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createInsertNewFix(methodCall, (PsiClass)resolved));
}
else {
TextRange range = getFixRange(methodCall);
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreateMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreateAbstractMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreatePropertyFromUsageFix(methodCall));
}
}
}
if (highlightInfo == null) {
highlightInfo = GenericsHighlightUtil.checkParameterizedReferenceTypeArguments(resolved, referenceToMethod, substitutor,
javaSdkVersion);
}
return highlightInfo;
}
private static void registerMethodReturnFixAction(HighlightInfo highlightInfo,
MethodCandidateInfo candidate,
PsiCall methodCall) {
if (methodCall.getParent() instanceof PsiReturnStatement) {
final PsiMethod containerMethod = PsiTreeUtil.getParentOfType(methodCall, PsiMethod.class, true, PsiLambdaExpression.class);
if (containerMethod != null) {
final PsiMethod method = candidate.getElement();
final PsiExpression methodCallCopy =
JavaPsiFacade.getElementFactory(method.getProject()).createExpressionFromText(methodCall.getText(), methodCall);
PsiType methodCallTypeByArgs = methodCallCopy.getType();
//ensure type params are not included
methodCallTypeByArgs = JavaPsiFacade.getElementFactory(method.getProject())
.createRawSubstitutor(method).substitute(methodCallTypeByArgs);
QuickFixAction.registerQuickFixAction(highlightInfo,
getFixRange(methodCall),
QUICK_FIX_FACTORY.createMethodReturnFix(containerMethod, methodCallTypeByArgs, true));
}
}
}
private static String buildOneLineMismatchDescription(@NotNull PsiExpressionList list,
@NotNull MethodCandidateInfo candidateInfo,
@NotNull Ref<PsiElement> elementToHighlight) {
final PsiExpression[] expressions = list.getExpressions();
final PsiMethod resolvedMethod = candidateInfo.getElement();
final PsiSubstitutor substitutor = candidateInfo.getSubstitutor();
final PsiParameter[] parameters = resolvedMethod.getParameterList().getParameters();
if (expressions.length == parameters.length && parameters.length > 1) {
int idx = -1;
for (int i = 0; i < expressions.length; i++) {
PsiExpression expression = expressions[i];
if (!TypeConversionUtil.areTypesAssignmentCompatible(substitutor.substitute(parameters[i].getType()), expression)) {
if (idx != -1) {
idx = -1;
break;
}
else {
idx = i;
}
}
}
if (idx > -1) {
final PsiExpression wrongArg = expressions[idx];
final PsiType argType = wrongArg.getType();
if (argType != null) {
elementToHighlight.set(wrongArg);
final String message = JavaErrorMessages
.message("incompatible.call.types", idx + 1, substitutor.substitute(parameters[idx].getType()).getCanonicalText(), argType.getCanonicalText());
return XmlStringUtil.wrapInHtml("<body>" + XmlStringUtil.escapeString(message) +
" <a href=\"#assignment/" + XmlStringUtil.escapeString(createMismatchedArgumentsHtmlTooltip(candidateInfo, list)) + "\"" +
(UIUtil.isUnderDarcula() ? " color=\"7AB4C9\" " : "") +
">" + DaemonBundle.message("inspection.extended.description") + "</a></body>");
}
}
}
return null;
}
static boolean isDummyConstructorCall(PsiMethodCallExpression methodCall,
PsiResolveHelper resolveHelper,
PsiExpressionList list,
PsiReferenceExpression referenceToMethod) {
boolean isDummy = false;
boolean isThisOrSuper = referenceToMethod.getReferenceNameElement() instanceof PsiKeyword;
if (isThisOrSuper) {
// super(..) or this(..)
if (list.getExpressions().length == 0) { // implicit ctr call
CandidateInfo[] candidates = resolveHelper.getReferencedMethodCandidates(methodCall, true);
if (candidates.length == 1 && !candidates[0].getElement().isPhysical()) {
isDummy = true;// dummy constructor
}
}
}
return isDummy;
}
@Nullable
static HighlightInfo checkAmbiguousMethodCallIdentifier(@NotNull PsiReferenceExpression referenceToMethod,
@NotNull JavaResolveResult[] resolveResults,
@NotNull PsiExpressionList list,
final PsiElement element,
@NotNull JavaResolveResult resolveResult,
@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper) {
MethodCandidateInfo methodCandidate1 = null;
MethodCandidateInfo methodCandidate2 = null;
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isApplicable() && !candidate.getElement().isConstructor()) {
if (methodCandidate1 == null) {
methodCandidate1 = candidate;
}
else {
methodCandidate2 = candidate;
break;
}
}
}
MethodCandidateInfo[] candidates = toMethodCandidates(resolveResults);
HighlightInfoType highlightInfoType = HighlightInfoType.ERROR;
if (methodCandidate2 != null) {
return null;
}
String description;
PsiElement elementToHighlight;
if (element != null && !resolveResult.isAccessible()) {
description = HighlightUtil.buildProblemWithAccessDescription(referenceToMethod, resolveResult);
elementToHighlight = referenceToMethod.getReferenceNameElement();
}
else if (element != null && !resolveResult.isStaticsScopeCorrect()) {
final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(referenceToMethod);
final String staticInterfaceMethodMessage =
element instanceof PsiMethod
? LambdaUtil.getInvalidQualifier4StaticInterfaceMethodMessage((PsiMethod)element, referenceToMethod,
resolveResult.getCurrentFileResolveScope(), languageLevel)
: null;
description = staticInterfaceMethodMessage != null
? staticInterfaceMethodMessage
: HighlightUtil.buildProblemWithStaticDescription(element);
elementToHighlight = referenceToMethod.getReferenceNameElement();
}
else {
String methodName = referenceToMethod.getReferenceName() + buildArgTypesList(list);
description = JavaErrorMessages.message("cannot.resolve.method", methodName);
if (candidates.length == 0) {
elementToHighlight = referenceToMethod.getReferenceNameElement();
highlightInfoType = HighlightInfoType.WRONG_REF;
}
else {
return null;
}
}
String toolTip = XmlStringUtil.escapeString(description);
HighlightInfo info =
HighlightInfo.newHighlightInfo(highlightInfoType).range(elementToHighlight).description(description).escapedToolTip(toolTip).create();
registerMethodCallIntentions(info, methodCall, list, resolveHelper);
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
HighlightUtil.registerStaticProblemQuickFixAction(element, info, referenceToMethod);
}
TextRange fixRange = getFixRange(elementToHighlight);
CastMethodArgumentFix.REGISTRAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
PermuteArgumentsFix.registerFix(info, methodCall, candidates, fixRange);
WrapExpressionFix.registerWrapAction(candidates, list.getExpressions(), info);
registerChangeParameterClassFix(methodCall, list, info);
return info;
}
@Nullable
static HighlightInfo checkAmbiguousMethodCallArguments(@NotNull PsiReferenceExpression referenceToMethod,
@NotNull JavaResolveResult[] resolveResults,
@NotNull PsiExpressionList list,
final PsiElement element,
@NotNull JavaResolveResult resolveResult,
@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper,
@NotNull PsiElement elementToHighlight) {
MethodCandidateInfo methodCandidate1 = null;
MethodCandidateInfo methodCandidate2 = null;
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isApplicable() && !candidate.getElement().isConstructor()) {
if (methodCandidate1 == null) {
methodCandidate1 = candidate;
}
else {
methodCandidate2 = candidate;
break;
}
}
}
MethodCandidateInfo[] candidates = toMethodCandidates(resolveResults);
String description;
String toolTip;
HighlightInfoType highlightInfoType = HighlightInfoType.ERROR;
if (methodCandidate2 != null) {
PsiMethod element1 = methodCandidate1.getElement();
String m1 = PsiFormatUtil.formatMethod(element1,
methodCandidate1.getSubstitutor(),
PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
PsiMethod element2 = methodCandidate2.getElement();
String m2 = PsiFormatUtil.formatMethod(element2,
methodCandidate2.getSubstitutor(),
PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
VirtualFile virtualFile1 = PsiUtilCore.getVirtualFile(element1);
VirtualFile virtualFile2 = PsiUtilCore.getVirtualFile(element2);
if (!Comparing.equal(virtualFile1, virtualFile2)) {
if (virtualFile1 != null) m1 += " (In " + virtualFile1.getPresentableUrl() + ")";
if (virtualFile2 != null) m2 += " (In " + virtualFile2.getPresentableUrl() + ")";
}
description = JavaErrorMessages.message("ambiguous.method.call", m1, m2);
toolTip = createAmbiguousMethodHtmlTooltip(new MethodCandidateInfo[]{methodCandidate1, methodCandidate2});
}
else {
if (element != null && !resolveResult.isAccessible()) {
return null;
}
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
return null;
}
String methodName = referenceToMethod.getReferenceName() + buildArgTypesList(list);
description = JavaErrorMessages.message("cannot.resolve.method", methodName);
if (candidates.length == 0) {
return null;
}
toolTip = XmlStringUtil.escapeString(description);
}
HighlightInfo info =
HighlightInfo.newHighlightInfo(highlightInfoType).range(elementToHighlight).description(description).escapedToolTip(toolTip).create();
if (methodCandidate2 == null) {
registerMethodCallIntentions(info, methodCall, list, resolveHelper);
}
if (!resolveResult.isAccessible() && resolveResult.isStaticsScopeCorrect() && methodCandidate2 != null) {
HighlightUtil.registerAccessQuickFixAction((PsiMember)element, referenceToMethod, info, resolveResult.getCurrentFileResolveScope());
}
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
HighlightUtil.registerStaticProblemQuickFixAction(element, info, referenceToMethod);
}
TextRange fixRange = getFixRange(elementToHighlight);
CastMethodArgumentFix.REGISTRAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
PermuteArgumentsFix.registerFix(info, methodCall, candidates, fixRange);
WrapExpressionFix.registerWrapAction(candidates, list.getExpressions(), info);
registerChangeParameterClassFix(methodCall, list, info);
return info;
}
@NotNull
private static MethodCandidateInfo[] toMethodCandidates(@NotNull JavaResolveResult[] resolveResults) {
List<MethodCandidateInfo> candidateList = new ArrayList<MethodCandidateInfo>(resolveResults.length);
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isAccessible()) candidateList.add(candidate);
}
return candidateList.toArray(new MethodCandidateInfo[candidateList.size()]);
}
private static void registerMethodCallIntentions(@Nullable HighlightInfo highlightInfo,
PsiMethodCallExpression methodCall,
PsiExpressionList list,
PsiResolveHelper resolveHelper) {
TextRange fixRange = getFixRange(methodCall);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateAbstractMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateConstructorFromSuperFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateConstructorFromThisFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreatePropertyFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateGetterSetterPropertyFromUsageFix(methodCall));
CandidateInfo[] methodCandidates = resolveHelper.getReferencedMethodCandidates(methodCall, false);
CastMethodArgumentFix.REGISTRAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
PermuteArgumentsFix.registerFix(highlightInfo, methodCall, methodCandidates, fixRange);
AddTypeArgumentsFix.REGISTRAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
registerMethodAccessLevelIntentions(methodCandidates, methodCall, list, highlightInfo);
registerChangeMethodSignatureFromUsageIntentions(methodCandidates, list, highlightInfo, fixRange);
RemoveRedundantArgumentsFix.registerIntentions(methodCandidates, list, highlightInfo, fixRange);
ConvertDoubleToFloatFix.registerIntentions(methodCandidates, list, highlightInfo, fixRange);
WrapExpressionFix.registerWrapAction(methodCandidates, list.getExpressions(), highlightInfo);
registerChangeParameterClassFix(methodCall, list, highlightInfo);
if (methodCandidates.length == 0) {
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createStaticImportMethodFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.addMethodQualifierFix(methodCall));
}
for (IntentionAction action : QUICK_FIX_FACTORY.getVariableTypeFromCallFixes(methodCall, list)) {
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, action);
}
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createReplaceAddAllArrayToCollectionFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createSurroundWithArrayFix(methodCall, null));
QualifyThisArgumentFix.registerQuickFixAction(methodCandidates, methodCall, highlightInfo, fixRange);
CandidateInfo[] candidates = resolveHelper.getReferencedMethodCandidates(methodCall, true);
ChangeStringLiteralToCharInMethodCallFix.registerFixes(candidates, methodCall, highlightInfo);
}
private static void registerMethodAccessLevelIntentions(CandidateInfo[] methodCandidates,
PsiMethodCallExpression methodCall,
PsiExpressionList exprList,
HighlightInfo highlightInfo) {
for (CandidateInfo methodCandidate : methodCandidates) {
PsiMethod method = (PsiMethod)methodCandidate.getElement();
if (!methodCandidate.isAccessible() && PsiUtil.isApplicable(method, methodCandidate.getSubstitutor(), exprList)) {
HighlightUtil.registerAccessQuickFixAction(method, methodCall.getMethodExpression(), highlightInfo, methodCandidate.getCurrentFileResolveScope());
}
}
}
@NotNull
private static String createAmbiguousMethodHtmlTooltip(MethodCandidateInfo[] methodCandidates) {
return JavaErrorMessages.message("ambiguous.method.html.tooltip",
Integer.valueOf(methodCandidates[0].getElement().getParameterList().getParametersCount() + 2),
createAmbiguousMethodHtmlTooltipMethodRow(methodCandidates[0]),
getContainingClassName(methodCandidates[0]),
createAmbiguousMethodHtmlTooltipMethodRow(methodCandidates[1]),
getContainingClassName(methodCandidates[1]));
}
private static String getContainingClassName(final MethodCandidateInfo methodCandidate) {
PsiMethod method = methodCandidate.getElement();
PsiClass containingClass = method.getContainingClass();
return containingClass == null ? method.getContainingFile().getName() : HighlightUtil.formatClass(containingClass, false);
}
@Language("HTML")
private static String createAmbiguousMethodHtmlTooltipMethodRow(final MethodCandidateInfo methodCandidate) {
PsiMethod method = methodCandidate.getElement();
PsiParameter[] parameters = method.getParameterList().getParameters();
PsiSubstitutor substitutor = methodCandidate.getSubstitutor();
@NonNls @Language("HTML") String ms = "<td><b>" + method.getName() + "</b></td>";
for (int j = 0; j < parameters.length; j++) {
PsiParameter parameter = parameters[j];
PsiType type = substitutor.substitute(parameter.getType());
ms += "<td><b>" + (j == 0 ? "(" : "") +
XmlStringUtil.escapeString(type.getPresentableText())
+ (j == parameters.length - 1 ? ")" : ",") + "</b></td>";
}
if (parameters.length == 0) {
ms += "<td><b>()</b></td>";
}
return ms;
}
private static String createMismatchedArgumentsHtmlTooltip(MethodCandidateInfo info, PsiExpressionList list) {
PsiMethod method = info.getElement();
PsiSubstitutor substitutor = info.getSubstitutor();
PsiClass aClass = method.getContainingClass();
PsiParameter[] parameters = method.getParameterList().getParameters();
String methodName = method.getName();
return createMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass);
}
private static String createShortMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
@Nullable MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
PsiExpression[] expressions = list.getExpressions();
int cols = Math.max(parameters.length, expressions.length);
@Language("HTML")
@NonNls String parensizedName = methodName + (parameters.length == 0 ? "( ) " : "");
final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
return JavaErrorMessages.message(
"argument.mismatch.html.tooltip",
Integer.valueOf(cols - parameters.length + 1), parensizedName,
HighlightUtil.formatClass(aClass, false),
createMismatchedArgsHtmlTooltipParamsRow(parameters, substitutor, expressions),
createMismatchedArgsHtmlTooltipArgumentsRow(expressions, parameters, substitutor, cols),
errorMessage != null ? "<br/>reason: " + XmlStringUtil.escapeString(errorMessage).replaceAll("\n", "<br/>") : ""
);
}
private static String esctrim(@NotNull String s) {
return XmlStringUtil.escapeString(trimNicely(s));
}
private static String trimNicely(String s) {
if (s.length() <= 40) return s;
List<TextRange> wordIndices = StringUtil.getWordIndicesIn(s);
if (wordIndices.size() > 2) {
int firstWordEnd = wordIndices.get(0).getEndOffset();
// try firstWord...remainder
for (int i = 1; i<wordIndices.size();i++) {
int stringLength = firstWordEnd + s.length() - wordIndices.get(i).getStartOffset();
if (stringLength <= 40) {
return s.substring(0, firstWordEnd) + "..." + s.substring(wordIndices.get(i).getStartOffset());
}
}
}
// maybe one last word will fit?
if (!wordIndices.isEmpty() && s.length() - wordIndices.get(wordIndices.size()-1).getStartOffset() <= 40) {
return "..." + s.substring(wordIndices.get(wordIndices.size()-1).getStartOffset());
}
return StringUtil.last(s, 40, true).toString();
}
private static String createMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
return Math.max(parameters.length, list.getExpressions().length) <= 2
? createShortMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass)
: createLongMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass);
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createLongMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
@Nullable MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
PsiExpression[] expressions = list.getExpressions();
@SuppressWarnings("NonConstantStringShouldBeStringBuffer") @NonNls
String s = "<html><body><table border=0>" +
"<tr><td colspan=3>" +
"<nobr><b>" + methodName + "()</b> in <b>" + HighlightUtil.formatClass(aClass, false) +"</b> cannot be applied to:</nobr>" +
"</td></tr>"+
"<tr><td colspan=2 align=left>Expected<br>Parameters:</td><td align=left>Actual<br>Arguments:</td></tr>"+
"<tr><td colspan=3><hr></td></tr>"
;
for (int i = 0; i < Math.max(parameters.length,expressions.length); i++) {
PsiParameter parameter = i < parameters.length ? parameters[i] : null;
PsiExpression expression = i < expressions.length ? expressions[i] : null;
boolean showShort = showShortType(i, parameters, expressions, substitutor);
@NonNls String mismatchColor = showShort ? null : UIUtil.isUnderDarcula() ? "FF6B68" : "red";
s += "<tr" + (i % 2 == 0 ? " style='background-color: #"
+ (UIUtil.isUnderDarcula() ? ColorUtil.toHex(ColorUtil.shift(UIUtil.getToolTipBackground(), 1.1)) : "eeeeee")
+ "'" : "") + ">";
s += "<td><b><nobr>";
if (parameter != null) {
String name = parameter.getName();
if (name != null) {
s += esctrim(name) +":";
}
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (parameter != null) {
PsiType type = substitutor.substitute(parameter.getType());
s += "<font " + (mismatchColor == null ? "" : "color=" + mismatchColor) + ">" +
esctrim(showShort ? type.getPresentableText() : JavaHighlightUtil.formatType(type))
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (expression != null) {
PsiType type = expression.getType();
s += "<font " + (mismatchColor == null ? "" : "color='" + mismatchColor + "'") + ">" +
esctrim(expression.getText()) + " "+
(mismatchColor == null || type == null || type == PsiType.NULL ? "" : "("+esctrim(JavaHighlightUtil.formatType(type))+")")
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "</tr>";
}
s+= "</table>";
final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
if (errorMessage != null) {
s+= "reason: ";
s += XmlStringUtil.escapeString(errorMessage).replaceAll("\n", "<br/>");
}
s+= "</body></html>";
return s;
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createMismatchedArgsHtmlTooltipArgumentsRow(final PsiExpression[] expressions, final PsiParameter[] parameters,
final PsiSubstitutor substitutor, final int cols) {
@Language("HTML")
@NonNls String ms = "";
for (int i = 0; i < expressions.length; i++) {
PsiExpression expression = expressions[i];
PsiType type = expression.getType();
boolean showShort = showShortType(i, parameters, expressions, substitutor);
@NonNls String mismatchColor = showShort ? null : MISMATCH_COLOR;
ms += "<td> " + "<b><nobr>" + (i == 0 ? "(" : "")
+ "<font " + (showShort ? "" : "color=" + mismatchColor) + ">" +
XmlStringUtil.escapeString(showShort ? type.getPresentableText() : JavaHighlightUtil.formatType(type))
+ "</font>"
+ (i == expressions.length - 1 ? ")" : ",") + "</nobr></b></td>";
}
for (int i = expressions.length; i < cols + 1; i++) {
ms += "<td>" + (i == 0 ? "<b>()</b>" : "") +
" </td>";
}
return ms;
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createMismatchedArgsHtmlTooltipParamsRow(final PsiParameter[] parameters,
final PsiSubstitutor substitutor,
final PsiExpression[] expressions) {
@NonNls String ms = "";
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
PsiType type = substitutor.substitute(parameter.getType());
ms += "<td><b><nobr>" + (i == 0 ? "(" : "") +
XmlStringUtil.escapeString(showShortType(i, parameters, expressions, substitutor)
? type.getPresentableText()
: JavaHighlightUtil.formatType(type))
+ (i == parameters.length - 1 ? ")" : ",") + "</nobr></b></td>";
}
return ms;
}
private static boolean showShortType(int i,
PsiParameter[] parameters,
PsiExpression[] expressions,
PsiSubstitutor substitutor) {
PsiExpression expression = i < expressions.length ? expressions[i] : null;
if (expression == null) return true;
PsiType paramType = i < parameters.length && parameters[i] != null
? substitutor.substitute(parameters[i].getType())
: null;
PsiType expressionType = expression.getType();
return paramType != null && expressionType != null && TypeConversionUtil.isAssignable(paramType, expressionType);
}
static HighlightInfo checkMethodMustHaveBody(PsiMethod method, PsiClass aClass) {
HighlightInfo errorResult = null;
if (method.getBody() == null
&& !method.hasModifierProperty(PsiModifier.ABSTRACT)
&& !method.hasModifierProperty(PsiModifier.NATIVE)
&& aClass != null
&& !aClass.isInterface()
&& !PsiUtilCore.hasErrorElementChild(method)) {
int start = method.getModifierList().getTextRange().getStartOffset();
int end = method.getTextRange().getEndOffset();
String description = JavaErrorMessages.message("missing.method.body");
errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(start, end).descriptionAndTooltip(description).create();
if (HighlightUtil.getIncompatibleModifier(PsiModifier.ABSTRACT, method.getModifierList()) == null) {
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, true, false));
}
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
}
return errorResult;
}
static HighlightInfo checkAbstractMethodInConcreteClass(PsiMethod method, PsiElement elementToHighlight) {
HighlightInfo errorResult = null;
PsiClass aClass = method.getContainingClass();
if (method.hasModifierProperty(PsiModifier.ABSTRACT)
&& aClass != null
&& !aClass.hasModifierProperty(PsiModifier.ABSTRACT)
&& !aClass.isEnum()
&& !PsiUtilCore.hasErrorElementChild(method)) {
String description = JavaErrorMessages.message("abstract.method.in.non.abstract.class");
errorResult =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(elementToHighlight).descriptionAndTooltip(description).create();
if (method.getBody() != null) {
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false));
}
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createModifierListFix(aClass, PsiModifier.ABSTRACT, true, false));
}
return errorResult;
}
static HighlightInfo checkConstructorName(PsiMethod method) {
String methodName = method.getName();
PsiClass aClass = method.getContainingClass();
HighlightInfo errorResult = null;
if (aClass != null) {
String className = aClass instanceof PsiAnonymousClass ? null : aClass.getName();
if (className == null || !Comparing.strEqual(methodName, className)) {
PsiElement element = method.getNameIdentifier();
String description = JavaErrorMessages.message("missing.return.type");
errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
if (className != null) {
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createRenameElementFix(method, className));
}
}
}
return errorResult;
}
@Nullable
static HighlightInfo checkDuplicateMethod(PsiClass aClass,
@NotNull PsiMethod method,
@NotNull MostlySingularMultiMap<MethodSignature, PsiMethod> duplicateMethods) {
if (aClass == null || method instanceof ExternallyDefinedPsiElement) return null;
MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
int methodCount = 1;
List<PsiMethod> methods = (List<PsiMethod>)duplicateMethods.get(methodSignature);
if (methods.size() > 1) {
methodCount++;
}
if (methodCount == 1 && aClass.isEnum() &&
GenericsHighlightUtil.isEnumSyntheticMethod(methodSignature, aClass.getProject())) {
methodCount++;
}
if (methodCount > 1) {
String description = JavaErrorMessages.message("duplicate.method",
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(aClass));
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).
range(method, textRange.getStartOffset(), textRange.getEndOffset()).
descriptionAndTooltip(description).create();
}
return null;
}
@Nullable
static HighlightInfo checkMethodCanHaveBody(@NotNull PsiMethod method, @NotNull LanguageLevel languageLevel) {
PsiClass aClass = method.getContainingClass();
boolean hasNoBody = method.getBody() == null;
boolean isInterface = aClass != null && aClass.isInterface();
boolean isExtension = method.hasModifierProperty(PsiModifier.DEFAULT);
boolean isStatic = method.hasModifierProperty(PsiModifier.STATIC);
boolean isPrivate = method.hasModifierProperty(PsiModifier.PRIVATE);
final List<IntentionAction> additionalFixes = new ArrayList<IntentionAction>();
String description = null;
if (hasNoBody) {
if (isExtension) {
description = JavaErrorMessages.message("extension.method.should.have.a.body");
additionalFixes.add(QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
}
else if (isInterface && isStatic && languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
description = "Static methods in interfaces should have a body";
}
}
else if (isInterface) {
if (!isExtension && !isStatic && !isPrivate) {
description = JavaErrorMessages.message("interface.methods.cannot.have.body");
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
additionalFixes.add(QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.DEFAULT, true, false));
additionalFixes.add(QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.STATIC, true, false));
}
}
}
else if (isExtension) {
description = JavaErrorMessages.message("extension.method.in.class");
}
else if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
description = JavaErrorMessages.message("abstract.methods.cannot.have.a.body");
}
else if (method.hasModifierProperty(PsiModifier.NATIVE)) {
description = JavaErrorMessages.message("native.methods.cannot.have.a.body");
}
if (description == null) return null;
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
if (!hasNoBody) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createDeleteMethodBodyFix(method));
}
if (method.hasModifierProperty(PsiModifier.ABSTRACT) && !isInterface) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false));
}
for (IntentionAction intentionAction : additionalFixes) {
QuickFixAction.registerQuickFixAction(info, intentionAction);
}
return info;
}
@Nullable
static HighlightInfo checkConstructorCallMustBeFirstStatement(@NotNull PsiMethodCallExpression methodCall) {
if (!RefactoringChangeUtil.isSuperOrThisMethodCall(methodCall)) return null;
PsiElement codeBlock = methodCall.getParent().getParent();
if (codeBlock instanceof PsiCodeBlock
&& codeBlock.getParent() instanceof PsiMethod
&& ((PsiMethod)codeBlock.getParent()).isConstructor()) {
PsiElement prevSibling = methodCall.getParent().getPrevSibling();
while (true) {
if (prevSibling == null) return null;
if (prevSibling instanceof PsiStatement) break;
prevSibling = prevSibling.getPrevSibling();
}
}
PsiReferenceExpression expression = methodCall.getMethodExpression();
String message = JavaErrorMessages.message("constructor.call.must.be.first.statement", expression.getText() + "()");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCall).descriptionAndTooltip(message).create();
}
static HighlightInfo checkSuperAbstractMethodDirectCall(@NotNull PsiMethodCallExpression methodCallExpression) {
PsiReferenceExpression expression = methodCallExpression.getMethodExpression();
if (!(expression.getQualifierExpression() instanceof PsiSuperExpression)) return null;
PsiMethod method = methodCallExpression.resolveMethod();
if (method != null && method.hasModifierProperty(PsiModifier.ABSTRACT)) {
String message = JavaErrorMessages.message("direct.abstract.method.access", JavaHighlightUtil.formatMethod(method));
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCallExpression).descriptionAndTooltip(message).create();
}
return null;
}
static HighlightInfo checkConstructorCallsBaseClassConstructor(PsiMethod constructor,
RefCountHolder refCountHolder,
PsiResolveHelper resolveHelper) {
if (!constructor.isConstructor()) return null;
PsiClass aClass = constructor.getContainingClass();
if (aClass == null) return null;
if (aClass.isEnum()) return null;
PsiCodeBlock body = constructor.getBody();
if (body == null) return null;
// check whether constructor call super(...) or this(...)
PsiElement element = new PsiMatcherImpl(body)
.firstChild(PsiMatchers.hasClass(PsiExpressionStatement.class))
.firstChild(PsiMatchers.hasClass(PsiMethodCallExpression.class))
.firstChild(PsiMatchers.hasClass(PsiReferenceExpression.class))
.firstChild(PsiMatchers.hasClass(PsiKeyword.class))
.getElement();
if (element != null) return null;
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(constructor);
PsiClassType[] handledExceptions = constructor.getThrowsList().getReferencedTypes();
HighlightInfo info = HighlightClassUtil.checkBaseClassDefaultConstructorProblem(aClass, refCountHolder, resolveHelper, textRange, handledExceptions);
if (info != null) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createInsertSuperFix(constructor));
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createAddDefaultConstructorFix(aClass.getSuperClass()));
}
return info;
}
/**
* @return error if static method overrides instance method or
* instance method overrides static. see JLS 8.4.6.1, 8.4.6.2
*/
static HighlightInfo checkStaticMethodOverride(@NotNull PsiMethod method,@NotNull PsiFile containingFile) {
// constructors are not members and therefor don't override class methods
if (method.isConstructor()) {
return null;
}
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
final HierarchicalMethodSignature methodSignature = PsiSuperMethodImplUtil.getHierarchicalMethodSignature(method);
final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures();
if (superSignatures.isEmpty()) {
return null;
}
boolean isStatic = method.hasModifierProperty(PsiModifier.STATIC);
for (HierarchicalMethodSignature signature : superSignatures) {
final PsiMethod superMethod = signature.getMethod();
final PsiClass superClass = superMethod.getContainingClass();
if (superClass == null) continue;
final HighlightInfo highlightInfo = checkStaticMethodOverride(aClass, method, isStatic, superClass, superMethod,containingFile);
if (highlightInfo != null) {
return highlightInfo;
}
}
return null;
}
private static HighlightInfo checkStaticMethodOverride(PsiClass aClass, PsiMethod method, boolean isMethodStatic, PsiClass superClass, PsiMethod superMethod,@NotNull PsiFile containingFile) {
if (superMethod == null) return null;
PsiManager manager = containingFile.getManager();
PsiModifierList superModifierList = superMethod.getModifierList();
PsiModifierList modifierList = method.getModifierList();
if (superModifierList.hasModifierProperty(PsiModifier.PRIVATE)) return null;
if (superModifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)
&& !JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(aClass, superClass)) {
return null;
}
boolean isSuperMethodStatic = superModifierList.hasModifierProperty(PsiModifier.STATIC);
if (isMethodStatic != isSuperMethodStatic) {
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
@NonNls final String messageKey = isMethodStatic
? "static.method.cannot.override.instance.method"
: "instance.method.cannot.override.static.method";
String description = JavaErrorMessages.message(messageKey,
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(aClass),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superClass));
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
if (!isSuperMethodStatic || HighlightUtil.getIncompatibleModifier(PsiModifier.STATIC, modifierList) == null) {
QuickFixAction.registerQuickFixAction(info,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.STATIC, isSuperMethodStatic, false));
}
if (manager.isInProject(superMethod) &&
(!isMethodStatic || HighlightUtil.getIncompatibleModifier(PsiModifier.STATIC, superModifierList) == null)) {
QuickFixAction.registerQuickFixAction(info,
QUICK_FIX_FACTORY.createModifierListFix(superMethod, PsiModifier.STATIC, isMethodStatic, true));
}
return info;
}
if (isMethodStatic) {
if (superClass.isInterface()) return null;
int accessLevel = PsiUtil.getAccessLevel(modifierList);
String accessModifier = PsiUtil.getAccessModifier(accessLevel);
HighlightInfo info = isWeaker(method, modifierList, accessModifier, accessLevel, superMethod, true);
if (info != null) return info;
info = checkSuperMethodIsFinal(method, superMethod);
if (info != null) return info;
}
return null;
}
private static HighlightInfo checkInterfaceInheritedMethodsReturnTypes(@NotNull List<? extends MethodSignatureBackedByPsiMethod> superMethodSignatures,
@NotNull LanguageLevel languageLevel) {
if (superMethodSignatures.size() < 2) return null;
MethodSignatureBackedByPsiMethod returnTypeSubstitutable = superMethodSignatures.get(0);
for (int i = 1; i < superMethodSignatures.size(); i++) {
PsiMethod currentMethod = returnTypeSubstitutable.getMethod();
PsiType currentType = returnTypeSubstitutable.getSubstitutor().substitute(currentMethod.getReturnType());
MethodSignatureBackedByPsiMethod otherSuperSignature = superMethodSignatures.get(i);
PsiMethod otherSuperMethod = otherSuperSignature.getMethod();
PsiType otherSuperReturnType = otherSuperSignature.getSubstitutor().substitute(otherSuperMethod.getReturnType());
PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(returnTypeSubstitutable,
otherSuperSignature);
if (unifyingSubstitutor != null) {
otherSuperReturnType = unifyingSubstitutor.substitute(otherSuperReturnType);
currentType = unifyingSubstitutor.substitute(currentType);
}
if (otherSuperReturnType == null || currentType == null || otherSuperReturnType.equals(currentType)) continue;
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) {
//http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8 Example 8.1.5-3
if (!(otherSuperReturnType instanceof PsiPrimitiveType || currentType instanceof PsiPrimitiveType)) {
if (otherSuperReturnType.isAssignableFrom(currentType)) continue;
if (currentType.isAssignableFrom(otherSuperReturnType)) {
returnTypeSubstitutable = otherSuperSignature;
continue;
}
}
if (otherSuperMethod.getTypeParameters().length > 0 && JavaGenericsUtil.isRawToGeneric(currentType, otherSuperReturnType)) continue;
}
return createIncompatibleReturnTypeMessage(otherSuperMethod, currentMethod, currentType, otherSuperReturnType,
JavaErrorMessages.message("unrelated.overriding.methods.return.types"), TextRange.EMPTY_RANGE);
}
return null;
}
static HighlightInfo checkOverrideEquivalentInheritedMethods(PsiClass aClass, PsiFile containingFile, @NotNull LanguageLevel languageLevel) {
String description = null;
final Collection<HierarchicalMethodSignature> visibleSignatures = aClass.getVisibleSignatures();
PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(aClass.getProject()).getResolveHelper();
Ultimate:
for (HierarchicalMethodSignature signature : visibleSignatures) {
PsiMethod method = signature.getMethod();
if (!resolveHelper.isAccessible(method, aClass, null)) continue;
List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures();
boolean allAbstracts = method.hasModifierProperty(PsiModifier.ABSTRACT);
final PsiClass containingClass = method.getContainingClass();
if (aClass.equals(containingClass)) continue; //to be checked at method level
if (aClass.isInterface() && !containingClass.isInterface()) continue;
HighlightInfo highlightInfo;
if (allAbstracts) {
superSignatures = new ArrayList<HierarchicalMethodSignature>(superSignatures);
superSignatures.add(0, signature);
highlightInfo = checkInterfaceInheritedMethodsReturnTypes(superSignatures, languageLevel);
}
else {
highlightInfo = checkMethodIncompatibleReturnType(signature, superSignatures, false);
}
if (highlightInfo != null) description = highlightInfo.getDescription();
if (method.hasModifierProperty(PsiModifier.STATIC)) {
for (HierarchicalMethodSignature superSignature : superSignatures) {
PsiMethod superMethod = superSignature.getMethod();
if (!superMethod.hasModifierProperty(PsiModifier.STATIC)) {
description = JavaErrorMessages.message("static.method.cannot.override.instance.method",
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(containingClass),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superMethod.getContainingClass()));
break Ultimate;
}
}
continue;
}
if (description == null) {
highlightInfo = checkMethodIncompatibleThrows(signature, superSignatures, false, aClass);
if (highlightInfo != null) description = highlightInfo.getDescription();
}
if (description == null) {
highlightInfo = checkMethodWeakerPrivileges(signature, superSignatures, false, containingFile);
if (highlightInfo != null) description = highlightInfo.getDescription();
}
if (description != null) break;
}
if (description != null) {
// show error info at the class level
TextRange textRange = HighlightNamesUtil.getClassDeclarationTextRange(aClass);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
}
return null;
}
static HighlightInfo checkConstructorHandleSuperClassExceptions(PsiMethod method) {
if (!method.isConstructor()) {
return null;
}
PsiCodeBlock body = method.getBody();
PsiStatement[] statements = body == null ? null : body.getStatements();
if (statements == null) return null;
// if we have unhandled exception inside method body, we could not have been called here,
// so the only problem it can catch here is with super ctr only
Collection<PsiClassType> unhandled = ExceptionUtil.collectUnhandledExceptions(method, method.getContainingClass());
if (unhandled.isEmpty()) return null;
String description = HighlightUtil.getUnhandledExceptionsDescriptor(unhandled);
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
for (PsiClassType exception : unhandled) {
QuickFixAction.registerQuickFixAction(highlightInfo, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(method, exception, true, false)));
}
return highlightInfo;
}
static HighlightInfo checkRecursiveConstructorInvocation(@NotNull PsiMethod method) {
if (HighlightControlFlowUtil.isRecursivelyCalledConstructor(method)) {
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
String description = JavaErrorMessages.message("recursive.constructor.invocation");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
}
return null;
}
@NotNull
public static TextRange getFixRange(@NotNull PsiElement element) {
TextRange range = element.getTextRange();
int start = range.getStartOffset();
int end = range.getEndOffset();
PsiElement nextSibling = element.getNextSibling();
if (nextSibling instanceof PsiJavaToken && ((PsiJavaToken)nextSibling).getTokenType() == JavaTokenType.SEMICOLON) {
return new TextRange(start, end + 1);
}
return range;
}
static void checkNewExpression(@NotNull PsiNewExpression expression,
PsiType type,
@NotNull HighlightInfoHolder holder,
@NotNull JavaSdkVersion javaSdkVersion) {
if (!(type instanceof PsiClassType)) return;
PsiClassType.ClassResolveResult typeResult = ((PsiClassType)type).resolveGenerics();
PsiClass aClass = typeResult.getElement();
if (aClass == null) return;
if (aClass instanceof PsiAnonymousClass) {
type = ((PsiAnonymousClass)aClass).getBaseClassType();
typeResult = ((PsiClassType)type).resolveGenerics();
aClass = typeResult.getElement();
if (aClass == null) return;
}
PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference();
checkConstructorCall(typeResult, expression, type, classReference, holder, javaSdkVersion);
}
static void checkConstructorCall(@NotNull PsiClassType.ClassResolveResult typeResolveResult,
@NotNull PsiConstructorCall constructorCall,
@NotNull PsiType type,
PsiJavaCodeReferenceElement classReference,
@NotNull HighlightInfoHolder holder,
@NotNull JavaSdkVersion javaSdkVersion) {
PsiExpressionList list = constructorCall.getArgumentList();
if (list == null) return;
PsiClass aClass = typeResolveResult.getElement();
if (aClass == null) return;
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(holder.getProject()).getResolveHelper();
PsiClass accessObjectClass = null;
if (constructorCall instanceof PsiNewExpression) {
PsiExpression qualifier = ((PsiNewExpression)constructorCall).getQualifier();
if (qualifier != null) {
accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement();
}
}
if (classReference != null && !resolveHelper.isAccessible(aClass, constructorCall, accessObjectClass)) {
String description = HighlightUtil.buildProblemWithAccessDescription(classReference, typeResolveResult);
PsiElement element = classReference.getReferenceNameElement();
HighlightInfo info =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
HighlightUtil.registerAccessQuickFixAction(aClass, classReference, info, null);
holder.add(info);
return;
}
PsiMethod[] constructors = aClass.getConstructors();
if (constructors.length == 0) {
if (list.getExpressions().length != 0) {
String constructorName = aClass.getName();
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.constructor.arguments", constructorName+"()", argTypes);
String tooltip = createMismatchedArgumentsHtmlTooltip(list, null, PsiParameter.EMPTY_ARRAY, constructorName, PsiSubstitutor.EMPTY, aClass);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).description(description).escapedToolTip(tooltip).navigationShift(+1).create();
QuickFixAction.registerQuickFixAction(info, constructorCall.getTextRange(), QUICK_FIX_FACTORY.createCreateConstructorFromCallFix(constructorCall));
if (classReference != null) {
ConstructorParametersFixer.registerFixActions(classReference, constructorCall, info,getFixRange(list));
}
holder.add(info);
return;
}
if (classReference != null && aClass.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass)) {
holder.add(buildAccessProblem(classReference, typeResolveResult, aClass));
} else if (aClass.isInterface() && constructorCall instanceof PsiNewExpression) {
final PsiReferenceParameterList typeArgumentList = ((PsiNewExpression)constructorCall).getTypeArgumentList();
if (typeArgumentList.getTypeArguments().length > 0) {
holder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeArgumentList)
.descriptionAndTooltip("Anonymous class implements interface; cannot have type arguments").create());
}
}
}
else {
PsiElement place = list;
if (constructorCall instanceof PsiNewExpression) {
final PsiAnonymousClass anonymousClass = ((PsiNewExpression)constructorCall).getAnonymousClass();
if (anonymousClass != null) place = anonymousClass;
}
JavaResolveResult[] results = resolveHelper.multiResolveConstructor((PsiClassType)type, list, place);
MethodCandidateInfo result = null;
if (results.length == 1) result = (MethodCandidateInfo)results[0];
PsiMethod constructor = result == null ? null : result.getElement();
boolean applicable = true;
try {
applicable = constructor != null && result.isApplicable();
}
catch (IndexNotReadyException e) {
// ignore
}
PsiElement infoElement = list.getTextLength() > 0 ? list : constructorCall;
if (constructor == null) {
String name = aClass.getName();
name += buildArgTypesList(list);
String description = JavaErrorMessages.message("cannot.resolve.constructor", name);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).descriptionAndTooltip(description).navigationShift(+1).create();
WrapExpressionFix.registerWrapAction(results, list.getExpressions(), info);
registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, results, infoElement, info);
holder.add(info);
}
else {
if (classReference != null && (!result.isAccessible() ||
constructor.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass))) {
holder.add(buildAccessProblem(classReference, result, constructor));
}
else if (!applicable) {
String constructorName = HighlightMessageUtil.getSymbolName(constructor, result.getSubstitutor());
String containerName = HighlightMessageUtil.getSymbolName(constructor.getContainingClass(), result.getSubstitutor());
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.method.arguments", constructorName, containerName, argTypes);
String toolTip = createMismatchedArgumentsHtmlTooltip(result, list);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(infoElement).description(description).escapedToolTip(toolTip).navigationShift(+1).create();
if (info != null) {
registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, results, infoElement, info);
registerMethodReturnFixAction(info, result, constructorCall);
holder.add(info);
}
}
else {
if (constructorCall instanceof PsiNewExpression) {
PsiReferenceParameterList typeArgumentList = ((PsiNewExpression)constructorCall).getTypeArgumentList();
HighlightInfo info = GenericsHighlightUtil.checkReferenceTypeArgumentList(constructor, typeArgumentList, result.getSubstitutor(), false, javaSdkVersion);
if (info != null) {
holder.add(info);
}
}
}
}
if (result != null && !holder.hasErrorResults()) {
holder.add(checkVarargParameterErasureToBeAccessible(result, constructorCall));
}
}
}
/**
* If the compile-time declaration is applicable by variable arity invocation,
* then where the last formal parameter type of the invocation type of the method is Fn[],
* it is a compile-time error if the type which is the erasure of Fn is not accessible at the point of invocation.
*/
private static HighlightInfo checkVarargParameterErasureToBeAccessible(MethodCandidateInfo info, PsiCall place) {
final PsiMethod method = info.getElement();
if (info.isVarargs() || method.isVarArgs() && !PsiUtil.isLanguageLevel8OrHigher(place)) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiType componentType = ((PsiEllipsisType)parameters[parameters.length - 1].getType()).getComponentType();
final PsiType substitutedTypeErasure = TypeConversionUtil.erasure(info.getSubstitutor().substitute(componentType));
final PsiClass targetClass = PsiUtil.resolveClassInClassTypeOnly(substitutedTypeErasure);
if (targetClass != null && !PsiUtil.isAccessible(targetClass, place, null)) {
final PsiExpressionList argumentList = place.getArgumentList();
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
.descriptionAndTooltip("Formal varargs element type " +
PsiFormatUtil.formatClass(targetClass, PsiFormatUtilBase.SHOW_FQ_NAME) +
" is inaccessible here")
.range(argumentList != null ? argumentList : place)
.create();
}
}
return null;
}
private static void registerFixesOnInvalidConstructorCall(PsiConstructorCall constructorCall,
PsiJavaCodeReferenceElement classReference,
PsiExpressionList list,
PsiClass aClass,
PsiMethod[] constructors,
JavaResolveResult[] results, PsiElement infoElement, HighlightInfo info) {
QuickFixAction
.registerQuickFixAction(info, constructorCall.getTextRange(), QUICK_FIX_FACTORY.createCreateConstructorFromCallFix(constructorCall));
if (classReference != null) {
ConstructorParametersFixer.registerFixActions(classReference, constructorCall, info, getFixRange(infoElement));
ChangeTypeArgumentsFix.registerIntentions(results, list, info, aClass);
ConvertDoubleToFloatFix.registerIntentions(results, list, info, null);
}
registerChangeMethodSignatureFromUsageIntentions(results, list, info, null);
PermuteArgumentsFix.registerFix(info, constructorCall, toMethodCandidates(results), getFixRange(list));
registerChangeParameterClassFix(constructorCall, list, info);
QuickFixAction.registerQuickFixAction(info, getFixRange(list), QUICK_FIX_FACTORY.createSurroundWithArrayFix(constructorCall,null));
ChangeStringLiteralToCharInMethodCallFix.registerFixes(constructors, constructorCall, info);
}
private static HighlightInfo buildAccessProblem(@NotNull PsiJavaCodeReferenceElement classReference, JavaResolveResult result, PsiMember elementToFix) {
String description = HighlightUtil.buildProblemWithAccessDescription(classReference, result);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(classReference).descriptionAndTooltip(
description).navigationShift(+1).create();
if (result.isStaticsScopeCorrect()) {
HighlightUtil.registerAccessQuickFixAction(elementToFix, classReference, info, result.getCurrentFileResolveScope());
}
return info;
}
private static boolean callingProtectedConstructorFromDerivedClass(PsiConstructorCall place, PsiClass constructorClass) {
if (constructorClass == null) return false;
// indirect instantiation via anonymous class is ok
if (place instanceof PsiNewExpression && ((PsiNewExpression)place).getAnonymousClass() != null) return false;
PsiElement curElement = place;
PsiClass containingClass = constructorClass.getContainingClass();
while (true) {
PsiClass aClass = PsiTreeUtil.getParentOfType(curElement, PsiClass.class);
if (aClass == null) return false;
curElement = aClass;
if ((aClass.isInheritor(constructorClass, true) || containingClass != null && aClass.isInheritor(containingClass, true))
&& !JavaPsiFacade.getInstance(aClass.getProject()).arePackagesTheSame(aClass, constructorClass)) {
return true;
}
}
}
private static String buildArgTypesList(PsiExpressionList list) {
StringBuilder builder = new StringBuilder();
builder.append("(");
PsiExpression[] args = list.getExpressions();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
builder.append(", ");
}
PsiType argType = args[i].getType();
builder.append(argType != null ? JavaHighlightUtil.formatType(argType) : "?");
}
builder.append(")");
return builder.toString();
}
private static void registerChangeParameterClassFix(@NotNull PsiCall methodCall,
@NotNull PsiExpressionList list,
HighlightInfo highlightInfo) {
final JavaResolveResult result = methodCall.resolveMethodGenerics();
PsiMethod method = (PsiMethod)result.getElement();
final PsiSubstitutor substitutor = result.getSubstitutor();
PsiExpression[] expressions = list.getExpressions();
if (method == null) return;
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length != expressions.length) return;
for (int i = 0; i < expressions.length; i++) {
final PsiExpression expression = expressions[i];
final PsiParameter parameter = parameters[i];
final PsiType expressionType = expression.getType();
final PsiType parameterType = substitutor.substitute(parameter.getType());
if (expressionType == null || expressionType instanceof PsiPrimitiveType || TypeConversionUtil.isNullType(expressionType) || expressionType instanceof PsiArrayType) continue;
if (parameterType instanceof PsiPrimitiveType || TypeConversionUtil.isNullType(parameterType) || parameterType instanceof PsiArrayType) continue;
if (parameterType.isAssignableFrom(expressionType)) continue;
PsiClass parameterClass = PsiUtil.resolveClassInType(parameterType);
PsiClass expressionClass = PsiUtil.resolveClassInType(expressionType);
if (parameterClass == null || expressionClass == null) continue;
if (expressionClass instanceof PsiAnonymousClass) continue;
if (parameterClass.isInheritor(expressionClass, true)) continue;
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createChangeParameterClassFix(expressionClass, (PsiClassType)parameterType));
}
}
private static void registerChangeMethodSignatureFromUsageIntentions(@NotNull JavaResolveResult[] candidates,
@NotNull PsiExpressionList list,
@Nullable HighlightInfo highlightInfo,
TextRange fixRange) {
if (candidates.length == 0) return;
PsiExpression[] expressions = list.getExpressions();
for (JavaResolveResult candidate : candidates) {
registerChangeMethodSignatureFromUsageIntention(expressions, highlightInfo, fixRange, candidate, list);
}
}
private static void registerChangeMethodSignatureFromUsageIntention(@NotNull PsiExpression[] expressions,
@Nullable HighlightInfo highlightInfo,
TextRange fixRange,
@NotNull JavaResolveResult candidate,
@NotNull PsiElement context) {
if (!candidate.isStaticsScopeCorrect()) return;
PsiMethod method = (PsiMethod)candidate.getElement();
PsiSubstitutor substitutor = candidate.getSubstitutor();
if (method != null && context.getManager().isInProject(method)) {
IntentionAction fix = QUICK_FIX_FACTORY.createChangeMethodSignatureFromUsageFix(method, expressions, substitutor, context, false, 2);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, fix);
IntentionAction f2 = QUICK_FIX_FACTORY.createChangeMethodSignatureFromUsageReverseOrderFix(method, expressions, substitutor, context,
false, 2);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, f2);
}
}
}
|
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.analysis;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.daemon.DaemonBundle;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.quickfix.*;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.codeInspection.LocalQuickFixOnPsiElementAsIntentionAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.*;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.ui.ColorUtil;
import com.intellij.util.containers.MostlySingularMultiMap;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Highlight method problems
*
* @author cdr
* Date: Aug 14, 2002
*/
public class HighlightMethodUtil {
private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance();
private static final String MISMATCH_COLOR = UIUtil.isUnderDarcula() ? "ff6464" : "red";
private HighlightMethodUtil() { }
static String createClashMethodMessage(PsiMethod method1, PsiMethod method2, boolean showContainingClasses) {
@NonNls String pattern = showContainingClasses ? "clash.methods.message.show.classes" : "clash.methods.message";
return JavaErrorMessages.message(pattern,
JavaHighlightUtil.formatMethod(method1),
JavaHighlightUtil.formatMethod(method2),
HighlightUtil.formatClass(method1.getContainingClass()),
HighlightUtil.formatClass(method2.getContainingClass()));
}
static HighlightInfo checkMethodWeakerPrivileges(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo,
@NotNull PsiFile containingFile) {
PsiMethod method = methodSignature.getMethod();
PsiModifierList modifierList = method.getModifierList();
if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) return null;
int accessLevel = PsiUtil.getAccessLevel(modifierList);
String accessModifier = PsiUtil.getAccessModifier(accessLevel);
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
if (method.hasModifierProperty(PsiModifier.ABSTRACT) && !MethodSignatureUtil.isSuperMethod(superMethod, method)) continue;
if (!PsiUtil.isAccessible(containingFile.getProject(), superMethod, method, null)) continue;
if (!includeRealPositionInfo && MethodSignatureUtil.isSuperMethod(superMethod, method)) continue;
HighlightInfo info = isWeaker(method, modifierList, accessModifier, accessLevel, superMethod, includeRealPositionInfo);
if (info != null) return info;
}
return null;
}
private static HighlightInfo isWeaker(final PsiMethod method, final PsiModifierList modifierList, final String accessModifier, final int accessLevel,
final PsiMethod superMethod,
final boolean includeRealPositionInfo) {
int superAccessLevel = PsiUtil.getAccessLevel(superMethod.getModifierList());
if (accessLevel < superAccessLevel) {
String description = JavaErrorMessages.message("weaker.privileges",
createClashMethodMessage(method, superMethod, true),
accessModifier,
PsiUtil.getAccessModifier(superAccessLevel));
TextRange textRange;
if (includeRealPositionInfo) {
if (modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
textRange = method.getNameIdentifier().getTextRange();
}
else {
PsiElement keyword = PsiUtil.findModifierInList(modifierList, accessModifier);
textRange = keyword.getTextRange();
}
}
else {
textRange = TextRange.EMPTY_RANGE;
}
HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(highlightInfo,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiUtil.getAccessModifier(superAccessLevel), true, false));
return highlightInfo;
}
return null;
}
static HighlightInfo checkMethodIncompatibleReturnType(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo) {
return checkMethodIncompatibleReturnType(methodSignature, superMethodSignatures, includeRealPositionInfo, null);
}
static HighlightInfo checkMethodIncompatibleReturnType(@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo,
@Nullable TextRange textRange) {
PsiMethod method = methodSignature.getMethod();
PsiType returnType = methodSignature.getSubstitutor().substitute(method.getReturnType());
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
PsiType declaredReturnType = superMethod.getReturnType();
PsiType superReturnType = declaredReturnType;
if (superMethodSignature.isRaw()) superReturnType = TypeConversionUtil.erasure(declaredReturnType);
if (returnType == null || superReturnType == null || method == superMethod) continue;
PsiClass superClass = superMethod.getContainingClass();
if (superClass == null) continue;
TextRange toHighlight = textRange != null ? textRange
: includeRealPositionInfo ? method.getReturnTypeElement().getTextRange() : TextRange.EMPTY_RANGE;
HighlightInfo highlightInfo = checkSuperMethodSignature(superMethod, superMethodSignature, superReturnType, method, methodSignature,
returnType, JavaErrorMessages.message("incompatible.return.type"),
toHighlight, PsiUtil.getLanguageLevel(aClass));
if (highlightInfo != null) return highlightInfo;
}
return null;
}
private static HighlightInfo checkSuperMethodSignature(@NotNull PsiMethod superMethod,
@NotNull MethodSignatureBackedByPsiMethod superMethodSignature,
PsiType superReturnType,
@NotNull PsiMethod method,
@NotNull MethodSignatureBackedByPsiMethod methodSignature,
@NotNull PsiType returnType,
@NotNull String detailMessage,
@NotNull TextRange range,
@NotNull LanguageLevel languageLevel) {
if (superReturnType == null) return null;
if ("clone".equals(method.getName())) {
final PsiClass containingClass = method.getContainingClass();
final PsiClass superContainingClass = superMethod.getContainingClass();
if (containingClass != null && superContainingClass != null && containingClass.isInterface() && !superContainingClass.isInterface()) {
return null;
}
}
PsiType substitutedSuperReturnType;
final boolean isJdk15 = languageLevel.isAtLeast(LanguageLevel.JDK_1_5);
if (isJdk15 && !superMethodSignature.isRaw() && superMethodSignature.equals(methodSignature)) { //see 8.4.5
PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature,
superMethodSignature);
substitutedSuperReturnType = unifyingSubstitutor == null
? superReturnType
: unifyingSubstitutor.substitute(superReturnType);
}
else {
substitutedSuperReturnType = TypeConversionUtil.erasure(superMethodSignature.getSubstitutor().substitute(superReturnType));
}
if (returnType.equals(substitutedSuperReturnType)) return null;
if (!(returnType instanceof PsiPrimitiveType) && substitutedSuperReturnType.getDeepComponentType() instanceof PsiClassType) {
if (isJdk15 && TypeConversionUtil.isAssignable(substitutedSuperReturnType, returnType)) {
return null;
}
}
return createIncompatibleReturnTypeMessage(method, superMethod, substitutedSuperReturnType, returnType, detailMessage, range);
}
private static HighlightInfo createIncompatibleReturnTypeMessage(@NotNull PsiMethod method,
@NotNull PsiMethod superMethod,
@NotNull PsiType substitutedSuperReturnType,
@NotNull PsiType returnType,
@NotNull String detailMessage,
@NotNull TextRange textRange) {
String description = MessageFormat.format("{0}; {1}", createClashMethodMessage(method, superMethod, true), detailMessage);
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(
description).create();
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createMethodReturnFix(method, substitutedSuperReturnType, false));
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createSuperMethodReturnFix(superMethod, returnType));
return errorResult;
}
static HighlightInfo checkMethodOverridesFinal(MethodSignatureBackedByPsiMethod methodSignature,
List<HierarchicalMethodSignature> superMethodSignatures) {
PsiMethod method = methodSignature.getMethod();
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
HighlightInfo info = checkSuperMethodIsFinal(method, superMethod);
if (info != null) return info;
}
return null;
}
private static HighlightInfo checkSuperMethodIsFinal(PsiMethod method, PsiMethod superMethod) {
// strange things happen when super method is from Object and method from interface
if (superMethod.hasModifierProperty(PsiModifier.FINAL)) {
String description = JavaErrorMessages.message("final.method.override",
JavaHighlightUtil.formatMethod(method),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superMethod.getContainingClass()));
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(superMethod, PsiModifier.FINAL, false, true));
return errorResult;
}
return null;
}
static HighlightInfo checkMethodIncompatibleThrows(MethodSignatureBackedByPsiMethod methodSignature,
List<HierarchicalMethodSignature> superMethodSignatures,
boolean includeRealPositionInfo, PsiClass analyzedClass) {
PsiMethod method = methodSignature.getMethod();
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(aClass, analyzedClass, PsiSubstitutor.EMPTY);
PsiClassType[] exceptions = method.getThrowsList().getReferencedTypes();
PsiJavaCodeReferenceElement[] referenceElements;
List<PsiElement> exceptionContexts;
if (includeRealPositionInfo) {
exceptionContexts = new ArrayList<PsiElement>();
referenceElements = method.getThrowsList().getReferenceElements();
}
else {
exceptionContexts = null;
referenceElements = null;
}
List<PsiClassType> checkedExceptions = new ArrayList<PsiClassType>();
for (int i = 0; i < exceptions.length; i++) {
PsiClassType exception = exceptions[i];
if (!ExceptionUtil.isUncheckedException(exception)) {
checkedExceptions.add(exception);
if (includeRealPositionInfo && i < referenceElements.length) {
PsiJavaCodeReferenceElement exceptionRef = referenceElements[i];
exceptionContexts.add(exceptionRef);
}
}
}
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
int index = getExtraExceptionNum(methodSignature, superMethodSignature, checkedExceptions, superSubstitutor);
if (index != -1) {
if (aClass.isInterface()) {
final PsiClass superContainingClass = superMethod.getContainingClass();
if (superContainingClass != null && !superContainingClass.isInterface()) continue;
if (superContainingClass != null && !aClass.isInheritor(superContainingClass, true)) continue;
}
PsiClassType exception = checkedExceptions.get(index);
String description = JavaErrorMessages.message("overridden.method.does.not.throw",
createClashMethodMessage(method, superMethod, true),
JavaHighlightUtil.formatType(exception));
TextRange textRange;
if (includeRealPositionInfo) {
PsiElement exceptionContext = exceptionContexts.get(index);
textRange = exceptionContext.getTextRange();
}
else {
textRange = TextRange.EMPTY_RANGE;
}
HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
QuickFixAction.registerQuickFixAction(errorResult, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(method, exception, false, false)));
QuickFixAction.registerQuickFixAction(errorResult, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(superMethod, exception, true, true)));
return errorResult;
}
}
return null;
}
// return number of exception which was not declared in super method or -1
private static int getExtraExceptionNum(final MethodSignature methodSignature,
final MethodSignatureBackedByPsiMethod superSignature,
List<PsiClassType> checkedExceptions, PsiSubstitutor substitutorForDerivedClass) {
PsiMethod superMethod = superSignature.getMethod();
PsiSubstitutor substitutorForMethod = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature, superSignature);
for (int i = 0; i < checkedExceptions.size(); i++) {
final PsiClassType checkedEx = checkedExceptions.get(i);
final PsiType substituted = substitutorForMethod != null ? substitutorForMethod.substitute(checkedEx) : TypeConversionUtil.erasure(checkedEx);
PsiType exception = substitutorForDerivedClass.substitute(substituted);
if (!isMethodThrows(superMethod, substitutorForMethod, exception, substitutorForDerivedClass)) {
return i;
}
}
return -1;
}
private static boolean isMethodThrows(PsiMethod method, @Nullable PsiSubstitutor substitutorForMethod, PsiType exception, PsiSubstitutor substitutorForDerivedClass) {
PsiClassType[] thrownExceptions = method.getThrowsList().getReferencedTypes();
for (PsiClassType thrownException1 : thrownExceptions) {
PsiType thrownException = substitutorForMethod != null ? substitutorForMethod.substitute(thrownException1) : TypeConversionUtil.erasure(thrownException1);
thrownException = substitutorForDerivedClass.substitute(thrownException);
if (TypeConversionUtil.isAssignable(thrownException, exception)) return true;
}
return false;
}
@Nullable
static HighlightInfo checkMethodCall(@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper,
@NotNull LanguageLevel languageLevel,
@NotNull JavaSdkVersion javaSdkVersion) {
PsiExpressionList list = methodCall.getArgumentList();
PsiReferenceExpression referenceToMethod = methodCall.getMethodExpression();
JavaResolveResult[] results = referenceToMethod.multiResolve(true);
JavaResolveResult resolveResult = results.length == 1 ? results[0] : JavaResolveResult.EMPTY;
PsiElement resolved = resolveResult.getElement();
boolean isDummy = isDummyConstructorCall(methodCall, resolveHelper, list, referenceToMethod);
if (isDummy) return null;
HighlightInfo highlightInfo;
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
if (resolved instanceof PsiMethod && resolveResult.isValidResult()) {
TextRange fixRange = getFixRange(methodCall);
highlightInfo = HighlightUtil.checkUnhandledExceptions(methodCall, fixRange);
if (highlightInfo == null) {
final String invalidCallMessage =
LambdaUtil.getInvalidQualifier4StaticInterfaceMethodMessage((PsiMethod)resolved, methodCall.getMethodExpression(), resolveResult.getCurrentFileResolveScope(), languageLevel);
if (invalidCallMessage != null) {
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).descriptionAndTooltip(invalidCallMessage).range(fixRange).create();
if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createIncreaseLanguageLevelFix(LanguageLevel.JDK_1_8));
}
} else {
highlightInfo = GenericsHighlightUtil.checkInferredIntersections(substitutor, fixRange);
}
if (highlightInfo == null) {
highlightInfo = checkVarargParameterErasureToBeAccessible((MethodCandidateInfo)resolveResult, methodCall);
}
if (highlightInfo == null && resolveResult instanceof MethodCandidateInfo) {
final String errorMessage = ((MethodCandidateInfo)resolveResult).getInferenceErrorMessage();
if (errorMessage != null) {
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).descriptionAndTooltip(errorMessage).range(fixRange).create();
if (highlightInfo != null) {
registerMethodCallIntentions(highlightInfo, methodCall, list, resolveHelper);
registerMethodReturnFixAction(highlightInfo, (MethodCandidateInfo)resolveResult, methodCall);
}
}
}
}
}
else {
PsiMethod resolvedMethod = null;
MethodCandidateInfo candidateInfo = null;
if (resolveResult instanceof MethodCandidateInfo) {
candidateInfo = (MethodCandidateInfo)resolveResult;
resolvedMethod = candidateInfo.getElement();
}
if (!resolveResult.isAccessible() || !resolveResult.isStaticsScopeCorrect()) {
highlightInfo = null;
}
else if (candidateInfo != null && !candidateInfo.isApplicable()) {
if (candidateInfo.isTypeArgumentsApplicable()) {
String methodName = HighlightMessageUtil.getSymbolName(resolved, substitutor);
PsiElement parent = resolved.getParent();
String containerName = parent == null ? "" : HighlightMessageUtil.getSymbolName(parent, substitutor);
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.method.arguments", methodName, containerName, argTypes);
final Ref<PsiElement> elementToHighlight = new Ref<PsiElement>(list);
String toolTip;
if (parent instanceof PsiClass && !ApplicationManager.getApplication().isUnitTestMode()) {
toolTip = buildOneLineMismatchDescription(list, candidateInfo, elementToHighlight);
if (toolTip == null) {
toolTip = createMismatchedArgumentsHtmlTooltip(candidateInfo, list);
}
}
else {
toolTip = description;
}
PsiElement element = elementToHighlight.get();
int navigationShift = element instanceof PsiExpressionList ? +1 : 0; // argument list starts with paren which there is no need to highlight
highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element)
.description(description).escapedToolTip(toolTip).navigationShift(navigationShift).create();
if (highlightInfo != null) {
registerMethodCallIntentions(highlightInfo, methodCall, list, resolveHelper);
registerMethodReturnFixAction(highlightInfo, candidateInfo, methodCall);
}
}
else {
PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
PsiReferenceParameterList typeArgumentList = methodCall.getTypeArgumentList();
if (typeArgumentList.getTypeArguments().length == 0 && resolvedMethod.hasTypeParameters()) {
highlightInfo = GenericsHighlightUtil.checkInferredTypeArguments(resolvedMethod, methodCall, substitutor);
}
else {
highlightInfo = GenericsHighlightUtil.checkParameterizedReferenceTypeArguments(resolved, methodExpression, substitutor, javaSdkVersion);
}
}
}
else {
String description = JavaErrorMessages.message("method.call.expected");
highlightInfo =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCall).descriptionAndTooltip(description).create();
if (resolved instanceof PsiClass) {
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createInsertNewFix(methodCall, (PsiClass)resolved));
}
else {
TextRange range = getFixRange(methodCall);
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreateMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreateAbstractMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, range, QUICK_FIX_FACTORY.createCreatePropertyFromUsageFix(methodCall));
}
}
}
if (highlightInfo == null) {
highlightInfo = GenericsHighlightUtil.checkParameterizedReferenceTypeArguments(resolved, referenceToMethod, substitutor,
javaSdkVersion);
}
return highlightInfo;
}
private static void registerMethodReturnFixAction(HighlightInfo highlightInfo,
MethodCandidateInfo candidate,
PsiCall methodCall) {
if (methodCall.getParent() instanceof PsiReturnStatement) {
final PsiMethod containerMethod = PsiTreeUtil.getParentOfType(methodCall, PsiMethod.class, true, PsiLambdaExpression.class);
if (containerMethod != null) {
final PsiMethod method = candidate.getElement();
final PsiExpression methodCallCopy =
JavaPsiFacade.getElementFactory(method.getProject()).createExpressionFromText(methodCall.getText(), methodCall);
PsiType methodCallTypeByArgs = methodCallCopy.getType();
//ensure type params are not included
methodCallTypeByArgs = JavaPsiFacade.getElementFactory(method.getProject())
.createRawSubstitutor(method).substitute(methodCallTypeByArgs);
QuickFixAction.registerQuickFixAction(highlightInfo,
getFixRange(methodCall),
QUICK_FIX_FACTORY.createMethodReturnFix(containerMethod, methodCallTypeByArgs, true));
}
}
}
private static String buildOneLineMismatchDescription(@NotNull PsiExpressionList list,
@NotNull MethodCandidateInfo candidateInfo,
@NotNull Ref<PsiElement> elementToHighlight) {
final PsiExpression[] expressions = list.getExpressions();
final PsiMethod resolvedMethod = candidateInfo.getElement();
final PsiSubstitutor substitutor = candidateInfo.getSubstitutor();
final PsiParameter[] parameters = resolvedMethod.getParameterList().getParameters();
if (expressions.length == parameters.length && parameters.length > 1) {
int idx = -1;
for (int i = 0; i < expressions.length; i++) {
PsiExpression expression = expressions[i];
if (!TypeConversionUtil.areTypesAssignmentCompatible(substitutor.substitute(parameters[i].getType()), expression)) {
if (idx != -1) {
idx = -1;
break;
}
else {
idx = i;
}
}
}
if (idx > -1) {
final PsiExpression wrongArg = expressions[idx];
final PsiType argType = wrongArg.getType();
if (argType != null) {
elementToHighlight.set(wrongArg);
final String message = JavaErrorMessages
.message("incompatible.call.types", idx + 1, substitutor.substitute(parameters[idx].getType()).getCanonicalText(), argType.getCanonicalText());
return XmlStringUtil.wrapInHtml("<body>" + XmlStringUtil.escapeString(message) +
" <a href=\"#assignment/" + XmlStringUtil.escapeString(createMismatchedArgumentsHtmlTooltip(candidateInfo, list)) + "\"" +
(UIUtil.isUnderDarcula() ? " color=\"7AB4C9\" " : "") +
">" + DaemonBundle.message("inspection.extended.description") + "</a></body>");
}
}
}
return null;
}
static boolean isDummyConstructorCall(PsiMethodCallExpression methodCall,
PsiResolveHelper resolveHelper,
PsiExpressionList list,
PsiReferenceExpression referenceToMethod) {
boolean isDummy = false;
boolean isThisOrSuper = referenceToMethod.getReferenceNameElement() instanceof PsiKeyword;
if (isThisOrSuper) {
// super(..) or this(..)
if (list.getExpressions().length == 0) { // implicit ctr call
CandidateInfo[] candidates = resolveHelper.getReferencedMethodCandidates(methodCall, true);
if (candidates.length == 1 && !candidates[0].getElement().isPhysical()) {
isDummy = true;// dummy constructor
}
}
}
return isDummy;
}
@Nullable
static HighlightInfo checkAmbiguousMethodCallIdentifier(@NotNull PsiReferenceExpression referenceToMethod,
@NotNull JavaResolveResult[] resolveResults,
@NotNull PsiExpressionList list,
final PsiElement element,
@NotNull JavaResolveResult resolveResult,
@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper) {
MethodCandidateInfo methodCandidate1 = null;
MethodCandidateInfo methodCandidate2 = null;
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isApplicable() && !candidate.getElement().isConstructor()) {
if (methodCandidate1 == null) {
methodCandidate1 = candidate;
}
else {
methodCandidate2 = candidate;
break;
}
}
}
MethodCandidateInfo[] candidates = toMethodCandidates(resolveResults);
HighlightInfoType highlightInfoType = HighlightInfoType.ERROR;
if (methodCandidate2 != null) {
return null;
}
String description;
PsiElement elementToHighlight;
if (element != null && !resolveResult.isAccessible()) {
description = HighlightUtil.buildProblemWithAccessDescription(referenceToMethod, resolveResult);
elementToHighlight = referenceToMethod.getReferenceNameElement();
}
else if (element != null && !resolveResult.isStaticsScopeCorrect()) {
final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(referenceToMethod);
final String staticInterfaceMethodMessage =
element instanceof PsiMethod
? LambdaUtil.getInvalidQualifier4StaticInterfaceMethodMessage((PsiMethod)element, referenceToMethod,
resolveResult.getCurrentFileResolveScope(), languageLevel)
: null;
description = staticInterfaceMethodMessage != null
? staticInterfaceMethodMessage
: HighlightUtil.buildProblemWithStaticDescription(element);
elementToHighlight = referenceToMethod.getReferenceNameElement();
}
else {
String methodName = referenceToMethod.getReferenceName() + buildArgTypesList(list);
description = JavaErrorMessages.message("cannot.resolve.method", methodName);
if (candidates.length == 0) {
elementToHighlight = referenceToMethod.getReferenceNameElement();
highlightInfoType = HighlightInfoType.WRONG_REF;
}
else {
return null;
}
}
String toolTip = XmlStringUtil.escapeString(description);
HighlightInfo info =
HighlightInfo.newHighlightInfo(highlightInfoType).range(elementToHighlight).description(description).escapedToolTip(toolTip).create();
registerMethodCallIntentions(info, methodCall, list, resolveHelper);
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
HighlightUtil.registerStaticProblemQuickFixAction(element, info, referenceToMethod);
}
TextRange fixRange = getFixRange(elementToHighlight);
CastMethodArgumentFix.REGISTRAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
PermuteArgumentsFix.registerFix(info, methodCall, candidates, fixRange);
WrapExpressionFix.registerWrapAction(candidates, list.getExpressions(), info);
registerChangeParameterClassFix(methodCall, list, info);
return info;
}
@Nullable
static HighlightInfo checkAmbiguousMethodCallArguments(@NotNull PsiReferenceExpression referenceToMethod,
@NotNull JavaResolveResult[] resolveResults,
@NotNull PsiExpressionList list,
final PsiElement element,
@NotNull JavaResolveResult resolveResult,
@NotNull PsiMethodCallExpression methodCall,
@NotNull PsiResolveHelper resolveHelper,
@NotNull PsiElement elementToHighlight) {
MethodCandidateInfo methodCandidate1 = null;
MethodCandidateInfo methodCandidate2 = null;
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isApplicable() && !candidate.getElement().isConstructor()) {
if (methodCandidate1 == null) {
methodCandidate1 = candidate;
}
else {
methodCandidate2 = candidate;
break;
}
}
}
MethodCandidateInfo[] candidates = toMethodCandidates(resolveResults);
String description;
String toolTip;
HighlightInfoType highlightInfoType = HighlightInfoType.ERROR;
if (methodCandidate2 != null) {
PsiMethod element1 = methodCandidate1.getElement();
String m1 = PsiFormatUtil.formatMethod(element1,
methodCandidate1.getSubstitutor(),
PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
PsiMethod element2 = methodCandidate2.getElement();
String m2 = PsiFormatUtil.formatMethod(element2,
methodCandidate2.getSubstitutor(),
PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
VirtualFile virtualFile1 = PsiUtilCore.getVirtualFile(element1);
VirtualFile virtualFile2 = PsiUtilCore.getVirtualFile(element2);
if (!Comparing.equal(virtualFile1, virtualFile2)) {
if (virtualFile1 != null) m1 += " (In " + virtualFile1.getPresentableUrl() + ")";
if (virtualFile2 != null) m2 += " (In " + virtualFile2.getPresentableUrl() + ")";
}
description = JavaErrorMessages.message("ambiguous.method.call", m1, m2);
toolTip = createAmbiguousMethodHtmlTooltip(new MethodCandidateInfo[]{methodCandidate1, methodCandidate2});
}
else {
if (element != null && !resolveResult.isAccessible()) {
return null;
}
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
return null;
}
String methodName = referenceToMethod.getReferenceName() + buildArgTypesList(list);
description = JavaErrorMessages.message("cannot.resolve.method", methodName);
if (candidates.length == 0) {
return null;
}
toolTip = XmlStringUtil.escapeString(description);
}
HighlightInfo info =
HighlightInfo.newHighlightInfo(highlightInfoType).range(elementToHighlight).description(description).escapedToolTip(toolTip).create();
if (methodCandidate2 == null) {
registerMethodCallIntentions(info, methodCall, list, resolveHelper);
}
if (!resolveResult.isAccessible() && resolveResult.isStaticsScopeCorrect() && methodCandidate2 != null) {
HighlightUtil.registerAccessQuickFixAction((PsiMember)element, referenceToMethod, info, resolveResult.getCurrentFileResolveScope());
}
if (element != null && !resolveResult.isStaticsScopeCorrect()) {
HighlightUtil.registerStaticProblemQuickFixAction(element, info, referenceToMethod);
}
TextRange fixRange = getFixRange(elementToHighlight);
CastMethodArgumentFix.REGISTRAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(candidates, methodCall, info, fixRange);
PermuteArgumentsFix.registerFix(info, methodCall, candidates, fixRange);
WrapExpressionFix.registerWrapAction(candidates, list.getExpressions(), info);
registerChangeParameterClassFix(methodCall, list, info);
return info;
}
@NotNull
private static MethodCandidateInfo[] toMethodCandidates(@NotNull JavaResolveResult[] resolveResults) {
List<MethodCandidateInfo> candidateList = new ArrayList<MethodCandidateInfo>(resolveResults.length);
for (JavaResolveResult result : resolveResults) {
if (!(result instanceof MethodCandidateInfo)) continue;
MethodCandidateInfo candidate = (MethodCandidateInfo)result;
if (candidate.isAccessible()) candidateList.add(candidate);
}
return candidateList.toArray(new MethodCandidateInfo[candidateList.size()]);
}
private static void registerMethodCallIntentions(@Nullable HighlightInfo highlightInfo,
PsiMethodCallExpression methodCall,
PsiExpressionList list,
PsiResolveHelper resolveHelper) {
TextRange fixRange = getFixRange(methodCall);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateAbstractMethodFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateConstructorFromSuperFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateConstructorFromThisFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreatePropertyFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createCreateGetterSetterPropertyFromUsageFix(methodCall));
CandidateInfo[] methodCandidates = resolveHelper.getReferencedMethodCandidates(methodCall, false);
CastMethodArgumentFix.REGISTRAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
PermuteArgumentsFix.registerFix(highlightInfo, methodCall, methodCandidates, fixRange);
AddTypeArgumentsFix.REGISTRAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
WrapArrayToArraysAsListFix.REGISTAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
WrapLongWithMathToIntExactFix.REGISTAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
registerMethodAccessLevelIntentions(methodCandidates, methodCall, list, highlightInfo);
registerChangeMethodSignatureFromUsageIntentions(methodCandidates, list, highlightInfo, fixRange);
RemoveRedundantArgumentsFix.registerIntentions(methodCandidates, list, highlightInfo, fixRange);
ConvertDoubleToFloatFix.registerIntentions(methodCandidates, list, highlightInfo, fixRange);
WrapExpressionFix.registerWrapAction(methodCandidates, list.getExpressions(), highlightInfo);
registerChangeParameterClassFix(methodCall, list, highlightInfo);
if (methodCandidates.length == 0) {
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createStaticImportMethodFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.addMethodQualifierFix(methodCall));
}
for (IntentionAction action : QUICK_FIX_FACTORY.getVariableTypeFromCallFixes(methodCall, list)) {
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, action);
}
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createReplaceAddAllArrayToCollectionFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, QUICK_FIX_FACTORY.createSurroundWithArrayFix(methodCall, null));
QualifyThisArgumentFix.registerQuickFixAction(methodCandidates, methodCall, highlightInfo, fixRange);
CandidateInfo[] candidates = resolveHelper.getReferencedMethodCandidates(methodCall, true);
ChangeStringLiteralToCharInMethodCallFix.registerFixes(candidates, methodCall, highlightInfo);
}
private static void registerMethodAccessLevelIntentions(CandidateInfo[] methodCandidates,
PsiMethodCallExpression methodCall,
PsiExpressionList exprList,
HighlightInfo highlightInfo) {
for (CandidateInfo methodCandidate : methodCandidates) {
PsiMethod method = (PsiMethod)methodCandidate.getElement();
if (!methodCandidate.isAccessible() && PsiUtil.isApplicable(method, methodCandidate.getSubstitutor(), exprList)) {
HighlightUtil.registerAccessQuickFixAction(method, methodCall.getMethodExpression(), highlightInfo, methodCandidate.getCurrentFileResolveScope());
}
}
}
@NotNull
private static String createAmbiguousMethodHtmlTooltip(MethodCandidateInfo[] methodCandidates) {
return JavaErrorMessages.message("ambiguous.method.html.tooltip",
Integer.valueOf(methodCandidates[0].getElement().getParameterList().getParametersCount() + 2),
createAmbiguousMethodHtmlTooltipMethodRow(methodCandidates[0]),
getContainingClassName(methodCandidates[0]),
createAmbiguousMethodHtmlTooltipMethodRow(methodCandidates[1]),
getContainingClassName(methodCandidates[1]));
}
private static String getContainingClassName(final MethodCandidateInfo methodCandidate) {
PsiMethod method = methodCandidate.getElement();
PsiClass containingClass = method.getContainingClass();
return containingClass == null ? method.getContainingFile().getName() : HighlightUtil.formatClass(containingClass, false);
}
@Language("HTML")
private static String createAmbiguousMethodHtmlTooltipMethodRow(final MethodCandidateInfo methodCandidate) {
PsiMethod method = methodCandidate.getElement();
PsiParameter[] parameters = method.getParameterList().getParameters();
PsiSubstitutor substitutor = methodCandidate.getSubstitutor();
@NonNls @Language("HTML") String ms = "<td><b>" + method.getName() + "</b></td>";
for (int j = 0; j < parameters.length; j++) {
PsiParameter parameter = parameters[j];
PsiType type = substitutor.substitute(parameter.getType());
ms += "<td><b>" + (j == 0 ? "(" : "") +
XmlStringUtil.escapeString(type.getPresentableText())
+ (j == parameters.length - 1 ? ")" : ",") + "</b></td>";
}
if (parameters.length == 0) {
ms += "<td><b>()</b></td>";
}
return ms;
}
private static String createMismatchedArgumentsHtmlTooltip(MethodCandidateInfo info, PsiExpressionList list) {
PsiMethod method = info.getElement();
PsiSubstitutor substitutor = info.getSubstitutor();
PsiClass aClass = method.getContainingClass();
PsiParameter[] parameters = method.getParameterList().getParameters();
String methodName = method.getName();
return createMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass);
}
private static String createShortMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
@Nullable MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
PsiExpression[] expressions = list.getExpressions();
int cols = Math.max(parameters.length, expressions.length);
@Language("HTML")
@NonNls String parensizedName = methodName + (parameters.length == 0 ? "( ) " : "");
final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
return JavaErrorMessages.message(
"argument.mismatch.html.tooltip",
Integer.valueOf(cols - parameters.length + 1), parensizedName,
HighlightUtil.formatClass(aClass, false),
createMismatchedArgsHtmlTooltipParamsRow(parameters, substitutor, expressions),
createMismatchedArgsHtmlTooltipArgumentsRow(expressions, parameters, substitutor, cols),
errorMessage != null ? "<br/>reason: " + XmlStringUtil.escapeString(errorMessage).replaceAll("\n", "<br/>") : ""
);
}
private static String esctrim(@NotNull String s) {
return XmlStringUtil.escapeString(trimNicely(s));
}
private static String trimNicely(String s) {
if (s.length() <= 40) return s;
List<TextRange> wordIndices = StringUtil.getWordIndicesIn(s);
if (wordIndices.size() > 2) {
int firstWordEnd = wordIndices.get(0).getEndOffset();
// try firstWord...remainder
for (int i = 1; i<wordIndices.size();i++) {
int stringLength = firstWordEnd + s.length() - wordIndices.get(i).getStartOffset();
if (stringLength <= 40) {
return s.substring(0, firstWordEnd) + "..." + s.substring(wordIndices.get(i).getStartOffset());
}
}
}
// maybe one last word will fit?
if (!wordIndices.isEmpty() && s.length() - wordIndices.get(wordIndices.size()-1).getStartOffset() <= 40) {
return "..." + s.substring(wordIndices.get(wordIndices.size()-1).getStartOffset());
}
return StringUtil.last(s, 40, true).toString();
}
private static String createMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
return Math.max(parameters.length, list.getExpressions().length) <= 2
? createShortMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass)
: createLongMismatchedArgumentsHtmlTooltip(list, info, parameters, methodName, substitutor, aClass);
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createLongMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
@Nullable MethodCandidateInfo info,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
PsiExpression[] expressions = list.getExpressions();
@SuppressWarnings("NonConstantStringShouldBeStringBuffer") @NonNls
String s = "<html><body><table border=0>" +
"<tr><td colspan=3>" +
"<nobr><b>" + methodName + "()</b> in <b>" + HighlightUtil.formatClass(aClass, false) +"</b> cannot be applied to:</nobr>" +
"</td></tr>"+
"<tr><td colspan=2 align=left>Expected<br>Parameters:</td><td align=left>Actual<br>Arguments:</td></tr>"+
"<tr><td colspan=3><hr></td></tr>"
;
for (int i = 0; i < Math.max(parameters.length,expressions.length); i++) {
PsiParameter parameter = i < parameters.length ? parameters[i] : null;
PsiExpression expression = i < expressions.length ? expressions[i] : null;
boolean showShort = showShortType(i, parameters, expressions, substitutor);
@NonNls String mismatchColor = showShort ? null : UIUtil.isUnderDarcula() ? "FF6B68" : "red";
s += "<tr" + (i % 2 == 0 ? " style='background-color: #"
+ (UIUtil.isUnderDarcula() ? ColorUtil.toHex(ColorUtil.shift(UIUtil.getToolTipBackground(), 1.1)) : "eeeeee")
+ "'" : "") + ">";
s += "<td><b><nobr>";
if (parameter != null) {
String name = parameter.getName();
if (name != null) {
s += esctrim(name) +":";
}
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (parameter != null) {
PsiType type = substitutor.substitute(parameter.getType());
s += "<font " + (mismatchColor == null ? "" : "color=" + mismatchColor) + ">" +
esctrim(showShort ? type.getPresentableText() : JavaHighlightUtil.formatType(type))
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (expression != null) {
PsiType type = expression.getType();
s += "<font " + (mismatchColor == null ? "" : "color='" + mismatchColor + "'") + ">" +
esctrim(expression.getText()) + " "+
(mismatchColor == null || type == null || type == PsiType.NULL ? "" : "("+esctrim(JavaHighlightUtil.formatType(type))+")")
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "</tr>";
}
s+= "</table>";
final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
if (errorMessage != null) {
s+= "reason: ";
s += XmlStringUtil.escapeString(errorMessage).replaceAll("\n", "<br/>");
}
s+= "</body></html>";
return s;
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createMismatchedArgsHtmlTooltipArgumentsRow(final PsiExpression[] expressions, final PsiParameter[] parameters,
final PsiSubstitutor substitutor, final int cols) {
@Language("HTML")
@NonNls String ms = "";
for (int i = 0; i < expressions.length; i++) {
PsiExpression expression = expressions[i];
PsiType type = expression.getType();
boolean showShort = showShortType(i, parameters, expressions, substitutor);
@NonNls String mismatchColor = showShort ? null : MISMATCH_COLOR;
ms += "<td> " + "<b><nobr>" + (i == 0 ? "(" : "")
+ "<font " + (showShort ? "" : "color=" + mismatchColor) + ">" +
XmlStringUtil.escapeString(showShort ? type.getPresentableText() : JavaHighlightUtil.formatType(type))
+ "</font>"
+ (i == expressions.length - 1 ? ")" : ",") + "</nobr></b></td>";
}
for (int i = expressions.length; i < cols + 1; i++) {
ms += "<td>" + (i == 0 ? "<b>()</b>" : "") +
" </td>";
}
return ms;
}
@SuppressWarnings("StringContatenationInLoop")
@Language("HTML")
private static String createMismatchedArgsHtmlTooltipParamsRow(final PsiParameter[] parameters,
final PsiSubstitutor substitutor,
final PsiExpression[] expressions) {
@NonNls String ms = "";
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
PsiType type = substitutor.substitute(parameter.getType());
ms += "<td><b><nobr>" + (i == 0 ? "(" : "") +
XmlStringUtil.escapeString(showShortType(i, parameters, expressions, substitutor)
? type.getPresentableText()
: JavaHighlightUtil.formatType(type))
+ (i == parameters.length - 1 ? ")" : ",") + "</nobr></b></td>";
}
return ms;
}
private static boolean showShortType(int i,
PsiParameter[] parameters,
PsiExpression[] expressions,
PsiSubstitutor substitutor) {
PsiExpression expression = i < expressions.length ? expressions[i] : null;
if (expression == null) return true;
PsiType paramType = i < parameters.length && parameters[i] != null
? substitutor.substitute(parameters[i].getType())
: null;
PsiType expressionType = expression.getType();
return paramType != null && expressionType != null && TypeConversionUtil.isAssignable(paramType, expressionType);
}
static HighlightInfo checkMethodMustHaveBody(PsiMethod method, PsiClass aClass) {
HighlightInfo errorResult = null;
if (method.getBody() == null
&& !method.hasModifierProperty(PsiModifier.ABSTRACT)
&& !method.hasModifierProperty(PsiModifier.NATIVE)
&& aClass != null
&& !aClass.isInterface()
&& !PsiUtilCore.hasErrorElementChild(method)) {
int start = method.getModifierList().getTextRange().getStartOffset();
int end = method.getTextRange().getEndOffset();
String description = JavaErrorMessages.message("missing.method.body");
errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(start, end).descriptionAndTooltip(description).create();
if (HighlightUtil.getIncompatibleModifier(PsiModifier.ABSTRACT, method.getModifierList()) == null) {
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, true, false));
}
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
}
return errorResult;
}
static HighlightInfo checkAbstractMethodInConcreteClass(PsiMethod method, PsiElement elementToHighlight) {
HighlightInfo errorResult = null;
PsiClass aClass = method.getContainingClass();
if (method.hasModifierProperty(PsiModifier.ABSTRACT)
&& aClass != null
&& !aClass.hasModifierProperty(PsiModifier.ABSTRACT)
&& !aClass.isEnum()
&& !PsiUtilCore.hasErrorElementChild(method)) {
String description = JavaErrorMessages.message("abstract.method.in.non.abstract.class");
errorResult =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(elementToHighlight).descriptionAndTooltip(description).create();
if (method.getBody() != null) {
QuickFixAction.registerQuickFixAction(errorResult,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false));
}
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createModifierListFix(aClass, PsiModifier.ABSTRACT, true, false));
}
return errorResult;
}
static HighlightInfo checkConstructorName(PsiMethod method) {
String methodName = method.getName();
PsiClass aClass = method.getContainingClass();
HighlightInfo errorResult = null;
if (aClass != null) {
String className = aClass instanceof PsiAnonymousClass ? null : aClass.getName();
if (className == null || !Comparing.strEqual(methodName, className)) {
PsiElement element = method.getNameIdentifier();
String description = JavaErrorMessages.message("missing.return.type");
errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
if (className != null) {
QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createRenameElementFix(method, className));
}
}
}
return errorResult;
}
@Nullable
static HighlightInfo checkDuplicateMethod(PsiClass aClass,
@NotNull PsiMethod method,
@NotNull MostlySingularMultiMap<MethodSignature, PsiMethod> duplicateMethods) {
if (aClass == null || method instanceof ExternallyDefinedPsiElement) return null;
MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
int methodCount = 1;
List<PsiMethod> methods = (List<PsiMethod>)duplicateMethods.get(methodSignature);
if (methods.size() > 1) {
methodCount++;
}
if (methodCount == 1 && aClass.isEnum() &&
GenericsHighlightUtil.isEnumSyntheticMethod(methodSignature, aClass.getProject())) {
methodCount++;
}
if (methodCount > 1) {
String description = JavaErrorMessages.message("duplicate.method",
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(aClass));
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).
range(method, textRange.getStartOffset(), textRange.getEndOffset()).
descriptionAndTooltip(description).create();
}
return null;
}
@Nullable
static HighlightInfo checkMethodCanHaveBody(@NotNull PsiMethod method, @NotNull LanguageLevel languageLevel) {
PsiClass aClass = method.getContainingClass();
boolean hasNoBody = method.getBody() == null;
boolean isInterface = aClass != null && aClass.isInterface();
boolean isExtension = method.hasModifierProperty(PsiModifier.DEFAULT);
boolean isStatic = method.hasModifierProperty(PsiModifier.STATIC);
boolean isPrivate = method.hasModifierProperty(PsiModifier.PRIVATE);
final List<IntentionAction> additionalFixes = new ArrayList<IntentionAction>();
String description = null;
if (hasNoBody) {
if (isExtension) {
description = JavaErrorMessages.message("extension.method.should.have.a.body");
additionalFixes.add(QUICK_FIX_FACTORY.createAddMethodBodyFix(method));
}
else if (isInterface && isStatic && languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
description = "Static methods in interfaces should have a body";
}
}
else if (isInterface) {
if (!isExtension && !isStatic && !isPrivate) {
description = JavaErrorMessages.message("interface.methods.cannot.have.body");
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
additionalFixes.add(QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.DEFAULT, true, false));
additionalFixes.add(QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.STATIC, true, false));
}
}
}
else if (isExtension) {
description = JavaErrorMessages.message("extension.method.in.class");
}
else if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
description = JavaErrorMessages.message("abstract.methods.cannot.have.a.body");
}
else if (method.hasModifierProperty(PsiModifier.NATIVE)) {
description = JavaErrorMessages.message("native.methods.cannot.have.a.body");
}
if (description == null) return null;
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
if (!hasNoBody) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createDeleteMethodBodyFix(method));
}
if (method.hasModifierProperty(PsiModifier.ABSTRACT) && !isInterface) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false));
}
for (IntentionAction intentionAction : additionalFixes) {
QuickFixAction.registerQuickFixAction(info, intentionAction);
}
return info;
}
@Nullable
static HighlightInfo checkConstructorCallMustBeFirstStatement(@NotNull PsiMethodCallExpression methodCall) {
if (!RefactoringChangeUtil.isSuperOrThisMethodCall(methodCall)) return null;
PsiElement codeBlock = methodCall.getParent().getParent();
if (codeBlock instanceof PsiCodeBlock
&& codeBlock.getParent() instanceof PsiMethod
&& ((PsiMethod)codeBlock.getParent()).isConstructor()) {
PsiElement prevSibling = methodCall.getParent().getPrevSibling();
while (true) {
if (prevSibling == null) return null;
if (prevSibling instanceof PsiStatement) break;
prevSibling = prevSibling.getPrevSibling();
}
}
PsiReferenceExpression expression = methodCall.getMethodExpression();
String message = JavaErrorMessages.message("constructor.call.must.be.first.statement", expression.getText() + "()");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCall).descriptionAndTooltip(message).create();
}
static HighlightInfo checkSuperAbstractMethodDirectCall(@NotNull PsiMethodCallExpression methodCallExpression) {
PsiReferenceExpression expression = methodCallExpression.getMethodExpression();
if (!(expression.getQualifierExpression() instanceof PsiSuperExpression)) return null;
PsiMethod method = methodCallExpression.resolveMethod();
if (method != null && method.hasModifierProperty(PsiModifier.ABSTRACT)) {
String message = JavaErrorMessages.message("direct.abstract.method.access", JavaHighlightUtil.formatMethod(method));
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(methodCallExpression).descriptionAndTooltip(message).create();
}
return null;
}
static HighlightInfo checkConstructorCallsBaseClassConstructor(PsiMethod constructor,
RefCountHolder refCountHolder,
PsiResolveHelper resolveHelper) {
if (!constructor.isConstructor()) return null;
PsiClass aClass = constructor.getContainingClass();
if (aClass == null) return null;
if (aClass.isEnum()) return null;
PsiCodeBlock body = constructor.getBody();
if (body == null) return null;
// check whether constructor call super(...) or this(...)
PsiElement element = new PsiMatcherImpl(body)
.firstChild(PsiMatchers.hasClass(PsiExpressionStatement.class))
.firstChild(PsiMatchers.hasClass(PsiMethodCallExpression.class))
.firstChild(PsiMatchers.hasClass(PsiReferenceExpression.class))
.firstChild(PsiMatchers.hasClass(PsiKeyword.class))
.getElement();
if (element != null) return null;
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(constructor);
PsiClassType[] handledExceptions = constructor.getThrowsList().getReferencedTypes();
HighlightInfo info = HighlightClassUtil.checkBaseClassDefaultConstructorProblem(aClass, refCountHolder, resolveHelper, textRange, handledExceptions);
if (info != null) {
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createInsertSuperFix(constructor));
QuickFixAction.registerQuickFixAction(info, QUICK_FIX_FACTORY.createAddDefaultConstructorFix(aClass.getSuperClass()));
}
return info;
}
/**
* @return error if static method overrides instance method or
* instance method overrides static. see JLS 8.4.6.1, 8.4.6.2
*/
static HighlightInfo checkStaticMethodOverride(@NotNull PsiMethod method,@NotNull PsiFile containingFile) {
// constructors are not members and therefor don't override class methods
if (method.isConstructor()) {
return null;
}
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
final HierarchicalMethodSignature methodSignature = PsiSuperMethodImplUtil.getHierarchicalMethodSignature(method);
final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures();
if (superSignatures.isEmpty()) {
return null;
}
boolean isStatic = method.hasModifierProperty(PsiModifier.STATIC);
for (HierarchicalMethodSignature signature : superSignatures) {
final PsiMethod superMethod = signature.getMethod();
final PsiClass superClass = superMethod.getContainingClass();
if (superClass == null) continue;
final HighlightInfo highlightInfo = checkStaticMethodOverride(aClass, method, isStatic, superClass, superMethod,containingFile);
if (highlightInfo != null) {
return highlightInfo;
}
}
return null;
}
private static HighlightInfo checkStaticMethodOverride(PsiClass aClass, PsiMethod method, boolean isMethodStatic, PsiClass superClass, PsiMethod superMethod,@NotNull PsiFile containingFile) {
if (superMethod == null) return null;
PsiManager manager = containingFile.getManager();
PsiModifierList superModifierList = superMethod.getModifierList();
PsiModifierList modifierList = method.getModifierList();
if (superModifierList.hasModifierProperty(PsiModifier.PRIVATE)) return null;
if (superModifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)
&& !JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(aClass, superClass)) {
return null;
}
boolean isSuperMethodStatic = superModifierList.hasModifierProperty(PsiModifier.STATIC);
if (isMethodStatic != isSuperMethodStatic) {
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
@NonNls final String messageKey = isMethodStatic
? "static.method.cannot.override.instance.method"
: "instance.method.cannot.override.static.method";
String description = JavaErrorMessages.message(messageKey,
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(aClass),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superClass));
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
if (!isSuperMethodStatic || HighlightUtil.getIncompatibleModifier(PsiModifier.STATIC, modifierList) == null) {
QuickFixAction.registerQuickFixAction(info,
QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.STATIC, isSuperMethodStatic, false));
}
if (manager.isInProject(superMethod) &&
(!isMethodStatic || HighlightUtil.getIncompatibleModifier(PsiModifier.STATIC, superModifierList) == null)) {
QuickFixAction.registerQuickFixAction(info,
QUICK_FIX_FACTORY.createModifierListFix(superMethod, PsiModifier.STATIC, isMethodStatic, true));
}
return info;
}
if (isMethodStatic) {
if (superClass.isInterface()) return null;
int accessLevel = PsiUtil.getAccessLevel(modifierList);
String accessModifier = PsiUtil.getAccessModifier(accessLevel);
HighlightInfo info = isWeaker(method, modifierList, accessModifier, accessLevel, superMethod, true);
if (info != null) return info;
info = checkSuperMethodIsFinal(method, superMethod);
if (info != null) return info;
}
return null;
}
private static HighlightInfo checkInterfaceInheritedMethodsReturnTypes(@NotNull List<? extends MethodSignatureBackedByPsiMethod> superMethodSignatures,
@NotNull LanguageLevel languageLevel) {
if (superMethodSignatures.size() < 2) return null;
MethodSignatureBackedByPsiMethod returnTypeSubstitutable = superMethodSignatures.get(0);
for (int i = 1; i < superMethodSignatures.size(); i++) {
PsiMethod currentMethod = returnTypeSubstitutable.getMethod();
PsiType currentType = returnTypeSubstitutable.getSubstitutor().substitute(currentMethod.getReturnType());
MethodSignatureBackedByPsiMethod otherSuperSignature = superMethodSignatures.get(i);
PsiMethod otherSuperMethod = otherSuperSignature.getMethod();
PsiType otherSuperReturnType = otherSuperSignature.getSubstitutor().substitute(otherSuperMethod.getReturnType());
PsiSubstitutor unifyingSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(returnTypeSubstitutable,
otherSuperSignature);
if (unifyingSubstitutor != null) {
otherSuperReturnType = unifyingSubstitutor.substitute(otherSuperReturnType);
currentType = unifyingSubstitutor.substitute(currentType);
}
if (otherSuperReturnType == null || currentType == null || otherSuperReturnType.equals(currentType)) continue;
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) {
//http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8 Example 8.1.5-3
if (!(otherSuperReturnType instanceof PsiPrimitiveType || currentType instanceof PsiPrimitiveType)) {
if (otherSuperReturnType.isAssignableFrom(currentType)) continue;
if (currentType.isAssignableFrom(otherSuperReturnType)) {
returnTypeSubstitutable = otherSuperSignature;
continue;
}
}
if (currentMethod.getTypeParameters().length > 0 && JavaGenericsUtil.isRawToGeneric(currentType, otherSuperReturnType)) continue;
}
return createIncompatibleReturnTypeMessage(otherSuperMethod, currentMethod, currentType, otherSuperReturnType,
JavaErrorMessages.message("unrelated.overriding.methods.return.types"), TextRange.EMPTY_RANGE);
}
return null;
}
static HighlightInfo checkOverrideEquivalentInheritedMethods(PsiClass aClass, PsiFile containingFile, @NotNull LanguageLevel languageLevel) {
String description = null;
final Collection<HierarchicalMethodSignature> visibleSignatures = aClass.getVisibleSignatures();
PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(aClass.getProject()).getResolveHelper();
Ultimate:
for (HierarchicalMethodSignature signature : visibleSignatures) {
PsiMethod method = signature.getMethod();
if (!resolveHelper.isAccessible(method, aClass, null)) continue;
List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures();
boolean allAbstracts = method.hasModifierProperty(PsiModifier.ABSTRACT);
final PsiClass containingClass = method.getContainingClass();
if (aClass.equals(containingClass)) continue; //to be checked at method level
if (aClass.isInterface() && !containingClass.isInterface()) continue;
HighlightInfo highlightInfo;
if (allAbstracts) {
superSignatures = new ArrayList<HierarchicalMethodSignature>(superSignatures);
superSignatures.add(0, signature);
highlightInfo = checkInterfaceInheritedMethodsReturnTypes(superSignatures, languageLevel);
}
else {
highlightInfo = checkMethodIncompatibleReturnType(signature, superSignatures, false);
}
if (highlightInfo != null) description = highlightInfo.getDescription();
if (method.hasModifierProperty(PsiModifier.STATIC)) {
for (HierarchicalMethodSignature superSignature : superSignatures) {
PsiMethod superMethod = superSignature.getMethod();
if (!superMethod.hasModifierProperty(PsiModifier.STATIC)) {
description = JavaErrorMessages.message("static.method.cannot.override.instance.method",
JavaHighlightUtil.formatMethod(method),
HighlightUtil.formatClass(containingClass),
JavaHighlightUtil.formatMethod(superMethod),
HighlightUtil.formatClass(superMethod.getContainingClass()));
break Ultimate;
}
}
continue;
}
if (description == null) {
highlightInfo = checkMethodIncompatibleThrows(signature, superSignatures, false, aClass);
if (highlightInfo != null) description = highlightInfo.getDescription();
}
if (description == null) {
highlightInfo = checkMethodWeakerPrivileges(signature, superSignatures, false, containingFile);
if (highlightInfo != null) description = highlightInfo.getDescription();
}
if (description != null) break;
}
if (description != null) {
// show error info at the class level
TextRange textRange = HighlightNamesUtil.getClassDeclarationTextRange(aClass);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
}
return null;
}
static HighlightInfo checkConstructorHandleSuperClassExceptions(PsiMethod method) {
if (!method.isConstructor()) {
return null;
}
PsiCodeBlock body = method.getBody();
PsiStatement[] statements = body == null ? null : body.getStatements();
if (statements == null) return null;
// if we have unhandled exception inside method body, we could not have been called here,
// so the only problem it can catch here is with super ctr only
Collection<PsiClassType> unhandled = ExceptionUtil.collectUnhandledExceptions(method, method.getContainingClass());
if (unhandled.isEmpty()) return null;
String description = HighlightUtil.getUnhandledExceptionsDescriptor(unhandled);
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
for (PsiClassType exception : unhandled) {
QuickFixAction.registerQuickFixAction(highlightInfo, new LocalQuickFixOnPsiElementAsIntentionAdapter(QUICK_FIX_FACTORY.createMethodThrowsFix(method, exception, true, false)));
}
return highlightInfo;
}
static HighlightInfo checkRecursiveConstructorInvocation(@NotNull PsiMethod method) {
if (HighlightControlFlowUtil.isRecursivelyCalledConstructor(method)) {
TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method);
String description = JavaErrorMessages.message("recursive.constructor.invocation");
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create();
}
return null;
}
@NotNull
public static TextRange getFixRange(@NotNull PsiElement element) {
TextRange range = element.getTextRange();
int start = range.getStartOffset();
int end = range.getEndOffset();
PsiElement nextSibling = element.getNextSibling();
if (nextSibling instanceof PsiJavaToken && ((PsiJavaToken)nextSibling).getTokenType() == JavaTokenType.SEMICOLON) {
return new TextRange(start, end + 1);
}
return range;
}
static void checkNewExpression(@NotNull PsiNewExpression expression,
PsiType type,
@NotNull HighlightInfoHolder holder,
@NotNull JavaSdkVersion javaSdkVersion) {
if (!(type instanceof PsiClassType)) return;
PsiClassType.ClassResolveResult typeResult = ((PsiClassType)type).resolveGenerics();
PsiClass aClass = typeResult.getElement();
if (aClass == null) return;
if (aClass instanceof PsiAnonymousClass) {
type = ((PsiAnonymousClass)aClass).getBaseClassType();
typeResult = ((PsiClassType)type).resolveGenerics();
aClass = typeResult.getElement();
if (aClass == null) return;
}
PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference();
checkConstructorCall(typeResult, expression, type, classReference, holder, javaSdkVersion);
}
static void checkConstructorCall(@NotNull PsiClassType.ClassResolveResult typeResolveResult,
@NotNull PsiConstructorCall constructorCall,
@NotNull PsiType type,
PsiJavaCodeReferenceElement classReference,
@NotNull HighlightInfoHolder holder,
@NotNull JavaSdkVersion javaSdkVersion) {
PsiExpressionList list = constructorCall.getArgumentList();
if (list == null) return;
PsiClass aClass = typeResolveResult.getElement();
if (aClass == null) return;
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(holder.getProject()).getResolveHelper();
PsiClass accessObjectClass = null;
if (constructorCall instanceof PsiNewExpression) {
PsiExpression qualifier = ((PsiNewExpression)constructorCall).getQualifier();
if (qualifier != null) {
accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement();
}
}
if (classReference != null && !resolveHelper.isAccessible(aClass, constructorCall, accessObjectClass)) {
String description = HighlightUtil.buildProblemWithAccessDescription(classReference, typeResolveResult);
PsiElement element = classReference.getReferenceNameElement();
HighlightInfo info =
HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create();
HighlightUtil.registerAccessQuickFixAction(aClass, classReference, info, null);
holder.add(info);
return;
}
PsiMethod[] constructors = aClass.getConstructors();
if (constructors.length == 0) {
if (list.getExpressions().length != 0) {
String constructorName = aClass.getName();
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.constructor.arguments", constructorName+"()", argTypes);
String tooltip = createMismatchedArgumentsHtmlTooltip(list, null, PsiParameter.EMPTY_ARRAY, constructorName, PsiSubstitutor.EMPTY, aClass);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).description(description).escapedToolTip(tooltip).navigationShift(+1).create();
QuickFixAction.registerQuickFixAction(info, constructorCall.getTextRange(), QUICK_FIX_FACTORY.createCreateConstructorFromCallFix(constructorCall));
if (classReference != null) {
ConstructorParametersFixer.registerFixActions(classReference, constructorCall, info,getFixRange(list));
}
holder.add(info);
return;
}
if (classReference != null && aClass.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass)) {
holder.add(buildAccessProblem(classReference, typeResolveResult, aClass));
} else if (aClass.isInterface() && constructorCall instanceof PsiNewExpression) {
final PsiReferenceParameterList typeArgumentList = ((PsiNewExpression)constructorCall).getTypeArgumentList();
if (typeArgumentList.getTypeArguments().length > 0) {
holder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeArgumentList)
.descriptionAndTooltip("Anonymous class implements interface; cannot have type arguments").create());
}
}
}
else {
PsiElement place = list;
if (constructorCall instanceof PsiNewExpression) {
final PsiAnonymousClass anonymousClass = ((PsiNewExpression)constructorCall).getAnonymousClass();
if (anonymousClass != null) place = anonymousClass;
}
JavaResolveResult[] results = resolveHelper.multiResolveConstructor((PsiClassType)type, list, place);
MethodCandidateInfo result = null;
if (results.length == 1) result = (MethodCandidateInfo)results[0];
PsiMethod constructor = result == null ? null : result.getElement();
boolean applicable = true;
try {
applicable = constructor != null && result.isApplicable();
}
catch (IndexNotReadyException e) {
// ignore
}
PsiElement infoElement = list.getTextLength() > 0 ? list : constructorCall;
if (constructor == null) {
String name = aClass.getName();
name += buildArgTypesList(list);
String description = JavaErrorMessages.message("cannot.resolve.constructor", name);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(list).descriptionAndTooltip(description).navigationShift(+1).create();
WrapExpressionFix.registerWrapAction(results, list.getExpressions(), info);
registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, results, infoElement, info);
holder.add(info);
}
else {
if (classReference != null && (!result.isAccessible() ||
constructor.hasModifierProperty(PsiModifier.PROTECTED) && callingProtectedConstructorFromDerivedClass(constructorCall, aClass))) {
holder.add(buildAccessProblem(classReference, result, constructor));
}
else if (!applicable) {
String constructorName = HighlightMessageUtil.getSymbolName(constructor, result.getSubstitutor());
String containerName = HighlightMessageUtil.getSymbolName(constructor.getContainingClass(), result.getSubstitutor());
String argTypes = buildArgTypesList(list);
String description = JavaErrorMessages.message("wrong.method.arguments", constructorName, containerName, argTypes);
String toolTip = createMismatchedArgumentsHtmlTooltip(result, list);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(infoElement).description(description).escapedToolTip(toolTip).navigationShift(+1).create();
if (info != null) {
registerFixesOnInvalidConstructorCall(constructorCall, classReference, list, aClass, constructors, results, infoElement, info);
registerMethodReturnFixAction(info, result, constructorCall);
holder.add(info);
}
}
else {
if (constructorCall instanceof PsiNewExpression) {
PsiReferenceParameterList typeArgumentList = ((PsiNewExpression)constructorCall).getTypeArgumentList();
HighlightInfo info = GenericsHighlightUtil.checkReferenceTypeArgumentList(constructor, typeArgumentList, result.getSubstitutor(), false, javaSdkVersion);
if (info != null) {
holder.add(info);
}
}
}
}
if (result != null && !holder.hasErrorResults()) {
holder.add(checkVarargParameterErasureToBeAccessible(result, constructorCall));
}
}
}
/**
* If the compile-time declaration is applicable by variable arity invocation,
* then where the last formal parameter type of the invocation type of the method is Fn[],
* it is a compile-time error if the type which is the erasure of Fn is not accessible at the point of invocation.
*/
private static HighlightInfo checkVarargParameterErasureToBeAccessible(MethodCandidateInfo info, PsiCall place) {
final PsiMethod method = info.getElement();
if (info.isVarargs() || method.isVarArgs() && !PsiUtil.isLanguageLevel8OrHigher(place)) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiType componentType = ((PsiEllipsisType)parameters[parameters.length - 1].getType()).getComponentType();
final PsiType substitutedTypeErasure = TypeConversionUtil.erasure(info.getSubstitutor().substitute(componentType));
final PsiClass targetClass = PsiUtil.resolveClassInClassTypeOnly(substitutedTypeErasure);
if (targetClass != null && !PsiUtil.isAccessible(targetClass, place, null)) {
final PsiExpressionList argumentList = place.getArgumentList();
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
.descriptionAndTooltip("Formal varargs element type " +
PsiFormatUtil.formatClass(targetClass, PsiFormatUtilBase.SHOW_FQ_NAME) +
" is inaccessible here")
.range(argumentList != null ? argumentList : place)
.create();
}
}
return null;
}
private static void registerFixesOnInvalidConstructorCall(PsiConstructorCall constructorCall,
PsiJavaCodeReferenceElement classReference,
PsiExpressionList list,
PsiClass aClass,
PsiMethod[] constructors,
JavaResolveResult[] results, PsiElement infoElement, HighlightInfo info) {
QuickFixAction
.registerQuickFixAction(info, constructorCall.getTextRange(), QUICK_FIX_FACTORY.createCreateConstructorFromCallFix(constructorCall));
if (classReference != null) {
ConstructorParametersFixer.registerFixActions(classReference, constructorCall, info, getFixRange(infoElement));
ChangeTypeArgumentsFix.registerIntentions(results, list, info, aClass);
ConvertDoubleToFloatFix.registerIntentions(results, list, info, null);
}
registerChangeMethodSignatureFromUsageIntentions(results, list, info, null);
PermuteArgumentsFix.registerFix(info, constructorCall, toMethodCandidates(results), getFixRange(list));
registerChangeParameterClassFix(constructorCall, list, info);
QuickFixAction.registerQuickFixAction(info, getFixRange(list), QUICK_FIX_FACTORY.createSurroundWithArrayFix(constructorCall,null));
ChangeStringLiteralToCharInMethodCallFix.registerFixes(constructors, constructorCall, info);
}
private static HighlightInfo buildAccessProblem(@NotNull PsiJavaCodeReferenceElement classReference, JavaResolveResult result, PsiMember elementToFix) {
String description = HighlightUtil.buildProblemWithAccessDescription(classReference, result);
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(classReference).descriptionAndTooltip(
description).navigationShift(+1).create();
if (result.isStaticsScopeCorrect()) {
HighlightUtil.registerAccessQuickFixAction(elementToFix, classReference, info, result.getCurrentFileResolveScope());
}
return info;
}
private static boolean callingProtectedConstructorFromDerivedClass(PsiConstructorCall place, PsiClass constructorClass) {
if (constructorClass == null) return false;
// indirect instantiation via anonymous class is ok
if (place instanceof PsiNewExpression && ((PsiNewExpression)place).getAnonymousClass() != null) return false;
PsiElement curElement = place;
PsiClass containingClass = constructorClass.getContainingClass();
while (true) {
PsiClass aClass = PsiTreeUtil.getParentOfType(curElement, PsiClass.class);
if (aClass == null) return false;
curElement = aClass;
if ((aClass.isInheritor(constructorClass, true) || containingClass != null && aClass.isInheritor(containingClass, true))
&& !JavaPsiFacade.getInstance(aClass.getProject()).arePackagesTheSame(aClass, constructorClass)) {
return true;
}
}
}
private static String buildArgTypesList(PsiExpressionList list) {
StringBuilder builder = new StringBuilder();
builder.append("(");
PsiExpression[] args = list.getExpressions();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
builder.append(", ");
}
PsiType argType = args[i].getType();
builder.append(argType != null ? JavaHighlightUtil.formatType(argType) : "?");
}
builder.append(")");
return builder.toString();
}
private static void registerChangeParameterClassFix(@NotNull PsiCall methodCall,
@NotNull PsiExpressionList list,
HighlightInfo highlightInfo) {
final JavaResolveResult result = methodCall.resolveMethodGenerics();
PsiMethod method = (PsiMethod)result.getElement();
final PsiSubstitutor substitutor = result.getSubstitutor();
PsiExpression[] expressions = list.getExpressions();
if (method == null) return;
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length != expressions.length) return;
for (int i = 0; i < expressions.length; i++) {
final PsiExpression expression = expressions[i];
final PsiParameter parameter = parameters[i];
final PsiType expressionType = expression.getType();
final PsiType parameterType = substitutor.substitute(parameter.getType());
if (expressionType == null || expressionType instanceof PsiPrimitiveType || TypeConversionUtil.isNullType(expressionType) || expressionType instanceof PsiArrayType) continue;
if (parameterType instanceof PsiPrimitiveType || TypeConversionUtil.isNullType(parameterType) || parameterType instanceof PsiArrayType) continue;
if (parameterType.isAssignableFrom(expressionType)) continue;
PsiClass parameterClass = PsiUtil.resolveClassInType(parameterType);
PsiClass expressionClass = PsiUtil.resolveClassInType(expressionType);
if (parameterClass == null || expressionClass == null) continue;
if (expressionClass instanceof PsiAnonymousClass) continue;
if (parameterClass.isInheritor(expressionClass, true)) continue;
QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createChangeParameterClassFix(expressionClass, (PsiClassType)parameterType));
}
}
private static void registerChangeMethodSignatureFromUsageIntentions(@NotNull JavaResolveResult[] candidates,
@NotNull PsiExpressionList list,
@Nullable HighlightInfo highlightInfo,
TextRange fixRange) {
if (candidates.length == 0) return;
PsiExpression[] expressions = list.getExpressions();
for (JavaResolveResult candidate : candidates) {
registerChangeMethodSignatureFromUsageIntention(expressions, highlightInfo, fixRange, candidate, list);
}
}
private static void registerChangeMethodSignatureFromUsageIntention(@NotNull PsiExpression[] expressions,
@Nullable HighlightInfo highlightInfo,
TextRange fixRange,
@NotNull JavaResolveResult candidate,
@NotNull PsiElement context) {
if (!candidate.isStaticsScopeCorrect()) return;
PsiMethod method = (PsiMethod)candidate.getElement();
PsiSubstitutor substitutor = candidate.getSubstitutor();
if (method != null && context.getManager().isInProject(method)) {
IntentionAction fix = QUICK_FIX_FACTORY.createChangeMethodSignatureFromUsageFix(method, expressions, substitutor, context, false, 2);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, fix);
IntentionAction f2 = QUICK_FIX_FACTORY.createChangeMethodSignatureFromUsageReverseOrderFix(method, expressions, substitutor, context,
false, 2);
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, f2);
}
}
}
|
return type equivalence: compare supers with current method, but check type parameters from super types
|
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
|
return type equivalence: compare supers with current method, but check type parameters from super types
|
|
Java
|
apache-2.0
|
6cb11a5e756de39a44b6c8872ed944a2edb53729
| 0
|
kdwink/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,caot/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,samthor/intellij-community,xfournet/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,supersven/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,caot/intellij-community,xfournet/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,izonder/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ahb0327/intellij-community,semonte/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,slisson/intellij-community,youdonghai/intellij-community,da1z/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,asedunov/intellij-community,signed/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,kool79/intellij-community,slisson/intellij-community,jagguli/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,caot/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,allotria/intellij-community,apixandru/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,asedunov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,supersven/intellij-community,clumsy/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,amith01994/intellij-community,blademainer/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,samthor/intellij-community,nicolargo/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,allotria/intellij-community,vladmm/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,kool79/intellij-community,retomerz/intellij-community,xfournet/intellij-community,samthor/intellij-community,da1z/intellij-community,ahb0327/intellij-community,samthor/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,amith01994/intellij-community,blademainer/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,signed/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ibinti/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,xfournet/intellij-community,xfournet/intellij-community,kool79/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,hurricup/intellij-community,jagguli/intellij-community,semonte/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,kool79/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,caot/intellij-community,nicolargo/intellij-community,kool79/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,samthor/intellij-community,dslomov/intellij-community,signed/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,signed/intellij-community,apixandru/intellij-community,hurricup/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,slisson/intellij-community,asedunov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,fnouama/intellij-community,dslomov/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,dslomov/intellij-community,kdwink/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,supersven/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,asedunov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,vladmm/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,caot/intellij-community,asedunov/intellij-community,da1z/intellij-community,signed/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,signed/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,signed/intellij-community,blademainer/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,blademainer/intellij-community,jagguli/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,kdwink/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,dslomov/intellij-community,da1z/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,da1z/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,retomerz/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ibinti/intellij-community,clumsy/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,apixandru/intellij-community,fitermay/intellij-community,caot/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ibinti/intellij-community,slisson/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,vladmm/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,caot/intellij-community,allotria/intellij-community,ibinti/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community
|
package com.jetbrains.edu.learning.courseGeneration;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.intellij.facet.ui.ValidationResult;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl;
import com.intellij.platform.templates.github.ZipUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.edu.EduNames;
import com.jetbrains.edu.courseFormat.Course;
import com.jetbrains.edu.courseFormat.Lesson;
import com.jetbrains.edu.courseFormat.Task;
import com.jetbrains.edu.courseFormat.TaskFile;
import com.jetbrains.edu.learning.StudyProjectComponent;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.stepic.CourseInfo;
import com.jetbrains.edu.stepic.EduStepicConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StudyProjectGenerator {
private static final Logger LOG = Logger.getInstance(StudyProjectGenerator.class.getName());
private final List<SettingsListener> myListeners = ContainerUtil.newArrayList();
private final File myCoursesDir = new File(PathManager.getConfigPath(), "courses");
private static final String CACHE_NAME = "courseNames.txt";
private List<CourseInfo> myCourses = new ArrayList<CourseInfo>();
private CourseInfo mySelectedCourseInfo;
private static final Pattern CACHE_PATTERN = Pattern.compile("name=(.*) description=(.*) folder=(.*) (instructor=(.*))*");
private static final String COURSE_META_FILE = "course.json";
private static final String COURSE_NAME_ATTRIBUTE = "name";
private static final String COURSE_DESCRIPTION = "description";
public static final String AUTHOR_ATTRIBUTE = "authors";
public void setCourses(List<CourseInfo> courses) {
myCourses = courses;
}
public void setSelectedCourse(@NotNull final CourseInfo courseName) {
mySelectedCourseInfo = courseName;
}
public void generateProject(@NotNull final Project project, @NotNull final VirtualFile baseDir) {
final Course course = getCourse();
if (course == null) return;
StudyTaskManager.getInstance(project).setCourse(course);
ApplicationManager.getApplication().invokeLater(
new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
course.initCourse(false);
final File courseDirectory = new File(myCoursesDir, course.getName());
StudyGenerator.createCourse(course, baseDir, courseDirectory, project);
course.setCourseDirectory(new File(myCoursesDir, mySelectedCourseInfo.getName()).getAbsolutePath());
VirtualFileManager.getInstance().refreshWithoutFileWatcher(true);
StudyProjectComponent.getInstance(project).registerStudyToolwindow(course);
openFirstTask(course, project);
}
});
}
});
}
private Course getCourse() {
Reader reader = null;
try {
final File courseFile = new File(new File(myCoursesDir, mySelectedCourseInfo.getName()), COURSE_META_FILE);
if (courseFile.exists()) {
reader = new InputStreamReader(new FileInputStream(courseFile), "UTF-8");
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
final Course course = gson.fromJson(reader, Course.class);
course.initCourse(false);
return course;
}
}
catch (FileNotFoundException e) {
LOG.error(e);
}
catch (UnsupportedEncodingException e) {
LOG.error(e);
}
finally {
StudyUtils.closeSilently(reader);
}
final Course course = EduStepicConnector.getCourse(mySelectedCourseInfo);
if (course != null) {
flushCourse(course);
}
return course;
}
public static void openFirstTask(@NotNull final Course course, @NotNull final Project project) {
LocalFileSystem.getInstance().refresh(false);
final Lesson firstLesson = StudyUtils.getFirst(course.getLessons());
final Task firstTask = StudyUtils.getFirst(firstLesson.getTaskList());
final VirtualFile taskDir = firstTask.getTaskDir(project);
if (taskDir == null) return;
final Map<String, TaskFile> taskFiles = firstTask.getTaskFiles();
VirtualFile activeVirtualFile = null;
for (Map.Entry<String, TaskFile> entry : taskFiles.entrySet()) {
final String name = entry.getKey();
final TaskFile taskFile = entry.getValue();
final VirtualFile virtualFile = ((VirtualDirectoryImpl)taskDir).refreshAndFindChild(name);
if (virtualFile != null) {
FileEditorManager.getInstance(project).openFile(virtualFile, true);
if (!taskFile.getAnswerPlaceholders().isEmpty()) {
activeVirtualFile = virtualFile;
}
}
}
if (activeVirtualFile != null) {
final PsiFile file = PsiManager.getInstance(project).findFile(activeVirtualFile);
ProjectView.getInstance(project).select(file, activeVirtualFile, true);
} else {
String first = StudyUtils.getFirst(taskFiles.keySet());
if (first != null) {
NewVirtualFile firstFile = ((VirtualDirectoryImpl)taskDir).refreshAndFindChild(first);
if (firstFile != null) {
FileEditorManager.getInstance(project).openFile(firstFile, true);
}
}
}
}
public void flushCourse(@NotNull final Course course) {
final File courseDirectory = new File(myCoursesDir, course.getName());
FileUtil.createDirectory(courseDirectory);
flushCourseJson(course, courseDirectory);
int lessonIndex = 1;
for (Lesson lesson : course.getLessons()) {
final File lessonDirectory = new File(courseDirectory, EduNames.LESSON + String.valueOf(lessonIndex));
flushLesson(lessonDirectory, lesson);
lessonIndex += 1;
}
}
public static void flushLesson(@NotNull final File lessonDirectory, @NotNull final Lesson lesson) {
FileUtil.createDirectory(lessonDirectory);
int taskIndex = 1;
for (Task task : lesson.taskList) {
final File taskDirectory = new File(lessonDirectory, EduNames.TASK + String.valueOf(taskIndex));
flushTask(task, taskDirectory);
taskIndex += 1;
}
}
public static void flushTask(@NotNull final Task task, @NotNull final File taskDirectory) {
FileUtil.createDirectory(taskDirectory);
for (Map.Entry<String, TaskFile> taskFileEntry : task.taskFiles.entrySet()) {
final String name = taskFileEntry.getKey();
final TaskFile taskFile = taskFileEntry.getValue();
final File file = new File(taskDirectory, name);
FileUtil.createIfDoesntExist(file);
try {
FileUtil.writeToFile(file, taskFile.text);
}
catch (IOException e) {
LOG.error("ERROR copying file " + name);
}
}
final Map<String, String> testsText = task.getTestsText();
for (Map.Entry<String, String> entry : testsText.entrySet()) {
final File testsFile = new File(taskDirectory, entry.getKey());
FileUtil.createIfDoesntExist(testsFile);
try {
FileUtil.writeToFile(testsFile, entry.getValue());
}
catch (IOException e) {
LOG.error("ERROR copying tests file");
}
}
final File taskText = new File(taskDirectory, "task.html");
FileUtil.createIfDoesntExist(taskText);
try {
FileUtil.writeToFile(taskText, task.getText());
}
catch (IOException e) {
LOG.error("ERROR copying tests file");
}
}
private static void flushCourseJson(@NotNull final Course course, @NotNull final File courseDirectory) {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String json = gson.toJson(course);
final File courseJson = new File(courseDirectory, "course.json");
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(courseJson);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
try {
outputStreamWriter.write(json);
}
catch (IOException e) {
Messages.showErrorDialog(e.getMessage(), "Failed to Generate Json");
LOG.info(e);
}
finally {
try {
outputStreamWriter.close();
}
catch (IOException e) {
LOG.info(e);
}
}
}
catch (FileNotFoundException e) {
LOG.info(e);
}
catch (UnsupportedEncodingException e) {
LOG.info(e);
}
}
/**
* Writes courses to cache file {@link StudyProjectGenerator#CACHE_NAME}
*/
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public void flushCache() {
File cacheFile = new File(myCoursesDir, CACHE_NAME);
PrintWriter writer = null;
try {
if (!myCoursesDir.exists()) {
final boolean created = myCoursesDir.mkdirs();
if (!created) {
LOG.error("Cannot flush courses cache. Can't create courses directory");
return;
}
}
if (!cacheFile.exists()) {
final boolean created = cacheFile.createNewFile();
if (!created) {
LOG.error("Cannot flush courses cache. Can't create " + CACHE_NAME + " file");
return;
}
}
writer = new PrintWriter(cacheFile);
for (CourseInfo courseInfo : myCourses) {
final List<CourseInfo.Instructor> instructors = courseInfo.getInstructors();
StringBuilder builder = new StringBuilder("name=").append(courseInfo.getName()).append(" ").append("description=").
append(courseInfo.getDescription()).append(" ").append("folder=").append(courseInfo.getName()).append(" ");
for (CourseInfo.Instructor instructor : instructors) {
builder.append("instructor=").append(instructor.getName()).append(" ");
}
writer.println(builder.toString());
}
}
catch (FileNotFoundException e) {
LOG.error(e);
}
catch (IOException e) {
LOG.error(e);
}
finally {
StudyUtils.closeSilently(writer);
}
}
public List<CourseInfo> getCourses(boolean force) {
if (myCoursesDir.exists()) {
File cacheFile = new File(myCoursesDir, CACHE_NAME);
if (cacheFile.exists()) {
myCourses = getCoursesFromCache(cacheFile);
}
}
if (force || myCourses.isEmpty()) {
myCourses = EduStepicConnector.getCourses();
flushCache();
}
return myCourses;
}
public void addSettingsStateListener(@NotNull SettingsListener listener) {
myListeners.add(listener);
}
public interface SettingsListener {
void stateChanged(ValidationResult result);
}
public void fireStateChanged(ValidationResult result) {
for (SettingsListener listener : myListeners) {
listener.stateChanged(result);
}
}
private static List<CourseInfo> getCoursesFromCache(@NotNull final File cacheFile) {
List<CourseInfo> courses = new ArrayList<CourseInfo>();
try {
final FileInputStream inputStream = new FileInputStream(cacheFile);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = CACHE_PATTERN.matcher(line);
if (matcher.matches()) {
String courseName = matcher.group(1);
final CourseInfo courseInfo = new CourseInfo();
courseInfo.setName(courseName);
courseInfo.setDescription(matcher.group(2));
courses.add(courseInfo);
final int groupCount = matcher.groupCount();
final ArrayList<CourseInfo.Instructor> instructors = new ArrayList<CourseInfo.Instructor>();
for (int i = 5; i <= groupCount; i++) {
instructors.add(new CourseInfo.Instructor(matcher.group(i)));
}
courseInfo.setInstructors(instructors);
}
}
}
catch (IOException e) {
LOG.error(e.getMessage());
}
finally {
StudyUtils.closeSilently(reader);
}
} finally {
StudyUtils.closeSilently(inputStream);
}
}
catch (FileNotFoundException e) {
LOG.error(e.getMessage());
}
return courses;
}
/**
* Adds course from zip archive to courses
*
* @return added course name or null if course is invalid
*/
@Nullable
public CourseInfo addLocalCourse(String zipFilePath) {
File file = new File(zipFilePath);
try {
String fileName = file.getName();
String unzippedName = fileName.substring(0, fileName.indexOf("."));
File courseDir = new File(myCoursesDir, unzippedName);
ZipUtil.unzip(null, courseDir, file, null, null, true);
CourseInfo courseName = addCourse(myCourses, courseDir);
flushCache();
if (courseName != null && !courseName.getName().equals(unzippedName)) {
courseDir.renameTo(new File(myCoursesDir, courseName.getName()));
courseDir.delete();
}
return courseName;
}
catch (IOException e) {
LOG.error("Failed to unzip course archive");
LOG.error(e);
}
return null;
}
/**
* Adds course to courses specified in params
*
*
* @param courses
* @param courseDir must be directory containing course file
* @return added course name or null if course is invalid
*/
@Nullable
private static CourseInfo addCourse(List<CourseInfo> courses, File courseDir) {
if (courseDir.isDirectory()) {
File[] courseFiles = courseDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(COURSE_META_FILE);
}
});
if (courseFiles.length != 1) {
LOG.info("User tried to add course with more than one or without course files");
return null;
}
File courseFile = courseFiles[0];
CourseInfo courseInfo = getCourseInfo(courseFile);
if (courseInfo != null) {
courses.add(courseInfo);
}
return courseInfo;
}
return null;
}
/**
* Parses course json meta file and finds course name
*
* @return information about course or null if course file is invalid
*/
@Nullable
private static CourseInfo getCourseInfo(File courseFile) {
CourseInfo courseInfo = null;
BufferedReader reader = null;
try {
if (courseFile.getName().equals(COURSE_META_FILE)) {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(courseFile), "UTF-8"));
JsonReader r = new JsonReader(reader);
JsonParser parser = new JsonParser();
JsonElement el = parser.parse(r);
String courseName = el.getAsJsonObject().get(COURSE_NAME_ATTRIBUTE).getAsString();
String courseDescription = el.getAsJsonObject().get(COURSE_DESCRIPTION).getAsString();
JsonArray courseAuthors = el.getAsJsonObject().get(AUTHOR_ATTRIBUTE).getAsJsonArray();
courseInfo = new CourseInfo();
courseInfo.setName(courseName);
courseInfo.setDescription(courseDescription);
final ArrayList<CourseInfo.Instructor> instructors = new ArrayList<CourseInfo.Instructor>();
for (JsonElement author : courseAuthors) {
final String authorAsString = author.getAsString();
instructors.add(new CourseInfo.Instructor(authorAsString));
}
courseInfo.setInstructors(instructors);
}
}
catch (Exception e) {
//error will be shown in UI
}
finally {
StudyUtils.closeSilently(reader);
}
return courseInfo;
}
}
|
python/educational/interactive-learning/src/com/jetbrains/edu/learning/courseGeneration/StudyProjectGenerator.java
|
package com.jetbrains.edu.learning.courseGeneration;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.intellij.facet.ui.ValidationResult;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl;
import com.intellij.platform.templates.github.ZipUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.edu.EduNames;
import com.jetbrains.edu.courseFormat.Course;
import com.jetbrains.edu.courseFormat.Lesson;
import com.jetbrains.edu.courseFormat.Task;
import com.jetbrains.edu.courseFormat.TaskFile;
import com.jetbrains.edu.learning.StudyProjectComponent;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.stepic.CourseInfo;
import com.jetbrains.edu.stepic.EduStepicConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StudyProjectGenerator {
private static final Logger LOG = Logger.getInstance(StudyProjectGenerator.class.getName());
private final List<SettingsListener> myListeners = ContainerUtil.newArrayList();
private final File myCoursesDir = new File(PathManager.getConfigPath(), "courses");
private static final String CACHE_NAME = "courseNames.txt";
private List<CourseInfo> myCourses = new ArrayList<CourseInfo>();
private CourseInfo mySelectedCourseInfo;
private static final Pattern CACHE_PATTERN = Pattern.compile("name=(.*) description=(.*) folder=(.*) (instructor=(.*))+");
private static final String COURSE_META_FILE = "course.json";
private static final String COURSE_NAME_ATTRIBUTE = "name";
private static final String COURSE_DESCRIPTION = "description";
public static final String AUTHOR_ATTRIBUTE = "authors";
public void setCourses(List<CourseInfo> courses) {
myCourses = courses;
}
public void setSelectedCourse(@NotNull final CourseInfo courseName) {
mySelectedCourseInfo = courseName;
}
public void generateProject(@NotNull final Project project, @NotNull final VirtualFile baseDir) {
final Course course = getCourse();
if (course == null) return;
StudyTaskManager.getInstance(project).setCourse(course);
ApplicationManager.getApplication().invokeLater(
new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
course.initCourse(false);
final File courseDirectory = new File(myCoursesDir, course.getName());
StudyGenerator.createCourse(course, baseDir, courseDirectory, project);
course.setCourseDirectory(new File(myCoursesDir, mySelectedCourseInfo.getName()).getAbsolutePath());
VirtualFileManager.getInstance().refreshWithoutFileWatcher(true);
StudyProjectComponent.getInstance(project).registerStudyToolwindow(course);
openFirstTask(course, project);
}
});
}
});
}
private Course getCourse() {
Reader reader = null;
try {
final File courseFile = new File(new File(myCoursesDir, mySelectedCourseInfo.getName()), COURSE_META_FILE);
if (courseFile.exists()) {
reader = new InputStreamReader(new FileInputStream(courseFile), "UTF-8");
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
final Course course = gson.fromJson(reader, Course.class);
course.initCourse(false);
return course;
}
}
catch (FileNotFoundException e) {
LOG.error(e);
}
catch (UnsupportedEncodingException e) {
LOG.error(e);
}
finally {
StudyUtils.closeSilently(reader);
}
final Course course = EduStepicConnector.getCourse(mySelectedCourseInfo);
if (course != null) {
flushCourse(course);
}
return course;
}
public static void openFirstTask(@NotNull final Course course, @NotNull final Project project) {
LocalFileSystem.getInstance().refresh(false);
final Lesson firstLesson = StudyUtils.getFirst(course.getLessons());
final Task firstTask = StudyUtils.getFirst(firstLesson.getTaskList());
final VirtualFile taskDir = firstTask.getTaskDir(project);
if (taskDir == null) return;
final Map<String, TaskFile> taskFiles = firstTask.getTaskFiles();
VirtualFile activeVirtualFile = null;
for (Map.Entry<String, TaskFile> entry : taskFiles.entrySet()) {
final String name = entry.getKey();
final TaskFile taskFile = entry.getValue();
final VirtualFile virtualFile = ((VirtualDirectoryImpl)taskDir).refreshAndFindChild(name);
if (virtualFile != null) {
FileEditorManager.getInstance(project).openFile(virtualFile, true);
if (!taskFile.getAnswerPlaceholders().isEmpty()) {
activeVirtualFile = virtualFile;
}
}
}
if (activeVirtualFile != null) {
final PsiFile file = PsiManager.getInstance(project).findFile(activeVirtualFile);
ProjectView.getInstance(project).select(file, activeVirtualFile, true);
} else {
String first = StudyUtils.getFirst(taskFiles.keySet());
if (first != null) {
NewVirtualFile firstFile = ((VirtualDirectoryImpl)taskDir).refreshAndFindChild(first);
if (firstFile != null) {
FileEditorManager.getInstance(project).openFile(firstFile, true);
}
}
}
}
public void flushCourse(@NotNull final Course course) {
final File courseDirectory = new File(myCoursesDir, course.getName());
FileUtil.createDirectory(courseDirectory);
flushCourseJson(course, courseDirectory);
int lessonIndex = 1;
for (Lesson lesson : course.getLessons()) {
final File lessonDirectory = new File(courseDirectory, EduNames.LESSON + String.valueOf(lessonIndex));
flushLesson(lessonDirectory, lesson);
lessonIndex += 1;
}
}
public static void flushLesson(@NotNull final File lessonDirectory, @NotNull final Lesson lesson) {
FileUtil.createDirectory(lessonDirectory);
int taskIndex = 1;
for (Task task : lesson.taskList) {
final File taskDirectory = new File(lessonDirectory, EduNames.TASK + String.valueOf(taskIndex));
flushTask(task, taskDirectory);
taskIndex += 1;
}
}
public static void flushTask(@NotNull final Task task, @NotNull final File taskDirectory) {
FileUtil.createDirectory(taskDirectory);
for (Map.Entry<String, TaskFile> taskFileEntry : task.taskFiles.entrySet()) {
final String name = taskFileEntry.getKey();
final TaskFile taskFile = taskFileEntry.getValue();
final File file = new File(taskDirectory, name);
FileUtil.createIfDoesntExist(file);
try {
FileUtil.writeToFile(file, taskFile.text);
}
catch (IOException e) {
LOG.error("ERROR copying file " + name);
}
}
final Map<String, String> testsText = task.getTestsText();
for (Map.Entry<String, String> entry : testsText.entrySet()) {
final File testsFile = new File(taskDirectory, entry.getKey());
FileUtil.createIfDoesntExist(testsFile);
try {
FileUtil.writeToFile(testsFile, entry.getValue());
}
catch (IOException e) {
LOG.error("ERROR copying tests file");
}
}
final File taskText = new File(taskDirectory, "task.html");
FileUtil.createIfDoesntExist(taskText);
try {
FileUtil.writeToFile(taskText, task.getText());
}
catch (IOException e) {
LOG.error("ERROR copying tests file");
}
}
private static void flushCourseJson(@NotNull final Course course, @NotNull final File courseDirectory) {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String json = gson.toJson(course);
final File courseJson = new File(courseDirectory, "course.json");
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(courseJson);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
try {
outputStreamWriter.write(json);
}
catch (IOException e) {
Messages.showErrorDialog(e.getMessage(), "Failed to Generate Json");
LOG.info(e);
}
finally {
try {
outputStreamWriter.close();
}
catch (IOException e) {
LOG.info(e);
}
}
}
catch (FileNotFoundException e) {
LOG.info(e);
}
catch (UnsupportedEncodingException e) {
LOG.info(e);
}
}
/**
* Writes courses to cache file {@link StudyProjectGenerator#CACHE_NAME}
*/
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public void flushCache() {
File cacheFile = new File(myCoursesDir, CACHE_NAME);
PrintWriter writer = null;
try {
if (!myCoursesDir.exists()) {
final boolean created = myCoursesDir.mkdirs();
if (!created) {
LOG.error("Cannot flush courses cache. Can't create courses directory");
return;
}
}
if (!cacheFile.exists()) {
final boolean created = cacheFile.createNewFile();
if (!created) {
LOG.error("Cannot flush courses cache. Can't create " + CACHE_NAME + " file");
return;
}
}
writer = new PrintWriter(cacheFile);
for (CourseInfo courseInfo : myCourses) {
final List<CourseInfo.Instructor> instructors = courseInfo.getInstructors();
StringBuilder builder = new StringBuilder("name=").append(courseInfo.getName()).append(" ").append("description=").
append(courseInfo.getDescription()).append(" ").append("folder=").append(courseInfo.getName()).append(" ");
for (CourseInfo.Instructor instructor : instructors) {
builder.append("instructor=").append(instructor.getName()).append(" ");
}
writer.println(builder.toString());
}
}
catch (FileNotFoundException e) {
LOG.error(e);
}
catch (IOException e) {
LOG.error(e);
}
finally {
StudyUtils.closeSilently(writer);
}
}
public List<CourseInfo> getCourses(boolean force) {
if (myCoursesDir.exists()) {
File cacheFile = new File(myCoursesDir, CACHE_NAME);
if (cacheFile.exists()) {
myCourses = getCoursesFromCache(cacheFile);
}
}
if (force || myCourses.isEmpty()) {
myCourses = EduStepicConnector.getCourses();
flushCache();
}
return myCourses;
}
public void addSettingsStateListener(@NotNull SettingsListener listener) {
myListeners.add(listener);
}
public interface SettingsListener {
void stateChanged(ValidationResult result);
}
public void fireStateChanged(ValidationResult result) {
for (SettingsListener listener : myListeners) {
listener.stateChanged(result);
}
}
private static List<CourseInfo> getCoursesFromCache(@NotNull final File cacheFile) {
List<CourseInfo> courses = new ArrayList<CourseInfo>();
try {
final FileInputStream inputStream = new FileInputStream(cacheFile);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = CACHE_PATTERN.matcher(line);
if (matcher.matches()) {
String courseName = matcher.group(1);
final CourseInfo courseInfo = new CourseInfo();
courseInfo.setName(courseName);
courseInfo.setDescription(matcher.group(2));
courses.add(courseInfo);
final int groupCount = matcher.groupCount();
final ArrayList<CourseInfo.Instructor> instructors = new ArrayList<CourseInfo.Instructor>();
for (int i = 5; i <= groupCount; i++) {
instructors.add(new CourseInfo.Instructor(matcher.group(i)));
}
courseInfo.setInstructors(instructors);
}
}
}
catch (IOException e) {
LOG.error(e.getMessage());
}
finally {
StudyUtils.closeSilently(reader);
}
} finally {
StudyUtils.closeSilently(inputStream);
}
}
catch (FileNotFoundException e) {
LOG.error(e.getMessage());
}
return courses;
}
/**
* Adds course from zip archive to courses
*
* @return added course name or null if course is invalid
*/
@Nullable
public CourseInfo addLocalCourse(String zipFilePath) {
File file = new File(zipFilePath);
try {
String fileName = file.getName();
String unzippedName = fileName.substring(0, fileName.indexOf("."));
File courseDir = new File(myCoursesDir, unzippedName);
ZipUtil.unzip(null, courseDir, file, null, null, true);
CourseInfo courseName = addCourse(myCourses, courseDir);
flushCache();
if (courseName != null && !courseName.getName().equals(unzippedName)) {
courseDir.renameTo(new File(myCoursesDir, courseName.getName()));
courseDir.delete();
}
return courseName;
}
catch (IOException e) {
LOG.error("Failed to unzip course archive");
LOG.error(e);
}
return null;
}
/**
* Adds course to courses specified in params
*
*
* @param courses
* @param courseDir must be directory containing course file
* @return added course name or null if course is invalid
*/
@Nullable
private static CourseInfo addCourse(List<CourseInfo> courses, File courseDir) {
if (courseDir.isDirectory()) {
File[] courseFiles = courseDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(COURSE_META_FILE);
}
});
if (courseFiles.length != 1) {
LOG.info("User tried to add course with more than one or without course files");
return null;
}
File courseFile = courseFiles[0];
CourseInfo courseInfo = getCourseInfo(courseFile);
if (courseInfo != null) {
courses.add(courseInfo);
}
return courseInfo;
}
return null;
}
/**
* Parses course json meta file and finds course name
*
* @return information about course or null if course file is invalid
*/
@Nullable
private static CourseInfo getCourseInfo(File courseFile) {
CourseInfo courseInfo = null;
BufferedReader reader = null;
try {
if (courseFile.getName().equals(COURSE_META_FILE)) {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(courseFile), "UTF-8"));
JsonReader r = new JsonReader(reader);
JsonParser parser = new JsonParser();
JsonElement el = parser.parse(r);
String courseName = el.getAsJsonObject().get(COURSE_NAME_ATTRIBUTE).getAsString();
String courseDescription = el.getAsJsonObject().get(COURSE_DESCRIPTION).getAsString();
JsonArray courseAuthors = el.getAsJsonObject().get(AUTHOR_ATTRIBUTE).getAsJsonArray();
courseInfo = new CourseInfo();
courseInfo.setName(courseName);
courseInfo.setDescription(courseDescription);
final ArrayList<CourseInfo.Instructor> instructors = new ArrayList<CourseInfo.Instructor>();
for (JsonElement author : courseAuthors) {
final String authorAsString = author.getAsString();
instructors.add(new CourseInfo.Instructor(authorAsString));
}
courseInfo.setInstructors(instructors);
}
}
catch (Exception e) {
//error will be shown in UI
}
finally {
StudyUtils.closeSilently(reader);
}
return courseInfo;
}
}
|
fixed cache pattern for courses
|
python/educational/interactive-learning/src/com/jetbrains/edu/learning/courseGeneration/StudyProjectGenerator.java
|
fixed cache pattern for courses
|
|
Java
|
apache-2.0
|
8eb1fe395b200fd4549f56e80a0b5199bdb41c46
| 0
|
ThiagoGarciaAlves/intellij-community,semonte/intellij-community,slisson/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,samthor/intellij-community,kool79/intellij-community,dslomov/intellij-community,adedayo/intellij-community,holmes/intellij-community,samthor/intellij-community,apixandru/intellij-community,asedunov/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,samthor/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,holmes/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,robovm/robovm-studio,izonder/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,vladmm/intellij-community,izonder/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,caot/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,signed/intellij-community,ryano144/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,signed/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,xfournet/intellij-community,slisson/intellij-community,ahb0327/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,amith01994/intellij-community,retomerz/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,caot/intellij-community,retomerz/intellij-community,asedunov/intellij-community,caot/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,FHannes/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,allotria/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,hurricup/intellij-community,caot/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,allotria/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,allotria/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,slisson/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,FHannes/intellij-community,dslomov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,adedayo/intellij-community,vladmm/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,vladmm/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,petteyg/intellij-community,adedayo/intellij-community,petteyg/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,da1z/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,signed/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,slisson/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,Lekanich/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,slisson/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,caot/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,clumsy/intellij-community,asedunov/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,jagguli/intellij-community,semonte/intellij-community,jagguli/intellij-community,izonder/intellij-community,retomerz/intellij-community,ibinti/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,izonder/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,kdwink/intellij-community,jagguli/intellij-community,dslomov/intellij-community,FHannes/intellij-community,signed/intellij-community,caot/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,izonder/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,jagguli/intellij-community,diorcety/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,fnouama/intellij-community,fitermay/intellij-community,caot/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,da1z/intellij-community,caot/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,allotria/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,vvv1559/intellij-community,caot/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,kool79/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,robovm/robovm-studio,apixandru/intellij-community,petteyg/intellij-community,retomerz/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,holmes/intellij-community,asedunov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,hurricup/intellij-community,signed/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vvv1559/intellij-community,slisson/intellij-community,diorcety/intellij-community,xfournet/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,amith01994/intellij-community,fnouama/intellij-community,blademainer/intellij-community,asedunov/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,slisson/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,signed/intellij-community,slisson/intellij-community,supersven/intellij-community,asedunov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,izonder/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fitermay/intellij-community,samthor/intellij-community,da1z/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,holmes/intellij-community,semonte/intellij-community,signed/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,alphafoobar/intellij-community,caot/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,retomerz/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,hurricup/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ryano144/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kool79/intellij-community,orekyuu/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,dslomov/intellij-community,ibinti/intellij-community,diorcety/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,da1z/intellij-community,ibinti/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,signed/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,izonder/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ryano144/intellij-community,diorcety/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,da1z/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,kool79/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,allotria/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,semonte/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,da1z/intellij-community,kool79/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,slisson/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,da1z/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,signed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,petteyg/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,blademainer/intellij-community,dslomov/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,clumsy/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,vvv1559/intellij-community
|
package com.jetbrains.python.module;
import com.intellij.ide.util.importProject.ModuleDescriptor;
import com.intellij.ide.util.importProject.ProjectDescriptor;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.ProjectWizardStepFactory;
import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot;
import com.intellij.ide.util.projectWizard.importSources.ProjectFromSourcesBuilder;
import com.intellij.ide.util.projectWizard.importSources.ProjectStructureDetector;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public class PyProjectStructureDetector extends ProjectStructureDetector {
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.module.PyProjectStructureDetector");
@NotNull
@Override
public DirectoryProcessingResult detectRoots(@NotNull File dir,
@NotNull File[] children,
@NotNull File base,
@NotNull List<DetectedProjectRoot> result) {
LOG.info("Detecting roots under " + dir);
for (File child : children) {
if (FileUtil.getExtension(child.getName()).equals("py")) {
LOG.info("Found Python file " + child.getPath());
result.add(new DetectedProjectRoot(dir) {
@NotNull
@Override
public String getRootTypeName() {
return "Python";
}
});
return DirectoryProcessingResult.SKIP_CHILDREN;
}
}
return DirectoryProcessingResult.PROCESS_CHILDREN;
}
@Override
public void setupProjectStructure(@NotNull Collection<DetectedProjectRoot> roots,
@NotNull ProjectDescriptor projectDescriptor,
@NotNull ProjectFromSourcesBuilder builder) {
if (!roots.isEmpty() && !hasRootsFromOtherDetectors(builder)) {
List<ModuleDescriptor> modules = projectDescriptor.getModules();
if (modules.isEmpty()) {
modules = new ArrayList<ModuleDescriptor>();
for (DetectedProjectRoot root : roots) {
modules.add(new ModuleDescriptor(root.getDirectory(), PythonModuleType.getInstance(), root));
}
projectDescriptor.setModules(modules);
}
}
}
@Override
public List<ModuleWizardStep> createWizardSteps(ProjectFromSourcesBuilder builder, ProjectDescriptor projectDescriptor, Icon stepIcon) {
return Collections.singletonList(ProjectWizardStepFactory.getInstance().createProjectJdkStep(builder.getContext()));
}
private static boolean hasRootsFromOtherDetectors(ProjectFromSourcesBuilder builder) {
for (ProjectStructureDetector projectStructureDetector : Extensions.getExtensions(EP_NAME)) {
if (!(projectStructureDetector instanceof PyProjectStructureDetector)) {
final Collection<DetectedProjectRoot> roots = builder.getProjectRoots(projectStructureDetector);
if (!roots.isEmpty()) {
return true;
}
}
}
return false;
}
}
|
python/pluginSrc/com/jetbrains/python/module/PyProjectStructureDetector.java
|
package com.jetbrains.python.module;
import com.intellij.ide.util.importProject.ModuleDescriptor;
import com.intellij.ide.util.importProject.ProjectDescriptor;
import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot;
import com.intellij.ide.util.projectWizard.importSources.ProjectFromSourcesBuilder;
import com.intellij.ide.util.projectWizard.importSources.ProjectStructureDetector;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author yole
*/
public class PyProjectStructureDetector extends ProjectStructureDetector {
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.module.PyProjectStructureDetector");
@NotNull
@Override
public DirectoryProcessingResult detectRoots(@NotNull File dir,
@NotNull File[] children,
@NotNull File base,
@NotNull List<DetectedProjectRoot> result) {
LOG.info("Detecting roots under " + dir);
for (File child : children) {
if (FileUtil.getExtension(child.getName()).equals("py")) {
LOG.info("Found Python file " + child.getPath());
result.add(new DetectedProjectRoot(dir) {
@NotNull
@Override
public String getRootTypeName() {
return "Python";
}
});
return DirectoryProcessingResult.SKIP_CHILDREN;
}
}
return DirectoryProcessingResult.PROCESS_CHILDREN;
}
@Override
public void setupProjectStructure(@NotNull Collection<DetectedProjectRoot> roots,
@NotNull ProjectDescriptor projectDescriptor,
@NotNull ProjectFromSourcesBuilder builder) {
if (!roots.isEmpty() && !hasRootsFromOtherDetectors(builder)) {
List<ModuleDescriptor> modules = projectDescriptor.getModules();
if (modules.isEmpty()) {
modules = new ArrayList<ModuleDescriptor>();
for (DetectedProjectRoot root : roots) {
modules.add(new ModuleDescriptor(root.getDirectory(), PythonModuleType.getInstance(), root));
}
projectDescriptor.setModules(modules);
}
}
}
private static boolean hasRootsFromOtherDetectors(ProjectFromSourcesBuilder builder) {
for (ProjectStructureDetector projectStructureDetector : Extensions.getExtensions(EP_NAME)) {
if (!(projectStructureDetector instanceof PyProjectStructureDetector)) {
final Collection<DetectedProjectRoot> roots = builder.getProjectRoots(projectStructureDetector);
if (!roots.isEmpty()) {
return true;
}
}
}
return false;
}
}
|
create project from existing sources: select suitable project sdk
|
python/pluginSrc/com/jetbrains/python/module/PyProjectStructureDetector.java
|
create project from existing sources: select suitable project sdk
|
|
Java
|
apache-2.0
|
a45f452d153975b499c12eeaa3ed4e1239cdfb71
| 0
|
jdeppe-pivotal/geode,prasi-in/geode,PurelyApplied/geode,pdxrunner/geode,charliemblack/geode,shankarh/geode,prasi-in/geode,masaki-yamakawa/geode,PurelyApplied/geode,shankarh/geode,davinash/geode,masaki-yamakawa/geode,davebarnes97/geode,pdxrunner/geode,smanvi-pivotal/geode,charliemblack/geode,charliemblack/geode,pivotal-amurmann/geode,davebarnes97/geode,pivotal-amurmann/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,PurelyApplied/geode,pivotal-amurmann/geode,smgoller/geode,smgoller/geode,prasi-in/geode,pdxrunner/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,PurelyApplied/geode,smgoller/geode,deepakddixit/incubator-geode,smgoller/geode,deepakddixit/incubator-geode,davebarnes97/geode,smgoller/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,shankarh/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,pdxrunner/geode,pivotal-amurmann/geode,davebarnes97/geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,davinash/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,davinash/geode,masaki-yamakawa/geode,smanvi-pivotal/geode,PurelyApplied/geode,PurelyApplied/geode,pdxrunner/geode,davebarnes97/geode,PurelyApplied/geode,davebarnes97/geode,davinash/geode,smgoller/geode,shankarh/geode,charliemblack/geode,pdxrunner/geode,smanvi-pivotal/geode,pivotal-amurmann/geode,smgoller/geode,jdeppe-pivotal/geode,davinash/geode,pdxrunner/geode,masaki-yamakawa/geode,prasi-in/geode,davinash/geode,shankarh/geode,davinash/geode,charliemblack/geode,deepakddixit/incubator-geode,davebarnes97/geode,prasi-in/geode
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.pdx;
import java.util.Properties;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.test.dunit.DistributedTestCase;
import com.gemstone.gemfire.test.dunit.Host;
import com.gemstone.gemfire.test.dunit.IgnoredException;
import com.gemstone.gemfire.test.dunit.SerializableCallable;
import com.gemstone.gemfire.test.dunit.VM;
import com.gemstone.gemfire.test.junit.categories.FlakyTest;
public class DistributedSystemIdDUnitTest extends DistributedTestCase {
public DistributedSystemIdDUnitTest(String name) {
super(name);
}
@Override
public void preSetUp() {
disconnectAllFromDS(); // GEODE-558 test fails due to infection from another test
}
public void testMatchingIds() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
int locatorPort = createLocator(vm0, "1");
createSystem(vm1, "1", locatorPort);
createSystem(vm2, "1", locatorPort);
checkId(vm0, 1);
checkId(vm1, 1);
checkId(vm2, 1);
}
public void testInfectiousId() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
int locatorPort = createLocator(vm0, "1");
createSystem(vm1, "-1", locatorPort);
checkId(vm1, 1);
}
public void testMismatch() {
IgnoredException.addIgnoredException("Rejected new system node");
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
int locatorPort = createLocator(vm0, "1");
try {
createSystem(vm1, "2", locatorPort);
fail("Should have gotten an exception");
} catch(Exception expected) {
}
checkId(vm0, 1);
}
public void testInvalid() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
try {
createLocator(vm0, "256");
fail("Should have gotten an exception");
} catch(Exception expected) {
}
try {
createLocator(vm0, "aardvark");
fail("Should have gotten an exception");
} catch(Exception expected) {
}
}
private void createSystem(VM vm, final String dsId, final int locatorPort) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.DISTRIBUTED_SYSTEM_ID_NAME, dsId);
props.setProperty(DistributionConfig.LOCATORS_NAME, "localhost[" + locatorPort + "]");
getSystem(props);
return null;
}
};
vm.invoke(createSystem);
}
private int createLocator(VM vm, final String dsId) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
int port = AvailablePortHelper.getRandomAvailableTCPPort();
Properties props = new Properties();
props.setProperty(DistributionConfig.DISTRIBUTED_SYSTEM_ID_NAME, dsId);
props.setProperty("mcast-port", "0");
props.setProperty(DistributionConfig.LOCATORS_NAME, "localhost[" + port + "]");
props.setProperty(DistributionConfig.START_LOCATOR_NAME, "localhost[" + port + "]");
getSystem(props);
// Locator locator = Locator.startLocatorAndDS(port, File.createTempFile("locator", ""), props);
// system = (InternalDistributedSystem) locator.getDistributedSystem();
return port;
}
};
return (Integer) vm.invoke(createSystem);
}
private void checkId(VM vm, final int dsId) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
DistributionManager dm = (DistributionManager) InternalDistributedSystem.getAnyInstance().getDistributionManager();
assertEquals(dsId, dm.getDistributedSystemId());
return null;
}
};
vm.invoke(createSystem);
}
}
|
geode-core/src/test/java/com/gemstone/gemfire/pdx/DistributedSystemIdDUnitTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.pdx;
import java.util.Properties;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.test.dunit.DistributedTestCase;
import com.gemstone.gemfire.test.dunit.Host;
import com.gemstone.gemfire.test.dunit.IgnoredException;
import com.gemstone.gemfire.test.dunit.SerializableCallable;
import com.gemstone.gemfire.test.dunit.VM;
import com.gemstone.gemfire.test.junit.categories.FlakyTest;
public class DistributedSystemIdDUnitTest extends DistributedTestCase {
public DistributedSystemIdDUnitTest(String name) {
super(name);
}
public void testMatchingIds() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
int locatorPort = createLocator(vm0, "1");
createSystem(vm1, "1", locatorPort);
createSystem(vm2, "1", locatorPort);
checkId(vm0, 1);
checkId(vm1, 1);
checkId(vm2, 1);
}
@Category(FlakyTest.class) // GEODE-558: random ports, test pollution (TODO: disconnect DS in setup?)
public void testInfectiousId() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
int locatorPort = createLocator(vm0, "1");
createSystem(vm1, "-1", locatorPort);
checkId(vm1, 1);
}
public void testMismatch() {
IgnoredException.addIgnoredException("Rejected new system node");
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
int locatorPort = createLocator(vm0, "1");
try {
createSystem(vm1, "2", locatorPort);
fail("Should have gotten an exception");
} catch(Exception expected) {
}
checkId(vm0, 1);
}
public void testInvalid() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
try {
createLocator(vm0, "256");
fail("Should have gotten an exception");
} catch(Exception expected) {
}
try {
createLocator(vm0, "aardvark");
fail("Should have gotten an exception");
} catch(Exception expected) {
}
}
private void createSystem(VM vm, final String dsId, final int locatorPort) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
Properties props = new Properties();
props.setProperty(DistributionConfig.DISTRIBUTED_SYSTEM_ID_NAME, dsId);
props.setProperty(DistributionConfig.LOCATORS_NAME, "localhost[" + locatorPort + "]");
getSystem(props);
return null;
}
};
vm.invoke(createSystem);
}
private int createLocator(VM vm, final String dsId) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
int port = AvailablePortHelper.getRandomAvailableTCPPort();
Properties props = new Properties();
props.setProperty(DistributionConfig.DISTRIBUTED_SYSTEM_ID_NAME, dsId);
props.setProperty("mcast-port", "0");
props.setProperty(DistributionConfig.LOCATORS_NAME, "localhost[" + port + "]");
props.setProperty(DistributionConfig.START_LOCATOR_NAME, "localhost[" + port + "]");
getSystem(props);
// Locator locator = Locator.startLocatorAndDS(port, File.createTempFile("locator", ""), props);
// system = (InternalDistributedSystem) locator.getDistributedSystem();
return port;
}
};
return (Integer) vm.invoke(createSystem);
}
private void checkId(VM vm, final int dsId) {
SerializableCallable createSystem = new SerializableCallable() {
public Object call() throws Exception {
DistributionManager dm = (DistributionManager) InternalDistributedSystem.getAnyInstance().getDistributionManager();
assertEquals(dsId, dm.getDistributedSystemId());
return null;
}
};
vm.invoke(createSystem);
}
}
|
GEODE-558 DistributedSystemIdDUnitTest.testInfectiousId locator already exist
Added disconnectAllFromDS to preSetUp to protect the test from other
flaky tests.
|
geode-core/src/test/java/com/gemstone/gemfire/pdx/DistributedSystemIdDUnitTest.java
|
GEODE-558 DistributedSystemIdDUnitTest.testInfectiousId locator already exist
|
|
Java
|
apache-2.0
|
0cb69836f91e39cc7dff5c2f695687981fd869a9
| 0
|
clibois/wss4j,clibois/wss4j,asoldano/wss4j,apache/wss4j,jimma/wss4j,asoldano/wss4j,jimma/wss4j,apache/wss4j
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.wss4j.dom.processor;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.Attachment;
import org.apache.wss4j.common.ext.AttachmentRequestCallback;
import org.apache.wss4j.common.ext.AttachmentResultCallback;
import org.apache.wss4j.common.util.AttachmentUtils;
import org.apache.xml.security.algorithms.JCEMapper;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.wss4j.common.bsp.BSPRule;
import org.apache.wss4j.common.crypto.AlgorithmSuite;
import org.apache.wss4j.common.crypto.AlgorithmSuiteValidator;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.WSDerivedKeyTokenPrincipal;
import org.apache.wss4j.common.util.KeyUtils;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.WSDataRef;
import org.apache.wss4j.dom.WSDocInfo;
import org.apache.wss4j.dom.WSSecurityEngineResult;
import org.apache.wss4j.dom.bsp.BSPEnforcer;
import org.apache.wss4j.dom.handler.RequestData;
import org.apache.wss4j.dom.message.CallbackLookup;
import org.apache.wss4j.dom.message.DOMCallbackLookup;
import org.apache.wss4j.dom.message.token.SecurityTokenReference;
import org.apache.wss4j.dom.str.STRParser;
import org.apache.wss4j.dom.str.SecurityTokenRefSTRParser;
import org.apache.wss4j.dom.util.WSSecurityUtil;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLEncryptionException;
public class ReferenceListProcessor implements Processor {
private static final org.slf4j.Logger LOG =
org.slf4j.LoggerFactory.getLogger(ReferenceListProcessor.class);
public List<WSSecurityEngineResult> handleToken(
Element elem,
RequestData data,
WSDocInfo wsDocInfo
) throws WSSecurityException {
if (LOG.isDebugEnabled()) {
LOG.debug("Found reference list element");
}
List<WSDataRef> dataRefs = handleReferenceList(elem, data, wsDocInfo);
WSSecurityEngineResult result =
new WSSecurityEngineResult(WSConstants.ENCR, dataRefs);
result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id"));
wsDocInfo.addTokenElement(elem);
wsDocInfo.addResult(result);
return java.util.Collections.singletonList(result);
}
/**
* Dereferences and decodes encrypted data elements.
*
* @param elem contains the <code>ReferenceList</code> to the encrypted
* data elements
*/
private List<WSDataRef> handleReferenceList(
Element elem,
RequestData data,
WSDocInfo wsDocInfo
) throws WSSecurityException {
List<WSDataRef> dataRefs = new ArrayList<WSDataRef>();
//find out if there's an EncryptedKey in the doc (AsymmetricBinding)
Element wsseHeaderElement = wsDocInfo.getSecurityHeader();
boolean asymBinding = WSSecurityUtil.getDirectChildElement(
wsseHeaderElement, WSConstants.ENC_KEY_LN, WSConstants.ENC_NS) != null;
for (Node node = elem.getFirstChild();
node != null;
node = node.getNextSibling()
) {
if (Node.ELEMENT_NODE == node.getNodeType()
&& WSConstants.ENC_NS.equals(node.getNamespaceURI())
&& "DataReference".equals(node.getLocalName())) {
String dataRefURI = ((Element) node).getAttributeNS(null, "URI");
if (dataRefURI.charAt(0) == '#') {
dataRefURI = dataRefURI.substring(1);
}
if (wsDocInfo.getResultByTag(WSConstants.ENCR, dataRefURI) == null) {
WSDataRef dataRef =
decryptDataRefEmbedded(
elem.getOwnerDocument(), dataRefURI, data, wsDocInfo, asymBinding);
dataRefs.add(dataRef);
}
}
}
return dataRefs;
}
/**
* Decrypt an (embedded) EncryptedData element referenced by dataRefURI.
*/
private WSDataRef decryptDataRefEmbedded(
Document doc,
String dataRefURI,
RequestData data,
WSDocInfo wsDocInfo,
boolean asymBinding
) throws WSSecurityException {
if (LOG.isDebugEnabled()) {
LOG.debug("Found data reference: " + dataRefURI);
}
//
// Find the encrypted data element referenced by dataRefURI
//
Element encryptedDataElement = findEncryptedDataElement(doc, wsDocInfo, dataRefURI);
if (encryptedDataElement != null && asymBinding && data.isRequireSignedEncryptedDataElements()) {
WSSecurityUtil.verifySignedElement(encryptedDataElement, doc, wsDocInfo.getSecurityHeader());
}
//
// Prepare the SecretKey object to decrypt EncryptedData
//
String symEncAlgo = X509Util.getEncAlgo(encryptedDataElement);
Element keyInfoElement =
WSSecurityUtil.getDirectChildElement(
encryptedDataElement, "KeyInfo", WSConstants.SIG_NS
);
// KeyInfo cannot be null
if (keyInfoElement == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noKeyinfo");
}
// Check BSP compliance
checkBSPCompliance(keyInfoElement, symEncAlgo, data.getBSPEnforcer());
//
// Try to get a security reference token, if none found try to get a
// shared key using a KeyName.
//
Element secRefToken =
WSSecurityUtil.getDirectChildElement(
keyInfoElement, "SecurityTokenReference", WSConstants.WSSE_NS
);
SecretKey symmetricKey = null;
Principal principal = null;
if (secRefToken == null) {
symmetricKey = X509Util.getSharedKey(keyInfoElement, symEncAlgo, data.getCallbackHandler());
} else {
STRParser strParser = new SecurityTokenRefSTRParser();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo);
strParser.parseSecurityTokenReference(
secRefToken, data,
wsDocInfo, parameters
);
byte[] secretKey = strParser.getSecretKey();
principal = strParser.getPrincipal();
symmetricKey = KeyUtils.prepareSecretKey(symEncAlgo, secretKey);
}
// Check for compliance against the defined AlgorithmSuite
AlgorithmSuite algorithmSuite = data.getAlgorithmSuite();
if (algorithmSuite != null) {
AlgorithmSuiteValidator algorithmSuiteValidator = new
AlgorithmSuiteValidator(algorithmSuite);
if (principal instanceof WSDerivedKeyTokenPrincipal) {
algorithmSuiteValidator.checkDerivedKeyAlgorithm(
((WSDerivedKeyTokenPrincipal)principal).getAlgorithm()
);
algorithmSuiteValidator.checkEncryptionDerivedKeyLength(
((WSDerivedKeyTokenPrincipal)principal).getLength()
);
}
algorithmSuiteValidator.checkSymmetricKeyLength(symmetricKey.getEncoded().length);
algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo);
}
return
decryptEncryptedData(
doc, dataRefURI, encryptedDataElement, symmetricKey, symEncAlgo, data
);
}
/**
* Check for BSP compliance
* @param keyInfoElement The KeyInfo element child
* @param encAlgo The encryption algorithm
* @throws WSSecurityException
*/
private static void checkBSPCompliance(
Element keyInfoElement,
String encAlgo,
BSPEnforcer bspEnforcer
) throws WSSecurityException {
// We can only have one token reference
int result = 0;
Node node = keyInfoElement.getFirstChild();
Element child = null;
while (node != null) {
if (Node.ELEMENT_NODE == node.getNodeType()) {
result++;
child = (Element)node;
}
node = node.getNextSibling();
}
if (result != 1) {
bspEnforcer.handleBSPRule(BSPRule.R5424);
}
if (child == null || !WSConstants.WSSE_NS.equals(child.getNamespaceURI()) ||
!SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(child.getLocalName())) {
bspEnforcer.handleBSPRule(BSPRule.R5426);
}
// EncryptionAlgorithm cannot be null
if (encAlgo == null) {
bspEnforcer.handleBSPRule(BSPRule.R5601);
}
// EncryptionAlgorithm must be 3DES, or AES128, or AES256
if (!WSConstants.TRIPLE_DES.equals(encAlgo)
&& !WSConstants.AES_128.equals(encAlgo)
&& !WSConstants.AES_128_GCM.equals(encAlgo)
&& !WSConstants.AES_256.equals(encAlgo)
&& !WSConstants.AES_256_GCM.equals(encAlgo)) {
bspEnforcer.handleBSPRule(BSPRule.R5620);
}
}
/**
* Look up the encrypted data. First try Id="someURI". If no such Id then try
* wsu:Id="someURI".
*
* @param doc The document in which to find EncryptedData
* @param wsDocInfo The WSDocInfo object to use
* @param dataRefURI The URI of EncryptedData
* @return The EncryptedData element
* @throws WSSecurityException if the EncryptedData element referenced by dataRefURI is
* not found
*/
public static Element
findEncryptedDataElement(
Document doc,
WSDocInfo wsDocInfo,
String dataRefURI
) throws WSSecurityException {
CallbackLookup callbackLookup = wsDocInfo.getCallbackLookup();
if (callbackLookup == null) {
callbackLookup = new DOMCallbackLookup(doc);
}
Element encryptedDataElement =
callbackLookup.getElement(dataRefURI, null, true);
if (encryptedDataElement == null) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.INVALID_SECURITY, "dataRef", dataRefURI);
}
if (encryptedDataElement.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
&& encryptedDataElement.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {
Node child = encryptedDataElement.getFirstChild();
while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
child = child.getNextSibling();
}
return (Element)child;
}
return encryptedDataElement;
}
/**
* Decrypt the EncryptedData argument using a SecretKey.
* @param doc The (document) owner of EncryptedData
* @param dataRefURI The URI of EncryptedData
* @param encData The EncryptedData element
* @param symmetricKey The SecretKey with which to decrypt EncryptedData
* @param symEncAlgo The symmetric encryption algorithm to use
* @throws WSSecurityException
*/
public static WSDataRef
decryptEncryptedData(
Document doc,
String dataRefURI,
Element encData,
SecretKey symmetricKey,
String symEncAlgo,
RequestData requestData
) throws WSSecurityException {
WSDataRef dataRef = new WSDataRef();
dataRef.setWsuId(dataRefURI);
dataRef.setAlgorithm(symEncAlgo);
String typeStr = encData.getAttribute("Type");
if (typeStr != null &&
(WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_CONTENT_ONLY.equals(typeStr) ||
WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE.equals(typeStr))) {
try {
Element cipherData = WSSecurityUtil.getDirectChildElement(encData, "CipherData", WSConstants.ENC_NS);
if (cipherData == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
Element cipherReference = WSSecurityUtil.getDirectChildElement(cipherData, "CipherReference", WSConstants.ENC_NS);
if (cipherReference == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
String uri = cipherReference.getAttributeNS(null, "URI");
if (uri == null || uri.length() < 5) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
if (!uri.startsWith("cid:")) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
dataRef.setWsuId(uri);
dataRef.setAttachment(true);
CallbackHandler attachmentCallbackHandler = requestData.getAttachmentCallbackHandler();
if (attachmentCallbackHandler == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
final String attachmentId = uri.substring(4);
AttachmentRequestCallback attachmentRequestCallback = new AttachmentRequestCallback();
attachmentRequestCallback.setAttachmentId(attachmentId);
attachmentCallbackHandler.handle(new Callback[]{attachmentRequestCallback});
List<Attachment> attachments = attachmentRequestCallback.getAttachments();
if (attachments == null || attachments.isEmpty() || !attachmentId.equals(attachments.get(0).getId())) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.INVALID_SECURITY,
"empty", "Attachment not found"
);
}
Attachment attachment = attachments.get(0);
final String encAlgo = X509Util.getEncAlgo(encData);
final String jceAlgorithm =
JCEMapper.translateURItoJCEID(encAlgo);
final Cipher cipher = Cipher.getInstance(jceAlgorithm);
InputStream attachmentInputStream =
AttachmentUtils.setupAttachmentDecryptionStream(
encAlgo, cipher, symmetricKey, attachment.getSourceStream());
Attachment resultAttachment = new Attachment();
resultAttachment.setId(attachment.getId());
resultAttachment.setMimeType(encData.getAttributeNS(null, "MimeType"));
resultAttachment.setSourceStream(attachmentInputStream);
resultAttachment.addHeaders(attachment.getHeaders());
if (WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE.equals(typeStr)) {
AttachmentUtils.readAndReplaceEncryptedAttachmentHeaders(
resultAttachment.getHeaders(), attachmentInputStream);
}
AttachmentResultCallback attachmentResultCallback = new AttachmentResultCallback();
attachmentResultCallback.setAttachment(resultAttachment);
attachmentResultCallback.setAttachmentId(resultAttachment.getId());
attachmentCallbackHandler.handle(new Callback[]{attachmentResultCallback});
} catch (UnsupportedCallbackException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (IOException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (NoSuchPaddingException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
}
dataRef.setContent(true);
// Remove this EncryptedData from the security header to avoid processing it again
encData.getParentNode().removeChild(encData);
return dataRef;
}
boolean content = X509Util.isContent(encData);
dataRef.setContent(content);
Node parent = encData.getParentNode();
Node previousSibling = encData.getPreviousSibling();
if (content) {
encData = (Element) encData.getParentNode();
parent = encData.getParentNode();
}
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(symEncAlgo);
xmlCipher.setSecureValidation(true);
xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
} catch (XMLEncryptionException ex) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, ex
);
}
try {
xmlCipher.doFinal(doc, encData, content);
} catch (Exception ex) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex);
}
if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
&& parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)
|| parent.getLocalName().equals(WSConstants.ENCRYPED_ASSERTION_LN)
&& parent.getNamespaceURI().equals(WSConstants.SAML2_NS)) {
Node decryptedHeader = parent.getFirstChild();
Node soapHeader = parent.getParentNode();
soapHeader.replaceChild(decryptedHeader, parent);
dataRef.setProtectedElement((Element)decryptedHeader);
dataRef.setXpath(getXPath(decryptedHeader));
} else if (content) {
dataRef.setProtectedElement(encData);
dataRef.setXpath(getXPath(encData));
} else {
Node decryptedNode;
if (previousSibling == null) {
decryptedNode = parent.getFirstChild();
} else {
decryptedNode = previousSibling.getNextSibling();
}
if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
dataRef.setProtectedElement((Element)decryptedNode);
}
dataRef.setXpath(getXPath(decryptedNode));
}
return dataRef;
}
public String getId() {
return null;
}
/**
* @param decryptedNode the decrypted node
* @return a fully built xpath
* (eg. "/soapenv:Envelope/soapenv:Body/ns:decryptedElement")
* if the decryptedNode is an Element or an Attr node and is not detached
* from the document. <code>null</code> otherwise
*/
public static String getXPath(Node decryptedNode) {
if (decryptedNode == null) {
return null;
}
String result = "";
if (Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
result = decryptedNode.getNodeName();
result = prependFullPath(result, decryptedNode.getParentNode());
} else if (Node.ATTRIBUTE_NODE == decryptedNode.getNodeType()) {
result = "@" + decryptedNode.getNodeName();
result = prependFullPath(result, ((Attr)decryptedNode).getOwnerElement());
} else {
return null;
}
return result;
}
/**
* Recursively build an absolute xpath (starting with the root "/")
*
* @param xpath the xpath expression built so far
* @param node the current node whose name is to be prepended
* @return a fully built xpath
*/
private static String prependFullPath(String xpath, Node node) {
if (node == null) {
// probably a detached node... not really useful
return null;
} else if (Node.ELEMENT_NODE == node.getNodeType()) {
xpath = node.getNodeName() + "/" + xpath;
return prependFullPath(xpath, node.getParentNode());
} else if (Node.DOCUMENT_NODE == node.getNodeType()) {
return "/" + xpath;
} else {
return prependFullPath(xpath, node.getParentNode());
}
}
}
|
ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/ReferenceListProcessor.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.wss4j.dom.processor;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.Attachment;
import org.apache.wss4j.common.ext.AttachmentRequestCallback;
import org.apache.wss4j.common.ext.AttachmentResultCallback;
import org.apache.wss4j.common.util.AttachmentUtils;
import org.apache.xml.security.algorithms.JCEMapper;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.wss4j.common.bsp.BSPRule;
import org.apache.wss4j.common.crypto.AlgorithmSuite;
import org.apache.wss4j.common.crypto.AlgorithmSuiteValidator;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.WSDerivedKeyTokenPrincipal;
import org.apache.wss4j.common.util.KeyUtils;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.WSDataRef;
import org.apache.wss4j.dom.WSDocInfo;
import org.apache.wss4j.dom.WSSecurityEngineResult;
import org.apache.wss4j.dom.bsp.BSPEnforcer;
import org.apache.wss4j.dom.handler.RequestData;
import org.apache.wss4j.dom.message.CallbackLookup;
import org.apache.wss4j.dom.message.DOMCallbackLookup;
import org.apache.wss4j.dom.message.token.SecurityTokenReference;
import org.apache.wss4j.dom.str.STRParser;
import org.apache.wss4j.dom.str.SecurityTokenRefSTRParser;
import org.apache.wss4j.dom.util.WSSecurityUtil;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLEncryptionException;
public class ReferenceListProcessor implements Processor {
private static final org.slf4j.Logger LOG =
org.slf4j.LoggerFactory.getLogger(ReferenceListProcessor.class);
public List<WSSecurityEngineResult> handleToken(
Element elem,
RequestData data,
WSDocInfo wsDocInfo
) throws WSSecurityException {
if (LOG.isDebugEnabled()) {
LOG.debug("Found reference list element");
}
List<WSDataRef> dataRefs = handleReferenceList(elem, data, wsDocInfo);
WSSecurityEngineResult result =
new WSSecurityEngineResult(WSConstants.ENCR, dataRefs);
result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id"));
wsDocInfo.addTokenElement(elem);
wsDocInfo.addResult(result);
return java.util.Collections.singletonList(result);
}
/**
* Dereferences and decodes encrypted data elements.
*
* @param elem contains the <code>ReferenceList</code> to the encrypted
* data elements
*/
private List<WSDataRef> handleReferenceList(
Element elem,
RequestData data,
WSDocInfo wsDocInfo
) throws WSSecurityException {
List<WSDataRef> dataRefs = new ArrayList<WSDataRef>();
//find out if there's an EncryptedKey in the doc (AsymmetricBinding)
Element wsseHeaderElement = wsDocInfo.getSecurityHeader();
boolean asymBinding = WSSecurityUtil.getDirectChildElement(
wsseHeaderElement, WSConstants.ENC_KEY_LN, WSConstants.ENC_NS) != null;
for (Node node = elem.getFirstChild();
node != null;
node = node.getNextSibling()
) {
if (Node.ELEMENT_NODE == node.getNodeType()
&& WSConstants.ENC_NS.equals(node.getNamespaceURI())
&& "DataReference".equals(node.getLocalName())) {
String dataRefURI = ((Element) node).getAttributeNS(null, "URI");
if (dataRefURI.charAt(0) == '#') {
dataRefURI = dataRefURI.substring(1);
}
if (wsDocInfo.getResultByTag(WSConstants.ENCR, dataRefURI) == null) {
WSDataRef dataRef =
decryptDataRefEmbedded(
elem.getOwnerDocument(), dataRefURI, data, wsDocInfo, asymBinding);
dataRefs.add(dataRef);
}
}
}
return dataRefs;
}
/**
* Decrypt an (embedded) EncryptedData element referenced by dataRefURI.
*/
private WSDataRef decryptDataRefEmbedded(
Document doc,
String dataRefURI,
RequestData data,
WSDocInfo wsDocInfo,
boolean asymBinding
) throws WSSecurityException {
if (LOG.isDebugEnabled()) {
LOG.debug("Found data reference: " + dataRefURI);
}
//
// Find the encrypted data element referenced by dataRefURI
//
Element encryptedDataElement = findEncryptedDataElement(doc, wsDocInfo, dataRefURI);
if (encryptedDataElement != null && asymBinding && data.isRequireSignedEncryptedDataElements()) {
WSSecurityUtil.verifySignedElement(encryptedDataElement, doc, wsDocInfo.getSecurityHeader());
}
//
// Prepare the SecretKey object to decrypt EncryptedData
//
String symEncAlgo = X509Util.getEncAlgo(encryptedDataElement);
Element keyInfoElement =
WSSecurityUtil.getDirectChildElement(
encryptedDataElement, "KeyInfo", WSConstants.SIG_NS
);
// KeyInfo cannot be null
if (keyInfoElement == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noKeyinfo");
}
// Check BSP compliance
checkBSPCompliance(keyInfoElement, symEncAlgo, data.getBSPEnforcer());
//
// Try to get a security reference token, if none found try to get a
// shared key using a KeyName.
//
Element secRefToken =
WSSecurityUtil.getDirectChildElement(
keyInfoElement, "SecurityTokenReference", WSConstants.WSSE_NS
);
SecretKey symmetricKey = null;
Principal principal = null;
if (secRefToken == null) {
symmetricKey = X509Util.getSharedKey(keyInfoElement, symEncAlgo, data.getCallbackHandler());
} else {
STRParser strParser = new SecurityTokenRefSTRParser();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo);
strParser.parseSecurityTokenReference(
secRefToken, data,
wsDocInfo, parameters
);
byte[] secretKey = strParser.getSecretKey();
principal = strParser.getPrincipal();
symmetricKey = KeyUtils.prepareSecretKey(symEncAlgo, secretKey);
}
// Check for compliance against the defined AlgorithmSuite
AlgorithmSuite algorithmSuite = data.getAlgorithmSuite();
if (algorithmSuite != null) {
AlgorithmSuiteValidator algorithmSuiteValidator = new
AlgorithmSuiteValidator(algorithmSuite);
if (principal instanceof WSDerivedKeyTokenPrincipal) {
algorithmSuiteValidator.checkDerivedKeyAlgorithm(
((WSDerivedKeyTokenPrincipal)principal).getAlgorithm()
);
algorithmSuiteValidator.checkEncryptionDerivedKeyLength(
((WSDerivedKeyTokenPrincipal)principal).getLength()
);
}
algorithmSuiteValidator.checkSymmetricKeyLength(symmetricKey.getEncoded().length);
algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo);
}
return
decryptEncryptedData(
doc, dataRefURI, encryptedDataElement, symmetricKey, symEncAlgo, data
);
}
/**
* Check for BSP compliance
* @param keyInfoElement The KeyInfo element child
* @param encAlgo The encryption algorithm
* @throws WSSecurityException
*/
private static void checkBSPCompliance(
Element keyInfoElement,
String encAlgo,
BSPEnforcer bspEnforcer
) throws WSSecurityException {
// We can only have one token reference
int result = 0;
Node node = keyInfoElement.getFirstChild();
Element child = null;
while (node != null) {
if (Node.ELEMENT_NODE == node.getNodeType()) {
result++;
child = (Element)node;
}
node = node.getNextSibling();
}
if (result != 1) {
bspEnforcer.handleBSPRule(BSPRule.R5424);
}
if (child == null || !WSConstants.WSSE_NS.equals(child.getNamespaceURI()) ||
!SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(child.getLocalName())) {
bspEnforcer.handleBSPRule(BSPRule.R5426);
}
// EncryptionAlgorithm cannot be null
if (encAlgo == null) {
bspEnforcer.handleBSPRule(BSPRule.R5601);
}
// EncryptionAlgorithm must be 3DES, or AES128, or AES256
if (!WSConstants.TRIPLE_DES.equals(encAlgo)
&& !WSConstants.AES_128.equals(encAlgo)
&& !WSConstants.AES_128_GCM.equals(encAlgo)
&& !WSConstants.AES_256.equals(encAlgo)
&& !WSConstants.AES_256_GCM.equals(encAlgo)) {
bspEnforcer.handleBSPRule(BSPRule.R5620);
}
}
/**
* Look up the encrypted data. First try Id="someURI". If no such Id then try
* wsu:Id="someURI".
*
* @param doc The document in which to find EncryptedData
* @param wsDocInfo The WSDocInfo object to use
* @param dataRefURI The URI of EncryptedData
* @return The EncryptedData element
* @throws WSSecurityException if the EncryptedData element referenced by dataRefURI is
* not found
*/
public static Element
findEncryptedDataElement(
Document doc,
WSDocInfo wsDocInfo,
String dataRefURI
) throws WSSecurityException {
CallbackLookup callbackLookup = wsDocInfo.getCallbackLookup();
if (callbackLookup == null) {
callbackLookup = new DOMCallbackLookup(doc);
}
Element encryptedDataElement =
callbackLookup.getElement(dataRefURI, null, true);
if (encryptedDataElement == null) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.INVALID_SECURITY, "dataRef", dataRefURI);
}
if (encryptedDataElement.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
&& encryptedDataElement.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {
Node child = encryptedDataElement.getFirstChild();
while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
child = child.getNextSibling();
}
return (Element)child;
}
return encryptedDataElement;
}
/**
* Decrypt the EncryptedData argument using a SecretKey.
* @param doc The (document) owner of EncryptedData
* @param dataRefURI The URI of EncryptedData
* @param encData The EncryptedData element
* @param symmetricKey The SecretKey with which to decrypt EncryptedData
* @param symEncAlgo The symmetric encryption algorithm to use
* @throws WSSecurityException
*/
public static WSDataRef
decryptEncryptedData(
Document doc,
String dataRefURI,
Element encData,
SecretKey symmetricKey,
String symEncAlgo,
RequestData requestData
) throws WSSecurityException {
WSDataRef dataRef = new WSDataRef();
dataRef.setWsuId(dataRefURI);
dataRef.setAlgorithm(symEncAlgo);
String typeStr = encData.getAttribute("Type");
if (typeStr != null &&
(WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_CONTENT_ONLY.equals(typeStr) ||
WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE.equals(typeStr))) {
try {
Element cipherData = WSSecurityUtil.getDirectChildElement(encData, "CipherData", WSConstants.ENC_NS);
if (cipherData == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
Element cipherReference = WSSecurityUtil.getDirectChildElement(cipherData, "CipherReference", WSConstants.ENC_NS);
if (cipherReference == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
String uri = cipherReference.getAttributeNS(null, "URI");
if (uri == null || uri.length() < 5) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
if (!uri.startsWith("cid:")) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
dataRef.setWsuId(uri);
dataRef.setAttachment(true);
CallbackHandler attachmentCallbackHandler = requestData.getAttachmentCallbackHandler();
if (attachmentCallbackHandler == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK);
}
final String attachmentId = uri.substring(4);
AttachmentRequestCallback attachmentRequestCallback = new AttachmentRequestCallback();
attachmentRequestCallback.setAttachmentId(attachmentId);
attachmentCallbackHandler.handle(new Callback[]{attachmentRequestCallback});
List<Attachment> attachments = attachmentRequestCallback.getAttachments();
if (attachments == null || attachments.isEmpty() || !attachmentId.equals(attachments.get(0).getId())) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.INVALID_SECURITY,
"empty", "Attachment not found"
);
}
Attachment attachment = attachments.get(0);
final String encAlgo = X509Util.getEncAlgo(encData);
final String jceAlgorithm =
JCEMapper.translateURItoJCEID(encAlgo);
final Cipher cipher = Cipher.getInstance(jceAlgorithm);
InputStream attachmentInputStream =
AttachmentUtils.setupAttachmentDecryptionStream(
encAlgo, cipher, symmetricKey, attachment.getSourceStream());
Attachment resultAttachment = new Attachment();
resultAttachment.setId(attachment.getId());
resultAttachment.setMimeType(encData.getAttributeNS(null, "MimeType"));
resultAttachment.setSourceStream(attachmentInputStream);
resultAttachment.addHeaders(attachment.getHeaders());
if (WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE.equals(typeStr)) {
AttachmentUtils.readAndReplaceEncryptedAttachmentHeaders(
resultAttachment.getHeaders(), attachmentInputStream);
}
AttachmentResultCallback attachmentResultCallback = new AttachmentResultCallback();
attachmentResultCallback.setAttachment(resultAttachment);
attachmentResultCallback.setAttachmentId(resultAttachment.getId());
attachmentCallbackHandler.handle(new Callback[]{attachmentResultCallback});
} catch (UnsupportedCallbackException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (IOException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
} catch (NoSuchPaddingException e) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.FAILED_CHECK, e);
}
dataRef.setContent(true);
// Remove this EncryptedData from the security header to avoid processing it again
encData.getParentNode().removeChild(encData);
return dataRef;
}
boolean content = X509Util.isContent(encData);
dataRef.setContent(content);
Node parent = encData.getParentNode();
Node previousSibling = encData.getPreviousSibling();
if (content) {
encData = (Element) encData.getParentNode();
parent = encData.getParentNode();
}
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(symEncAlgo);
xmlCipher.setSecureValidation(true);
xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
} catch (XMLEncryptionException ex) {
throw new WSSecurityException(
WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, ex
);
}
try {
xmlCipher.doFinal(doc, encData, content);
} catch (Exception ex) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_CHECK, ex);
}
if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
&& parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {
Node decryptedHeader = parent.getFirstChild();
Node soapHeader = parent.getParentNode();
soapHeader.replaceChild(decryptedHeader, parent);
dataRef.setProtectedElement((Element)decryptedHeader);
dataRef.setXpath(getXPath(decryptedHeader));
} else if (content) {
dataRef.setProtectedElement(encData);
dataRef.setXpath(getXPath(encData));
} else {
Node decryptedNode;
if (previousSibling == null) {
decryptedNode = parent.getFirstChild();
} else {
decryptedNode = previousSibling.getNextSibling();
}
if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
dataRef.setProtectedElement((Element)decryptedNode);
}
dataRef.setXpath(getXPath(decryptedNode));
}
return dataRef;
}
public String getId() {
return null;
}
/**
* @param decryptedNode the decrypted node
* @return a fully built xpath
* (eg. "/soapenv:Envelope/soapenv:Body/ns:decryptedElement")
* if the decryptedNode is an Element or an Attr node and is not detached
* from the document. <code>null</code> otherwise
*/
public static String getXPath(Node decryptedNode) {
if (decryptedNode == null) {
return null;
}
String result = "";
if (Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
result = decryptedNode.getNodeName();
result = prependFullPath(result, decryptedNode.getParentNode());
} else if (Node.ATTRIBUTE_NODE == decryptedNode.getNodeType()) {
result = "@" + decryptedNode.getNodeName();
result = prependFullPath(result, ((Attr)decryptedNode).getOwnerElement());
} else {
return null;
}
return result;
}
/**
* Recursively build an absolute xpath (starting with the root "/")
*
* @param xpath the xpath expression built so far
* @param node the current node whose name is to be prepended
* @return a fully built xpath
*/
private static String prependFullPath(String xpath, Node node) {
if (node == null) {
// probably a detached node... not really useful
return null;
} else if (Node.ELEMENT_NODE == node.getNodeType()) {
xpath = node.getNodeName() + "/" + xpath;
return prependFullPath(xpath, node.getParentNode());
} else if (Node.DOCUMENT_NODE == node.getNodeType()) {
return "/" + xpath;
} else {
return prependFullPath(xpath, node.getParentNode());
}
}
}
|
[CXF-497] - Remove the EncryptedAssertion wrapper after decrypting
git-svn-id: 10bc45916fe30ae642aa5037c9a4b05727bba413@1589701 13f79535-47bb-0310-9956-ffa450edef68
|
ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/ReferenceListProcessor.java
|
[CXF-497] - Remove the EncryptedAssertion wrapper after decrypting
|
|
Java
|
apache-2.0
|
93b5e832b63ef42e2621d8797a40c508a7cd5b1c
| 0
|
DavidAlphaFox/netty,DavidAlphaFox/netty,DavidAlphaFox/netty,yipen9/netty,imangry/netty-zh,yipen9/netty,purplefox/netty-4.0.2.8-hacked,purplefox/netty-4.0.2.8-hacked,purplefox/netty-4.0.2.8-hacked,chanakaudaya/netty,purplefox/netty-4.0.2.8-hacked,imangry/netty-zh,yipen9/netty,imangry/netty-zh,chanakaudaya/netty,imangry/netty-zh,yipen9/netty,imangry/netty-zh,chanakaudaya/netty,chanakaudaya/netty,chanakaudaya/netty,DavidAlphaFox/netty
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import java.util.List;
/**
* A decoder that splits the received {@link ByteBuf}s by one or more
* delimiters. It is particularly useful for decoding the frames which ends
* with a delimiter such as {@link Delimiters#nulDelimiter() NUL} or
* {@linkplain Delimiters#lineDelimiter() newline characters}.
*
* <h3>Predefined delimiters</h3>
* <p>
* {@link Delimiters} defines frequently used delimiters for convenience' sake.
*
* <h3>Specifying more than one delimiter</h3>
* <p>
* {@link DelimiterBasedFrameDecoder} allows you to specify more than one
* delimiter. If more than one delimiter is found in the buffer, it chooses
* the delimiter which produces the shortest frame. For example, if you have
* the following data in the buffer:
* <pre>
* +--------------+
* | ABC\nDEF\r\n |
* +--------------+
* </pre>
* a {@link DelimiterBasedFrameDecoder}({@link Delimiters#lineDelimiter() Delimiters.lineDelimiter()})
* will choose {@code '\n'} as the first delimiter and produce two frames:
* <pre>
* +-----+-----+
* | ABC | DEF |
* +-----+-----+
* </pre>
* rather than incorrectly choosing {@code '\r\n'} as the first delimiter:
* <pre>
* +----------+
* | ABC\nDEF |
* +----------+
* </pre>
*/
public class DelimiterBasedFrameDecoder extends ByteToMessageDecoder {
private final ByteBuf[] delimiters;
private final int maxFrameLength;
private final boolean stripDelimiter;
private final boolean failFast;
private boolean discardingTooLongFrame;
private int tooLongFrameLength;
/** Set only when decoding with "\n" and "\r\n" as the delimiter. */
private final LineBasedFrameDecoder lineBasedDecoder;
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf delimiter) {
this(maxFrameLength, true, delimiter);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, ByteBuf delimiter) {
this(maxFrameLength, stripDelimiter, true, delimiter);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param failFast If <tt>true</tt>, a {@link TooLongFrameException} is
* thrown as soon as the decoder notices the length of the
* frame will exceed <tt>maxFrameLength</tt> regardless of
* whether the entire frame has been read.
* If <tt>false</tt>, a {@link TooLongFrameException} is
* thrown after the entire frame that exceeds
* <tt>maxFrameLength</tt> has been read.
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, boolean failFast,
ByteBuf delimiter) {
this(maxFrameLength, stripDelimiter, failFast, new ByteBuf[] {
delimiter.slice(delimiter.readerIndex(), delimiter.readableBytes())});
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf... delimiters) {
this(maxFrameLength, true, delimiters);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, ByteBuf... delimiters) {
this(maxFrameLength, stripDelimiter, true, delimiters);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param failFast If <tt>true</tt>, a {@link TooLongFrameException} is
* thrown as soon as the decoder notices the length of the
* frame will exceed <tt>maxFrameLength</tt> regardless of
* whether the entire frame has been read.
* If <tt>false</tt>, a {@link TooLongFrameException} is
* thrown after the entire frame that exceeds
* <tt>maxFrameLength</tt> has been read.
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, boolean failFast, ByteBuf... delimiters) {
validateMaxFrameLength(maxFrameLength);
if (delimiters == null) {
throw new NullPointerException("delimiters");
}
if (delimiters.length == 0) {
throw new IllegalArgumentException("empty delimiters");
}
if (isLineBased(delimiters) && !isSubclass()) {
lineBasedDecoder = new LineBasedFrameDecoder(maxFrameLength, stripDelimiter, failFast);
this.delimiters = null;
} else {
this.delimiters = new ByteBuf[delimiters.length];
for (int i = 0; i < delimiters.length; i ++) {
ByteBuf d = delimiters[i];
validateDelimiter(d);
this.delimiters[i] = d.slice(d.readerIndex(), d.readableBytes());
}
lineBasedDecoder = null;
}
this.maxFrameLength = maxFrameLength;
this.stripDelimiter = stripDelimiter;
this.failFast = failFast;
}
/** Returns true if the delimiters are "\n" and "\r\n". */
private static boolean isLineBased(final ByteBuf[] delimiters) {
if (delimiters.length != 2) {
return false;
}
ByteBuf a = delimiters[0];
ByteBuf b = delimiters[1];
if (a.capacity() < b.capacity()) {
a = delimiters[1];
b = delimiters[0];
}
return a.capacity() == 2 && b.capacity() == 1
&& a.getByte(0) == '\r' && a.getByte(1) == '\n'
&& b.getByte(0) == '\n';
}
/**
* Return {@code true} if the current instance is a subclass of DelimiterBasedFrameDecoder
*/
private boolean isSubclass() {
return getClass() != DelimiterBasedFrameDecoder.class;
}
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Object decoded = decode(ctx, in);
if (decoded != null) {
out.add(decoded);
}
}
/**
* Create a frame out of the {@link ByteBuf} and return it.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
* @param buffer the {@link ByteBuf} from which to read data
* @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
* be created.
*/
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
if (lineBasedDecoder != null) {
return lineBasedDecoder.decode(ctx, buffer);
}
// Try all delimiters and choose the delimiter which yields the shortest frame.
int minFrameLength = Integer.MAX_VALUE;
ByteBuf minDelim = null;
for (ByteBuf delim: delimiters) {
int frameLength = indexOf(buffer, delim);
if (frameLength >= 0 && frameLength < minFrameLength) {
minFrameLength = frameLength;
minDelim = delim;
}
}
if (minDelim != null) {
int minDelimLength = minDelim.capacity();
ByteBuf frame;
if (discardingTooLongFrame) {
// We've just finished discarding a very large frame.
// Go back to the initial state.
discardingTooLongFrame = false;
buffer.skipBytes(minFrameLength + minDelimLength);
int tooLongFrameLength = this.tooLongFrameLength;
this.tooLongFrameLength = 0;
if (!failFast) {
fail(tooLongFrameLength);
}
return null;
}
if (minFrameLength > maxFrameLength) {
// Discard read frame.
buffer.skipBytes(minFrameLength + minDelimLength);
fail(minFrameLength);
return null;
}
if (stripDelimiter) {
frame = buffer.readSlice(minFrameLength);
buffer.skipBytes(minDelimLength);
} else {
frame = buffer.readSlice(minFrameLength + minDelimLength);
}
return frame.retain();
} else {
if (!discardingTooLongFrame) {
if (buffer.readableBytes() > maxFrameLength) {
// Discard the content of the buffer until a delimiter is found.
tooLongFrameLength = buffer.readableBytes();
buffer.skipBytes(buffer.readableBytes());
discardingTooLongFrame = true;
if (failFast) {
fail(tooLongFrameLength);
}
}
} else {
// Still discarding the buffer since a delimiter is not found.
tooLongFrameLength += buffer.readableBytes();
buffer.skipBytes(buffer.readableBytes());
}
return null;
}
}
private void fail(long frameLength) {
if (frameLength > 0) {
throw new TooLongFrameException(
"frame length exceeds " + maxFrameLength +
": " + frameLength + " - discarded");
} else {
throw new TooLongFrameException(
"frame length exceeds " + maxFrameLength +
" - discarding");
}
}
/**
* Returns the number of bytes between the readerIndex of the haystack and
* the first needle found in the haystack. -1 is returned if no needle is
* found in the haystack.
*/
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) {
int haystackIndex = i;
int needleIndex;
for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) {
if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
break;
} else {
haystackIndex ++;
if (haystackIndex == haystack.writerIndex() &&
needleIndex != needle.capacity() - 1) {
return -1;
}
}
}
if (needleIndex == needle.capacity()) {
// Found the needle from the haystack!
return i - haystack.readerIndex();
}
}
return -1;
}
private static void validateDelimiter(ByteBuf delimiter) {
if (delimiter == null) {
throw new NullPointerException("delimiter");
}
if (!delimiter.isReadable()) {
throw new IllegalArgumentException("empty delimiter");
}
}
private static void validateMaxFrameLength(int maxFrameLength) {
if (maxFrameLength <= 0) {
throw new IllegalArgumentException(
"maxFrameLength must be a positive integer: " +
maxFrameLength);
}
}
}
|
codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import java.util.List;
/**
* A decoder that splits the received {@link ByteBuf}s by one or more
* delimiters. It is particularly useful for decoding the frames which ends
* with a delimiter such as {@link Delimiters#nulDelimiter() NUL} or
* {@linkplain Delimiters#lineDelimiter() newline characters}.
*
* <h3>Predefined delimiters</h3>
* <p>
* {@link Delimiters} defines frequently used delimiters for convenience' sake.
*
* <h3>Specifying more than one delimiter</h3>
* <p>
* {@link DelimiterBasedFrameDecoder} allows you to specify more than one
* delimiter. If more than one delimiter is found in the buffer, it chooses
* the delimiter which produces the shortest frame. For example, if you have
* the following data in the buffer:
* <pre>
* +--------------+
* | ABC\nDEF\r\n |
* +--------------+
* </pre>
* a {@link DelimiterBasedFrameDecoder}({@link Delimiters#lineDelimiter() Delimiters.lineDelimiter()})
* will choose {@code '\n'} as the first delimiter and produce two frames:
* <pre>
* +-----+-----+
* | ABC | DEF |
* +-----+-----+
* </pre>
* rather than incorrectly choosing {@code '\r\n'} as the first delimiter:
* <pre>
* +----------+
* | ABC\nDEF |
* +----------+
* </pre>
*/
public class DelimiterBasedFrameDecoder extends ByteToMessageDecoder {
private final ByteBuf[] delimiters;
private final int maxFrameLength;
private final boolean stripDelimiter;
private final boolean failFast;
private boolean discardingTooLongFrame;
private int tooLongFrameLength;
/** Set only when decoding with "\n" and "\r\n" as the delimiter. */
private final LineBasedFrameDecoder lineBasedDecoder;
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf delimiter) {
this(maxFrameLength, true, delimiter);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, ByteBuf delimiter) {
this(maxFrameLength, stripDelimiter, true, delimiter);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param failFast If <tt>true</tt>, a {@link TooLongFrameException} is
* thrown as soon as the decoder notices the length of the
* frame will exceed <tt>maxFrameLength</tt> regardless of
* whether the entire frame has been read.
* If <tt>false</tt>, a {@link TooLongFrameException} is
* thrown after the entire frame that exceeds
* <tt>maxFrameLength</tt> has been read.
* @param delimiter the delimiter
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, boolean failFast,
ByteBuf delimiter) {
this(maxFrameLength, stripDelimiter, failFast, new ByteBuf[] {
delimiter.slice(delimiter.readerIndex(), delimiter.readableBytes())});
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf... delimiters) {
this(maxFrameLength, true, delimiters);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, ByteBuf... delimiters) {
this(maxFrameLength, stripDelimiter, true, delimiters);
}
/**
* Creates a new instance.
*
* @param maxFrameLength the maximum length of the decoded frame.
* A {@link TooLongFrameException} is thrown if
* the length of the frame exceeds this value.
* @param stripDelimiter whether the decoded frame should strip out the
* delimiter or not
* @param failFast If <tt>true</tt>, a {@link TooLongFrameException} is
* thrown as soon as the decoder notices the length of the
* frame will exceed <tt>maxFrameLength</tt> regardless of
* whether the entire frame has been read.
* If <tt>false</tt>, a {@link TooLongFrameException} is
* thrown after the entire frame that exceeds
* <tt>maxFrameLength</tt> has been read.
* @param delimiters the delimiters
*/
public DelimiterBasedFrameDecoder(
int maxFrameLength, boolean stripDelimiter, boolean failFast, ByteBuf... delimiters) {
validateMaxFrameLength(maxFrameLength);
if (delimiters == null) {
throw new NullPointerException("delimiters");
}
if (delimiters.length == 0) {
throw new IllegalArgumentException("empty delimiters");
}
if (isLineBased(delimiters) && !isSubclass()) {
lineBasedDecoder = new LineBasedFrameDecoder(maxFrameLength, stripDelimiter, failFast);
this.delimiters = null;
} else {
this.delimiters = new ByteBuf[delimiters.length];
for (int i = 0; i < delimiters.length; i ++) {
ByteBuf d = delimiters[i];
validateDelimiter(d);
this.delimiters[i] = d.slice(d.readerIndex(), d.readableBytes());
}
lineBasedDecoder = null;
}
this.maxFrameLength = maxFrameLength;
this.stripDelimiter = stripDelimiter;
this.failFast = failFast;
}
/** Returns true if the delimiters are "\n" and "\r\n". */
private static boolean isLineBased(final ByteBuf[] delimiters) {
if (delimiters.length != 2) {
return false;
}
ByteBuf a = delimiters[0];
ByteBuf b = delimiters[1];
if (a.capacity() < b.capacity()) {
a = delimiters[1];
b = delimiters[0];
}
return a.capacity() == 2 && b.capacity() == 1
&& a.getByte(0) == '\r' && a.getByte(1) == '\n'
&& b.getByte(0) == '\n';
}
/**
* Return {@code true} if the current instance is a subclass of DelimiterBasedFrameDecoder
*/
private boolean isSubclass() {
return getClass() != DelimiterBasedFrameDecoder.class;
}
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Object decoded = decode(ctx, in);
if (decoded != null) {
out.add(decoded);
}
}
/**
* Create a frame out of the {@link ByteBuf} and return it.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
* @param buffer the {@link ByteBuf} from which to read data
* @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
* be created.
*/
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
if (lineBasedDecoder != null) {
return lineBasedDecoder.decode(ctx, buffer);
}
// Try all delimiters and choose the delimiter which yields the shortest frame.
int minFrameLength = Integer.MAX_VALUE;
ByteBuf minDelim = null;
for (ByteBuf delim: delimiters) {
int frameLength = indexOf(buffer, delim);
if (frameLength >= 0 && frameLength < minFrameLength) {
minFrameLength = frameLength;
minDelim = delim;
}
}
if (minDelim != null) {
int minDelimLength = minDelim.capacity();
ByteBuf frame;
if (discardingTooLongFrame) {
// We've just finished discarding a very large frame.
// Go back to the initial state.
discardingTooLongFrame = false;
buffer.skipBytes(minFrameLength + minDelimLength);
int tooLongFrameLength = this.tooLongFrameLength;
this.tooLongFrameLength = 0;
if (!failFast) {
fail(ctx, tooLongFrameLength);
}
return null;
}
if (minFrameLength > maxFrameLength) {
// Discard read frame.
buffer.skipBytes(minFrameLength + minDelimLength);
fail(ctx, minFrameLength);
return null;
}
if (stripDelimiter) {
frame = buffer.readSlice(minFrameLength);
buffer.skipBytes(minDelimLength);
} else {
frame = buffer.readSlice(minFrameLength + minDelimLength);
}
return frame.retain();
} else {
if (!discardingTooLongFrame) {
if (buffer.readableBytes() > maxFrameLength) {
// Discard the content of the buffer until a delimiter is found.
tooLongFrameLength = buffer.readableBytes();
buffer.skipBytes(buffer.readableBytes());
discardingTooLongFrame = true;
if (failFast) {
fail(ctx, tooLongFrameLength);
}
}
} else {
// Still discarding the buffer since a delimiter is not found.
tooLongFrameLength += buffer.readableBytes();
buffer.skipBytes(buffer.readableBytes());
}
return null;
}
}
private void fail(ChannelHandlerContext ctx, long frameLength) {
if (frameLength > 0) {
ctx.fireExceptionCaught(
new TooLongFrameException(
"frame length exceeds " + maxFrameLength +
": " + frameLength + " - discarded"));
} else {
ctx.fireExceptionCaught(
new TooLongFrameException(
"frame length exceeds " + maxFrameLength +
" - discarding"));
}
}
/**
* Returns the number of bytes between the readerIndex of the haystack and
* the first needle found in the haystack. -1 is returned if no needle is
* found in the haystack.
*/
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) {
int haystackIndex = i;
int needleIndex;
for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) {
if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
break;
} else {
haystackIndex ++;
if (haystackIndex == haystack.writerIndex() &&
needleIndex != needle.capacity() - 1) {
return -1;
}
}
}
if (needleIndex == needle.capacity()) {
// Found the needle from the haystack!
return i - haystack.readerIndex();
}
}
return -1;
}
private static void validateDelimiter(ByteBuf delimiter) {
if (delimiter == null) {
throw new NullPointerException("delimiter");
}
if (!delimiter.isReadable()) {
throw new IllegalArgumentException("empty delimiter");
}
}
private static void validateMaxFrameLength(int maxFrameLength) {
if (maxFrameLength <= 0) {
throw new IllegalArgumentException(
"maxFrameLength must be a positive integer: " +
maxFrameLength);
}
}
}
|
[#2643] Throw TooLongFrameException instead of using fireExceptionCaught
Motivation:
It's not always the case that there is another handler in the pipeline that will intercept the exceptionCaught event because sometimes users just sub-class. In this case the exception will just hit the end of the pipeline.
Modification:
Throw the TooLongFrameException so that sub-classes can handle it in the exceptionCaught(...) method directly.
Result:
Sub-classes can correctly handle the exception,
|
codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java
|
[#2643] Throw TooLongFrameException instead of using fireExceptionCaught
|
|
Java
|
apache-2.0
|
2f200801e4d5e669fe4f7e7642a1714c007db405
| 0
|
MKLab-ITI/mklab-framework-client,MKLab-ITI/mklab-framework-client,MKLab-ITI/mklab-framework-client,socialsensor/socialsensor-framework-client,MKLab-ITI/mklab-framework-client,socialsensor/socialsensor-framework-client,socialsensor/socialsensor-framework-client
|
package eu.socialsensor.framework.client.dao.impl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.BasicDBObject;
import eu.socialsensor.framework.client.dao.ItemDAO;
import eu.socialsensor.framework.client.mongo.MongoHandler;
import eu.socialsensor.framework.client.mongo.Selector;
import eu.socialsensor.framework.client.mongo.UpdateItem;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.factories.ItemFactory;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author etzoannos - e.tzoannos@atc.gr
*/
public class ItemDAOImpl implements ItemDAO {
List<String> indexes = new ArrayList<String>();
private static String db = "Streams";
private static String collection = "Items";
private MongoHandler mongoHandler;
public ItemDAOImpl(String host) throws Exception {
this(host, db, collection);
}
public ItemDAOImpl(String host, String db) throws Exception {
this(host, db, collection);
}
public ItemDAOImpl(String host, String db, String collection) throws Exception {
indexes.add("publicationTime");
indexes.add("insertionTime");
mongoHandler = new MongoHandler(host, db, collection, indexes);
}
@Override
public void insertItem(Item item) {
mongoHandler.insert(item);
}
@Override
public void replaceItem(Item item) {
mongoHandler.update("id", item.getId(), item);
}
@Override
public void updateItem(Item item) {
UpdateItem changes = new UpdateItem();
changes.setField("likes", item.getLikes());
changes.setField("shares", item.getShares());
changes.setField("indexed", item.isIndexed());
mongoHandler.update("id", item.getId(), changes);
}
@Override
public void setIndexedStatusTrue(String itemId) {
UpdateItem changes = new UpdateItem();
changes.setField("indexed", Boolean.TRUE);
mongoHandler.update("id", itemId, changes);
}
@Override
public boolean deleteItem(String id) {
return mongoHandler.delete("id", id);
}
@Override
public List<Item> getLatestItems(int n) {
List<String> jsonItems = mongoHandler.findManySortedByPublicationTime(new Selector(), n);
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
return results;
}
//@Override
//public int getUserRetweets(String userName) {
// Pattern user = Pattern.compile("^RT @" + userName);
// return mongoHandler.findCount(user);
// List<Item> results = new ArrayList<Item>();
//
// for (String json : jsonItems) {
// try {
// results.add(ItemFactory.create(json));
// } catch (Exception e) {
// Logger.getRootLogger().warn("Ignore incomplete tweet.");
// }
// }
// return results;
//}
@Override
public List<Item> getItemsSince(long date) {
Selector query = new Selector();
query.selectGreaterThan("publicationTime", date);
long l = System.currentTimeMillis();
List<String> jsonItems = mongoHandler.findMany(query, 0);
l = System.currentTimeMillis() - l;
System.out.println("Fetch time: " + l + " msecs");
l = System.currentTimeMillis() - l;
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time: " + l + " msecs");
return results;
}
@Override
public List<Item> getItemsInRange(long start, long end) {
Selector query = new Selector();
query.selectGreaterThan("insertionTime", start);
query.selectLessThan("insertionTime", end);
long l = System.currentTimeMillis();
List<String> jsonItems = mongoHandler.findManyNoSorting(query, 0);
l = System.currentTimeMillis() - l;
System.out.println("Fetch time: " + l + " msecs");
l = System.currentTimeMillis() - l;
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time: " + l + " msecs");
return results;
}
@Override
public Item getItem(String id) {
String json = mongoHandler.findOne("id", id);
Item item = ItemFactory.create(json);
return item;
}
@Override
public boolean exists(String id) {
return mongoHandler.exists("id", id);
}
@Override
public List<Item> getItemsInTimeslot(String timeslotId) {
System.out.println("DAO: get items from timeslot: " + timeslotId);
long l = System.currentTimeMillis();
BasicDBObject query = new BasicDBObject("timeslotId", timeslotId);
List<String> jsonItems = mongoHandler.findMany(query, 0);
List<Item> results = new ArrayList<Item>();
System.out.println("DAO: find " + jsonItems.size() + " results");
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time2: " + l + " msecs " + timeslotId + " items: " + jsonItems.size());
return results;
}
@Override
public List<Item> getUnindexedItems(int max) {
Selector query = new Selector();
query.select("indexed", Boolean.FALSE);
query.select("original", Boolean.TRUE);
List<String> jsonItems = mongoHandler.findManyNoSorting(query, max);
List<Item> items = new ArrayList<Item>();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
for (String json : jsonItems) {
Item item = gson.fromJson(json, Item.class);
items.add(item);
}
return items;
}
@Override
public List<Item> readItems() {
List<String> jsonItems = mongoHandler.findMany(-1);
System.out.println("I have read " + jsonItems.size() + " jsonItems");
List<Item> items = new ArrayList<Item>();
for (String json : jsonItems) {
Item item = ItemFactory.create(json);
items.add(item);
}
return items;
}
@Override
public List<Item> readItemsByStatus() {
Selector query = new Selector();
query.select("isSearched", Boolean.FALSE);
List<String> jsonItems = mongoHandler.findMany(query, -1);
List<Item> items = new ArrayList<Item>();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
for (String json : jsonItems) {
Item item = gson.fromJson(json, Item.class);
items.add(item);
}
return items;
}
public static void main(String... args) {
ItemDAO dao = null;
try {
dao = new ItemDAOImpl("social1.atc.gr", "Streams", "Items");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Item> items = dao.getUnindexedItems(10);
for (Item item : items) {
if (item.isOriginal() == true) {
System.out.println("fine");
}
if (item.isOriginal() == false) {
System.out.println("problem!! it's false");
}
// System.out.println(item.getId());
// dao.setIndexedStatusTrue(item.getId());
}
System.out.println("finished");
// ItemDAO dao = new ItemDAOImpl("160.40.50.207");
// MediaItemDAO mDao = new MediaItemDAOImpl("160.40.50.207");
// StreamUserDAO uDao = new StreamUserDAOImpl("160.40.50.207");
//
// long end = 1386856206000L;
// long start = end - 5 * 60000;//1386856100000L;
//
//
// List<Item> items = dao.getItemsInRange(start, end);
// System.out.println(items.size() + " in " + ((end - start) / 60000.0) + " minutes");
//
// long t = System.currentTimeMillis();
//
// for (Item item : items) {
// String uid = item.getUserId();
// StreamUser streamUser = uDao.getStreamUser(uid);
// item.setStreamUser(streamUser);
//
// List<MediaItem> mItems = new ArrayList<MediaItem>();
//
// List<String> mediaIds = item.getMediaIds();
// for (String mId : mediaIds) {
// MediaItem mItem = mDao.getMediaItem(mId);
// mItems.add(mItem);
// }
// item.setMediaItems(mItems);
// }
// t = System.currentTimeMillis() - t;
//
// System.out.println("Fetch users and MediaItems in " + t + " msecs");
}
}
|
src/main/java/eu/socialsensor/framework/client/dao/impl/ItemDAOImpl.java
|
package eu.socialsensor.framework.client.dao.impl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.BasicDBObject;
import eu.socialsensor.framework.client.dao.ItemDAO;
import eu.socialsensor.framework.client.mongo.MongoHandler;
import eu.socialsensor.framework.client.mongo.Selector;
import eu.socialsensor.framework.client.mongo.UpdateItem;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.factories.ItemFactory;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author etzoannos - e.tzoannos@atc.gr
*/
public class ItemDAOImpl implements ItemDAO {
List<String> indexes = new ArrayList<String>();
private static String db = "Streams";
private static String collection = "Items";
private MongoHandler mongoHandler;
public ItemDAOImpl(String host) throws Exception {
this(host, db, collection);
}
public ItemDAOImpl(String host, String db) throws Exception {
this(host, db, collection);
}
public ItemDAOImpl(String host, String db, String collection) throws Exception {
indexes.add("publicationTime");
indexes.add("insertionTime");
mongoHandler = new MongoHandler(host, db, collection, indexes);
}
@Override
public void insertItem(Item item) {
mongoHandler.insert(item);
}
@Override
public void replaceItem(Item item) {
mongoHandler.update("id", item.getId(), item);
}
@Override
public void updateItem(Item item) {
UpdateItem changes = new UpdateItem();
changes.setField("likes", item.getLikes());
changes.setField("shares", item.getShares());
//changes.setField("indexed", item.isIndexed());
mongoHandler.update("id", item.getId(), changes);
}
@Override
public void setIndexedStatusTrue(String itemId) {
UpdateItem changes = new UpdateItem();
changes.setField("indexed", Boolean.TRUE);
mongoHandler.update("id", itemId, changes);
}
@Override
public boolean deleteItem(String id) {
return mongoHandler.delete("id", id);
}
@Override
public List<Item> getLatestItems(int n) {
List<String> jsonItems = mongoHandler.findManySortedByPublicationTime(new Selector(), n);
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
return results;
}
//@Override
//public int getUserRetweets(String userName) {
// Pattern user = Pattern.compile("^RT @" + userName);
// return mongoHandler.findCount(user);
// List<Item> results = new ArrayList<Item>();
//
// for (String json : jsonItems) {
// try {
// results.add(ItemFactory.create(json));
// } catch (Exception e) {
// Logger.getRootLogger().warn("Ignore incomplete tweet.");
// }
// }
// return results;
//}
@Override
public List<Item> getItemsSince(long date) {
Selector query = new Selector();
query.selectGreaterThan("publicationTime", date);
long l = System.currentTimeMillis();
List<String> jsonItems = mongoHandler.findMany(query, 0);
l = System.currentTimeMillis() - l;
System.out.println("Fetch time: " + l + " msecs");
l = System.currentTimeMillis() - l;
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time: " + l + " msecs");
return results;
}
@Override
public List<Item> getItemsInRange(long start, long end) {
Selector query = new Selector();
query.selectGreaterThan("insertionTime", start);
query.selectLessThan("insertionTime", end);
long l = System.currentTimeMillis();
List<String> jsonItems = mongoHandler.findManyNoSorting(query, 0);
l = System.currentTimeMillis() - l;
System.out.println("Fetch time: " + l + " msecs");
l = System.currentTimeMillis() - l;
List<Item> results = new ArrayList<Item>();
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time: " + l + " msecs");
return results;
}
@Override
public Item getItem(String id) {
String json = mongoHandler.findOne("id", id);
Item item = ItemFactory.create(json);
return item;
}
@Override
public boolean exists(String id) {
return mongoHandler.exists("id", id);
}
@Override
public List<Item> getItemsInTimeslot(String timeslotId) {
System.out.println("DAO: get items from timeslot: " + timeslotId);
long l = System.currentTimeMillis();
BasicDBObject query = new BasicDBObject("timeslotId", timeslotId);
List<String> jsonItems = mongoHandler.findMany(query, 0);
List<Item> results = new ArrayList<Item>();
System.out.println("DAO: find " + jsonItems.size() + " results");
for (String json : jsonItems) {
results.add(ItemFactory.create(json));
}
l = System.currentTimeMillis() - l;
System.out.println("List time2: " + l + " msecs " + timeslotId + " items: " + jsonItems.size());
return results;
}
@Override
public List<Item> getUnindexedItems(int max) {
Selector query = new Selector();
query.select("indexed", Boolean.FALSE);
query.select("original", Boolean.TRUE);
List<String> jsonItems = mongoHandler.findManyNoSorting(query, max);
List<Item> items = new ArrayList<Item>();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
for (String json : jsonItems) {
Item item = gson.fromJson(json, Item.class);
items.add(item);
}
return items;
}
@Override
public List<Item> readItems() {
List<String> jsonItems = mongoHandler.findMany(-1);
System.out.println("I have read " + jsonItems.size() + " jsonItems");
List<Item> items = new ArrayList<Item>();
for (String json : jsonItems) {
Item item = ItemFactory.create(json);
items.add(item);
}
return items;
}
@Override
public List<Item> readItemsByStatus() {
Selector query = new Selector();
query.select("isSearched", Boolean.FALSE);
List<String> jsonItems = mongoHandler.findMany(query, -1);
List<Item> items = new ArrayList<Item>();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
for (String json : jsonItems) {
Item item = gson.fromJson(json, Item.class);
items.add(item);
}
return items;
}
public static void main(String... args) {
ItemDAO dao = null;
try {
dao = new ItemDAOImpl("social1.atc.gr", "Streams", "Items");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Item> items = dao.getUnindexedItems(10);
for (Item item : items) {
if (item.isOriginal() == true) {
System.out.println("fine");
}
if (item.isOriginal() == false) {
System.out.println("problem!! it's false");
}
// System.out.println(item.getId());
// dao.setIndexedStatusTrue(item.getId());
}
System.out.println("finished");
// ItemDAO dao = new ItemDAOImpl("160.40.50.207");
// MediaItemDAO mDao = new MediaItemDAOImpl("160.40.50.207");
// StreamUserDAO uDao = new StreamUserDAOImpl("160.40.50.207");
//
// long end = 1386856206000L;
// long start = end - 5 * 60000;//1386856100000L;
//
//
// List<Item> items = dao.getItemsInRange(start, end);
// System.out.println(items.size() + " in " + ((end - start) / 60000.0) + " minutes");
//
// long t = System.currentTimeMillis();
//
// for (Item item : items) {
// String uid = item.getUserId();
// StreamUser streamUser = uDao.getStreamUser(uid);
// item.setStreamUser(streamUser);
//
// List<MediaItem> mItems = new ArrayList<MediaItem>();
//
// List<String> mediaIds = item.getMediaIds();
// for (String mId : mediaIds) {
// MediaItem mItem = mDao.getMediaItem(mId);
// mItems.add(mItem);
// }
// item.setMediaItems(mItems);
// }
// t = System.currentTimeMillis() - t;
//
// System.out.println("Fetch users and MediaItems in " + t + " msecs");
}
}
|
allow update item indexed status
|
src/main/java/eu/socialsensor/framework/client/dao/impl/ItemDAOImpl.java
|
allow update item indexed status
|
|
Java
|
apache-2.0
|
bdb8408b74ba5f7b7a72eda4aa6bf62dee924123
| 0
|
apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fitermay/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,fitermay/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,da1z/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,da1z/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,semonte/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,hurricup/intellij-community,semonte/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,signed/intellij-community,allotria/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,allotria/intellij-community,retomerz/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,FHannes/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,fitermay/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,signed/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,retomerz/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,retomerz/intellij-community,ibinti/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,xfournet/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,retomerz/intellij-community,hurricup/intellij-community,signed/intellij-community,asedunov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.actions.DebuggerActions;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.*;
import com.intellij.debugger.jdi.StackFrameProxyImpl;
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.AlternativeSourceNotificationProvider;
import com.intellij.debugger.ui.DebuggerContentInfo;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.impl.ThreadsPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.MessageDescriptor;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.ExecutionConsoleEx;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotifications;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.frame.XStackFrame;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.LocatableEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider;
import java.util.ArrayList;
import java.util.List;
/**
* @author egor
*/
public class JavaDebugProcess extends XDebugProcess {
private final DebuggerSession myJavaSession;
private final JavaDebuggerEditorsProvider myEditorsProvider;
private final XBreakpointHandler<?>[] myBreakpointHandlers;
private final NodeManagerImpl myNodeManager;
public static JavaDebugProcess create(@NotNull final XDebugSession session, final DebuggerSession javaSession) {
JavaDebugProcess res = new JavaDebugProcess(session, javaSession);
javaSession.getProcess().setXDebugProcess(res);
return res;
}
protected JavaDebugProcess(@NotNull final XDebugSession session, final DebuggerSession javaSession) {
super(session);
myJavaSession = javaSession;
myEditorsProvider = new JavaDebuggerEditorsProvider();
final DebugProcessImpl process = javaSession.getProcess();
List<XBreakpointHandler> handlers = new ArrayList<XBreakpointHandler>();
handlers.add(new JavaBreakpointHandler.JavaLineBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaExceptionBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaFieldBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaMethodBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaWildcardBreakpointHandler(process));
for (JavaBreakpointHandlerFactory factory : Extensions.getExtensions(JavaBreakpointHandlerFactory.EP_NAME)) {
handlers.add(factory.createHandler(process));
}
myBreakpointHandlers = handlers.toArray(new XBreakpointHandler[handlers.size()]);
myJavaSession.getContextManager().addListener(new DebuggerContextListener() {
@Override
public void changeEvent(@NotNull final DebuggerContextImpl newContext, DebuggerSession.Event event) {
if (event == DebuggerSession.Event.PAUSE
|| event == DebuggerSession.Event.CONTEXT
|| event == DebuggerSession.Event.REFRESH
|| event == DebuggerSession.Event.REFRESH_WITH_STACK
&& myJavaSession.isPaused()) {
final SuspendContextImpl newSuspendContext = newContext.getSuspendContext();
if (newSuspendContext != null &&
(shouldApplyContext(newContext) || event == DebuggerSession.Event.REFRESH_WITH_STACK)) {
process.getManagerThread().schedule(new SuspendContextCommandImpl(newSuspendContext) {
@Override
public void contextAction() throws Exception {
ThreadReferenceProxyImpl threadProxy = newContext.getThreadProxy();
newSuspendContext.initExecutionStacks(threadProxy);
Pair<Breakpoint, Event> item = ContainerUtil.getFirstItem(DebuggerUtilsEx.getEventDescriptors(newSuspendContext));
if (item != null) {
XBreakpoint xBreakpoint = item.getFirst().getXBreakpoint();
Event second = item.getSecond();
if (xBreakpoint != null && second instanceof LocatableEvent &&
threadProxy != null && ((LocatableEvent)second).thread() == threadProxy.getThreadReference()) {
((XDebugSessionImpl)getSession()).breakpointReachedNoProcessing(xBreakpoint, newSuspendContext);
unsetPausedIfNeeded(newContext);
return;
}
}
getSession().positionReached(newSuspendContext);
unsetPausedIfNeeded(newContext);
}
});
}
}
else if (event == DebuggerSession.Event.ATTACHED) {
getSession().rebuildViews(); // to refresh variables views message
}
}
});
myNodeManager = new NodeManagerImpl(session.getProject(), null) {
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(MessageDescriptor descriptor) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(String message) {
return new DebuggerTreeNodeImpl(null, new MessageDescriptor(message));
}
};
session.addSessionListener(new XDebugSessionAdapter() {
@Override
public void sessionPaused() {
saveNodeHistory();
showAlternativeNotification(session.getCurrentStackFrame());
}
@Override
public void stackFrameChanged() {
XStackFrame frame = session.getCurrentStackFrame();
if (frame instanceof JavaStackFrame) {
showAlternativeNotification(frame);
StackFrameProxyImpl frameProxy = ((JavaStackFrame)frame).getStackFrameProxy();
DebuggerContextUtil.setStackFrame(javaSession.getContextManager(), frameProxy);
saveNodeHistory(frameProxy);
}
}
private void showAlternativeNotification(@Nullable XStackFrame frame) {
if (frame != null) {
XSourcePosition position = frame.getSourcePosition();
if (position != null) {
VirtualFile file = position.getFile();
if (!AlternativeSourceNotificationProvider.fileProcessed(file)) {
EditorNotifications.getInstance(session.getProject()).updateNotifications(file);
}
}
}
}
});
}
private void unsetPausedIfNeeded(DebuggerContextImpl context) {
SuspendContextImpl suspendContext = context.getSuspendContext();
if (suspendContext != null && !suspendContext.suspends(context.getThreadProxy())) {
((XDebugSessionImpl)getSession()).unsetPaused();
}
}
private boolean shouldApplyContext(DebuggerContextImpl context) {
SuspendContextImpl suspendContext = context.getSuspendContext();
SuspendContextImpl currentContext = (SuspendContextImpl)getSession().getSuspendContext();
if (suspendContext != null && !suspendContext.equals(currentContext)) return true;
JavaExecutionStack currentExecutionStack = currentContext != null ? currentContext.getActiveExecutionStack() : null;
return currentExecutionStack == null || !Comparing.equal(context.getThreadProxy(), currentExecutionStack.getThreadProxy());
}
public void saveNodeHistory() {
saveNodeHistory(getDebuggerStateManager().getContext().getFrameProxy());
}
private void saveNodeHistory(final StackFrameProxyImpl frameProxy) {
myJavaSession.getProcess().getManagerThread().invoke(new DebuggerCommandImpl() {
@Override
protected void action() throws Exception {
myNodeManager.setHistoryByContext(frameProxy);
}
@Override
public Priority getPriority() {
return Priority.NORMAL;
}
});
}
private DebuggerStateManager getDebuggerStateManager() {
return myJavaSession.getContextManager();
}
public DebuggerSession getDebuggerSession() {
return myJavaSession;
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return myEditorsProvider;
}
@Override
public void startStepOver() {
myJavaSession.stepOver(false);
}
@Override
public void startStepInto() {
myJavaSession.stepInto(false, null);
}
@Override
public void startForceStepInto() {
myJavaSession.stepInto(true, null);
}
@Override
public void startStepOut() {
myJavaSession.stepOut();
}
@Override
public void stop() {
myJavaSession.dispose();
myNodeManager.dispose();
}
@Override
public void startPausing() {
myJavaSession.pause();
}
@Override
public void resume() {
myJavaSession.resume();
}
@Override
public void runToPosition(@NotNull XSourcePosition position) {
myJavaSession.runToCursor(position, false);
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return myBreakpointHandlers;
}
@Override
public boolean checkCanInitBreakpoints() {
return false;
}
@Nullable
@Override
protected ProcessHandler doGetProcessHandler() {
return myJavaSession.getProcess().getProcessHandler();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
ExecutionConsole console = myJavaSession.getProcess().getExecutionResult().getExecutionConsole();
if (console != null) return console;
return super.createConsole();
}
@NotNull
@Override
public XDebugTabLayouter createTabLayouter() {
return new XDebugTabLayouter() {
@Override
public void registerAdditionalContent(@NotNull RunnerLayoutUi ui) {
final ThreadsPanel panel = new ThreadsPanel(myJavaSession.getProject(), getDebuggerStateManager());
final Content threadsContent = ui.createContent(
DebuggerContentInfo.THREADS_CONTENT, panel, XDebuggerBundle.message("debugger.session.tab.threads.title"),
AllIcons.Debugger.Threads, null);
Disposer.register(threadsContent, panel);
threadsContent.setCloseable(false);
ui.addContent(threadsContent, 0, PlaceInGrid.left, true);
ui.addListener(new ContentManagerAdapter() {
@Override
public void selectionChanged(ContentManagerEvent event) {
if (event.getContent() == threadsContent) {
if (threadsContent.isSelected()) {
panel.setUpdateEnabled(true);
if (panel.isRefreshNeeded()) {
panel.rebuildIfVisible(DebuggerSession.Event.CONTEXT);
}
}
else {
panel.setUpdateEnabled(false);
}
}
}
}, threadsContent);
}
@NotNull
@Override
public Content registerConsoleContent(@NotNull RunnerLayoutUi ui, @NotNull ExecutionConsole console) {
Content content = null;
if (console instanceof ExecutionConsoleEx) {
((ExecutionConsoleEx)console).buildUi(ui);
content = ui.findContent(DebuggerContentInfo.CONSOLE_CONTENT);
}
if (content == null) {
content = super.registerConsoleContent(ui, console);
}
return content;
}
};
}
@Override
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar, @NotNull DefaultActionGroup settings) {
Constraints beforeRunner = new Constraints(Anchor.BEFORE, "Runner.Layout");
leftToolbar.add(Separator.getInstance(), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.DUMP_THREADS), beforeRunner);
leftToolbar.add(Separator.getInstance(), beforeRunner);
Constraints beforeSort = new Constraints(Anchor.BEFORE, "XDebugger.ToggleSortValues");
settings.addAction(new WatchLastMethodReturnValueAction(), beforeSort);
settings.addAction(new AutoVarsSwitchAction(), beforeSort);
}
private static class AutoVarsSwitchAction extends ToggleAction {
private volatile boolean myAutoModeEnabled;
public AutoVarsSwitchAction() {
super(DebuggerBundle.message("action.auto.variables.mode"), DebuggerBundle.message("action.auto.variables.mode.description"), null);
myAutoModeEnabled = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
}
@Override
public boolean isSelected(AnActionEvent e) {
return myAutoModeEnabled;
}
@Override
public void setSelected(AnActionEvent e, boolean enabled) {
myAutoModeEnabled = enabled;
DebuggerSettings.getInstance().AUTO_VARIABLES_MODE = enabled;
XDebuggerUtilImpl.rebuildAllSessionsViews(e.getProject());
}
}
private static class WatchLastMethodReturnValueAction extends ToggleAction {
private volatile boolean myWatchesReturnValues;
private final String myText;
private final String myTextUnavailable;
public WatchLastMethodReturnValueAction() {
super("", DebuggerBundle.message("action.watch.method.return.value.description"), null);
myWatchesReturnValues = DebuggerSettings.getInstance().WATCH_RETURN_VALUES;
myText = DebuggerBundle.message("action.watches.method.return.value.enable");
myTextUnavailable = DebuggerBundle.message("action.watches.method.return.value.unavailable.reason");
}
@Override
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
DebugProcessImpl process = getCurrentDebugProcess(e.getProject());
if (process == null || process.canGetMethodReturnValue()) {
presentation.setEnabled(true);
presentation.setText(myText);
}
else {
presentation.setEnabled(false);
presentation.setText(myTextUnavailable);
}
}
@Override
public boolean isSelected(AnActionEvent e) {
return myWatchesReturnValues;
}
@Override
public void setSelected(AnActionEvent e, boolean watch) {
myWatchesReturnValues = watch;
DebuggerSettings.getInstance().WATCH_RETURN_VALUES = watch;
DebugProcessImpl process = getCurrentDebugProcess(e.getProject());
if (process != null) {
process.setWatchMethodReturnValuesEnabled(watch);
}
}
}
@Nullable
private static DebugProcessImpl getCurrentDebugProcess(@Nullable Project project) {
if (project != null) {
XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
if (session != null) {
XDebugProcess process = session.getDebugProcess();
if (process instanceof JavaDebugProcess) {
return ((JavaDebugProcess)process).getDebuggerSession().getProcess();
}
}
}
return null;
}
public NodeManagerImpl getNodeManager() {
return myNodeManager;
}
@Override
public String getCurrentStateMessage() {
String description = myJavaSession.getStateDescription();
return description != null ? description : super.getCurrentStateMessage();
}
@Nullable
@Override
public XValueMarkerProvider<?, ?> createValueMarkerProvider() {
return new JavaValueMarker();
}
@Override
public boolean isLibraryFrameFilterSupported() {
return true;
}
}
|
java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.actions.DebuggerActions;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.*;
import com.intellij.debugger.jdi.StackFrameProxyImpl;
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.AlternativeSourceNotificationProvider;
import com.intellij.debugger.ui.DebuggerContentInfo;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.impl.ThreadsPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.MessageDescriptor;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.ExecutionConsoleEx;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotifications;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.frame.XStackFrame;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
import com.sun.jdi.event.BreakpointEvent;
import com.sun.jdi.event.Event;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider;
import java.util.ArrayList;
import java.util.List;
/**
* @author egor
*/
public class JavaDebugProcess extends XDebugProcess {
private final DebuggerSession myJavaSession;
private final JavaDebuggerEditorsProvider myEditorsProvider;
private final XBreakpointHandler<?>[] myBreakpointHandlers;
private final NodeManagerImpl myNodeManager;
public static JavaDebugProcess create(@NotNull final XDebugSession session, final DebuggerSession javaSession) {
JavaDebugProcess res = new JavaDebugProcess(session, javaSession);
javaSession.getProcess().setXDebugProcess(res);
return res;
}
protected JavaDebugProcess(@NotNull final XDebugSession session, final DebuggerSession javaSession) {
super(session);
myJavaSession = javaSession;
myEditorsProvider = new JavaDebuggerEditorsProvider();
final DebugProcessImpl process = javaSession.getProcess();
List<XBreakpointHandler> handlers = new ArrayList<XBreakpointHandler>();
handlers.add(new JavaBreakpointHandler.JavaLineBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaExceptionBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaFieldBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaMethodBreakpointHandler(process));
handlers.add(new JavaBreakpointHandler.JavaWildcardBreakpointHandler(process));
for (JavaBreakpointHandlerFactory factory : Extensions.getExtensions(JavaBreakpointHandlerFactory.EP_NAME)) {
handlers.add(factory.createHandler(process));
}
myBreakpointHandlers = handlers.toArray(new XBreakpointHandler[handlers.size()]);
myJavaSession.getContextManager().addListener(new DebuggerContextListener() {
@Override
public void changeEvent(@NotNull final DebuggerContextImpl newContext, DebuggerSession.Event event) {
if (event == DebuggerSession.Event.PAUSE
|| event == DebuggerSession.Event.CONTEXT
|| event == DebuggerSession.Event.REFRESH
|| event == DebuggerSession.Event.REFRESH_WITH_STACK
&& myJavaSession.isPaused()) {
final SuspendContextImpl newSuspendContext = newContext.getSuspendContext();
if (newSuspendContext != null &&
(shouldApplyContext(newContext) || event == DebuggerSession.Event.REFRESH_WITH_STACK)) {
process.getManagerThread().schedule(new SuspendContextCommandImpl(newSuspendContext) {
@Override
public void contextAction() throws Exception {
ThreadReferenceProxyImpl threadProxy = newContext.getThreadProxy();
newSuspendContext.initExecutionStacks(threadProxy);
Pair<Breakpoint, Event> item = ContainerUtil.getFirstItem(DebuggerUtilsEx.getEventDescriptors(newSuspendContext));
if (item != null) {
XBreakpoint xBreakpoint = item.getFirst().getXBreakpoint();
Event second = item.getSecond();
if (xBreakpoint != null && second instanceof BreakpointEvent &&
threadProxy != null && ((BreakpointEvent)second).thread() == threadProxy.getThreadReference()) {
((XDebugSessionImpl)getSession()).breakpointReachedNoProcessing(xBreakpoint, newSuspendContext);
unsetPausedIfNeeded(newContext);
return;
}
}
getSession().positionReached(newSuspendContext);
unsetPausedIfNeeded(newContext);
}
});
}
}
else if (event == DebuggerSession.Event.ATTACHED) {
getSession().rebuildViews(); // to refresh variables views message
}
}
});
myNodeManager = new NodeManagerImpl(session.getProject(), null) {
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(MessageDescriptor descriptor) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(String message) {
return new DebuggerTreeNodeImpl(null, new MessageDescriptor(message));
}
};
session.addSessionListener(new XDebugSessionAdapter() {
@Override
public void sessionPaused() {
saveNodeHistory();
showAlternativeNotification(session.getCurrentStackFrame());
}
@Override
public void stackFrameChanged() {
XStackFrame frame = session.getCurrentStackFrame();
if (frame instanceof JavaStackFrame) {
showAlternativeNotification(frame);
StackFrameProxyImpl frameProxy = ((JavaStackFrame)frame).getStackFrameProxy();
DebuggerContextUtil.setStackFrame(javaSession.getContextManager(), frameProxy);
saveNodeHistory(frameProxy);
}
}
private void showAlternativeNotification(@Nullable XStackFrame frame) {
if (frame != null) {
XSourcePosition position = frame.getSourcePosition();
if (position != null) {
VirtualFile file = position.getFile();
if (!AlternativeSourceNotificationProvider.fileProcessed(file)) {
EditorNotifications.getInstance(session.getProject()).updateNotifications(file);
}
}
}
}
});
}
private void unsetPausedIfNeeded(DebuggerContextImpl context) {
SuspendContextImpl suspendContext = context.getSuspendContext();
if (suspendContext != null && !suspendContext.suspends(context.getThreadProxy())) {
((XDebugSessionImpl)getSession()).unsetPaused();
}
}
private boolean shouldApplyContext(DebuggerContextImpl context) {
SuspendContextImpl suspendContext = context.getSuspendContext();
SuspendContextImpl currentContext = (SuspendContextImpl)getSession().getSuspendContext();
if (suspendContext != null && !suspendContext.equals(currentContext)) return true;
JavaExecutionStack currentExecutionStack = currentContext != null ? currentContext.getActiveExecutionStack() : null;
return currentExecutionStack == null || !Comparing.equal(context.getThreadProxy(), currentExecutionStack.getThreadProxy());
}
public void saveNodeHistory() {
saveNodeHistory(getDebuggerStateManager().getContext().getFrameProxy());
}
private void saveNodeHistory(final StackFrameProxyImpl frameProxy) {
myJavaSession.getProcess().getManagerThread().invoke(new DebuggerCommandImpl() {
@Override
protected void action() throws Exception {
myNodeManager.setHistoryByContext(frameProxy);
}
@Override
public Priority getPriority() {
return Priority.NORMAL;
}
});
}
private DebuggerStateManager getDebuggerStateManager() {
return myJavaSession.getContextManager();
}
public DebuggerSession getDebuggerSession() {
return myJavaSession;
}
@NotNull
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
return myEditorsProvider;
}
@Override
public void startStepOver() {
myJavaSession.stepOver(false);
}
@Override
public void startStepInto() {
myJavaSession.stepInto(false, null);
}
@Override
public void startForceStepInto() {
myJavaSession.stepInto(true, null);
}
@Override
public void startStepOut() {
myJavaSession.stepOut();
}
@Override
public void stop() {
myJavaSession.dispose();
myNodeManager.dispose();
}
@Override
public void startPausing() {
myJavaSession.pause();
}
@Override
public void resume() {
myJavaSession.resume();
}
@Override
public void runToPosition(@NotNull XSourcePosition position) {
myJavaSession.runToCursor(position, false);
}
@NotNull
@Override
public XBreakpointHandler<?>[] getBreakpointHandlers() {
return myBreakpointHandlers;
}
@Override
public boolean checkCanInitBreakpoints() {
return false;
}
@Nullable
@Override
protected ProcessHandler doGetProcessHandler() {
return myJavaSession.getProcess().getProcessHandler();
}
@NotNull
@Override
public ExecutionConsole createConsole() {
ExecutionConsole console = myJavaSession.getProcess().getExecutionResult().getExecutionConsole();
if (console != null) return console;
return super.createConsole();
}
@NotNull
@Override
public XDebugTabLayouter createTabLayouter() {
return new XDebugTabLayouter() {
@Override
public void registerAdditionalContent(@NotNull RunnerLayoutUi ui) {
final ThreadsPanel panel = new ThreadsPanel(myJavaSession.getProject(), getDebuggerStateManager());
final Content threadsContent = ui.createContent(
DebuggerContentInfo.THREADS_CONTENT, panel, XDebuggerBundle.message("debugger.session.tab.threads.title"),
AllIcons.Debugger.Threads, null);
Disposer.register(threadsContent, panel);
threadsContent.setCloseable(false);
ui.addContent(threadsContent, 0, PlaceInGrid.left, true);
ui.addListener(new ContentManagerAdapter() {
@Override
public void selectionChanged(ContentManagerEvent event) {
if (event.getContent() == threadsContent) {
if (threadsContent.isSelected()) {
panel.setUpdateEnabled(true);
if (panel.isRefreshNeeded()) {
panel.rebuildIfVisible(DebuggerSession.Event.CONTEXT);
}
}
else {
panel.setUpdateEnabled(false);
}
}
}
}, threadsContent);
}
@NotNull
@Override
public Content registerConsoleContent(@NotNull RunnerLayoutUi ui, @NotNull ExecutionConsole console) {
Content content = null;
if (console instanceof ExecutionConsoleEx) {
((ExecutionConsoleEx)console).buildUi(ui);
content = ui.findContent(DebuggerContentInfo.CONSOLE_CONTENT);
}
if (content == null) {
content = super.registerConsoleContent(ui, console);
}
return content;
}
};
}
@Override
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar, @NotNull DefaultActionGroup settings) {
Constraints beforeRunner = new Constraints(Anchor.BEFORE, "Runner.Layout");
leftToolbar.add(Separator.getInstance(), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.DUMP_THREADS), beforeRunner);
leftToolbar.add(Separator.getInstance(), beforeRunner);
Constraints beforeSort = new Constraints(Anchor.BEFORE, "XDebugger.ToggleSortValues");
settings.addAction(new WatchLastMethodReturnValueAction(), beforeSort);
settings.addAction(new AutoVarsSwitchAction(), beforeSort);
}
private static class AutoVarsSwitchAction extends ToggleAction {
private volatile boolean myAutoModeEnabled;
public AutoVarsSwitchAction() {
super(DebuggerBundle.message("action.auto.variables.mode"), DebuggerBundle.message("action.auto.variables.mode.description"), null);
myAutoModeEnabled = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
}
@Override
public boolean isSelected(AnActionEvent e) {
return myAutoModeEnabled;
}
@Override
public void setSelected(AnActionEvent e, boolean enabled) {
myAutoModeEnabled = enabled;
DebuggerSettings.getInstance().AUTO_VARIABLES_MODE = enabled;
XDebuggerUtilImpl.rebuildAllSessionsViews(e.getProject());
}
}
private static class WatchLastMethodReturnValueAction extends ToggleAction {
private volatile boolean myWatchesReturnValues;
private final String myText;
private final String myTextUnavailable;
public WatchLastMethodReturnValueAction() {
super("", DebuggerBundle.message("action.watch.method.return.value.description"), null);
myWatchesReturnValues = DebuggerSettings.getInstance().WATCH_RETURN_VALUES;
myText = DebuggerBundle.message("action.watches.method.return.value.enable");
myTextUnavailable = DebuggerBundle.message("action.watches.method.return.value.unavailable.reason");
}
@Override
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
DebugProcessImpl process = getCurrentDebugProcess(e.getProject());
if (process == null || process.canGetMethodReturnValue()) {
presentation.setEnabled(true);
presentation.setText(myText);
}
else {
presentation.setEnabled(false);
presentation.setText(myTextUnavailable);
}
}
@Override
public boolean isSelected(AnActionEvent e) {
return myWatchesReturnValues;
}
@Override
public void setSelected(AnActionEvent e, boolean watch) {
myWatchesReturnValues = watch;
DebuggerSettings.getInstance().WATCH_RETURN_VALUES = watch;
DebugProcessImpl process = getCurrentDebugProcess(e.getProject());
if (process != null) {
process.setWatchMethodReturnValuesEnabled(watch);
}
}
}
@Nullable
private static DebugProcessImpl getCurrentDebugProcess(@Nullable Project project) {
if (project != null) {
XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
if (session != null) {
XDebugProcess process = session.getDebugProcess();
if (process instanceof JavaDebugProcess) {
return ((JavaDebugProcess)process).getDebuggerSession().getProcess();
}
}
}
return null;
}
public NodeManagerImpl getNodeManager() {
return myNodeManager;
}
@Override
public String getCurrentStateMessage() {
String description = myJavaSession.getStateDescription();
return description != null ? description : super.getCurrentStateMessage();
}
@Nullable
@Override
public XValueMarkerProvider<?, ?> createValueMarkerProvider() {
return new JavaValueMarker();
}
@Override
public boolean isLibraryFrameFilterSupported() {
return true;
}
}
|
fixed no icon for method breakpoints hit in other place
|
java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java
|
fixed no icon for method breakpoints hit in other place
|
|
Java
|
apache-2.0
|
991deaf0b911662663280c9585604bc195ad12b8
| 0
|
sebasbaumh/gwt-ol3,TDesjardins/gwt-ol3,TDesjardins/GWT-OL3-Playground,TDesjardins/GWT-OL3-Playground,TDesjardins/gwt-ol3,sebasbaumh/gwt-ol3,TDesjardins/gwt-ol3,sebasbaumh/gwt-ol3,TDesjardins/GWT-OL3-Playground
|
/*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.tdesjardins.ol3.demo.client.example;
import com.github.tdesjardins.ol3.demo.client.utils.DemoUtils;
import ol.Collection;
import ol.Coordinate;
import ol.Extent;
import ol.Map;
import ol.MapOptions;
import ol.View;
import ol.ViewOptions;
import ol.control.Rotate;
import ol.control.ScaleLine;
import ol.interaction.KeyboardPan;
import ol.interaction.KeyboardZoom;
import ol.layer.Base;
import ol.layer.Image;
import ol.layer.LayerOptions;
import ol.proj.Projection;
import ol.source.ImageMapGuide;
import ol.source.ImageMapGuideOptions;
import ol.source.ImageMapGuideParams;
/**
* Example with MapGuide layers.
*
* @author Tobias Lochmann
*
*/
public class MapGuideExample implements Example {
/* (non-Javadoc)
* @see de.desjardins.ol3.demo.client.example.Example#show()
*/
@Override
public void show(String exampleId) {
// create a projection
Projection projection = Projection.get("EPSG:4326");
// create a MapGuide params
ImageMapGuideParams imageMapGuideParams = new ImageMapGuideParams();
imageMapGuideParams.setFormat("PNG");
imageMapGuideParams.setMapDefinition("Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition");
imageMapGuideParams.setUserName("OpenLayers");
imageMapGuideParams.setPassword("OpenLayers");
// create a MapGuide image
ImageMapGuideOptions imageMapGuideOptions = new ImageMapGuideOptions();
imageMapGuideOptions.setParams(imageMapGuideParams);
imageMapGuideOptions.setUrl("http://www.buoyshark.com/mapguide/mapagent/mapagent.fcgi?");
imageMapGuideOptions.setUseOverlay(false);
imageMapGuideOptions.setMetersPerUnit(111319.4908d);
imageMapGuideOptions.setRatio(2.0f);
ImageMapGuide imageMapGuideSource = new ImageMapGuide(imageMapGuideOptions);
LayerOptions layerOptions = new LayerOptions();
Extent bounds = new Extent(-87.865114442365922d,43.665065564837931d,-87.595394059497067d,43.823852564430069d);
layerOptions.setExtent(bounds);
layerOptions.setSource(imageMapGuideSource);
Image mapGuideLayer = new Image(layerOptions);
// create a view
ViewOptions viewOptions = new ViewOptions();
viewOptions.setProjection(projection);
viewOptions.setZoom(12.0d);
Coordinate centerCoordinate = new Coordinate(-87.7302542509315d, 43.744459064634d);
viewOptions.setCenter(centerCoordinate);
View view = new View(viewOptions);
// create the map
MapOptions mapOptions = new MapOptions();
mapOptions.setTarget(exampleId);
mapOptions.setView(view);
Collection<Base> lstLayer = new Collection<Base>();
lstLayer.push(mapGuideLayer);
mapOptions.setLayers(lstLayer);
Map map = new Map(mapOptions);
// add some controls
map.addControl(new ScaleLine());
DemoUtils.addDefaultControls(map.getControls());
// add some interactions
map.addInteraction(new KeyboardPan());
map.addInteraction(new KeyboardZoom());
map.addControl(new Rotate());
}
}
|
gwt-ol3-demo/src/main/java/com/github/tdesjardins/ol3/demo/client/example/MapGuideExample.java
|
/*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.tdesjardins.ol3.demo.client.example;
import com.github.tdesjardins.ol3.demo.client.utils.DemoUtils;
import ol.Collection;
import ol.Coordinate;
import ol.Extent;
import ol.Map;
import ol.MapOptions;
import ol.OLFactory;
import ol.View;
import ol.ViewOptions;
import ol.layer.Base;
import ol.layer.Image;
import ol.layer.LayerOptions;
import ol.proj.Projection;
import ol.source.ImageMapGuide;
import ol.source.ImageMapGuideOptions;
import ol.source.ImageMapGuideParams;
/**
* Example with MapGuide layers.
*
* @author Tobias Lochmann
*
*/
public class MapGuideExample implements Example {
/* (non-Javadoc)
* @see de.desjardins.ol3.demo.client.example.Example#show()
*/
@Override
public void show(String exampleId) {
// create a projection
Projection projection = Projection.get("EPSG:4326");
// create a MapGuide params
ImageMapGuideParams imageMapGuideParams = OLFactory.createOptions();
imageMapGuideParams.setFormat("PNG");
imageMapGuideParams.setMapDefinition("Library://Public/Samples/Sheboygan/Maps/Sheboygan.MapDefinition");
imageMapGuideParams.setUserName("OpenLayers");
imageMapGuideParams.setPassword("OpenLayers");
// create a MapGuide image
ImageMapGuideOptions imageMapGuideOptions = OLFactory.createOptions();
imageMapGuideOptions.setParams(imageMapGuideParams);
imageMapGuideOptions.setUrl("http://www.buoyshark.com/mapguide/mapagent/mapagent.fcgi?");
imageMapGuideOptions.setUseOverlay(false);
imageMapGuideOptions.setMetersPerUnit(111319.4908d);
imageMapGuideOptions.setRatio(2.0f);
ImageMapGuide imageMapGuideSource = OLFactory.createImageMapGuideSource(imageMapGuideOptions);
LayerOptions layerOptions = OLFactory.createOptions();
Extent bounds = Extent.create(-87.865114442365922d,43.665065564837931d,-87.595394059497067d,43.823852564430069d);
layerOptions.setExtent(bounds);
layerOptions.setSource(imageMapGuideSource);
Image MapGuideLayer = OLFactory.createImageLayer(layerOptions);
// create a view
ViewOptions viewOptions = OLFactory.createOptions();
viewOptions.setProjection(projection);
viewOptions.setZoom(12.0d);
Coordinate centerCoordinate = OLFactory.createCoordinate(-87.7302542509315d, 43.744459064634d);
viewOptions.setCenter(centerCoordinate);
View view = OLFactory.createView(viewOptions);
// create the map
MapOptions mapOptions = OLFactory.createOptions();
mapOptions.setTarget(exampleId);
mapOptions.setView(view);
Collection<Base> lstLayer = OLFactory.createCollection();
lstLayer.push(MapGuideLayer);
mapOptions.setLayers(lstLayer);
Map map = OLFactory.createMap(mapOptions);
// add some controls
map.addControl(OLFactory.createScaleLine());
DemoUtils.addDefaultControls(map.getControls());
// add some interactions
map.addInteraction(OLFactory.createKeyboardPan());
map.addInteraction(OLFactory.createKeyboardZoom());
map.addControl(OLFactory.createRotate());
}
}
|
Refactor MapGuideExample
|
gwt-ol3-demo/src/main/java/com/github/tdesjardins/ol3/demo/client/example/MapGuideExample.java
|
Refactor MapGuideExample
|
|
Java
|
apache-2.0
|
5e5b8d4f52635d19767c75092f7ad5ccc693f0ed
| 0
|
diorcety/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,retomerz/intellij-community,samthor/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,signed/intellij-community,da1z/intellij-community,petteyg/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,caot/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ibinti/intellij-community,izonder/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ibinti/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,kool79/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,izonder/intellij-community,dslomov/intellij-community,samthor/intellij-community,xfournet/intellij-community,allotria/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,fitermay/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,signed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,petteyg/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,diorcety/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,caot/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,adedayo/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,allotria/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,Distrotech/intellij-community,signed/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,clumsy/intellij-community,jagguli/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ryano144/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,samthor/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,semonte/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,signed/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,holmes/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,allotria/intellij-community,xfournet/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,holmes/intellij-community,izonder/intellij-community,izonder/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,slisson/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ibinti/intellij-community,kdwink/intellij-community,samthor/intellij-community,izonder/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,kool79/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,apixandru/intellij-community,slisson/intellij-community,slisson/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,slisson/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,amith01994/intellij-community,kdwink/intellij-community,semonte/intellij-community,caot/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,xfournet/intellij-community,caot/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,da1z/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,petteyg/intellij-community,diorcety/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,robovm/robovm-studio,samthor/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,jagguli/intellij-community,slisson/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,kdwink/intellij-community,fitermay/intellij-community,fnouama/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,holmes/intellij-community,signed/intellij-community,fitermay/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,xfournet/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,fnouama/intellij-community,caot/intellij-community,fitermay/intellij-community,dslomov/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,kdwink/intellij-community,holmes/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,alphafoobar/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,FHannes/intellij-community,caot/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ryano144/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,da1z/intellij-community,supersven/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,signed/intellij-community,robovm/robovm-studio,vladmm/intellij-community,allotria/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,caot/intellij-community,FHannes/intellij-community,adedayo/intellij-community,dslomov/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,asedunov/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,retomerz/intellij-community,amith01994/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,akosyakov/intellij-community,signed/intellij-community,gnuhub/intellij-community,caot/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,jagguli/intellij-community,allotria/intellij-community,vvv1559/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,slisson/intellij-community,tmpgit/intellij-community,semonte/intellij-community,fitermay/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,robovm/robovm-studio,mglukhikh/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,holmes/intellij-community,robovm/robovm-studio,da1z/intellij-community,vladmm/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,dslomov/intellij-community,hurricup/intellij-community,semonte/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,blademainer/intellij-community,hurricup/intellij-community,dslomov/intellij-community,vladmm/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,vladmm/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,allotria/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,holmes/intellij-community,adedayo/intellij-community,vladmm/intellij-community,caot/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,caot/intellij-community,asedunov/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,apixandru/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,retomerz/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,tmpgit/intellij-community,holmes/intellij-community,diorcety/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,supersven/intellij-community,hurricup/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,izonder/intellij-community,diorcety/intellij-community,kool79/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,slisson/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,da1z/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,supersven/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.bytecodeAnalysis;
import com.intellij.codeInspection.bytecodeAnalysis.asm.ASMUtils;
import com.intellij.codeInspection.bytecodeAnalysis.asm.ControlFlowGraph.Edge;
import com.intellij.codeInspection.bytecodeAnalysis.asm.RichControlFlow;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.org.objectweb.asm.Handle;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.tree.*;
import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException;
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicInterpreter;
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue;
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.intellij.codeInspection.bytecodeAnalysis.AbstractValues.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
class InOutAnalysis extends Analysis<Result<Key, Value>> {
private static final ThreadLocal<Result<Key, Value>[]> ourResults = new ThreadLocal<Result<Key, Value>[]>() {
@Override
protected Result<Key, Value>[] initialValue() {
return new Result[Analysis.STEPS_LIMIT];
}
};
static final ResultUtil<Key, Value> resultUtil =
new ResultUtil<Key, Value>(new ELattice<Value>(Value.Bot, Value.Top));
private final InOutInterpreter interpreter;
private final Value inValue;
private final int generalizeShift;
protected InOutAnalysis(RichControlFlow richControlFlow, Direction direction, boolean[] resultOrigins, boolean stable) {
super(richControlFlow, direction, stable, ourResults.get());
interpreter = new InOutInterpreter(direction, richControlFlow.controlFlow.methodNode.instructions, resultOrigins);
inValue = direction instanceof InOut ? ((InOut)direction).inValue : null;
generalizeShift = (methodNode.access & ACC_STATIC) == 0 ? 1 : 0;
}
@Override
Result<Key, Value> identity() {
return new Final<Key, Value>(Value.Bot);
}
@Override
Result<Key, Value> combineResults(Result<Key, Value> delta, int[] subResults) throws AnalyzerException {
Result<Key, Value> result = null;
for (int subResult : subResults) {
if (result == null) {
result = results[subResult];
} else {
result = resultUtil.join(result, results[subResult]);
}
}
return result;
}
@Override
boolean isEarlyResult(Result<Key, Value> res) {
if (res instanceof Final) {
return ((Final<?, Value>)res).value == Value.Top;
}
return false;
}
@NotNull
@Override
Equation<Key, Value> mkEquation(Result<Key, Value> res) {
return new Equation<Key, Value>(aKey, res);
}
private int id = 0;
@Override
void processState(State state) throws AnalyzerException {
int stateIndex = state.index;
Conf preConf = state.conf;
int insnIndex = preConf.insnIndex;
boolean loopEnter = dfsTree.loopEnters[insnIndex];
Conf conf = loopEnter ? generalize(preConf) : preConf;
List<Conf> history = state.history;
boolean taken = state.taken;
Frame<BasicValue> frame = conf.frame;
AbstractInsnNode insnNode = methodNode.instructions.get(insnIndex);
List<Conf> nextHistory = loopEnter ? append(history, conf) : history;
Frame<BasicValue> nextFrame = execute(frame, insnNode);
if (interpreter.deReferenced) {
results[stateIndex] = new Final<Key, Value>(Value.Bot);
addComputed(insnIndex, state);
return;
}
int opcode = insnNode.getOpcode();
switch (opcode) {
case ARETURN:
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case RETURN:
BasicValue stackTop = popValue(frame);
if (FalseValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.False);
addComputed(insnIndex, state);
}
else if (TrueValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.True);
addComputed(insnIndex, state);
}
else if (NullValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.Null);
addComputed(insnIndex, state);
}
else if (stackTop instanceof NotNullValue) {
results[stateIndex] = new Final<Key, Value>(Value.NotNull);
addComputed(insnIndex, state);
}
else if (stackTop instanceof ParamValue) {
results[stateIndex] = new Final<Key, Value>(inValue);
addComputed(insnIndex, state);
}
else if (stackTop instanceof CallResultValue) {
Set<Key> keys = ((CallResultValue) stackTop).inters;
results[stateIndex] = new Pending<Key, Value>(Collections.singleton(new Product<Key, Value>(Value.Top, keys)));
addComputed(insnIndex, state);
}
else {
earlyResult = new Final<Key, Value>(Value.Top);
}
return;
case ATHROW:
results[stateIndex] = new Final<Key, Value>(Value.Bot);
addComputed(insnIndex, state);
return;
default:
}
if (opcode == IFNONNULL && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.Null ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNULL && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.NotNull ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFEQ && popValue(frame) == InstanceOfCheckValue && inValue == Value.Null) {
int nextInsnIndex = methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNE && popValue(frame) == InstanceOfCheckValue && inValue == Value.Null) {
int nextInsnIndex = insnIndex + 1;
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFEQ && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.True ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNE && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.False ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
// general case
int[] nextInsnIndices = controlFlow.transitions[insnIndex];
int[] subIndices = new int[nextInsnIndices.length];
for (int i = 0; i < nextInsnIndices.length; i++) {
subIndices[i] = ++id;
}
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, subIndices));
for (int i = 0; i < nextInsnIndices.length; i++) {
int nextInsnIndex = nextInsnIndices[i];
Frame<BasicValue> nextFrame1 = nextFrame;
if (controlFlow.errors[nextInsnIndex] && controlFlow.errorTransitions.contains(new Edge(insnIndex, nextInsnIndex))) {
nextFrame1 = new Frame<BasicValue>(frame);
nextFrame1.clearStack();
nextFrame1.push(ASMUtils.THROWABLE_VALUE);
}
pendingPush(new ProceedState<Result<Key, Value>>(
new State(subIndices[i], new Conf(nextInsnIndex, nextFrame1), nextHistory, taken, false)));
}
}
private Frame<BasicValue> execute(Frame<BasicValue> frame, AbstractInsnNode insnNode) throws AnalyzerException {
interpreter.deReferenced = false;
switch (insnNode.getType()) {
case AbstractInsnNode.LABEL:
case AbstractInsnNode.LINE:
case AbstractInsnNode.FRAME:
return frame;
default:
Frame<BasicValue> nextFrame = new Frame<BasicValue>(frame);
nextFrame.execute(insnNode, interpreter);
return nextFrame;
}
}
private Conf generalize(Conf conf) {
Frame<BasicValue> frame = new Frame<BasicValue>(conf.frame);
for (int i = generalizeShift; i < frame.getLocals(); i++) {
BasicValue value = frame.getLocal(i);
Class<?> valueClass = value.getClass();
if (valueClass != BasicValue.class && valueClass != ParamValue.class) {
frame.setLocal(i, new BasicValue(value.getType()));
}
}
BasicValue[] stack = new BasicValue[frame.getStackSize()];
for (int i = 0; i < frame.getStackSize(); i++) {
stack[i] = frame.getStack(i);
}
frame.clearStack();
for (BasicValue value : stack) {
Class<?> valueClass = value.getClass();
if (valueClass != BasicValue.class && valueClass != ParamValue.class) {
frame.push(new BasicValue(value.getType()));
} else {
frame.push(value);
}
}
return new Conf(conf.insnIndex, frame);
}
}
class InOutInterpreter extends BasicInterpreter {
final Direction direction;
final InsnList insns;
final boolean[] resultOrigins;
final boolean nullAnalysis;
boolean deReferenced = false;
InOutInterpreter(Direction direction, InsnList insns, boolean[] resultOrigins) {
this.direction = direction;
this.insns = insns;
this.resultOrigins = resultOrigins;
nullAnalysis = (direction instanceof InOut) && (((InOut)direction).inValue) == Value.Null;
}
@Override
public BasicValue newOperation(AbstractInsnNode insn) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
if (propagate) {
switch (insn.getOpcode()) {
case ICONST_0:
return FalseValue;
case ICONST_1:
return TrueValue;
case ACONST_NULL:
return NullValue;
case LDC:
Object cst = ((LdcInsnNode)insn).cst;
if (cst instanceof Type) {
Type type = (Type)cst;
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return CLASS_VALUE;
}
if (type.getSort() == Type.METHOD) {
return METHOD_VALUE;
}
}
else if (cst instanceof String) {
return STRING_VALUE;
}
else if (cst instanceof Handle) {
return METHOD_HANDLE_VALUE;
}
break;
case NEW:
return new NotNullValue(Type.getObjectType(((TypeInsnNode)insn).desc));
default:
}
}
return super.newOperation(insn);
}
@Override
public BasicValue unaryOperation(AbstractInsnNode insn, BasicValue value) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
switch (insn.getOpcode()) {
case GETFIELD:
case ARRAYLENGTH:
case MONITORENTER:
if (nullAnalysis && value instanceof ParamValue) {
deReferenced = true;
}
return super.unaryOperation(insn, value);
case CHECKCAST:
if (value instanceof ParamValue) {
return new ParamValue(Type.getObjectType(((TypeInsnNode)insn).desc));
}
break;
case INSTANCEOF:
if (value instanceof ParamValue) {
return InstanceOfCheckValue;
}
break;
case NEWARRAY:
case ANEWARRAY:
if (propagate) {
return new NotNullValue(super.unaryOperation(insn, value).getType());
}
break;
default:
}
return super.unaryOperation(insn, value);
}
@Override
public BasicValue binaryOperation(AbstractInsnNode insn, BasicValue value1, BasicValue value2) throws AnalyzerException {
switch (insn.getOpcode()) {
case IALOAD:
case LALOAD:
case FALOAD:
case DALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
case PUTFIELD:
if (nullAnalysis && value1 instanceof ParamValue) {
deReferenced = true;
}
break;
default:
}
return super.binaryOperation(insn, value1, value2);
}
@Override
public BasicValue ternaryOperation(AbstractInsnNode insn, BasicValue value1, BasicValue value2, BasicValue value3) throws AnalyzerException {
switch (insn.getOpcode()) {
case IASTORE:
case LASTORE:
case FASTORE:
case DASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
if (nullAnalysis && value1 instanceof ParamValue) {
deReferenced = true;
}
default:
}
return super.ternaryOperation(insn, value1, value2, value3);
}
@Override
public BasicValue naryOperation(AbstractInsnNode insn, List<? extends BasicValue> values) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
int opCode = insn.getOpcode();
int shift = opCode == INVOKESTATIC ? 0 : 1;
switch (opCode) {
case INVOKESPECIAL:
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
if (nullAnalysis && values.get(0) instanceof ParamValue) {
deReferenced = true;
return super.naryOperation(insn, values);
}
}
if (propagate) {
switch (opCode) {
case INVOKESTATIC:
case INVOKESPECIAL:
case INVOKEVIRTUAL:
case INVOKEINTERFACE:
boolean stable = opCode == INVOKESTATIC || opCode == INVOKESPECIAL;
MethodInsnNode mNode = (MethodInsnNode)insn;
Method method = new Method(mNode.owner, mNode.name, mNode.desc);
Type retType = Type.getReturnType(mNode.desc);
boolean isRefRetType = retType.getSort() == Type.OBJECT || retType.getSort() == Type.ARRAY;
if (!Type.VOID_TYPE.equals(retType)) {
if (direction instanceof InOut) {
InOut inOut = (InOut)direction;
HashSet<Key> keys = new HashSet<Key>();
for (int i = shift; i < values.size(); i++) {
if (values.get(i) instanceof ParamValue) {
keys.add(new Key(method, new InOut(i - shift, inOut.inValue), stable));
}
}
if (isRefRetType) {
keys.add(new Key(method, new Out(), stable));
}
if (!keys.isEmpty()) {
return new CallResultValue(retType, keys);
}
}
else if (isRefRetType) {
HashSet<Key> keys = new HashSet<Key>();
keys.add(new Key(method, new Out(), stable));
return new CallResultValue(retType, keys);
}
}
break;
case MULTIANEWARRAY:
return new NotNullValue(super.naryOperation(insn, values).getType());
default:
}
}
return super.naryOperation(insn, values);
}
}
|
java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.bytecodeAnalysis;
import com.intellij.codeInspection.bytecodeAnalysis.asm.ASMUtils;
import com.intellij.codeInspection.bytecodeAnalysis.asm.ControlFlowGraph.Edge;
import com.intellij.codeInspection.bytecodeAnalysis.asm.RichControlFlow;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.org.objectweb.asm.Handle;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.tree.*;
import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException;
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicInterpreter;
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue;
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.intellij.codeInspection.bytecodeAnalysis.AbstractValues.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
class InOutAnalysis extends Analysis<Result<Key, Value>> {
private static final ThreadLocal<Result<Key, Value>[]> ourResults = new ThreadLocal<Result<Key, Value>[]>() {
@Override
protected Result<Key, Value>[] initialValue() {
return new Result[Analysis.STEPS_LIMIT];
}
};
static final ResultUtil<Key, Value> resultUtil =
new ResultUtil<Key, Value>(new ELattice<Value>(Value.Bot, Value.Top));
private final InOutInterpreter interpreter;
private final Value inValue;
protected InOutAnalysis(RichControlFlow richControlFlow, Direction direction, boolean[] resultOrigins, boolean stable) {
super(richControlFlow, direction, stable, ourResults.get());
interpreter = new InOutInterpreter(direction, richControlFlow.controlFlow.methodNode.instructions, resultOrigins);
inValue = direction instanceof InOut ? ((InOut)direction).inValue : null;
}
@Override
Result<Key, Value> identity() {
return new Final<Key, Value>(Value.Bot);
}
@Override
Result<Key, Value> combineResults(Result<Key, Value> delta, int[] subResults) throws AnalyzerException {
Result<Key, Value> result = null;
for (int subResult : subResults) {
if (result == null) {
result = results[subResult];
} else {
result = resultUtil.join(result, results[subResult]);
}
}
return result;
}
@Override
boolean isEarlyResult(Result<Key, Value> res) {
if (res instanceof Final) {
return ((Final<?, Value>)res).value == Value.Top;
}
return false;
}
@NotNull
@Override
Equation<Key, Value> mkEquation(Result<Key, Value> res) {
return new Equation<Key, Value>(aKey, res);
}
private int id = 0;
@Override
void processState(State state) throws AnalyzerException {
int stateIndex = state.index;
Conf preConf = state.conf;
int insnIndex = preConf.insnIndex;
boolean loopEnter = dfsTree.loopEnters[insnIndex];
Conf conf = loopEnter ? generalize(preConf) : preConf;
List<Conf> history = state.history;
boolean taken = state.taken;
Frame<BasicValue> frame = conf.frame;
AbstractInsnNode insnNode = methodNode.instructions.get(insnIndex);
List<Conf> nextHistory = loopEnter ? append(history, conf) : history;
Frame<BasicValue> nextFrame = execute(frame, insnNode);
if (interpreter.deReferenced) {
results[stateIndex] = new Final<Key, Value>(Value.Bot);
addComputed(insnIndex, state);
return;
}
int opcode = insnNode.getOpcode();
switch (opcode) {
case ARETURN:
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case RETURN:
BasicValue stackTop = popValue(frame);
if (FalseValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.False);
addComputed(insnIndex, state);
}
else if (TrueValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.True);
addComputed(insnIndex, state);
}
else if (NullValue == stackTop) {
results[stateIndex] = new Final<Key, Value>(Value.Null);
addComputed(insnIndex, state);
}
else if (stackTop instanceof NotNullValue) {
results[stateIndex] = new Final<Key, Value>(Value.NotNull);
addComputed(insnIndex, state);
}
else if (stackTop instanceof ParamValue) {
results[stateIndex] = new Final<Key, Value>(inValue);
addComputed(insnIndex, state);
}
else if (stackTop instanceof CallResultValue) {
Set<Key> keys = ((CallResultValue) stackTop).inters;
results[stateIndex] = new Pending<Key, Value>(Collections.singleton(new Product<Key, Value>(Value.Top, keys)));
addComputed(insnIndex, state);
}
else {
earlyResult = new Final<Key, Value>(Value.Top);
}
return;
case ATHROW:
results[stateIndex] = new Final<Key, Value>(Value.Bot);
addComputed(insnIndex, state);
return;
default:
}
if (opcode == IFNONNULL && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.Null ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNULL && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.NotNull ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFEQ && popValue(frame) == InstanceOfCheckValue && inValue == Value.Null) {
int nextInsnIndex = methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNE && popValue(frame) == InstanceOfCheckValue && inValue == Value.Null) {
int nextInsnIndex = insnIndex + 1;
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFEQ && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.True ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
if (opcode == IFNE && popValue(frame) instanceof ParamValue) {
int nextInsnIndex = inValue == Value.False ? insnIndex + 1 : methodNode.instructions.indexOf(((JumpInsnNode)insnNode).label);
State nextState = new State(++id, new Conf(nextInsnIndex, nextFrame), nextHistory, true, false);
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, new int[]{nextState.index}));
pendingPush(new ProceedState<Result<Key, Value>>(nextState));
return;
}
// general case
int[] nextInsnIndices = controlFlow.transitions[insnIndex];
int[] subIndices = new int[nextInsnIndices.length];
for (int i = 0; i < nextInsnIndices.length; i++) {
subIndices[i] = ++id;
}
pendingPush(new MakeResult<Result<Key, Value>>(state, myIdentity, subIndices));
for (int i = 0; i < nextInsnIndices.length; i++) {
int nextInsnIndex = nextInsnIndices[i];
Frame<BasicValue> nextFrame1 = nextFrame;
if (controlFlow.errors[nextInsnIndex] && controlFlow.errorTransitions.contains(new Edge(insnIndex, nextInsnIndex))) {
nextFrame1 = new Frame<BasicValue>(frame);
nextFrame1.clearStack();
nextFrame1.push(ASMUtils.THROWABLE_VALUE);
}
pendingPush(new ProceedState<Result<Key, Value>>(
new State(subIndices[i], new Conf(nextInsnIndex, nextFrame1), nextHistory, taken, false)));
}
}
private Frame<BasicValue> execute(Frame<BasicValue> frame, AbstractInsnNode insnNode) throws AnalyzerException {
interpreter.deReferenced = false;
switch (insnNode.getType()) {
case AbstractInsnNode.LABEL:
case AbstractInsnNode.LINE:
case AbstractInsnNode.FRAME:
return frame;
default:
Frame<BasicValue> nextFrame = new Frame<BasicValue>(frame);
nextFrame.execute(insnNode, interpreter);
return nextFrame;
}
}
private static Conf generalize(Conf conf) {
Frame<BasicValue> frame = new Frame<BasicValue>(conf.frame);
for (int i = 0; i < frame.getLocals(); i++) {
BasicValue value = frame.getLocal(i);
Class<?> valueClass = value.getClass();
if (valueClass != BasicValue.class && valueClass != ParamValue.class) {
frame.setLocal(i, new BasicValue(value.getType()));
}
}
BasicValue[] stack = new BasicValue[frame.getStackSize()];
for (int i = 0; i < frame.getStackSize(); i++) {
stack[i] = frame.getStack(i);
}
frame.clearStack();
for (BasicValue value : stack) {
Class<?> valueClass = value.getClass();
if (valueClass != BasicValue.class && valueClass != ParamValue.class) {
frame.push(new BasicValue(value.getType()));
} else {
frame.push(value);
}
}
return new Conf(conf.insnIndex, frame);
}
}
class InOutInterpreter extends BasicInterpreter {
final Direction direction;
final InsnList insns;
final boolean[] resultOrigins;
final boolean nullAnalysis;
boolean deReferenced = false;
InOutInterpreter(Direction direction, InsnList insns, boolean[] resultOrigins) {
this.direction = direction;
this.insns = insns;
this.resultOrigins = resultOrigins;
nullAnalysis = (direction instanceof InOut) && (((InOut)direction).inValue) == Value.Null;
}
@Override
public BasicValue newOperation(AbstractInsnNode insn) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
if (propagate) {
switch (insn.getOpcode()) {
case ICONST_0:
return FalseValue;
case ICONST_1:
return TrueValue;
case ACONST_NULL:
return NullValue;
case LDC:
Object cst = ((LdcInsnNode)insn).cst;
if (cst instanceof Type) {
Type type = (Type)cst;
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return CLASS_VALUE;
}
if (type.getSort() == Type.METHOD) {
return METHOD_VALUE;
}
}
else if (cst instanceof String) {
return STRING_VALUE;
}
else if (cst instanceof Handle) {
return METHOD_HANDLE_VALUE;
}
break;
case NEW:
return new NotNullValue(Type.getObjectType(((TypeInsnNode)insn).desc));
default:
}
}
return super.newOperation(insn);
}
@Override
public BasicValue unaryOperation(AbstractInsnNode insn, BasicValue value) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
switch (insn.getOpcode()) {
case GETFIELD:
case ARRAYLENGTH:
case MONITORENTER:
if (nullAnalysis && value instanceof ParamValue) {
deReferenced = true;
}
return super.unaryOperation(insn, value);
case CHECKCAST:
if (value instanceof ParamValue) {
return new ParamValue(Type.getObjectType(((TypeInsnNode)insn).desc));
}
break;
case INSTANCEOF:
if (value instanceof ParamValue) {
return InstanceOfCheckValue;
}
break;
case NEWARRAY:
case ANEWARRAY:
if (propagate) {
return new NotNullValue(super.unaryOperation(insn, value).getType());
}
break;
default:
}
return super.unaryOperation(insn, value);
}
@Override
public BasicValue binaryOperation(AbstractInsnNode insn, BasicValue value1, BasicValue value2) throws AnalyzerException {
switch (insn.getOpcode()) {
case IALOAD:
case LALOAD:
case FALOAD:
case DALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
case PUTFIELD:
if (nullAnalysis && value1 instanceof ParamValue) {
deReferenced = true;
}
break;
default:
}
return super.binaryOperation(insn, value1, value2);
}
@Override
public BasicValue ternaryOperation(AbstractInsnNode insn, BasicValue value1, BasicValue value2, BasicValue value3) throws AnalyzerException {
switch (insn.getOpcode()) {
case IASTORE:
case LASTORE:
case FASTORE:
case DASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
if (nullAnalysis && value1 instanceof ParamValue) {
deReferenced = true;
}
default:
}
return super.ternaryOperation(insn, value1, value2, value3);
}
@Override
public BasicValue naryOperation(AbstractInsnNode insn, List<? extends BasicValue> values) throws AnalyzerException {
boolean propagate = resultOrigins[insns.indexOf(insn)];
int opCode = insn.getOpcode();
int shift = opCode == INVOKESTATIC ? 0 : 1;
switch (opCode) {
case INVOKESPECIAL:
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
if (nullAnalysis && values.get(0) instanceof ParamValue) {
deReferenced = true;
return super.naryOperation(insn, values);
}
}
if (propagate) {
switch (opCode) {
case INVOKESTATIC:
case INVOKESPECIAL:
case INVOKEVIRTUAL:
case INVOKEINTERFACE:
boolean stable = opCode == INVOKESTATIC || opCode == INVOKESPECIAL;
MethodInsnNode mNode = (MethodInsnNode)insn;
Method method = new Method(mNode.owner, mNode.name, mNode.desc);
Type retType = Type.getReturnType(mNode.desc);
boolean isRefRetType = retType.getSort() == Type.OBJECT || retType.getSort() == Type.ARRAY;
if (!Type.VOID_TYPE.equals(retType)) {
if (direction instanceof InOut) {
InOut inOut = (InOut)direction;
HashSet<Key> keys = new HashSet<Key>();
for (int i = shift; i < values.size(); i++) {
if (values.get(i) instanceof ParamValue) {
keys.add(new Key(method, new InOut(i - shift, inOut.inValue), stable));
}
}
if (isRefRetType) {
keys.add(new Key(method, new Out(), stable));
}
if (!keys.isEmpty()) {
return new CallResultValue(retType, keys);
}
}
else if (isRefRetType) {
HashSet<Key> keys = new HashSet<Key>();
keys.add(new Key(method, new Out(), stable));
return new CallResultValue(retType, keys);
}
}
break;
case MULTIANEWARRAY:
return new NotNullValue(super.naryOperation(insn, values).getType());
default:
}
}
return super.naryOperation(insn, values);
}
}
|
bytecode analysis: do not generalize this
|
java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java
|
bytecode analysis: do not generalize this
|
|
Java
|
apache-2.0
|
error: pathspec 'sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java' did not match any file(s) known to git
|
11415ce63ff993c42a10e4a48f39092f6042a941
| 1
|
apache/mina-sshd,landro/mina-sshd,fschopp/mina-sshd,apache/mina-sshd,avthart/mina-sshd,lgoldstein/mina-sshd,ieure/mina-sshd,fschopp/mina-sshd,landro/mina-sshd,lgoldstein/mina-sshd,avthart/mina-sshd,avthart/mina-sshd,apache/mina-sshd,lgoldstein/mina-sshd,landro/mina-sshd,ieure/mina-sshd,ieure/mina-sshd,apache/mina-sshd,lgoldstein/mina-sshd
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.sshd.common.util;
import java.security.InvalidParameterException;
/**
* Provides Base64 encoding and decoding as defined by RFC 2045.
*
* <p>This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite>
* from RFC 2045 <cite>Multipurpose Internet Mail Extensions (MIME) Part One:
* Format of Internet Message Bodies</cite> by Freed and Borenstein.</p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
*
* This class was
* @author Apache Software Foundation commons codec (http://commons.apache.org/codec/)
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class Base64 {
/**
* Chunk size per RFC 2045 section 6.8.
*
* <p>The {@value} character limit does not count the trailing CRLF, but counts
* all other characters, including any equal signs.</p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
static final int CHUNK_SIZE = 76;
/**
* Chunk separator per RFC 2045 section 2.1.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
*/
static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
/**
* The base length.
*/
static final int BASELENGTH = 255;
/**
* Lookup length.
*/
static final int LOOKUPLENGTH = 64;
/**
* Used to calculate the number of bits in a byte.
*/
static final int EIGHTBIT = 8;
/**
* Used when encoding something which has fewer than 24 bits.
*/
static final int SIXTEENBIT = 16;
/**
* Used to determine how many bits data contains.
*/
static final int TWENTYFOURBITGROUP = 24;
/**
* Used to get the number of Quadruples.
*/
static final int FOURBYTE = 4;
/**
* Used to test the sign of a byte.
*/
static final int SIGN = -128;
/**
* Byte used to pad output.
*/
static final byte PAD = (byte) '=';
// Create arrays to hold the base64 characters and a
// lookup for base64 chars
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
// Populating the lookup and character arrays
static {
for (int i = 0; i < BASELENGTH; i++) {
base64Alphabet[i] = (byte) -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (byte) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('0' + j);
}
lookUpBase64Alphabet[62] = (byte) '+';
lookUpBase64Alphabet[63] = (byte) '/';
}
private static boolean isBase64(byte octect) {
if (octect == PAD) {
return true;
} else if (base64Alphabet[octect] == -1) {
return false;
} else {
return true;
}
}
/**
* Tests a given byte array to see if it contains
* only valid characters within the Base64 alphabet.
*
* @param arrayOctect byte array to test
* @return true if all bytes are valid characters in the Base64
* alphabet or if the byte array is empty; false, otherwise
*/
public static boolean isArrayByteBase64(byte[] arrayOctect) {
arrayOctect = discardWhitespace(arrayOctect);
int length = arrayOctect.length;
if (length == 0) {
// shouldn't a 0 length array be valid base64 data?
return true;
}
for (int i = 0; i < length; i++) {
if (!isBase64(arrayOctect[i])) {
return false;
}
}
return true;
}
/**
* Encodes binary data using the base64 algorithm but
* does not chunk the output.
*
* @param binaryData binary data to encode
* @return Base64 characters
*/
public static byte[] encodeBase64(byte[] binaryData) {
return encodeBase64(binaryData, false);
}
/**
* Encodes binary data using the base64 algorithm and chunks
* the encoded output into 76 character blocks
*
* @param binaryData binary data to encode
* @return Base64 characters chunked in 76 character blocks
*/
public static byte[] encodeBase64Chunked(byte[] binaryData) {
return encodeBase64(binaryData, true);
}
/**
* Decodes an Object using the base64 algorithm. This method
* is provided in order to satisfy the requirements of the
* Decoder interface, and will throw a DecoderException if the
* supplied object is not of type byte[].
*
* @param pObject Object to decode
* @return An object (of type byte[]) containing the
* binary data which corresponds to the byte[] supplied.
* @throws InvalidParameterException if the parameter supplied is not
* of type byte[]
*/
public Object decode(Object pObject) {
if (!(pObject instanceof byte[])) {
throw new InvalidParameterException("Parameter supplied to Base64 decode is not a byte[]");
}
return decode((byte[]) pObject);
}
/**
* Decodes a byte[] containing containing
* characters in the Base64 alphabet.
*
* @param pArray A byte array containing Base64 character data
* @return a byte array containing binary data
*/
public byte[] decode(byte[] pArray) {
return decodeBase64(pArray);
}
/**
* Encodes binary data using the base64 algorithm, optionally
* chunking the output into 76 character blocks.
*
* @param binaryData Array containing binary data to encode.
* @param isChunked if isChunked is true this encoder will chunk
* the base64 output into 76 character blocks
* @return Base64-encoded data.
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
int lengthDataBits = binaryData.length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
byte encodedData[] = null;
int encodedDataLength = 0;
int nbrChunks = 0;
if (fewerThan24bits != 0) {
//data not divisible by 24 bit
encodedDataLength = (numberTriplets + 1) * 4;
} else {
// 16 or 8 bit
encodedDataLength = numberTriplets * 4;
}
// If the output is to be "chunked" into 76 character sections,
// for compliance with RFC 2045 MIME, then it is important to
// allow for extra length to account for the separator(s)
if (isChunked) {
nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
}
encodedData = new byte[encodedDataLength];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
int nextSeparatorIndex = CHUNK_SIZE;
int chunksSoFar = 0;
for (i = 0; i < numberTriplets; i++) {
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
encodedIndex += 4;
// If we are chunking, let's put a chunk separator down.
if (isChunked) {
// this assumes that CHUNK_SIZE % 4 == 0
if (encodedIndex == nextSeparatorIndex) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
chunksSoFar++;
nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length);
encodedIndex += CHUNK_SEPARATOR.length;
}
}
}
// form integral number of 6-bit groups
dataIndex = i * 3;
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
if (isChunked) {
// we also add a separator to the end of the final chunk.
if (chunksSoFar < nbrChunks) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length,
CHUNK_SEPARATOR.length);
}
}
return encodedData;
}
/**
* Decodes Base64 data into octects
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
// RFC 2045 requires that we discard ALL non-Base64 characters
base64Data = discardNonBase64(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == PAD) {
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else if (marker1 == PAD) {
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
/**
* Discards any whitespace from a base-64 encoded block.
*
* @param data The base-64 encoded data to discard the whitespace
* from.
* @return The data, less whitespace (see RFC 2045).
*/
static byte[] discardWhitespace(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++) {
switch (data[i]) {
case (byte) ' ':
case (byte) '\n':
case (byte) '\r':
case (byte) '\t':
break;
default:
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
/**
* Discards any characters outside of the base64 alphabet, per
* the requirements on page 25 of RFC 2045 - "Any characters
* outside of the base64 alphabet are to be ignored in base64
* encoded data."
*
* @param data The base-64 encoded data to groom
* @return The data, less non-base64 characters (see RFC 2045).
*/
static byte[] discardNonBase64(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++) {
if (isBase64(data[i])) {
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
// Implementation of the Encoder Interface
/**
* Encodes an Object using the base64 algorithm. This method
* is provided in order to satisfy the requirements of the
* Encoder interface, and will throw an EncoderException if the
* supplied object is not of type byte[].
*
* @param pObject Object to encode
* @return An object (of type byte[]) containing the
* base64 encoded data which corresponds to the byte[] supplied.
* @throws InvalidParameterException if the parameter supplied is not
* of type byte[]
*/
public Object encode(Object pObject) {
if (!(pObject instanceof byte[])) {
throw new InvalidParameterException("Parameter supplied to Base64 encode is not a byte[]");
}
return encode((byte[]) pObject);
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing
* characters in the Base64 alphabet.
*
* @param pArray a byte array containing binary data
* @return A byte array containing only Base64 character data
*/
public byte[] encode(byte[] pArray) {
return encodeBase64(pArray, false);
}
}
|
sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java
|
[SSHD-259] Provide Base64 in sshd
|
sshd-core/src/main/java/org/apache/sshd/common/util/Base64.java
|
[SSHD-259] Provide Base64 in sshd
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/com/github/pedrovgs/problem66/TreeToListByLevel.java' did not match any file(s) known to git
|
e8dfcf1242a0976c8589f9df635576342c15dab4
| 1
|
JeffreyWei/Algorithms,zmywly8866/Algorithms,VeskoI/Algorithms,chengjinqian/Algorithms,AppScientist/Algorithms,mrgenco/Algorithms-1,ajinkyakolhe112/Algorithms,pedrovgs/Algorithms,zhdh2008/Algorithms,ArlenLiu/Algorithms,jibaro/Algorithms,007slm/Algorithms,Arkar-Aung/Algorithms,sridhar-newsdistill/Algorithms,Ariloum/Algorithms,inexistence/Algorithms
|
/*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pedrovgs.problem66;
import com.github.pedrovgs.binarytree.BinaryNode;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* Given a binary tree, design an algorithm which creates a linked list of all the nodes at
* each depth (e.g., if you have a tree with depth D, you'll have D linked lists).
*
* @author Pedro Vicente Gómez Sánchez.
*/
public class TreeToListByLevel {
}
|
src/main/java/com/github/pedrovgs/problem66/TreeToListByLevel.java
|
Add statement to problem 66
|
src/main/java/com/github/pedrovgs/problem66/TreeToListByLevel.java
|
Add statement to problem 66
|
|
Java
|
apache-2.0
|
error: pathspec 'fidm/src/main/java/com/esuta/fidm/gui/component/model/LoadableModel.java' did not match any file(s) known to git
|
e1f6323cfffcc5bb99d84b5f5e6c98abcd8bbfb2
| 1
|
eriksuta/fidm,eriksuta/fidm,eriksuta/fidm
|
package com.esuta.fidm.gui.component.model;
import org.apache.wicket.model.IModel;
/**
* @author shood
*
* This IModel implementation is loosely based on LoadableModel
* class from Evolveum/MidPoint (https://github.com/Evolveum/midpoint/blob/a6c023945dbea34db69a8ff17c9a61b7184c42cc/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/LoadableModel.java)
* Autor of class: Viliam Repan
* */
public abstract class LoadableModel<T> implements IModel<T> {
private T object;
private boolean loaded = false;
private boolean alwaysReload;
public LoadableModel(){
this(null, true);
}
public LoadableModel(boolean alwaysReload){
this(null, alwaysReload);
}
public LoadableModel(T object){
this(object, true);
}
public LoadableModel(T object, boolean alwaysReload){
this.object = object;
this.alwaysReload = alwaysReload;
}
@Override
public T getObject() {
if(!loaded){
setObject(load());
onLoad();
this.loaded = true;
}
if(object instanceof IModel){
IModel model = (IModel) object;
return (T)model.getObject();
}
return object;
}
@Override
public void setObject(T object) {
if(this.object instanceof IModel){
((IModel<T>)this.object).setObject(object);
} else {
this.object = object;
}
this.loaded = true;
}
public boolean isLoaded() {
return loaded;
}
public void reset(){
loaded = false;
}
@Override
public void detach() {
if(loaded && alwaysReload){
this.loaded = false;
onDetach();
}
}
protected abstract T load();
protected void onLoad(){}
protected void onDetach(){}
}
|
fidm/src/main/java/com/esuta/fidm/gui/component/model/LoadableModel.java
|
Adding LoadableModel to gui component
|
fidm/src/main/java/com/esuta/fidm/gui/component/model/LoadableModel.java
|
Adding LoadableModel to gui component
|
|
Java
|
apache-2.0
|
error: pathspec 'server/master/src/test/java/org/apache/accumulo/master/upgrade/Upgrader9to10Test.java' did not match any file(s) known to git
|
20209e7a9f5571831704301a79368b08f4f2ab9d
| 1
|
ctubbsii/accumulo,mjwall/accumulo,milleruntime/accumulo,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,milleruntime/accumulo,keith-turner/accumulo,apache/accumulo,ivakegg/accumulo,phrocker/accumulo-1,lstav/accumulo,apache/accumulo,lstav/accumulo,mjwall/accumulo,ctubbsii/accumulo,keith-turner/accumulo,keith-turner/accumulo,phrocker/accumulo-1,apache/accumulo,lstav/accumulo,phrocker/accumulo-1,lstav/accumulo,ivakegg/accumulo,keith-turner/accumulo,apache/accumulo,ivakegg/accumulo,phrocker/accumulo-1,phrocker/accumulo-1,milleruntime/accumulo,phrocker/accumulo-1,ivakegg/accumulo,lstav/accumulo,milleruntime/accumulo,mjwall/accumulo,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,ivakegg/accumulo,ivakegg/accumulo,ivakegg/accumulo,mjwall/accumulo,milleruntime/accumulo,keith-turner/accumulo,apache/accumulo,apache/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,lstav/accumulo,lstav/accumulo,keith-turner/accumulo,mjwall/accumulo,keith-turner/accumulo,phrocker/accumulo-1,apache/accumulo
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.master.upgrade;
import static org.apache.accumulo.core.Constants.BULK_PREFIX;
import static org.junit.Assert.assertEquals;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.server.gc.GcVolumeUtil;
import org.junit.Test;
public class Upgrader9to10Test {
@Test
public void testSwitchRelative() {
assertEquals(GcVolumeUtil.getDeleteTabletOnAllVolumesUri(TableId.of("5a"), "t-0005"),
Upgrader9to10.switchToAllVolumes("/5a/t-0005"));
assertEquals("/5a/" + BULK_PREFIX + "0005",
Upgrader9to10.switchToAllVolumes("/5a/" + BULK_PREFIX + "0005"));
assertEquals("/5a/t-0005/F0009.rf", Upgrader9to10.switchToAllVolumes("/5a/t-0005/F0009.rf"));
}
@Test(expected = IllegalStateException.class)
public void testBadRelativeTooShort() {
Upgrader9to10.switchToAllVolumes("/5a");
}
@Test(expected = IllegalStateException.class)
public void testBadRelativeTooLong() {
Upgrader9to10.switchToAllVolumes("/5a/5a/t-0005/F0009.rf");
}
@Test
public void testSwitch() {
assertEquals(GcVolumeUtil.getDeleteTabletOnAllVolumesUri(TableId.of("5a"), "t-0005"),
Upgrader9to10.switchToAllVolumes("hdfs://localhost:9000/accumulo/tables/5a/t-0005"));
assertEquals("hdfs://localhost:9000/accumulo/tables/5a/" + BULK_PREFIX + "0005", Upgrader9to10
.switchToAllVolumes("hdfs://localhost:9000/accumulo/tables/5a/" + BULK_PREFIX + "0005"));
assertEquals("hdfs://localhost:9000/accumulo/tables/5a/t-0005/C0009.rf", Upgrader9to10
.switchToAllVolumes("hdfs://localhost:9000/accumulo/tables/5a/t-0005/C0009.rf"));
}
@Test
public void testUpgradeDir() {
assertEquals("t-0005",
Upgrader9to10.upgradeDirColumn("hdfs://localhost:9000/accumulo/tables/5a/t-0005"));
assertEquals("t-0005", Upgrader9to10.upgradeDirColumn("../5a/t-0005"));
assertEquals("t-0005", Upgrader9to10.upgradeDirColumn("/t-0005"));
assertEquals("t-0005", Upgrader9to10.upgradeDirColumn("t-0005"));
}
}
|
server/master/src/test/java/org/apache/accumulo/master/upgrade/Upgrader9to10Test.java
|
Add upgrade unit test
This file was supposed to go with #1389 but I forgot to add it.
|
server/master/src/test/java/org/apache/accumulo/master/upgrade/Upgrader9to10Test.java
|
Add upgrade unit test
|
|
Java
|
bsd-2-clause
|
error: pathspec 'src/ublu/command/CmdSocket.java' did not match any file(s) known to git
|
4b8b7f7640cf1222761f41c235c61f02ec9416c7
| 1
|
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
|
/*
* Copyright (c) 2014, Absolute Performance, Inc. http://www.absolute-performance.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ublu.command;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import ublu.util.Tuple;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.SQLException;
import java.util.logging.Level;
import ublu.util.Generics.ByteArrayList;
/**
* Get a list of objects on the system
*
* @author jwoehr
*/
public class CmdSocket extends Command {
{
setNameAndDescription("sock", "/0 [-to datasink] [--,-sock ~@sock] [-host ~@{host_or_ip_addr}] [-port ~@{portnum}] [-locaddr ~@{local_addr}] [-locport ~@{local_portnum}] [-instance | -close | -avail | -read ~@{count} | -write ~@bytes] : create and manipulate sockets");
}
/**
* the operations we know
*/
protected enum OPS {
/**
* Create the socket
*/
INSTANCE,
/**
* available count
*/
AVAIL,
/**
* read
*/
READ,
/**
* write
*/
WRITE,
/**
* close
*/
CLOSE,
/**
* query setting
*/
QUERY,
/**
* set setting
*/
SET
}
/**
* Arity-0 ctor
*/
public CmdSocket() {
}
private String host = null;
private Integer portnum = null;
private String localAddr = null;
private Integer localPort = null;
private Tuple sockTuple = null;
private Tuple writeTuple = null;
private int readCount = 0;
/**
* retrieve a (filtered) list of OS400 Objects on the system
*
* @param argArray the remainder of the command stream
* @return the new remainder of the command stream
*/
public ArgArray doSock(ArgArray argArray) {
OPS op = OPS.INSTANCE;
while (argArray.hasDashCommand()) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
String destName = argArray.next();
setDataDest(DataSink.fromSinkName(destName));
break;
case "-sock":
case "--":
sockTuple = argArray.nextTupleOrPop();
break;
case "-instance":
op = OPS.INSTANCE;
break;
case "-port":
portnum = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-host":
host = argArray.nextMaybeQuotationTuplePopString();
break;
case "-locaddr":
localAddr = argArray.nextMaybeQuotationTuplePopString();
break;
case "-locport":
localPort = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-close":
op = OPS.CLOSE;
break;
case "-avail":
op = OPS.AVAIL;
break;
case "-read":
op = OPS.READ;
readCount = argArray.nextIntMaybeQuotationTuplePopString();
break;
case "-write":
op = OPS.WRITE;
writeTuple = argArray.nextTupleOrPop();
break;
default:
unknownDashCommand(dashCommand);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
} else {
Socket socket = null;
byte[] b;
ByteArrayList bytesRead = null;
switch (op) {
case INSTANCE: {
try {
socket = sockInstance();
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Exception creating socket in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
if (socket != null) {
try {
put(socket);
} catch (SQLException | AS400SecurityException | RequestNotSupportedException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException ex) {
getLogger().log(Level.SEVERE, "Exception putting socket in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
break;
case CLOSE:
socket = sockFromTuple();
if (socket != null) {
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Exception closing socket in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
break;
case AVAIL:
socket = sockFromTuple();
if (socket != null) {
try {
put(socket.getInputStream().available());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Exception getting or putting available count in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
break;
case READ:
socket = sockFromTuple();
if (socket != null) {
try {
InputStream is = socket.getInputStream();
b = new byte[readCount];
int numread = is.read(b);
bytesRead = new ByteArrayList(b, numread);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Exception reading socket in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
try {
put(bytesRead);
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Exception putting read bytes in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
}
break;
case WRITE:
socket = sockFromTuple();
b = bytesFromWriteTuple();
if (socket != null) {
if (b != null) {
try {
OutputStream os = socket.getOutputStream();
os.write(b);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Exception writing socket in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
} else {
getLogger().log(Level.INFO, "No bytes provided and no bytes written in {0}", getNameAndDescription());
}
}
break;
default:
getLogger().log(Level.WARNING, "Unknown operation in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
}
return argArray;
}
private Socket sockInstance() throws IOException {
Socket so = null;
if ((localAddr == null && localPort != null)
|| (localAddr != null && localPort == null)
|| host == null || portnum == null) {
getLogger().log(Level.WARNING, "Incompatible settings (missing value?) in instancing socket in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
} else if (localAddr == null) {
so = new Socket(InetAddress.getByName(host), portnum);
} else {
so = new Socket(InetAddress.getByName(host), portnum, InetAddress.getByName(localAddr), localPort);
}
return so;
}
private Socket sockFromTuple() {
Socket so = null;
if (sockTuple != null) {
Object o = sockTuple.getValue();
if (o instanceof Socket) {
so = Socket.class
.cast(o);
}
}
if (so == null) {
getLogger().log(Level.WARNING, "No socket provided in {0}", getNameAndDescription());
setCommandResult(COMMANDRESULT.FAILURE);
}
return so;
}
private byte[] bytesFromWriteTuple() {
byte[] b = null;
if (writeTuple != null) {
Object o = writeTuple.getValue();
if (o instanceof String) {
b = o.toString().getBytes();
} else if (o instanceof ByteArrayList) {
b = ByteArrayList.class.cast(o).byteArray();
} else if (o instanceof byte[]) {
b = (byte[]) o;
}
}
return b;
}
@Override
public ArgArray cmd(ArgArray args) {
reinit();
return doSock(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
}
|
src/ublu/command/CmdSocket.java
|
CmdSocket
|
src/ublu/command/CmdSocket.java
|
CmdSocket
|
|
Java
|
bsd-3-clause
|
error: pathspec 'src/com/thaiopensource/xml/util/Name.java' did not match any file(s) known to git
|
f02c5fb09db902466982155aea108a0cd5cb2a04
| 1
|
vandenoever/jing,vandenoever/jing,vandenoever/jing
|
package com.thaiopensource.xml.util;
public final class Name {
final private String namespaceUri;
final private String localName;
final private int hc;
public Name(String namespaceUri, String localName) {
this.namespaceUri = namespaceUri;
this.localName = localName;
this.hc = namespaceUri.hashCode() ^ localName.hashCode();
}
public String getNamespaceUri() {
return namespaceUri;
}
public String getLocalName() {
return localName;
}
public boolean equals(Object obj) {
if (!(obj instanceof Name))
return false;
Name other = (Name)obj;
return (this.hc == other.hc
&& this.namespaceUri.equals(other.namespaceUri)
&& this.localName.equals(other.localName));
}
public int hashCode() {
return hc;
}
}
|
src/com/thaiopensource/xml/util/Name.java
|
Recover merged version
git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@1967 369101cc-9a96-11dd-8e58-870c635edf7a
|
src/com/thaiopensource/xml/util/Name.java
|
Recover merged version
|
|
Java
|
bsd-3-clause
|
error: pathspec 'openxc/tests/com/openxc/sources/BytestreamDataSourceTest.java' did not match any file(s) known to git
|
a33cf79b9ee0eef1c39bad1ed2ba1915095b867a
| 1
|
mray19027/openxc-android,prateeknitish391/demo,dhootha/openxc-android,prateeknitish391/demo,ChernyshovYuriy/openxc-android,petemaclellan/openxc-android,ChernyshovYuriy/openxc-android,petemaclellan/openxc-android,msowka/openxc-android,dhootha/openxc-android,openxc/openxc-android,openxc/openxc-android,mray19027/openxc-android,prateeknitish391/demo,msowka/openxc-android
|
package com.openxc.sources;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.Robolectric;
import com.openxc.TestUtils;
import com.openxc.messages.VehicleMessage;
import com.openxc.messages.SimpleVehicleMessage;
import com.openxc.messages.streamers.JsonStreamer;
@Config(emulateSdk = 18, manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class BytestreamDataSourceTest {
TestBytestreamSource source;
SourceCallback callback = mock(SourceCallback.class);
@Before
public void setup() {
source = new TestBytestreamSource(callback);
}
@After
public void teardown() {
source.stop();
}
@Test
public void startedIsRunning() {
source.start();
assertTrue(source.isRunning());
}
@Test
public void initializedNotRunning() {
assertFalse(source.isRunning());
}
@Test
public void stoppedNotRunning() {
source.start();
source.stop();
assertFalse(source.isRunning());
}
@Test
public void errorOnReadDisconnects() {
source.start();
source.connect();
source.nextReadIsError = true;
source.inject(new byte[] {1,2,3,4});
TestUtils.pause(10);
assertTrue(source.isRunning());
assertFalse(source.isConnected());
}
@Test
public void exceptionOnReadDisconnects() {
source.start();
source.connect();
source.nextReadThrowsException = true;
source.inject(new byte[] {1,2,3,4});
TestUtils.pause(10);
assertTrue(source.isRunning());
assertFalse(source.isConnected());
}
@Test
public void readNotCalledUntilConnected() {
source.start();
source.inject(new byte[] {1,2,3,4});
assertFalse(source.packets.isEmpty());
source.connect();
TestUtils.pause(10);
assertTrue(source.packets.isEmpty());
}
@Test
public void receiveInvalidDataNoCallback() {
source.start();
source.connect();
source.inject(new byte[] {1,2,3,4});
TestUtils.pause(10);
verify(callback, never()).receive(Mockito.any(VehicleMessage.class));
}
@Test
public void receiveValidJsonTriggersCallback() {
source.start();
source.connect();
SimpleVehicleMessage message = new SimpleVehicleMessage("foo", "bar");
source.inject(new JsonStreamer().serializeForStream(message));
TestUtils.pause(30);
ArgumentCaptor<VehicleMessage> argument = ArgumentCaptor.forClass(
VehicleMessage.class);
verify(callback).receive(argument.capture());
VehicleMessage received = argument.getValue();
received.untimestamp();
assertEquals(received, message);
}
private class TestBytestreamSource extends BytestreamDataSource {
public boolean connected = false;
public ArrayList<byte[]> packets = new ArrayList<>();
private Lock mPacketLock = new ReentrantLock();
private Condition mPacketReceived = mPacketLock.newCondition();
public boolean nextReadIsError = false;
public boolean nextReadThrowsException = false;
public TestBytestreamSource(SourceCallback callback) {
super(callback, Robolectric.application);
}
@Override
public boolean isConnected() {
return connected;
}
public void inject(byte[] bytes) {
try {
mPacketLock.lock();
packets.add(bytes);
mPacketReceived.signal();
} finally {
mPacketLock.unlock();
}
}
protected int read(byte[] bytes) throws IOException {
try {
mPacketLock.lock();
while(packets.isEmpty()) {
mPacketReceived.await();
}
if(nextReadIsError) {
return -1;
} else if(nextReadThrowsException) {
throw new IOException();
} else {
byte[] data = packets.remove(0);
System.arraycopy(data, 0, bytes, 0, data.length);
return data.length;
}
} catch(InterruptedException e) {
return -1;
} finally {
mPacketLock.unlock();
}
}
protected void disconnect() {
mConnectionLock.writeLock().lock();
connected = false;
disconnected();
mConnectionLock.writeLock().unlock();
}
protected void connect() {
mConnectionLock.writeLock().lock();
connected = true;
disconnected();
mConnectionLock.writeLock().unlock();
}
}
}
|
openxc/tests/com/openxc/sources/BytestreamDataSourceTest.java
|
Add tests for BytestreamDataSource.
This is the closest we can get to a full end-to-end test without running
on an emulator or device.
|
openxc/tests/com/openxc/sources/BytestreamDataSourceTest.java
|
Add tests for BytestreamDataSource.
|
|
Java
|
isc
|
4ba9ca49dc741bcc59f614518061fc04d0ba5f43
| 0
|
TealCube/strife
|
package info.faceland.strife.util;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.data.StrifeMob;
import info.faceland.strife.util.DamageUtil.OriginLocation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
public class TargetingUtil {
public static void filterFriendlyEntities(Set<LivingEntity> targets, StrifeMob caster,
boolean friendly) {
Set<LivingEntity> friendlyEntities = getFriendlyEntities(caster, targets);
if (friendly) {
targets.clear();
targets.addAll(friendlyEntities);
} else {
targets.removeAll(friendlyEntities);
}
}
public static Set<LivingEntity> getFriendlyEntities(StrifeMob caster, Set<LivingEntity> targets) {
return targets.stream().filter(target -> isFriendly(caster, target)).collect(Collectors.toSet());
}
public static boolean isFriendly(StrifeMob caster, LivingEntity target) {
if (caster.getEntity() == target) {
return true;
}
if (caster.getEntity() instanceof Player && target instanceof Player) {
return !DamageUtil.canAttack((Player) caster.getEntity(), (Player) target);
}
for (StrifeMob mob : caster.getMinions()) {
if (target == mob.getEntity()) {
return true;
}
}
// for (StrifeMob mob : getPartyMembers {
// }
return false;
}
public static Set<LivingEntity> getEntitiesInArea(LivingEntity caster, double radius) {
Collection<Entity> targetList = caster.getWorld()
.getNearbyEntities(caster.getLocation(), radius, radius, radius);
Set<LivingEntity> validTargets = new HashSet<>();
for (Entity e : targetList) {
if (!e.isValid() || e instanceof ArmorStand || !(e instanceof LivingEntity)) {
continue;
}
if (caster.hasLineOfSight(e)) {
validTargets.add((LivingEntity) e);
}
}
return validTargets;
}
public static boolean isDetectionStand(LivingEntity le) {
return le instanceof ArmorStand && le.hasMetadata("STANDO");
}
public static ArmorStand buildAndRemoveDetectionStand(Location location) {
ArmorStand stando = location.getWorld().spawn(location, ArmorStand.class,
e -> e.setVisible(false));
stando.setSmall(true);
stando.setMetadata("STANDO", new FixedMetadataValue(StrifePlugin.getInstance(), ""));
Bukkit.getScheduler().runTaskLater(StrifePlugin.getInstance(), stando::remove, 1L);
return stando;
}
public static Set<LivingEntity> getTempStandTargetList(Location loc, float groundCheckRange) {
Set<LivingEntity> targets = new HashSet<>();
if (groundCheckRange < 1) {
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
} else {
for (int i = 0; i < groundCheckRange; i++) {
if (loc.getBlock().getType().isSolid()) {
loc.setY(loc.getBlockY() + 1.1);
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
}
loc.add(0, -1, 0);
}
return targets;
}
}
public static Set<LivingEntity> getEntitiesInLine(LivingEntity caster, double range) {
Set<LivingEntity> targets = new HashSet<>();
Location eyeLoc = caster.getEyeLocation();
Vector direction = caster.getEyeLocation().getDirection();
ArrayList<Entity> entities = (ArrayList<Entity>) caster.getNearbyEntities(range, range, range);
for (double incRange = 0; incRange <= range; incRange += 1) {
Location loc = eyeLoc.clone().add(direction.clone().multiply(incRange));
if (loc.getBlock().getType() != Material.AIR) {
if (!loc.getBlock().getType().isTransparent()) {
break;
}
}
for (Entity entity : entities) {
if (entityWithinBounds(entity, loc)) {
targets.add((LivingEntity) entity);
}
}
}
return targets;
}
public static LivingEntity getFirstEntityInLine(LivingEntity caster, double range) {
RayTraceResult result = caster.getWorld()
.rayTraceEntities(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
entity -> entity instanceof LivingEntity);
if (result == null || result.getHitEntity() == null) {
return null;
}
return (LivingEntity) result.getHitEntity();
}
private static boolean entityWithinBounds(Entity entity, Location loc) {
if (!(entity instanceof LivingEntity) || !entity.isValid()) {
return false;
}
double ex = entity.getLocation().getX();
double ey = entity.getLocation().getY() + ((LivingEntity) entity).getEyeHeight() / 2;
double ez = entity.getLocation().getZ();
return Math.abs(loc.getX() - ex) < 0.85 && Math.abs(loc.getZ() - ez) < 0.85
&& Math.abs(loc.getY() - ey) < 3;
}
public static LivingEntity selectFirstEntityInSight(LivingEntity caster, double range) {
LivingEntity mobTarget = TargetingUtil.getMobTarget(caster);
return mobTarget != null ? mobTarget : getFirstEntityInLine(caster, range);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
boolean targetEntities) {
return getTargetLocation(caster, target, range, OriginLocation.CENTER, targetEntities);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
OriginLocation originLocation, boolean targetEntities) {
if (target != null) {
return getOriginLocation(target, originLocation);
}
RayTraceResult result;
if (targetEntities) {
result = caster.getWorld()
.rayTrace(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true, 0.2,
entity -> entity instanceof LivingEntity && entity != caster);
} else {
result = caster.getWorld()
.rayTraceBlocks(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true);
}
if (result == null) {
LogUtil.printDebug(" - Using MAX RANGE location calculation");
return caster.getEyeLocation().add(
caster.getEyeLocation().getDirection().multiply(Math.max(0, range - 1)));
}
if (result.getHitEntity() != null) {
LogUtil.printDebug(" - Using ENTITY location calculation");
return getOriginLocation((LivingEntity) result.getHitEntity(), originLocation);
}
if (result.getHitBlock() != null) {
LogUtil.printDebug(" - Using BLOCK location calculation");
return result.getHitBlock().getLocation().add(0.5, 0.8, 0.5)
.add(result.getHitBlockFace().getDirection());
}
LogUtil.printDebug(" - Using HIT RANGE location calculation");
return new Location(caster.getWorld(), result.getHitPosition().getX(),
result.getHitPosition().getBlockY(), result.getHitPosition().getZ());
}
public static LivingEntity getMobTarget(StrifeMob strifeMob) {
return getMobTarget(strifeMob.getEntity());
}
public static LivingEntity getMobTarget(LivingEntity livingEntity) {
if (!(livingEntity instanceof Mob)) {
return null;
}
if (((Mob) livingEntity).getTarget() == null || !((Mob) livingEntity).getTarget().isValid()) {
return null;
}
return ((Mob) livingEntity).getTarget();
}
public static Location getOriginLocation(LivingEntity le, OriginLocation origin) {
switch (origin) {
case HEAD:
return le.getEyeLocation();
case BELOW_HEAD:
return le.getEyeLocation().clone().add(0, -0.35, 0);
case CENTER:
Location location = le.getEyeLocation().clone();
location.setY(location.getY() - le.getEyeHeight() / 2);
return location;
case GROUND:
default:
return le.getLocation();
}
}
}
|
src/main/java/info/faceland/strife/util/TargetingUtil.java
|
package info.faceland.strife.util;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.data.StrifeMob;
import info.faceland.strife.util.DamageUtil.OriginLocation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
public class TargetingUtil {
public static void filterFriendlyEntities(Set<LivingEntity> targets, StrifeMob caster,
boolean friendly) {
Set<LivingEntity> friendlyEntities = getFriendlyEntities(caster, targets);
if (friendly) {
targets.clear();
targets.addAll(friendlyEntities);
} else {
targets.removeAll(friendlyEntities);
}
}
public static Set<LivingEntity> getFriendlyEntities(StrifeMob caster, Set<LivingEntity> targets) {
return targets.stream().filter(target -> isFriendly(caster, target)).collect(Collectors.toSet());
}
public static boolean isFriendly(StrifeMob caster, LivingEntity target) {
if (caster.getEntity() == target) {
return true;
}
if (caster.getEntity() instanceof Player && target instanceof Player) {
return !DamageUtil.canAttack((Player) caster.getEntity(), (Player) target);
}
for (StrifeMob mob : caster.getMinions()) {
if (target == mob.getEntity()) {
return true;
}
}
// for (StrifeMob mob : getPartyMembers {
// }
return false;
}
public static Set<LivingEntity> getEntitiesInArea(LivingEntity caster, double radius) {
Collection<Entity> targetList = caster.getWorld()
.getNearbyEntities(caster.getLocation(), radius, radius, radius);
Set<LivingEntity> validTargets = new HashSet<>();
for (Entity e : targetList) {
if (!e.isValid() || e instanceof ArmorStand || !(e instanceof LivingEntity)) {
continue;
}
if (caster.hasLineOfSight(e)) {
validTargets.add((LivingEntity) e);
}
}
return validTargets;
}
public static boolean isDetectionStand(LivingEntity le) {
return le instanceof ArmorStand && le.hasMetadata("STANDO");
}
public static ArmorStand buildAndRemoveDetectionStand(Location location) {
ArmorStand stando = location.getWorld().spawn(location, ArmorStand.class,
e -> e.setVisible(false));
stando.setSmall(true);
stando.setMetadata("STANDO", new FixedMetadataValue(StrifePlugin.getInstance(), ""));
Bukkit.getScheduler().runTaskLater(StrifePlugin.getInstance(), stando::remove, 1L);
return stando;
}
public static Set<LivingEntity> getTempStandTargetList(Location loc, float groundCheckRange) {
Set<LivingEntity> targets = new HashSet<>();
if (groundCheckRange < 1) {
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
} else {
for (int i = 0; i < groundCheckRange; i++) {
if (loc.getBlock().getType().isSolid()) {
loc.setY(loc.getBlockY() + 1.1);
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
}
loc.add(0, -1, 0);
}
return targets;
}
}
public static Set<LivingEntity> getEntitiesInLine(LivingEntity caster, double range) {
Set<LivingEntity> targets = new HashSet<>();
Location eyeLoc = caster.getEyeLocation();
Vector direction = caster.getEyeLocation().getDirection();
ArrayList<Entity> entities = (ArrayList<Entity>) caster.getNearbyEntities(range, range, range);
for (double incRange = 0; incRange <= range; incRange += 1) {
Location loc = eyeLoc.clone().add(direction.clone().multiply(incRange));
if (loc.getBlock().getType() != Material.AIR) {
if (!loc.getBlock().getType().isTransparent()) {
break;
}
}
for (Entity entity : entities) {
if (entityWithinBounds(entity, loc)) {
targets.add((LivingEntity) entity);
}
}
}
return targets;
}
public static LivingEntity getFirstEntityInLine(LivingEntity caster, double range) {
RayTraceResult result = caster.getWorld()
.rayTraceEntities(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
entity -> entity instanceof LivingEntity);
if (result == null || result.getHitEntity() == null) {
return null;
}
return (LivingEntity) result.getHitEntity();
}
private static boolean entityWithinBounds(Entity entity, Location loc) {
if (!(entity instanceof LivingEntity) || !entity.isValid()) {
return false;
}
double ex = entity.getLocation().getX();
double ey = entity.getLocation().getY() + ((LivingEntity) entity).getEyeHeight() / 2;
double ez = entity.getLocation().getZ();
return Math.abs(loc.getX() - ex) < 0.85 && Math.abs(loc.getZ() - ez) < 0.85
&& Math.abs(loc.getY() - ey) < 3;
}
public static LivingEntity selectFirstEntityInSight(LivingEntity caster, double range) {
LivingEntity mobTarget = TargetingUtil.getMobTarget(caster);
return mobTarget != null ? mobTarget : getFirstEntityInLine(caster, range);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
boolean targetEntities) {
return getTargetLocation(caster, target, range, OriginLocation.CENTER, targetEntities);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
OriginLocation originLocation, boolean targetEntities) {
if (target != null) {
return getOriginLocation(target, originLocation);
}
RayTraceResult result;
if (targetEntities) {
result = caster.getWorld()
.rayTrace(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true, 0.2,
entity -> entity instanceof LivingEntity && entity != caster);
} else {
result = caster.getWorld()
.rayTraceBlocks(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true);
}
if (result == null) {
LogUtil.printDebug(" - Using MAX RANGE location calculation");
return caster.getEyeLocation().add(
caster.getEyeLocation().getDirection().multiply(Math.max(0, range - 1)));
}
if (result.getHitEntity() != null) {
LogUtil.printDebug(" - Using ENTITY location calculation");
return getOriginLocation((LivingEntity) result.getHitEntity(), originLocation);
}
if (result.getHitBlock() != null) {
LogUtil.printDebug(" - Using BLOCK location calculation");
return result.getHitBlock().getLocation().add(0.5, 0.8, 0.5)
.add(result.getHitBlockFace().getDirection());
}
LogUtil.printDebug(" - Using HIT RANGE location calculation");
return new Location(caster.getWorld(), result.getHitPosition().getX(),
result.getHitPosition().getBlockY(), result.getHitPosition().getZ());
}
public static LivingEntity getMobTarget(StrifeMob strifeMob) {
return getMobTarget(strifeMob.getEntity());
}
public static LivingEntity getMobTarget(LivingEntity livingEntity) {
if (!(livingEntity instanceof Mob)) {
return null;
}
if (((Mob) livingEntity).getTarget() == null || !((Mob) livingEntity).getTarget().isValid()) {
return null;
}
return ((Mob) livingEntity).getTarget();
}
public static Location getOriginLocation(LivingEntity le, OriginLocation origin) {
switch (origin) {
case HEAD:
return le.getEyeLocation();
case CENTER:
return le.getEyeLocation().clone()
.subtract(le.getEyeLocation().clone().subtract(le.getLocation()).multiply(0.5));
case GROUND:
default:
return le.getLocation();
}
}
}
|
Adding extra origin location and making center more centered
|
src/main/java/info/faceland/strife/util/TargetingUtil.java
|
Adding extra origin location and making center more centered
|
|
Java
|
mit
|
76214e22c6ce26cd9ea8ba91eecbfb079ae66468
| 0
|
Permafrost/Tundra.java,Permafrost/Tundra.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Lachlan Dowding
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package permafrost.tundra.io;
import com.wm.app.b2b.server.MimeTypes;
import com.wm.app.b2b.server.ServerAPI;
import com.wm.app.b2b.server.ServiceException;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.data.IDataUtil;
import permafrost.tundra.data.IDataHelper;
import permafrost.tundra.io.filter.RegularExpressionFilenameFilter;
import permafrost.tundra.io.filter.WildcardFilenameFilter;
import permafrost.tundra.lang.BooleanHelper;
import permafrost.tundra.lang.CharsetHelper;
import permafrost.tundra.lang.ExceptionHelper;
import permafrost.tundra.lang.StringHelper;
import permafrost.tundra.math.LongHelper;
import permafrost.tundra.mime.MIMETypeHelper;
import permafrost.tundra.net.uri.URIHelper;
import permafrost.tundra.server.ServiceHelper;
import permafrost.tundra.time.DateTimeHelper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* A collection of convenience methods for working with files.
*/
public final class FileHelper {
/**
* Disallow instantiation of this class.
*/
private FileHelper() {}
/**
* @return True if the file system is case insensitive.
*/
public static boolean isCaseInsensitive() {
return (new File("TUNDRA")).equals(new File("tundra"));
}
/**
* @return True if the file system is case sensitive.
*/
public static boolean isCaseSensitive() {
return !isCaseInsensitive();
}
/**
* Returns the MIME media type that describes the content of the given file.
*
* @param file The file whose MIME type is to be returned.
* @return The MIME media type that describes the content of the given file.
*/
public static String getMIMEType(File file) {
String type = null;
if (file != null) type = MimeTypes.getTypeFromName(file.getName());
if (type == null) type = MIMETypeHelper.DEFAULT_MIME_TYPE_STRING;
return type;
}
/**
* Returns the MIME media type that describes the content of the given file.
*
* @param filename The file whose MIME type is to be returned.
* @return The MIME media type that describes the content of the given file.
*/
public static String getMIMEType(String filename) {
return getMIMEType(construct(filename));
}
/**
* Returns true if the given file exists and is a file.
*
* @param file The file to check existence of.
* @return True if the given file exists and is a file.
*/
public static boolean exists(File file) {
return file != null && file.exists() && file.isFile();
}
/**
* Returns true if the given file exists and is a file.
*
* @param filename The file to check existence of.
* @return True if the given file exists and is a file.
*/
public static boolean exists(String filename) {
return exists(construct(filename));
}
/**
* Creates a new, empty temporary file.
*
* @return The file which was created.
* @throws IOException If the file already exists.
*/
public static File create() throws IOException {
return create((File)null);
}
/**
* Creates a new, empty file; if file is null, a temporary file is created.
*
* @param file The file to be created.
* @return The file which was created.
* @throws IOException If the file already exists.
*/
public static File create(File file) throws IOException {
if (file == null) {
file = File.createTempFile("tundra", null);
} else {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs(); // automatically create directories if required
if (!file.createNewFile()) {
throw new IOException("Unable to create file because it already exists: " + normalize(file));
}
}
return file;
}
/**
* Creates a new, empty file; if filename is null, a temporary file is created.
*
* @param filename The name of the file to be created.
* @return The name of the file which was created.
* @throws IOException If the filename is unparseable or the file already exists.
*/
public static String create(String filename) throws IOException {
return normalize(create(construct(filename)));
}
/**
* Opens a file for reading, appending, or writing, and processes it by calling the given service with the resulting
* stream.
*
* @param file The file to be processed.
* @param mode The mode to use when opening the file.
* @param service The service to be invoked to process the opened stream
* @param input The input variable name to use for the opened stream.
* @param pipeline The input pipeline.
* @param raise Whether to rethrow any errors that occur.
* @param logError Whether to log any errors that occur when raise is false.
* @return The output pipeline.
* @throws ServiceException If any errors occur during processing.
*/
public static IData process(File file, String mode, String service, String input, IData pipeline, boolean raise, boolean logError) throws ServiceException {
if (file != null) {
if (input == null) input = "$stream";
Closeable stream = null;
try {
if (mode == null || mode.equalsIgnoreCase("read")) {
stream = InputStreamHelper.normalize(new FileInputStream(file));
} else {
if (!FileHelper.exists(file)) FileHelper.create(file);
stream = OutputStreamHelper.normalize(new FileOutputStream(file, mode.equalsIgnoreCase("append")));
}
IDataCursor cursor = pipeline.getCursor();
IDataHelper.put(cursor, input, stream);
cursor.destroy();
pipeline = ServiceHelper.invoke(service, pipeline, true);
} catch (Throwable exception) {
if (raise) {
ExceptionHelper.raise(exception);
} else {
pipeline = ServiceHelper.addExceptionToPipeline(pipeline, exception);
if (logError) ServerAPI.logError(exception);
}
} finally {
CloseableHelper.close(stream);
IDataCursor cursor = pipeline.getCursor();
IDataHelper.remove(cursor, input);
cursor.destroy();
}
}
return pipeline;
}
/**
* Deletes the given file.
*
* @param file The file to be deleted.
* @throws IOException If the file cannot be deleted.
*/
public static void remove(File file) throws IOException {
if (file != null && exists(file) && !file.delete()) {
throw new IOException("Unable to remove file: " + normalize(file));
}
}
/**
* Deletes the given file.
*
* @param filename The name of the file to be deleted.
* @throws IOException If the filename is unparseable or the file cannot be deleted.
*/
public static void remove(String filename) throws IOException {
remove(construct(filename));
}
/**
* Update the modified time of the given file to the current time, or create it if it does not exist.
*
* @param file The file to be touched.
* @throws IOException If the file cannot be created.
*/
public static void touch(File file) throws IOException {
if (file.exists()) {
file.setLastModified((new Date()).getTime());
} else {
create(file);
}
}
/**
* Update the modified time of the given file to the current time, or create it if it does not exist.
*
* @param filename The name of the file to be touched.
* @throws IOException If the filename is unparseable.
*/
public static void touch(String filename) throws IOException {
touch(construct(filename));
}
/**
* Renames the source file to the target name.
*
* @param source The file to be renamed.
* @param target The new name of the file.
* @throws IOException If the file cannot be renamed.
*/
public static void rename(File source, File target) throws IOException {
if (source != null && target != null) {
if (!exists(source) || exists(target) || !source.renameTo(target)) {
throw new IOException("Unable to rename file " + normalize(source) + " to " + normalize(target));
}
}
}
/**
* Renames the source file to the target name.
*
* @param source The file to be renamed.
* @param target The new name of the file.
* @throws IOException If file cannot be renamed.
*/
public static void rename(String source, String target) throws IOException {
rename(construct(source), construct(target));
}
/**
* Reads the given file completely, returning the file's content as a byte[].
*
* @param filename The name of the file to be read.
* @return A byte[] containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static byte[] readToBytes(String filename) throws IOException {
return readToBytes(construct(filename));
}
/**
* Reads the given file completely, returning the file's content as a byte[].
*
* @param file The file to be read.
* @return A byte[] containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static byte[] readToBytes(File file) throws IOException {
byte[] content = null;
if (file != null) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = new FileInputStream(file);
outputStream = new ByteArrayOutputStream(InputOutputHelper.DEFAULT_BUFFER_SIZE);
InputOutputHelper.copy(inputStream, outputStream);
content = outputStream.toByteArray();
} finally {
CloseableHelper.close(inputStream, outputStream);
}
}
return content;
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename) throws IOException {
return readToString(filename, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @param charsetName The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename, String charsetName) throws IOException {
return readToString(filename, CharsetHelper.normalize(charsetName));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @param charset The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename, Charset charset) throws IOException {
return readToString(construct(filename), CharsetHelper.normalize(charset));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file) throws IOException {
return readToString(file, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @param charsetName The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file, String charsetName) throws IOException {
return readToString(file, CharsetHelper.normalize(charsetName));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @param charset The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file, Charset charset) throws IOException {
return StringHelper.normalize(readToBytes(file), CharsetHelper.normalize(charset));
}
/**
* Reads the given file completely, returning the file's content as an InputStream.
*
* @param filename The name of the file to be read.
* @return An InputStream containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static InputStream readToStream(String filename) throws IOException {
return readToStream(construct(filename));
}
/**
* Reads the given file completely, returning the file's content as an InputStream.
*
* @param file The file to be read.
* @return An InputStream containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static InputStream readToStream(File file) throws IOException {
return new ByteArrayInputStream(readToBytes(file));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromStream(File file, InputStream content, boolean append) throws IOException {
if (file == null || !exists(file)) file = create(file);
if (content != null) InputOutputHelper.copy(content, new FileOutputStream(file, append));
return file;
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static String writeFromStream(String filename, InputStream content, boolean append) throws IOException {
return normalize(writeFromStream(construct(filename), content, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromBytes(File file, byte[] content, boolean append) throws IOException {
return writeFromStream(file, InputStreamHelper.normalize(content), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromBytes(String filename, byte[] content, boolean append) throws IOException {
return normalize(writeFromBytes(construct(filename), content, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param charsetName The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, String charsetName, boolean append) throws IOException {
return writeFromString(file, content, CharsetHelper.normalize(charsetName), append);
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param charset The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, Charset charset, boolean append) throws IOException {
return writeFromStream(file, InputStreamHelper.normalize(content, charset), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param charsetName The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, String charsetName, boolean append) throws IOException {
return writeFromString(filename, content, CharsetHelper.normalize(charsetName), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param charset The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, Charset charset, boolean append) throws IOException {
return normalize(writeFromString(construct(filename), content, charset, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, boolean append) throws IOException {
return writeFromString(file, content, CharsetHelper.DEFAULT_CHARSET, append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, boolean append) throws IOException {
return normalize(writeFromString(construct(filename), content, append));
}
/**
* Copies the content in the source file to the target file.
*
* @param source The file from which content will be copied.
* @param target The file to which content will be copied.
* @param append If true, the target content will be appended to, otherwise any previous content will be
* overwritten.
* @throws IOException If the source file does not exist or there is a problem copying it.
*/
public static void copy(File source, File target, boolean append) throws IOException {
if (source != null && target != null) {
if (!source.getCanonicalPath().equals(target.getCanonicalPath())) {
// only needs to copy file when the paths are different
InputOutputHelper.copy(new FileInputStream(source), new FileOutputStream(target, append));
} else if (append) {
// read fully into memory before writing to itself
InputOutputHelper.copy(InputStreamHelper.memoize(new FileInputStream(source)), new FileOutputStream(target, append));
} else {
// otherwise update the last modified date
touch(source);
}
}
}
/**
* Copies the content in the source file to the target file.
*
* @param source The file from which content will be copied.
* @param target The file to which content will be copied.
* @param append If true, the target content will be appended to, otherwise any previous content will be
* overwritten.
* @throws IOException If the source file does not exist or there is a problem copying it.
*/
public static void copy(String source, String target, boolean append) throws IOException {
copy(construct(source), construct(target), append);
}
/**
* GZips the given file as a new file in the same directory with the same name suffixed with ".gz".
*
* @param source The file to be gzipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static String gzip(String source, boolean replace) throws IOException {
return normalize(gzip(construct(source), replace));
}
/**
* Gzips the given file as a new file in the same directory with the same name suffixed with ".gz".
*
* @param source The file to be gzipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static File gzip(File source, boolean replace) throws IOException {
return gzip(source, null, replace);
}
/**
* Gzips the given file as a new file with the given target name.
*
* @param source The file to be gzipped.
* @param target The file to write the gzipped content to.
* @param replace Whether the source file should be deleted once compressed.*
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static String gzip(String source, String target, boolean replace) throws IOException {
return normalize(gzip(construct(source), construct(target), replace));
}
/**
* Gzips the given file as a new file with the given target name.
*
* @param source The file to be gzipped.
* @param target The file to write the gzipped content to.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static File gzip(File source, File target, boolean replace) throws IOException {
if (source == null) throw new NullPointerException("source must not be null");
if (target == null) target = new File(source.getParentFile(), source.getName() + ".gz");
if (source.exists()) {
if (source.isFile()) {
if (source.canRead() && (!replace || source.canWrite())) {
if (target.exists()) {
throw new IOException("Unable to create file because it already exists: " + normalize(target));
} else {
InputOutputHelper.copy(new FileInputStream(source), new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(target), InputOutputHelper.DEFAULT_BUFFER_SIZE)));
target.setLastModified(source.lastModified());
if (replace) source.delete();
return target;
}
} else {
throw new IOException("Unable to gzip file because access is denied: " + normalize(source));
}
} else {
throw new IOException("Unable to gzip file because it is a directory: " + normalize(source));
}
} else {
throw new IOException("Unable to gzip file because it does not exist: " + normalize(source));
}
}
/**
* Zips the given file as a new file in the same directory with the same name suffixed with ".zip".
*
* @param source The file to be zipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static String zip(String source, boolean replace) throws IOException {
return normalize(zip(construct(source), replace));
}
/**
* Zips the given file as a new file in the same directory with the same name suffixed with ".zip".
*
* @param source The file to be zipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static File zip(File source, boolean replace) throws IOException {
return zip(source, null, replace);
}
/**
* Zips the given file as a new file with the given name.
*
* @param source The file to be zipped.
* @param target The file to write the zipped content to.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static String zip(String source, String target, boolean replace) throws IOException {
return normalize(zip(construct(source), construct(target), replace));
}
/**
* Zips the given file as a new file with the given target name.
*
* @param source The file to be zipped.
* @param target The file to write the zipped content to. If not specified, defaults to a file with
* the same name as source suffixed with ".zip".
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static File zip(File source, File target, boolean replace) throws IOException {
if (source == null) throw new NullPointerException("source must not be null");
if (target == null) target = new File(source.getParentFile(), source.getName() + ".zip");
if (source.exists()) {
if (source.isFile()) {
if (source.canRead() && (!replace || source.canWrite())) {
if (target.exists()) {
throw new IOException("Unable to create file because it already exists: " + normalize(target));
} else {
InputStream inputStream = null;
ZipOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(source), InputOutputHelper.DEFAULT_BUFFER_SIZE);
outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target), InputOutputHelper.DEFAULT_BUFFER_SIZE));
outputStream.putNextEntry(new ZipEntry(source.getName()));
InputOutputHelper.copy(inputStream, outputStream, false);
} finally {
if (outputStream != null) outputStream.closeEntry();
CloseableHelper.close(inputStream, outputStream);
target.setLastModified(source.lastModified());
if (replace) source.delete();
}
return target;
}
} else {
throw new IOException("Unable to zip file because access is denied: " + normalize(source));
}
} else {
throw new IOException("Unable to zip file because it is a directory: " + normalize(source));
}
} else {
throw new IOException("Unable to zip file because it does not exist: " + normalize(source));
}
}
/**
* Returns a File object given a file name.
*
* @param filename The name of the file, specified as a path or file:// URI.
* @return The file representing the given name.
*/
public static File construct(String filename) {
File file = null;
if (filename != null) {
if (filename.toLowerCase().startsWith("file:")) {
try {
file = new File(new URI(filename));
} catch (IllegalArgumentException ex) {
// work around java's weird handling of file://server/path style URIs on Windows, by changing the URI
// to be file:////server/path
if (filename.toLowerCase().startsWith("file://") && !filename.toLowerCase().startsWith("file:///")) {
file = construct("file:////" + filename.substring(6, filename.length()));
} else {
throw ex;
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
} else {
file = new File(filename);
}
}
return file;
}
/**
* Returns the canonical file:// URI representation of the given file.
*
* @param file The file to be normalized.
* @return The canonical file:// URI representation of the given file.
*/
public static String normalize(File file) {
String filename = null;
try {
if (file != null) filename = URIHelper.normalize(file.getCanonicalFile().toURI().toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
return filename;
}
/**
* Returns the canonical file:// URI representation of the given file.
*
* @param filename The name of the file to be normalized.
* @return The canonical file:// URI representation of the given file.
*/
public static String normalize(String filename) {
return normalize(construct(filename));
}
/**
* Returns true if the given file matches the given pattern.
*
* @param filename The name of the file to check against the pattern.
* @param pattern Either a regular expression or wildcard pattern.
* @param patternIsRegularExpression Boolean indicating if the given pattern is a regular expression or wildcard
* pattern.
* @return True if the given file matches the given pattern.
*/
public static boolean match(String filename, String pattern, boolean patternIsRegularExpression) {
return match(construct(filename), pattern, patternIsRegularExpression);
}
/**
* Returns true if the given file matches the given pattern.
*
* @param file The file to check against the pattern.
* @param pattern Either a regular expression or wildcard pattern.
* @param patternIsRegularExpression Boolean indicating if the given pattern is a regular expression or wildcard
* pattern.
* @return True if the given file matches the given pattern.
*/
public static boolean match(File file, String pattern, boolean patternIsRegularExpression) {
boolean match = false;
if (file != null && pattern != null) {
java.io.FilenameFilter filter;
if (patternIsRegularExpression) {
filter = new RegularExpressionFilenameFilter(pattern);
} else {
filter = new WildcardFilenameFilter(pattern);
}
match = filter.accept(file.getParentFile(), file.getName());
}
return match;
}
/**
* Returns whether the given file can be written to by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is writable by this process.
*/
public static boolean isWritable(File file) {
if (file == null) return false;
return file.canWrite();
}
/**
* Returns whether the given file can be written to by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is writable by this process.
*/
public static boolean isWritable(String filename) {
return isWritable(construct(filename));
}
/**
* Returns whether the given file can be read by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is readable by this process.
*/
public static boolean isReadable(File file) {
if (file == null) return false;
return file.canRead();
}
/**
* Returns whether the given file can be read by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is readable by this process.
*/
public static boolean isReadable(String filename) {
return isReadable(construct(filename));
}
/**
* Returns whether the given file can be executed by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is executable by this process.
*/
public static boolean isExecutable(File file) {
if (file == null) return false;
return file.canExecute();
}
/**
* Returns whether the given file can be executed by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is executable by this process.
*/
public static boolean isExecutable(String filename) {
return isExecutable(construct(filename));
}
/**
* Returns the length of the given file in bytes.
*
* @param file The file to check the length of.
* @return The length in bytes of the given file.
*/
public static long length(File file) {
if (file == null) return 0;
return file.length();
}
/**
* Returns the length of the given file in bytes.
*
* @param filename The file to check the length of.
* @return The length in bytes of the given file.
*/
public static long length(String filename) {
return length(construct(filename));
}
/**
* Returns only the name component of the given file.
*
* @param file The file to return the name of.
* @return The name component only of the given file.
*/
public static String getName(File file) {
if (file == null || file.equals("")) return null;
return file.getName();
}
/**
* Returns only the name component of the given file.
*
* @param filename The file to return the name of.
* @return The name component only of the given file.
*/
public static String getName(String filename) {
return getName(construct(filename));
}
/**
* Returns the base and extension parts of the given file's name.
*
* @param file The file to get the name parts of.
* @return The parts of the given file's name.
*/
public static String[] getNameParts(File file) {
String[] parts = null;
String name = getName(file);
if (name != null) {
parts = name.split("\\.(?=[^\\.]+$)");
}
return parts;
}
/**
* Returns the filename extension for the given file.
*
* @param file The file whose extension is to be returned.
* @return The filename extension for the given file.
*/
public static String getExtension(File file) {
if (file == null) return null;
String extension;
String[] parts = getNameParts(file);
if (parts.length > 1) {
extension = parts[parts.length - 1];
} else {
extension = null;
}
return extension;
}
/**
* Returns the base and extension parts of the given file's name.
*
* @param filename The file to get the name parts of.
* @return The parts of the given file's name.
*/
public static String[] getNameParts(String filename) {
return getNameParts(construct(filename));
}
/**
* Returns the parent directory containing the given file.
*
* @param file The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static File getParentDirectory(File file) {
if (file == null) return null;
return file.getParentFile();
}
/**
* Returns the parent directory containing the given file.
*
* @param filename The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static File getParentDirectory(String filename) {
return getParentDirectory(construct(filename));
}
/**
* Returns the parent directory containing the given file as a string.
*
* @param file The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static String getParentDirectoryAsString(File file) {
return normalize(getParentDirectory(file));
}
/**
* Returns the parent directory containing the given file as a string.
*
* @param filename The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static String getParentDirectoryAsString(String filename) {
return getParentDirectoryAsString(construct(filename));
}
/**
* Returns the last modified datetime of the given file.
*
* @param file The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static Date getLastModifiedDate(File file) {
if (file == null) return null;
return new Date(file.lastModified());
}
/**
* Returns the last modified datetime of the given file.
*
* @param filename The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static Date getLastModifiedDate(String filename) {
return getLastModifiedDate(construct(filename));
}
/**
* Returns the last modified datetime of the given file as an ISO8601 formatted datetime string.
*
* @param file The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static String getLastModifiedDateTimeString(File file) {
return DateTimeHelper.emit(getLastModifiedDate(file));
}
/**
* Returns the last modified datetime of the given file as an ISO8601 formatted datetime string.
*
* @param filename The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static String getLastModifiedDateTimeString(String filename) {
return getLastModifiedDateTimeString(construct(filename));
}
/**
* Returns an IData document containing the properties of the given file.
*
* @param filename The file to return the properties for.
* @return The properties of the given file as an IData document.
*/
public static IData getPropertiesAsIData(String filename) {
return getPropertiesAsIData(construct(filename));
}
/**
* Returns an IData document containing the properties of the given file.
*
* @param file The file to return the properties for.
* @return The properties of the given file as an IData document.
*/
public static IData getPropertiesAsIData(File file) {
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
boolean isFile = file.isFile();
boolean exists = exists(file);
IDataUtil.put(cursor, "exists?", BooleanHelper.emit(exists));
String parent = getParentDirectoryAsString(file);
if (parent != null) IDataUtil.put(cursor, "parent", parent);
String name = getName(file);
if (name != null) IDataUtil.put(cursor, "name", name);
String[] parts = getNameParts(file);
if (parts != null) {
if (parts.length > 0) IDataUtil.put(cursor, "base", parts[0]);
if (parts.length > 1) IDataUtil.put(cursor, "extension", parts[1]);
}
if (isFile) IDataUtil.put(cursor, "type", getMIMEType(file));
if (exists) {
IDataUtil.put(cursor, "length", LongHelper.emit(length(file)));
IDataUtil.put(cursor, "modified", getLastModifiedDateTimeString(file));
IDataUtil.put(cursor, "executable?", BooleanHelper.emit(isExecutable(file)));
IDataUtil.put(cursor, "readable?", BooleanHelper.emit(isReadable(file)));
IDataUtil.put(cursor, "writable?", BooleanHelper.emit(isWritable(file)));
}
IDataUtil.put(cursor, "uri", normalize(file));
cursor.destroy();
return output;
}
}
|
src/main/java/permafrost/tundra/io/FileHelper.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Lachlan Dowding
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package permafrost.tundra.io;
import com.wm.app.b2b.server.MimeTypes;
import com.wm.app.b2b.server.ServerAPI;
import com.wm.app.b2b.server.ServiceException;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.data.IDataUtil;
import permafrost.tundra.data.IDataHelper;
import permafrost.tundra.io.filter.RegularExpressionFilenameFilter;
import permafrost.tundra.io.filter.WildcardFilenameFilter;
import permafrost.tundra.lang.BooleanHelper;
import permafrost.tundra.lang.CharsetHelper;
import permafrost.tundra.lang.ExceptionHelper;
import permafrost.tundra.lang.StringHelper;
import permafrost.tundra.math.LongHelper;
import permafrost.tundra.mime.MIMETypeHelper;
import permafrost.tundra.net.uri.URIHelper;
import permafrost.tundra.server.ServiceHelper;
import permafrost.tundra.time.DateTimeHelper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* A collection of convenience methods for working with files.
*/
public final class FileHelper {
/**
* Disallow instantiation of this class.
*/
private FileHelper() {}
/**
* @return True if the file system is case insensitive.
*/
public static boolean isCaseInsensitive() {
return (new File("TUNDRA")).equals(new File("tundra"));
}
/**
* @return True if the file system is case sensitive.
*/
public static boolean isCaseSensitive() {
return !isCaseInsensitive();
}
/**
* Returns the MIME media type that describes the content of the given file.
*
* @param file The file whose MIME type is to be returned.
* @return The MIME media type that describes the content of the given file.
*/
public static String getMIMEType(File file) {
String type = null;
if (file != null) type = MimeTypes.getTypeFromName(file.getName());
if (type == null) type = MIMETypeHelper.DEFAULT_MIME_TYPE_STRING;
return type;
}
/**
* Returns the MIME media type that describes the content of the given file.
*
* @param filename The file whose MIME type is to be returned.
* @return The MIME media type that describes the content of the given file.
*/
public static String getMIMEType(String filename) {
return getMIMEType(construct(filename));
}
/**
* Returns true if the given file exists and is a file.
*
* @param file The file to check existence of.
* @return True if the given file exists and is a file.
*/
public static boolean exists(File file) {
return file != null && file.exists() && file.isFile();
}
/**
* Returns true if the given file exists and is a file.
*
* @param filename The file to check existence of.
* @return True if the given file exists and is a file.
*/
public static boolean exists(String filename) {
return exists(construct(filename));
}
/**
* Creates a new, empty temporary file.
*
* @return The file which was created.
* @throws IOException If the file already exists.
*/
public static File create() throws IOException {
return create((File)null);
}
/**
* Creates a new, empty file; if file is null, a temporary file is created.
*
* @param file The file to be created.
* @return The file which was created.
* @throws IOException If the file already exists.
*/
public static File create(File file) throws IOException {
if (file == null) {
file = File.createTempFile("tundra", null);
} else {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs(); // automatically create directories if required
if (!file.createNewFile()) {
throw new IOException("Unable to create file because it already exists: " + normalize(file));
}
}
return file;
}
/**
* Creates a new, empty file; if filename is null, a temporary file is created.
*
* @param filename The name of the file to be created.
* @return The name of the file which was created.
* @throws IOException If the filename is unparseable or the file already exists.
*/
public static String create(String filename) throws IOException {
return normalize(create(construct(filename)));
}
/**
* Opens a file for reading, appending, or writing, and processes it by calling the given service with the resulting
* stream.
*
* @param file The file to be processed.
* @param mode The mode to use when opening the file.
* @param service The service to be invoked to process the opened stream
* @param input The input variable name to use for the opened stream.
* @param pipeline The input pipeline.
* @param raise Whether to rethrow any errors that occur.
* @param logError Whether to log any errors that occur when raise is false.
* @return The output pipeline.
* @throws ServiceException If any errors occur during processing.
*/
public static IData process(File file, String mode, String service, String input, IData pipeline, boolean raise, boolean logError) throws ServiceException {
if (file != null) {
if (input == null) input = "$stream";
Closeable stream = null;
try {
if (mode == null || mode.equalsIgnoreCase("read")) {
stream = InputStreamHelper.normalize(new FileInputStream(file));
} else {
if (!FileHelper.exists(file)) FileHelper.create(file);
stream = OutputStreamHelper.normalize(new FileOutputStream(file, mode.equalsIgnoreCase("append")));
}
IDataCursor cursor = pipeline.getCursor();
IDataHelper.put(cursor, input, stream);
cursor.destroy();
pipeline = ServiceHelper.invoke(service, pipeline, true);
} catch (Throwable exception) {
if (raise) {
ExceptionHelper.raise(exception);
} else {
pipeline = ServiceHelper.addExceptionToPipeline(pipeline, exception);
if (logError) ServerAPI.logError(exception);
}
} finally {
CloseableHelper.close(stream);
IDataCursor cursor = pipeline.getCursor();
IDataHelper.remove(cursor, input);
cursor.destroy();
}
}
return pipeline;
}
/**
* Deletes the given file.
*
* @param file The file to be deleted.
* @throws IOException If the file cannot be deleted.
*/
public static void remove(File file) throws IOException {
if (file != null && exists(file) && !file.delete()) {
throw new IOException("Unable to remove file: " + normalize(file));
}
}
/**
* Deletes the given file.
*
* @param filename The name of the file to be deleted.
* @throws IOException If the filename is unparseable or the file cannot be deleted.
*/
public static void remove(String filename) throws IOException {
remove(construct(filename));
}
/**
* Update the modified time of the given file to the current time, or create it if it does not exist.
*
* @param file The file to be touched.
* @throws IOException If the file cannot be created.
*/
public static void touch(File file) throws IOException {
if (file.exists()) {
file.setLastModified((new Date()).getTime());
} else {
create(file);
}
}
/**
* Update the modified time of the given file to the current time, or create it if it does not exist.
*
* @param filename The name of the file to be touched.
* @throws IOException If the filename is unparseable.
*/
public static void touch(String filename) throws IOException {
touch(construct(filename));
}
/**
* Renames the source file to the target name.
*
* @param source The file to be renamed.
* @param target The new name of the file.
* @throws IOException If the file cannot be renamed.
*/
public static void rename(File source, File target) throws IOException {
if (source != null && target != null) {
if (!exists(source) || exists(target) || !source.renameTo(target)) {
throw new IOException("Unable to rename file " + normalize(source) + " to " + normalize(target));
}
}
}
/**
* Renames the source file to the target name.
*
* @param source The file to be renamed.
* @param target The new name of the file.
* @throws IOException If file cannot be renamed.
*/
public static void rename(String source, String target) throws IOException {
rename(construct(source), construct(target));
}
/**
* Reads the given file completely, returning the file's content as a byte[].
*
* @param filename The name of the file to be read.
* @return A byte[] containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static byte[] readToBytes(String filename) throws IOException {
return readToBytes(construct(filename));
}
/**
* Reads the given file completely, returning the file's content as a byte[].
*
* @param file The file to be read.
* @return A byte[] containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static byte[] readToBytes(File file) throws IOException {
byte[] content = null;
if (file != null) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = new FileInputStream(file);
outputStream = new ByteArrayOutputStream(InputOutputHelper.DEFAULT_BUFFER_SIZE);
InputOutputHelper.copy(inputStream, outputStream);
content = outputStream.toByteArray();
} finally {
CloseableHelper.close(inputStream, outputStream);
}
}
return content;
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename) throws IOException {
return readToString(filename, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @param charsetName The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename, String charsetName) throws IOException {
return readToString(filename, CharsetHelper.normalize(charsetName));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param filename The name of the file to be read.
* @param charset The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(String filename, Charset charset) throws IOException {
return readToString(construct(filename), CharsetHelper.normalize(charset));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file) throws IOException {
return readToString(file, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @param charsetName The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file, String charsetName) throws IOException {
return readToString(file, CharsetHelper.normalize(charsetName));
}
/**
* Reads the given file completely, returning the file's content as a String.
*
* @param file The file to be read.
* @param charset The character set the file's content is encoded with.
* @return A String containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static String readToString(File file, Charset charset) throws IOException {
return StringHelper.normalize(readToBytes(file), CharsetHelper.normalize(charset));
}
/**
* Reads the given file completely, returning the file's content as an InputStream.
*
* @param filename The name of the file to be read.
* @return An InputStream containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static InputStream readToStream(String filename) throws IOException {
return readToStream(construct(filename));
}
/**
* Reads the given file completely, returning the file's content as an InputStream.
*
* @param file The file to be read.
* @return An InputStream containing the file's content.
* @throws IOException If there is a problem reading the file.
*/
public static InputStream readToStream(File file) throws IOException {
return new ByteArrayInputStream(readToBytes(file));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromStream(File file, InputStream content, boolean append) throws IOException {
if (file == null || !exists(file)) file = create(file);
if (content != null) InputOutputHelper.copy(content, new FileOutputStream(file, append));
return file;
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static String writeFromStream(String filename, InputStream content, boolean append) throws IOException {
return normalize(writeFromStream(construct(filename), content, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromBytes(File file, byte[] content, boolean append) throws IOException {
return writeFromStream(file, InputStreamHelper.normalize(content), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromBytes(String filename, byte[] content, boolean append) throws IOException {
return normalize(writeFromBytes(construct(filename), content, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param charsetName The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, String charsetName, boolean append) throws IOException {
return writeFromString(file, content, CharsetHelper.normalize(charsetName), append);
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param charset The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, Charset charset, boolean append) throws IOException {
return writeFromStream(file, InputStreamHelper.normalize(content, charset), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param charsetName The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, String charsetName, boolean append) throws IOException {
return writeFromString(filename, content, CharsetHelper.normalize(charsetName), append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param charset The character set to encode the content with.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If the filename is unparseable or there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, Charset charset, boolean append) throws IOException {
return normalize(writeFromString(construct(filename), content, charset, append));
}
/**
* Writes content to a file; if the given file is null, a new temporary file is automatically created.
*
* @param file The file to be written to; if null, a new temporary file is automatically created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static File writeFromString(File file, String content, boolean append) throws IOException {
return writeFromString(file, content, CharsetHelper.DEFAULT_CHARSET, append);
}
/**
* Writes content to a file; if the given filename is null, a new temporary file is automatically created.
*
* @param filename The name of the file to be written to; if null, a new temporary file is automatically
* created.
* @param content The content to be written.
* @param append If true, the content will be appended to the file, otherwise the content will overwrite any
* previous content in the file.
* @return The name of the file which the content was written to.
* @throws IOException If there is a problem writing to the file.
*/
public static String writeFromString(String filename, String content, boolean append) throws IOException {
return normalize(writeFromString(construct(filename), content, append));
}
/**
* Copies the content in the source file to the target file.
*
* @param source The file from which content will be copied.
* @param target The file to which content will be copied.
* @param append If true, the target content will be appended to, otherwise any previous content will be
* overwritten.
* @throws IOException If the source file does not exist or there is a problem copying it.
*/
public static void copy(File source, File target, boolean append) throws IOException {
if (source != null && target != null) {
if (!source.getCanonicalPath().equals(target.getCanonicalPath())) {
// only needs to copy file when the paths are different
InputOutputHelper.copy(new FileInputStream(source), new FileOutputStream(target, append));
} else if (append) {
// read fully into memory before writing to itself
InputOutputHelper.copy(InputStreamHelper.memoize(new FileInputStream(source)), new FileOutputStream(target, append));
} else {
// otherwise update the last modified date
touch(source);
}
}
}
/**
* Copies the content in the source file to the target file.
*
* @param source The file from which content will be copied.
* @param target The file to which content will be copied.
* @param append If true, the target content will be appended to, otherwise any previous content will be
* overwritten.
* @throws IOException If the source file does not exist or there is a problem copying it.
*/
public static void copy(String source, String target, boolean append) throws IOException {
copy(construct(source), construct(target), append);
}
/**
* GZips the given file as a new file in the same directory with the same name suffixed with ".gz".
*
* @param source The file to be gzipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static String gzip(String source, boolean replace) throws IOException {
return normalize(gzip(construct(source), replace));
}
/**
* Gzips the given file as a new file in the same directory with the same name suffixed with ".gz".
*
* @param source The file to be gzipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static File gzip(File source, boolean replace) throws IOException {
return gzip(source, null, replace);
}
/**
* Gzips the given file as a new file with the given target name.
*
* @param source The file to be gzipped.
* @param target The file to write the gzipped content to.
* @param replace Whether the source file should be deleted once compressed.*
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static String gzip(String source, String target, boolean replace) throws IOException {
return normalize(gzip(construct(source), construct(target), replace));
}
/**
* Gzips the given file as a new file with the given target name.
*
* @param source The file to be gzipped.
* @param target The file to write the gzipped content to.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting gzipped file.
* @throws IOException If an IO error occurs.
*/
public static File gzip(File source, File target, boolean replace) throws IOException {
if (source == null) throw new NullPointerException("source must not be null");
if (target == null) target = new File(source.getParentFile(), source.getName() + ".gz");
if (source.exists()) {
if (source.isFile()) {
if (source.canRead() && (!replace || source.canWrite())) {
if (target.exists()) {
throw new IOException("Unable to create file because it already exists: " + normalize(target));
} else {
InputOutputHelper.copy(new FileInputStream(source), new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(target), InputOutputHelper.DEFAULT_BUFFER_SIZE)));
target.setLastModified(source.lastModified());
if (replace) source.delete();
return target;
}
} else {
throw new IOException("Unable to gzip file because access is denied: " + normalize(source));
}
} else {
throw new IOException("Unable to gzip file because it is a directory: " + normalize(source));
}
} else {
throw new IOException("Unable to gzip file because it does not exist: " + normalize(source));
}
}
/**
* Zips the given file as a new file in the same directory with the same name suffixed with ".zip".
*
* @param source The file to be zipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static String zip(String source, boolean replace) throws IOException {
return normalize(zip(construct(source), replace));
}
/**
* Zips the given file as a new file in the same directory with the same name suffixed with ".zip".
*
* @param source The file to be zipped.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static File zip(File source, boolean replace) throws IOException {
return zip(source, null, replace);
}
/**
* Zips the given file as a new file with the given name.
*
* @param source The file to be zipped.
* @param target The file to write the zipped content to.
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static String zip(String source, String target, boolean replace) throws IOException {
return normalize(zip(construct(source), construct(target), replace));
}
/**
* Zips the given file as a new file with the given target name.
*
* @param source The file to be zipped.
* @param target The file to write the zipped content to. If not specified, defaults to a file with
* the same name as source suffixed with ".zip".
* @param replace Whether the source file should be deleted once compressed.
* @return The resulting zipped file.
* @throws IOException If an IO error occurs.
*/
public static File zip(File source, File target, boolean replace) throws IOException {
if (source == null) throw new NullPointerException("source must not be null");
if (target == null) target = new File(source.getParentFile(), source.getName() + ".zip");
if (source.exists()) {
if (source.isFile()) {
if (source.canRead() && (!replace || source.canWrite())) {
if (target.exists()) {
throw new IOException("Unable to create file because it already exists: " + normalize(target));
} else {
InputStream inputStream = null;
ZipOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(source), InputOutputHelper.DEFAULT_BUFFER_SIZE);
outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target), InputOutputHelper.DEFAULT_BUFFER_SIZE));
outputStream.putNextEntry(new ZipEntry(source.getName()));
InputOutputHelper.copy(inputStream, outputStream, false);
} finally {
if (outputStream != null) outputStream.closeEntry();
CloseableHelper.close(inputStream, outputStream);
target.setLastModified(source.lastModified());
if (replace) source.delete();
}
return target;
}
} else {
throw new IOException("Unable to zip file because access is denied: " + normalize(source));
}
} else {
throw new IOException("Unable to zip file because it is a directory: " + normalize(source));
}
} else {
throw new IOException("Unable to zip file because it does not exist: " + normalize(source));
}
}
/**
* Returns a File object given a file name.
*
* @param filename The name of the file, specified as a path or file:// URI.
* @return The file representing the given name.
*/
public static File construct(String filename) {
File file = null;
if (filename != null) {
if (filename.toLowerCase().startsWith("file:")) {
try {
file = new File(new URI(filename));
} catch (IllegalArgumentException ex) {
// work around java's weird handling of file://server/path style URIs on Windows, by changing the URI
// to be file:////server/path
if (filename.toLowerCase().startsWith("file://") && !filename.toLowerCase().startsWith("file:///")) {
file = construct("file:////" + filename.substring(6, filename.length()));
} else {
throw ex;
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
} else {
file = new File(filename);
}
}
return file;
}
/**
* Returns the canonical file:// URI representation of the given file.
*
* @param file The file to be normalized.
* @return The canonical file:// URI representation of the given file.
*/
public static String normalize(File file) {
String filename = null;
try {
if (file != null) filename = URIHelper.normalize(file.getCanonicalFile().toURI().toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
return filename;
}
/**
* Returns the canonical file:// URI representation of the given file.
*
* @param filename The name of the file to be normalized.
* @return The canonical file:// URI representation of the given file.
*/
public static String normalize(String filename) {
return normalize(construct(filename));
}
/**
* Returns true if the given file matches the given pattern.
*
* @param filename The name of the file to check against the pattern.
* @param pattern Either a regular expression or wildcard pattern.
* @param patternIsRegularExpression Boolean indicating if the given pattern is a regular expression or wildcard
* pattern.
* @return True if the given file matches the given pattern.
*/
public static boolean match(String filename, String pattern, boolean patternIsRegularExpression) {
return match(construct(filename), pattern, patternIsRegularExpression);
}
/**
* Returns true if the given file matches the given pattern.
*
* @param file The file to check against the pattern.
* @param pattern Either a regular expression or wildcard pattern.
* @param patternIsRegularExpression Boolean indicating if the given pattern is a regular expression or wildcard
* pattern.
* @return True if the given file matches the given pattern.
*/
public static boolean match(File file, String pattern, boolean patternIsRegularExpression) {
boolean match = false;
if (file != null && pattern != null) {
java.io.FilenameFilter filter;
if (patternIsRegularExpression) {
filter = new RegularExpressionFilenameFilter(pattern);
} else {
filter = new WildcardFilenameFilter(pattern);
}
match = filter.accept(file.getParentFile(), file.getName());
}
return match;
}
/**
* Returns whether the given file can be written to by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is writable by this process.
*/
public static boolean isWritable(File file) {
if (file == null) return false;
return file.canWrite();
}
/**
* Returns whether the given file can be written to by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is writable by this process.
*/
public static boolean isWritable(String filename) {
return isWritable(construct(filename));
}
/**
* Returns whether the given file can be read by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is readable by this process.
*/
public static boolean isReadable(File file) {
if (file == null) return false;
return file.canRead();
}
/**
* Returns whether the given file can be read by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is readable by this process.
*/
public static boolean isReadable(String filename) {
return isReadable(construct(filename));
}
/**
* Returns whether the given file can be executed by this process.
*
* @param file The file to check the permissions of.
* @return Whether the given file is executable by this process.
*/
public static boolean isExecutable(File file) {
if (file == null) return false;
return file.canExecute();
}
/**
* Returns whether the given file can be executed by this process.
*
* @param filename The file to check the permissions of.
* @return Whether the given file is executable by this process.
*/
public static boolean isExecutable(String filename) {
return isExecutable(construct(filename));
}
/**
* Returns the length of the given file in bytes.
*
* @param file The file to check the length of.
* @return The length in bytes of the given file.
*/
public static long length(File file) {
if (file == null) return 0;
return file.length();
}
/**
* Returns the length of the given file in bytes.
*
* @param filename The file to check the length of.
* @return The length in bytes of the given file.
*/
public static long length(String filename) {
return length(construct(filename));
}
/**
* Returns only the name component of the given file.
*
* @param file The file to return the name of.
* @return The name component only of the given file.
*/
public static String getName(File file) {
if (file == null || file.equals("")) return null;
return file.getName();
}
/**
* Returns only the name component of the given file.
*
* @param filename The file to return the name of.
* @return The name component only of the given file.
*/
public static String getName(String filename) {
return getName(construct(filename));
}
/**
* Returns the base and extension parts of the given file's name.
*
* @param file The file to get the name parts of.
* @return The parts of the given file's name.
*/
public static String[] getNameParts(File file) {
String[] parts = null;
String name = getName(file);
if (name != null) {
parts = name.split("\\.(?=[^\\.]+$)");
}
return parts;
}
/**
* Returns the filename extension for the given file.
*
* @param file The file whose extension is to be returned.
* @return The filename extension for the given file.
*/
public static String getExtension(File file) {
return file == null ? null : MimeTypes.getExtensionFromName(file.getName());
}
/**
* Returns the base and extension parts of the given file's name.
*
* @param filename The file to get the name parts of.
* @return The parts of the given file's name.
*/
public static String[] getNameParts(String filename) {
return getNameParts(construct(filename));
}
/**
* Returns the parent directory containing the given file.
*
* @param file The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static File getParentDirectory(File file) {
if (file == null) return null;
return file.getParentFile();
}
/**
* Returns the parent directory containing the given file.
*
* @param filename The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static File getParentDirectory(String filename) {
return getParentDirectory(construct(filename));
}
/**
* Returns the parent directory containing the given file as a string.
*
* @param file The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static String getParentDirectoryAsString(File file) {
return normalize(getParentDirectory(file));
}
/**
* Returns the parent directory containing the given file as a string.
*
* @param filename The file to return the parent directory of.
* @return The parent directory of the given file.
*/
public static String getParentDirectoryAsString(String filename) {
return getParentDirectoryAsString(construct(filename));
}
/**
* Returns the last modified datetime of the given file.
*
* @param file The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static Date getLastModifiedDate(File file) {
if (file == null) return null;
return new Date(file.lastModified());
}
/**
* Returns the last modified datetime of the given file.
*
* @param filename The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static Date getLastModifiedDate(String filename) {
return getLastModifiedDate(construct(filename));
}
/**
* Returns the last modified datetime of the given file as an ISO8601 formatted datetime string.
*
* @param file The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static String getLastModifiedDateTimeString(File file) {
return DateTimeHelper.emit(getLastModifiedDate(file));
}
/**
* Returns the last modified datetime of the given file as an ISO8601 formatted datetime string.
*
* @param filename The file to return the last modified datetime of.
* @return The last modified datetime of the given file.
*/
public static String getLastModifiedDateTimeString(String filename) {
return getLastModifiedDateTimeString(construct(filename));
}
/**
* Returns an IData document containing the properties of the given file.
*
* @param filename The file to return the properties for.
* @return The properties of the given file as an IData document.
*/
public static IData getPropertiesAsIData(String filename) {
return getPropertiesAsIData(construct(filename));
}
/**
* Returns an IData document containing the properties of the given file.
*
* @param file The file to return the properties for.
* @return The properties of the given file as an IData document.
*/
public static IData getPropertiesAsIData(File file) {
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
boolean isFile = file.isFile();
boolean exists = exists(file);
IDataUtil.put(cursor, "exists?", BooleanHelper.emit(exists));
String parent = getParentDirectoryAsString(file);
if (parent != null) IDataUtil.put(cursor, "parent", parent);
String name = getName(file);
if (name != null) IDataUtil.put(cursor, "name", name);
String[] parts = getNameParts(file);
if (parts != null) {
if (parts.length > 0) IDataUtil.put(cursor, "base", parts[0]);
if (parts.length > 1) IDataUtil.put(cursor, "extension", parts[1]);
}
if (isFile) IDataUtil.put(cursor, "type", getMIMEType(file));
if (exists) {
IDataUtil.put(cursor, "length", LongHelper.emit(length(file)));
IDataUtil.put(cursor, "modified", getLastModifiedDateTimeString(file));
IDataUtil.put(cursor, "executable?", BooleanHelper.emit(isExecutable(file)));
IDataUtil.put(cursor, "readable?", BooleanHelper.emit(isReadable(file)));
IDataUtil.put(cursor, "writable?", BooleanHelper.emit(isWritable(file)));
}
IDataUtil.put(cursor, "uri", normalize(file));
cursor.destroy();
return output;
}
}
|
Change FileHelper.getExtension to not lowercase the returned extension
|
src/main/java/permafrost/tundra/io/FileHelper.java
|
Change FileHelper.getExtension to not lowercase the returned extension
|
|
Java
|
mit
|
3a9cf9728052ba7f2ef05936f1e9617633b1ed9f
| 0
|
JoshuaKissoon/SocialKademlia
|
package kademlia.operation;
import kademlia.message.Receiver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import kademlia.KademliaNode;
import kademlia.dht.GetParameter;
import kademlia.core.KadConfiguration;
import kademlia.core.KadServer;
import kademlia.dht.GetParameterFUC;
import kademlia.dht.StorageEntry;
import kademlia.exceptions.RoutingException;
import kademlia.exceptions.UnknownMessageException;
import kademlia.exceptions.UpToDateContentException;
import kademlia.message.ContentLookupMessageFUC;
import kademlia.message.ContentMessage;
import kademlia.message.Message;
import kademlia.message.NodeReplyMessage;
import kademlia.message.UpToDateContentMessage;
import kademlia.node.KeyComparator;
import kademlia.node.Node;
/**
* Looks up a specified Content and returns it
*
* @author Joshua Kissoon
* @since 20140422
*/
public class ContentLookupOperationFUC implements Operation, Receiver
{
/* Constants */
private static final Byte UNASKED = (byte) 0x00;
private static final Byte AWAITING = (byte) 0x01;
private static final Byte ASKED = (byte) 0x02;
private static final Byte FAILED = (byte) 0x03;
private final KadServer server;
private final KademliaNode localNode;
private final GetParameter params;
private final List<StorageEntry> contentFound;
private int numNodesToQuery;
private final KadConfiguration config;
private final Message lookupMessage;
private boolean contentsFound;
private boolean newerContentExist = false; // Whether the content we have is up to date
private final SortedMap<Node, Byte> nodes;
/* Tracks messages in transit and awaiting reply */
private final Map<Integer, Node> messagesTransiting;
/* Used to sort nodes */
private final Comparator comparator;
{
contentFound = new ArrayList<>();
messagesTransiting = new HashMap<>();
contentsFound = false;
}
/**
* @param server
* @param localNode
* @param params The parameters to search for the content which we need to find
* @param numNodesToQuery The number of nodes to query to get this content. We return the content among these nodes.
* @param config
*/
public ContentLookupOperationFUC(KadServer server, KademliaNode localNode, GetParameterFUC params, int numNodesToQuery, KadConfiguration config)
{
/* Construct our lookup message */
this.lookupMessage = new ContentLookupMessageFUC(localNode.getNode(), params);
this.server = server;
this.localNode = localNode;
this.params = params;
this.numNodesToQuery = numNodesToQuery;
this.config = config;
/**
* We initialize a TreeMap to store nodes.
* This map will be sorted by which nodes are closest to the lookupId
*/
this.comparator = new KeyComparator(params.getKey());
this.nodes = new TreeMap(this.comparator);
}
/**
* @throws java.io.IOException
* @throws kademlia.exceptions.RoutingException
*/
@Override
public synchronized void execute() throws IOException, RoutingException
{
try
{
/* Set the local node as already asked */
nodes.put(this.localNode.getNode(), ASKED);
/**
* We add all nodes here instead of the K-Closest because there may be the case that the K-Closest are offline
* - The operation takes care of looking at the K-Closest.
*/
this.addNodes(this.localNode.getRoutingTable().getAllNodes());
/**
* If we haven't found the requested amount of content as yet,
* keey trying until config.operationTimeout() time has expired
*/
int totalTimeWaited = 0;
int timeInterval = 100; // We re-check every 300 milliseconds
while (totalTimeWaited < this.config.operationTimeout())
{
if (!this.askNodesorFinish() && !contentsFound)
{
wait(timeInterval);
totalTimeWaited += timeInterval;
}
else
{
break;
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
/**
* Add nodes from this list to the set of nodes to lookup
*
* @param list The list from which to add nodes
*/
public void addNodes(List<Node> list)
{
for (Node o : list)
{
/* If this node is not in the list, add the node */
if (!nodes.containsKey(o))
{
nodes.put(o, UNASKED);
}
}
}
/**
* Asks some of the K closest nodes seen but not yet queried.
* Assures that no more than DefaultConfiguration.CONCURRENCY messages are in transit at a time
*
* This method should be called every time a reply is received or a timeout occurs.
*
* If all K closest nodes have been asked and there are no messages in transit,
* the algorithm is finished.
*
* @return <code>true</code> if finished OR <code>false</code> otherwise
*/
private boolean askNodesorFinish() throws IOException
{
/* If >= CONCURRENCY nodes are in transit, don't do anything */
if (this.config.maxConcurrentMessagesTransiting() <= this.messagesTransiting.size())
{
return false;
}
/* Get unqueried nodes among the K closest seen that have not FAILED */
List<Node> unasked = this.closestNodesNotFailed(UNASKED);
if (unasked.isEmpty() && this.messagesTransiting.isEmpty())
{
/* We have no unasked nodes nor any messages in transit, we're finished! */
return true;
}
/* Sort nodes according to criteria */
Collections.sort(unasked, this.comparator);
/**
* Send messages to nodes in the list;
* making sure than no more than CONCURRENCY messsages are in transit
*/
for (int i = 0; (this.messagesTransiting.size() < this.config.maxConcurrentMessagesTransiting()) && (i < unasked.size()); i++)
{
Node n = (Node) unasked.get(i);
int comm = server.sendMessage(n, lookupMessage, this);
this.nodes.put(n, AWAITING);
this.messagesTransiting.put(comm, n);
}
/* We're not finished as yet, return false */
return false;
}
/**
* Find The K closest nodes to the target lookupId given that have not FAILED.
* From those K, get those that have the specified status
*
* @param status The status of the nodes to return
*
* @return A List of the closest nodes
*/
private List<Node> closestNodesNotFailed(Byte status)
{
List<Node> closestNodes = new ArrayList<>(this.config.k());
int remainingSpaces = this.config.k();
for (Map.Entry e : this.nodes.entrySet())
{
if (!FAILED.equals(e.getValue()))
{
if (status.equals(e.getValue()))
{
/* We got one with the required status, now add it */
closestNodes.add((Node) e.getKey());
}
if (--remainingSpaces == 0)
{
break;
}
}
}
return closestNodes;
}
@Override
public synchronized void receive(Message incoming, int comm) throws IOException, RoutingException
{
if (this.contentsFound)
{
return;
}
if (incoming instanceof ContentMessage)
{
/* The reply received is a content message with the required content, take it in */
ContentMessage msg = (ContentMessage) incoming;
/* Add the origin node to our routing table */
this.localNode.getRoutingTable().insert(msg.getOrigin());
/* Get the Content and check if it satisfies the required parameters */
StorageEntry content = msg.getContent();
System.out.println("Content Received: " + content);
this.contentFound.add(content);
if (this.contentFound.size() == this.numNodesToQuery)
{
/* We've got all the content required, let's stop the loopup operation */
this.contentsFound = true;
}
/* We've received a newer content than our own, lets specify that newer content exist */
this.newerContentExist = true;
}
else if (incoming instanceof UpToDateContentMessage)
{
/**
* The content we have is up to date
* No sense in adding our own content to the resultset, so lets just decrement the number of nodes left to query
*/
numNodesToQuery--;
}
else
{
/* The reply received is a NodeReplyMessage with nodes closest to the content needed */
NodeReplyMessage msg = (NodeReplyMessage) incoming;
/* Add the origin node to our routing table */
Node origin = msg.getOrigin();
this.localNode.getRoutingTable().insert(origin);
/* Set that we've completed ASKing the origin node */
this.nodes.put(origin, ASKED);
/* Remove this msg from messagesTransiting since it's completed now */
this.messagesTransiting.remove(comm);
/* Add the received nodes to our nodes list to query */
this.addNodes(msg.getNodes());
this.askNodesorFinish();
}
}
/**
* A node does not respond or a packet was lost, we set this node as failed
*
* @param comm
*
* @throws java.io.IOException
*/
@Override
public synchronized void timeout(int comm) throws IOException
{
/* Get the node associated with this communication */
Node n = this.messagesTransiting.get(new Integer(comm));
if (n == null)
{
throw new UnknownMessageException("Unknown comm: " + comm);
}
/* Mark this node as failed and inform the routing table that it's unresponsive */
this.nodes.put(n, FAILED);
this.localNode.getRoutingTable().setUnresponsiveContact(n);
this.messagesTransiting.remove(comm);
this.askNodesorFinish();
}
/**
* @return The list of all content found during the lookup operation
*/
public List<StorageEntry> getContentFound()
{
return this.contentFound;
}
/**
* Check the content found and get the most up to date version
*
* @return The latest version of the content from all found
*
* @throws kademlia.exceptions.UpToDateContentException
*/
public StorageEntry getLatestContentFound() throws UpToDateContentException
{
/* We don't have any newer content */
if (this.contentFound.isEmpty())
{
throw new UpToDateContentException("The content is up to date");
}
/* We have some newer content, lets get it */
StorageEntry latest = null;
for (StorageEntry e : this.contentFound)
{
if (latest == null)
{
latest = e;
}
if (e.getContentMetadata().getLastUpdatedTimestamp() > latest.getContentMetadata().getLastUpdatedTimestamp())
{
latest = e;
}
}
return latest;
}
/**
* @return Boolean whether newer content exist or not
*/
public boolean newerContentExist()
{
return this.newerContentExist;
}
}
|
src/kademlia/operation/ContentLookupOperationFUC.java
|
package kademlia.operation;
import kademlia.message.Receiver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import kademlia.KademliaNode;
import kademlia.dht.GetParameter;
import kademlia.core.KadConfiguration;
import kademlia.core.KadServer;
import kademlia.dht.GetParameterFUC;
import kademlia.dht.StorageEntry;
import kademlia.exceptions.RoutingException;
import kademlia.exceptions.UnknownMessageException;
import kademlia.exceptions.UpToDateContentException;
import kademlia.message.ContentLookupMessageFUC;
import kademlia.message.ContentMessage;
import kademlia.message.Message;
import kademlia.message.NodeReplyMessage;
import kademlia.message.UpToDateContentMessage;
import kademlia.node.KeyComparator;
import kademlia.node.Node;
/**
* Looks up a specified Content and returns it
*
* @author Joshua Kissoon
* @since 20140422
*/
public class ContentLookupOperationFUC implements Operation, Receiver
{
/* Constants */
private static final Byte UNASKED = (byte) 0x00;
private static final Byte AWAITING = (byte) 0x01;
private static final Byte ASKED = (byte) 0x02;
private static final Byte FAILED = (byte) 0x03;
private final KadServer server;
private final KademliaNode localNode;
private final GetParameter params;
private final List<StorageEntry> contentFound;
private int numNodesToQuery;
private final KadConfiguration config;
private final Message lookupMessage;
private boolean contentsFound;
private boolean newerContentExist = false; // Whether the content we have is up to date
private final SortedMap<Node, Byte> nodes;
/* Tracks messages in transit and awaiting reply */
private final Map<Integer, Node> messagesTransiting;
/* Used to sort nodes */
private final Comparator comparator;
{
contentFound = new ArrayList<>();
messagesTransiting = new HashMap<>();
contentsFound = false;
}
/**
* @param server
* @param localNode
* @param params The parameters to search for the content which we need to find
* @param numNodesToQuery The number of nodes to query to get this content. We return the content among these nodes.
* @param config
*/
public ContentLookupOperationFUC(KadServer server, KademliaNode localNode, GetParameterFUC params, int numNodesToQuery, KadConfiguration config)
{
/* Construct our lookup message */
this.lookupMessage = new ContentLookupMessageFUC(localNode.getNode(), params);
this.server = server;
this.localNode = localNode;
this.params = params;
this.numNodesToQuery = numNodesToQuery;
this.config = config;
/**
* We initialize a TreeMap to store nodes.
* This map will be sorted by which nodes are closest to the lookupId
*/
this.comparator = new KeyComparator(params.getKey());
this.nodes = new TreeMap(this.comparator);
}
/**
* @throws java.io.IOException
* @throws kademlia.exceptions.RoutingException
*/
@Override
public synchronized void execute() throws IOException, RoutingException
{
try
{
/* Set the local node as already asked */
nodes.put(this.localNode.getNode(), ASKED);
this.addNodes(this.localNode.getRoutingTable().getAllNodes());
/**
* If we haven't found the requested amount of content as yet,
* keey trying until config.operationTimeout() time has expired
*/
int totalTimeWaited = 0;
int timeInterval = 100; // We re-check every 300 milliseconds
while (totalTimeWaited < this.config.operationTimeout())
{
if (!this.askNodesorFinish() && !contentsFound)
{
wait(timeInterval);
totalTimeWaited += timeInterval;
}
else
{
break;
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
/**
* Add nodes from this list to the set of nodes to lookup
*
* @param list The list from which to add nodes
*/
public void addNodes(List<Node> list)
{
for (Node o : list)
{
/* If this node is not in the list, add the node */
if (!nodes.containsKey(o))
{
nodes.put(o, UNASKED);
}
}
}
/**
* Asks some of the K closest nodes seen but not yet queried.
* Assures that no more than DefaultConfiguration.CONCURRENCY messages are in transit at a time
*
* This method should be called every time a reply is received or a timeout occurs.
*
* If all K closest nodes have been asked and there are no messages in transit,
* the algorithm is finished.
*
* @return <code>true</code> if finished OR <code>false</code> otherwise
*/
private boolean askNodesorFinish() throws IOException
{
/* If >= CONCURRENCY nodes are in transit, don't do anything */
if (this.config.maxConcurrentMessagesTransiting() <= this.messagesTransiting.size())
{
return false;
}
/* Get unqueried nodes among the K closest seen that have not FAILED */
List<Node> unasked = this.closestNodesNotFailed(UNASKED);
if (unasked.isEmpty() && this.messagesTransiting.isEmpty())
{
/* We have no unasked nodes nor any messages in transit, we're finished! */
return true;
}
/* Sort nodes according to criteria */
Collections.sort(unasked, this.comparator);
/**
* Send messages to nodes in the list;
* making sure than no more than CONCURRENCY messsages are in transit
*/
for (int i = 0; (this.messagesTransiting.size() < this.config.maxConcurrentMessagesTransiting()) && (i < unasked.size()); i++)
{
Node n = (Node) unasked.get(i);
int comm = server.sendMessage(n, lookupMessage, this);
this.nodes.put(n, AWAITING);
this.messagesTransiting.put(comm, n);
}
/* We're not finished as yet, return false */
return false;
}
/**
* Find The K closest nodes to the target lookupId given that have not FAILED.
* From those K, get those that have the specified status
*
* @param status The status of the nodes to return
*
* @return A List of the closest nodes
*/
private List<Node> closestNodesNotFailed(Byte status)
{
List<Node> closestNodes = new ArrayList<>(this.config.k());
int remainingSpaces = this.config.k();
for (Map.Entry e : this.nodes.entrySet())
{
if (!FAILED.equals(e.getValue()))
{
if (status.equals(e.getValue()))
{
/* We got one with the required status, now add it */
closestNodes.add((Node) e.getKey());
}
if (--remainingSpaces == 0)
{
break;
}
}
}
return closestNodes;
}
@Override
public synchronized void receive(Message incoming, int comm) throws IOException, RoutingException
{
if (this.contentsFound)
{
return;
}
if (incoming instanceof ContentMessage)
{
/* The reply received is a content message with the required content, take it in */
ContentMessage msg = (ContentMessage) incoming;
/* Add the origin node to our routing table */
this.localNode.getRoutingTable().insert(msg.getOrigin());
/* Get the Content and check if it satisfies the required parameters */
StorageEntry content = msg.getContent();
System.out.println("Content Received: " + content);
this.contentFound.add(content);
if (this.contentFound.size() == this.numNodesToQuery)
{
/* We've got all the content required, let's stop the loopup operation */
this.contentsFound = true;
}
/* We've received a newer content than our own, lets specify that newer content exist */
this.newerContentExist = true;
}
else if (incoming instanceof UpToDateContentMessage)
{
/**
* The content we have is up to date
* No sense in adding our own content to the resultset, so lets just decrement the number of nodes left to query
*/
numNodesToQuery--;
}
else
{
/* The reply received is a NodeReplyMessage with nodes closest to the content needed */
NodeReplyMessage msg = (NodeReplyMessage) incoming;
/* Add the origin node to our routing table */
Node origin = msg.getOrigin();
this.localNode.getRoutingTable().insert(origin);
/* Set that we've completed ASKing the origin node */
this.nodes.put(origin, ASKED);
/* Remove this msg from messagesTransiting since it's completed now */
this.messagesTransiting.remove(comm);
/* Add the received nodes to our nodes list to query */
this.addNodes(msg.getNodes());
this.askNodesorFinish();
}
}
/**
* A node does not respond or a packet was lost, we set this node as failed
*
* @param comm
*
* @throws java.io.IOException
*/
@Override
public synchronized void timeout(int comm) throws IOException
{
/* Get the node associated with this communication */
Node n = this.messagesTransiting.get(new Integer(comm));
if (n == null)
{
throw new UnknownMessageException("Unknown comm: " + comm);
}
/* Mark this node as failed and inform the routing table that it's unresponsive */
this.nodes.put(n, FAILED);
this.localNode.getRoutingTable().setUnresponsiveContact(n);
this.messagesTransiting.remove(comm);
this.askNodesorFinish();
}
/**
* @return The list of all content found during the lookup operation
*/
public List<StorageEntry> getContentFound()
{
return this.contentFound;
}
/**
* Check the content found and get the most up to date version
*
* @return The latest version of the content from all found
*
* @throws kademlia.exceptions.UpToDateContentException
*/
public StorageEntry getLatestContentFound() throws UpToDateContentException
{
/* We don't have any newer content */
if (this.contentFound.isEmpty())
{
throw new UpToDateContentException("The content is up to date");
}
/* We have some newer content, lets get it */
StorageEntry latest = null;
for (StorageEntry e : this.contentFound)
{
if (latest == null)
{
latest = e;
}
if (e.getContentMetadata().getLastUpdatedTimestamp() > latest.getContentMetadata().getLastUpdatedTimestamp())
{
latest = e;
}
}
return latest;
}
/**
* @return Boolean whether newer content exist or not
*/
public boolean newerContentExist()
{
return this.newerContentExist;
}
}
|
Added the previous changes to the FUC operaiton
|
src/kademlia/operation/ContentLookupOperationFUC.java
|
Added the previous changes to the FUC operaiton
|
|
Java
|
mit
|
cfbcf7e54cc82376a848a2170bff79682a2085d0
| 0
|
amwenger/igv,amwenger/igv,amwenger/igv,godotgildor/igv,igvteam/igv,itenente/igv,godotgildor/igv,itenente/igv,itenente/igv,godotgildor/igv,igvteam/igv,amwenger/igv,amwenger/igv,igvteam/igv,godotgildor/igv,itenente/igv,itenente/igv,godotgildor/igv,igvteam/igv,igvteam/igv
|
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.session;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.RegionOfInterest;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.lists.GeneList;
import org.broad.igv.lists.GeneListManager;
import org.broad.igv.renderer.ColorScale;
import org.broad.igv.renderer.ColorScaleFactory;
import org.broad.igv.renderer.ContinuousColorScale;
import org.broad.igv.track.*;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.TrackFilter;
import org.broad.igv.ui.TrackFilterElement;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.panel.TrackPanel;
import org.broad.igv.ui.panel.TrackPanelScrollPane;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.FilterElement.BooleanOperator;
import org.broad.igv.util.FilterElement.Operator;
import org.broad.igv.util.ParsingUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.Utilities;
import org.broad.igv.util.collections.CollUtils;
import org.w3c.dom.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.List;
/**
* Class to parse an IGV session file
*/
public class IGVSessionReader implements SessionReader {
private static Logger log = Logger.getLogger(IGVSessionReader.class);
private static String INPUT_FILE_KEY = "INPUT_FILE_KEY";
// Temporary values used in processing
//package-private for unit testing
Collection<ResourceLocator> dataFiles;
private Collection<ResourceLocator> missingDataFiles;
private static Map<String, String> attributeSynonymMap = new HashMap();
private boolean panelElementPresent = false;
private int version;
private IGV igv;
private static WeakReference<IGVSessionReader> currentReader;
/**
* Classes that have been registered for use with JAXB
*/
private static List<Class> registeredClasses = new ArrayList<Class>();
/**
* Map of track id -> track. It is important to maintain the order in which tracks are added, thus
* the use of LinkedHashMap. We add tracks here when loaded and remove them when attributes are specified.
*/
private final Map<String, List<Track>> leftoverTrackDictionary = Collections.synchronizedMap(new LinkedHashMap());
/**
* Map of id -> track, for second pass through when tracks reference each other
*/
private final Map<String, List<Track>> allTracks = Collections.synchronizedMap(new LinkedHashMap<String, List<Track>>());
public List<Track> getTracksById(String trackId){
return allTracks.get(trackId);
}
/**
* Map of full path -> relative path.
*/
Map<String, String> fullToRelPathMap = new HashMap<String, String>();
private Track geneTrack = null;
private Track seqTrack = null;
private boolean hasTrackElments;
//Temporary holder for generating tracks
protected static AbstractTrack nextTrack;
static {
attributeSynonymMap.put("DATA FILE", "DATA SET");
attributeSynonymMap.put("TRACK NAME", "NAME");
registerClass(AbstractTrack.class);
}
/**
* Session Element types
*/
public static enum SessionElement {
PANEL("Panel"),
PANEL_LAYOUT("PanelLayout"),
TRACK("Track"),
COLOR_SCALE("ColorScale"),
COLOR_SCALES("ColorScales"),
DATA_TRACK("DataTrack"),
DATA_TRACKS("DataTracks"),
FEATURE_TRACKS("FeatureTracks"),
DATA_FILE("DataFile"),
RESOURCE("Resource"),
RESOURCES("Resources"),
FILES("Files"),
FILTER_ELEMENT("FilterElement"),
FILTER("Filter"),
SESSION("Session"),
GLOBAL("Global"),
REGION("Region"),
REGIONS("Regions"),
DATA_RANGE("DataRange"),
PREFERENCES("Preferences"),
PROPERTY("Property"),
GENE_LIST("GeneList"),
HIDDEN_ATTRIBUTES("HiddenAttributes"),
VISIBLE_ATTRIBUTES("VisibleAttributes"),
ATTRIBUTE("Attribute"),
VISIBLE_ATTRIBUTE("VisibleAttribute"),
FRAME("Frame");
private String name;
SessionElement(String name) {
this.name = name;
}
public String getText() {
return name;
}
@Override
public String toString() {
return getText();
}
static public SessionElement findEnum(String value) {
if (value == null) {
return null;
} else {
return SessionElement.valueOf(value);
}
}
}
/**
* Session Attribute types
*/
public static enum SessionAttribute {
BOOLEAN_OPERATOR("booleanOperator"),
COLOR("color"),
ALT_COLOR("altColor"),
COLOR_MODE("colorMode"),
CHROMOSOME("chromosome"),
END_INDEX("end"),
EXPAND("expand"),
SQUISH("squish"),
DISPLAY_MODE("displayMode"),
FILTER_MATCH("match"),
FILTER_SHOW_ALL_TRACKS("showTracks"),
GENOME("genome"),
GROUP_TRACKS_BY("groupTracksBy"),
HEIGHT("height"),
ID("id"),
ITEM("item"),
LOCUS("locus"),
NAME("name"),
SAMPLE_ID("sampleID"),
RESOURCE_TYPE("resourceType"),
OPERATOR("operator"),
RELATIVE_PATH("relativePath"),
RENDERER("renderer"),
SCALE("scale"),
START_INDEX("start"),
VALUE("value"),
VERSION("version"),
VISIBLE("visible"),
WINDOW_FUNCTION("windowFunction"),
RENDER_NAME("renderName"),
GENOTYPE_HEIGHT("genotypeHeight"),
VARIANT_HEIGHT("variantHeight"),
PREVIOUS_HEIGHT("previousHeight"),
FEATURE_WINDOW("featureVisibilityWindow"),
DISPLAY_NAME("displayName"),
COLOR_SCALE("colorScale"),
HAS_GENE_TRACK("hasGeneTrack"),
HAS_SEQ_TRACK("hasSequenceTrack"),
//RESOURCE ATTRIBUTES
PATH("path"),
LABEL("label"),
SERVER_URL("serverURL"),
HYPERLINK("hyperlink"),
INFOLINK("infolink"),
URL("url"),
FEATURE_URL("featureURL"),
DESCRIPTION("description"),
TYPE("type"),
COVERAGE("coverage"),
TRACK_LINE("trackLine"),
CHR("chr"),
START("start"),
END("end");
//TODO Add the following into the Attributes
/*
ShadeBasesOption shadeBases;
boolean shadeCenters;
boolean flagUnmappedPairs;
boolean showAllBases;
int insertSizeThreshold;
boolean colorByStrand;
boolean colorByAmpliconStrand;
*/
private String name;
SessionAttribute(String name) {
this.name = name;
}
public String getText() {
return name;
}
@Override
public String toString() {
return getText();
}
}
public IGVSessionReader(IGV igv) {
this.igv = igv;
currentReader = new WeakReference<IGVSessionReader>(this);
}
/**
* @param inputStream
* @param session
* @param sessionPath @return
* @throws RuntimeException
*/
public void loadSession(InputStream inputStream, Session session, String sessionPath) {
log.debug("Load session");
Document document = null;
try {
document = Utilities.createDOMDocumentFromXmlStream(inputStream);
} catch (Exception e) {
log.error("Load session error", e);
throw new RuntimeException(e);
}
NodeList tracks = document.getElementsByTagName("Track");
hasTrackElments = tracks.getLength() > 0;
HashMap additionalInformation = new HashMap();
additionalInformation.put(INPUT_FILE_KEY, sessionPath);
NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText());
if (nodes == null || nodes.getLength() == 0) {
nodes = document.getElementsByTagName(SessionElement.SESSION.getText());
}
processRootNode(session, nodes.item(0), additionalInformation, sessionPath);
// Add tracks not explicitly allocated to panels. It is legal to define sessions with the Resources
// section only (no Panel or Track elements).
addLeftoverTracks(leftoverTrackDictionary.values());
if (igv != null) {
if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) {
igv.setGroupByAttribute(session.getGroupTracksBy());
}
if (session.isRemoveEmptyPanels()) {
igv.getMainPanel().removeEmptyDataPanels();
}
igv.resetOverlayTracks();
}
}
private void processRootNode(Session session, Node node, HashMap additionalInformation, String rootPath) {
if ((node == null) || (session == null)) {
MessageUtils.showMessage("Invalid session file: root node not found");
return;
}
String nodeName = node.getNodeName();
if (!(nodeName.equalsIgnoreCase(SessionElement.GLOBAL.getText()) || nodeName.equalsIgnoreCase(SessionElement.SESSION.getText()))) {
MessageUtils.showMessage("Session files must begin with a \"Global\" or \"Session\" element. Found: " + nodeName);
return;
}
process(session, node, additionalInformation, rootPath);
Element element = (Element) node;
String versionString = getAttribute(element, SessionAttribute.VERSION.getText());
try {
version = Integer.parseInt(versionString);
} catch (NumberFormatException e) {
log.error("Non integer version number in session file: " + versionString);
}
// Load the genome, which can be an ID, or a path or URL to a .genome or indexed fasta file.
String genomeId = getAttribute(element, SessionAttribute.GENOME.getText());
String hasGeneTrackStr = getAttribute(element, SessionAttribute.HAS_GENE_TRACK.getText());
boolean hasGeneTrack = true;
if(hasGeneTrackStr != null){
hasGeneTrack = Boolean.parseBoolean(hasGeneTrackStr);
}
boolean hasSeqTrack = hasGeneTrack;
String hasSeqTrackStr = getAttribute(element, SessionAttribute.HAS_SEQ_TRACK.getText());
if(hasSeqTrackStr != null){
hasSeqTrack = Boolean.parseBoolean(hasSeqTrackStr);
}
if (genomeId != null && genomeId.length() > 0) {
if (genomeId.equals(GenomeManager.getInstance().getGenomeId())) {
// We don't have to reload the genome, but the gene track for the current genome should be restored.
if(hasGeneTrack || hasSeqTrack){
Genome genome = GenomeManager.getInstance().getCurrentGenome();
FeatureTrack geneTrack = hasGeneTrack ? genome.getGeneTrack() : null;
IGV.getInstance().setGenomeTracks(geneTrack);
}
} else {
// Selecting a genome will actually "reset" the session so we have to
// save the path and restore it.
String sessionPath = session.getPath();
//Loads genome from list, or from server or cache
igv.selectGenomeFromList(genomeId);
if (!genomeId.equals(GenomeManager.getInstance().getGenomeId())) {
String genomePath = genomeId;
if (!ParsingUtils.pathExists(genomePath)) {
genomePath = FileUtils.getAbsolutePath(genomeId, session.getPath());
}
if (ParsingUtils.pathExists(genomePath)) {
try {
IGV.getInstance().loadGenome(genomePath, null, hasGeneTrack);
} catch (IOException e) {
throw new RuntimeException("Error loading genome: " + genomeId);
}
} else {
MessageUtils.showMessage("Warning: Could not locate genome: " + genomeId);
}
}
session.setPath(sessionPath);
}
}
//TODO Remove these nearly identical if/then statements
if(!hasGeneTrack && igv.hasGeneTrack()){
//Need to remove gene track if it was loaded because it's not supposed to be in the session
igv.removeTracks(Arrays.<Track>asList(GenomeManager.getInstance().getCurrentGenome().getGeneTrack()));
geneTrack = null;
}else{
//For later lookup and to prevent dual adding, we keep a reference to the gene track
geneTrack = GenomeManager.getInstance().getCurrentGenome().getGeneTrack();
if(geneTrack != null){
allTracks.put(geneTrack.getId(), Arrays.asList(geneTrack));
}
}
SequenceTrack tmpSeqTrack = igv.getSequenceTrack();
if(!hasSeqTrack && igv.hasSequenceTrack()){
//Need to remove seq track if it was loaded because it's not supposed to be in the session
igv.removeTracks(Arrays.<Track>asList(tmpSeqTrack));
seqTrack = null;
}else{
//For later lookup and to prevent dual adding, we keep a reference to the sequence track
seqTrack = tmpSeqTrack;
if(seqTrack != null){
allTracks.put(seqTrack.getId(), Arrays.asList(seqTrack));
}
}
session.setLocus(getAttribute(element, SessionAttribute.LOCUS.getText()));
session.setGroupTracksBy(getAttribute(element, SessionAttribute.GROUP_TRACKS_BY.getText()));
String removeEmptyTracks = getAttribute(element, "removeEmptyTracks");
if (removeEmptyTracks != null) {
try {
Boolean b = Boolean.parseBoolean(removeEmptyTracks);
session.setRemoveEmptyPanels(b);
} catch (Exception e) {
log.error("Error parsing removeEmptyTracks string: " + removeEmptyTracks, e);
}
}
session.setVersion(version);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
// ReferenceFrame.getInstance().invalidateLocationScale();
}
//TODO Check to make sure tracks are not being created twice
//TODO -- DONT DO THIS FOR NEW SESSIONS
private void addLeftoverTracks(Collection<List<Track>> tmp) {
Map<String, TrackPanel> trackPanelCache = new HashMap();
if (version < 3 || !panelElementPresent) {
log.debug("Adding \"leftover\" tracks");
//For resetting track panels later
List<Map<TrackPanelScrollPane, Integer>> trackPanelAttrs = null;
if(IGV.hasInstance()){
trackPanelAttrs = IGV.getInstance().getTrackPanelAttrs();
}
for (List<Track> tracks : tmp) {
for (Track track : tracks) {
if (track != geneTrack && track != seqTrack && track.getResourceLocator() != null) {
TrackPanel panel = trackPanelCache.get(track.getResourceLocator().getPath());
if (panel == null) {
panel = IGV.getInstance().getPanelFor(track.getResourceLocator());
trackPanelCache.put(track.getResourceLocator().getPath(), panel);
}
panel.addTrack(track);
}
}
}
if(IGV.hasInstance()){
IGV.getInstance().resetPanelHeights(trackPanelAttrs.get(0), trackPanelAttrs.get(1));
}
}
}
/**
* Process a single session element node.
*
* @param session
* @param element
*/
private void process(Session session, Node element, HashMap additionalInformation, String rootPath) {
if ((element == null) || (session == null)) {
return;
}
String nodeName = element.getNodeName();
if (nodeName.equalsIgnoreCase(SessionElement.RESOURCES.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.FILES.getText())) {
processResources(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.RESOURCE.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.DATA_FILE.getText())) {
processResource(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.REGIONS.getText())) {
processRegions(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.REGION.getText())) {
processRegion(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.GENE_LIST.getText())) {
processGeneList(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.FILTER.getText())) {
processFilter(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.FILTER_ELEMENT.getText())) {
processFilterElement(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALES.getText())) {
processColorScales(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALE.getText())) {
processColorScale(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.PREFERENCES.getText())) {
processPreferences(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.DATA_TRACKS.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.FEATURE_TRACKS.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.PANEL.getText())) {
processPanel(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.PANEL_LAYOUT.getText())) {
processPanelLayout(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.HIDDEN_ATTRIBUTES.getText())) {
processHiddenAttributes(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.VISIBLE_ATTRIBUTES.getText())) {
processVisibleAttributes(session, (Element) element, additionalInformation);
}
}
private void processResources(Session session, Element element, HashMap additionalInformation, String rootPath) {
dataFiles = new ArrayList();
missingDataFiles = new ArrayList();
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
if (missingDataFiles.size() > 0) {
StringBuffer message = new StringBuffer();
message.append("<html>The following data file(s) could not be located.<ul>");
for (ResourceLocator file : missingDataFiles) {
if (file.getDBUrl() == null) {
message.append("<li>");
message.append(file.getPath());
message.append("</li>");
} else {
message.append("<li>Server: ");
message.append(file.getDBUrl());
message.append(" Path: ");
message.append(file.getPath());
message.append("</li>");
}
}
message.append("</ul>");
message.append("Common reasons for this include: ");
message.append("<ul><li>The session or data files have been moved.</li> ");
message.append("<li>The data files are located on a drive that is not currently accessible.</li></ul>");
message.append("</html>");
MessageUtils.showMessage(message.toString());
}
if (dataFiles.size() > 0) {
final List<String> errors = new ArrayList<String>();
// Load files concurrently -- TODO, put a limit on # of threads?
List<Thread> threads = new ArrayList(dataFiles.size());
long t0 = System.currentTimeMillis();
int i = 0;
List<Runnable> synchronousLoads = new ArrayList<Runnable>();
for (final ResourceLocator locator : dataFiles) {
final String suppliedPath = locator.getPath();
final String relPath = fullToRelPathMap.get(suppliedPath);
Runnable runnable = new Runnable() {
public void run() {
List<Track> tracks = null;
try {
tracks = igv.load(locator);
for (Track track : tracks) {
if (track == null) {
log.info("Null track for resource " + locator.getPath());
continue;
}
String id = track.getId();
if (id == null) {
log.info("Null track id for resource " + locator.getPath());
continue;
}
if (relPath != null) {
id = id.replace(suppliedPath, relPath);
}
List<Track> trackList = leftoverTrackDictionary.get(id);
if (trackList == null) {
trackList = new ArrayList();
leftoverTrackDictionary.put(id, trackList);
allTracks.put(id, trackList);
}
trackList.add(track);
}
} catch (Exception e) {
log.error("Error loading resource " + locator.getPath(), e);
String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p " + e.toString() + "<br>";
errors.add(ms);
}
}
};
boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") ||
locator.getPath().endsWith(".sam");
// Run synchronously if in batch mode or if there are no "track" elments, or if this is an alignment file
// EVERYTHING IS RUN SYNCHRONOUSLY FOR NOW UNTIL WE CAN FIGURE OUT WHAT TO DO TO PREVENT MULTIPLE
// AUTHENTICATION DIALOGS
if (isAlignment || Globals.isBatch() || !hasTrackElments) {
synchronousLoads.add(runnable);
} else {
Thread t = new Thread(runnable);
threads.add(t);
t.start();
}
i++;
}
// Wait for all threads to complete
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException ignore) {
}
}
// Now load data that must be loaded synchronously
for (Runnable runnable : synchronousLoads) {
runnable.run();
}
long dt = System.currentTimeMillis() - t0;
log.debug("Total load time = " + dt);
if (errors.size() > 0) {
StringBuffer buf = new StringBuffer();
buf.append("<html>Errors were encountered loading the session:<br>");
for (String msg : errors) {
buf.append(msg);
}
MessageUtils.showMessage(buf.toString());
}
}
dataFiles = null;
}
/**
* Load a single resource.
* <p/>
* Package private for unit testing
*
* @param session
* @param element
* @param additionalInformation
*/
void processResource(Session session, Element element, HashMap additionalInformation, String rootPath) {
String nodeName = element.getNodeName();
boolean oldSession = nodeName.equals(SessionElement.DATA_FILE.getText());
String label = getAttribute(element, SessionAttribute.LABEL.getText());
String name = getAttribute(element, SessionAttribute.NAME.getText());
String sampleId = getAttribute(element, SessionAttribute.SAMPLE_ID.getText());
String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText());
String type = getAttribute(element, SessionAttribute.TYPE.getText());
String coverage = getAttribute(element, SessionAttribute.COVERAGE.getText());
String trackLine = getAttribute(element, SessionAttribute.TRACK_LINE.getText());
String colorString = getAttribute(element, SessionAttribute.COLOR.getText());
//String relPathValue = getAttribute(element, SessionAttribute.RELATIVE_PATH.getText());
//boolean isRelativePath = ((relPathValue != null) && relPathValue.equalsIgnoreCase("true"));
String serverURL = getAttribute(element, SessionAttribute.SERVER_URL.getText());
// Older sessions used the "name" attribute for the path.
String path = getAttribute(element, SessionAttribute.PATH.getText());
if (oldSession && name != null) {
path = name;
int idx = name.lastIndexOf("/");
if (idx > 0 && idx + 1 < name.length()) {
name = name.substring(idx + 1);
}
}
if (rootPath == null) {
log.error("Null root path -- this is not expected");
MessageUtils.showMessage("Unexpected error loading session: null root path");
return;
}
String absolutePath = FileUtils.getAbsolutePath(path, rootPath);
fullToRelPathMap.put(absolutePath, path);
ResourceLocator resourceLocator = new ResourceLocator(serverURL, absolutePath);
if (coverage != null) {
String absoluteCoveragePath = FileUtils.getAbsolutePath(coverage, rootPath);
resourceLocator.setCoverage(absoluteCoveragePath);
}
String url = getAttribute(element, SessionAttribute.URL.getText());
if (url == null) {
url = getAttribute(element, SessionAttribute.FEATURE_URL.getText());
}
resourceLocator.setFeatureInfoURL(url);
String infolink = getAttribute(element, SessionAttribute.HYPERLINK.getText());
if (infolink == null) {
infolink = getAttribute(element, SessionAttribute.INFOLINK.getText());
}
resourceLocator.setTrackInforURL(infolink);
// Label is deprecated in favor of name.
if (name != null) {
resourceLocator.setName(name);
} else {
resourceLocator.setName(label);
}
resourceLocator.setSampleId(sampleId);
resourceLocator.setDescription(description);
// This test added to get around earlier bug in the writer
if (type != null && !type.equals("local")) {
resourceLocator.setType(type);
}
resourceLocator.setCoverage(coverage);
resourceLocator.setTrackLine(trackLine);
if (colorString != null) {
try {
Color c = ColorUtilities.stringToColor(colorString);
resourceLocator.setColor(c);
} catch (Exception e) {
log.error("Error setting color: ", e);
}
}
dataFiles.add(resourceLocator);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processRegions(Session session, Element element, HashMap additionalInformation, String rootPath) {
session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processRegion(Session session, Element element, HashMap additionalInformation, String rootPath) {
String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText());
String start = getAttribute(element, SessionAttribute.START_INDEX.getText());
String end = getAttribute(element, SessionAttribute.END_INDEX.getText());
String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText());
RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description);
IGV.getInstance().addRegionOfInterest(region);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processHiddenAttributes(Session session, Element element, HashMap additionalInformation) {
// session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Set<String> attributes = new HashSet();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) {
attributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText()));
}
}
session.setHiddenAttributes(attributes);
}
}
/**
* For backward compatibility
*
* @param session
* @param element
* @param additionalInformation
*/
private void processVisibleAttributes(Session session, Element element, HashMap additionalInformation) {
// session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Set<String> visibleAttributes = new HashSet();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) {
visibleAttributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText()));
}
}
final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames();
Set<String> hiddenAttributes = new HashSet<String>(attributeNames);
hiddenAttributes.removeAll(visibleAttributes);
session.setHiddenAttributes(hiddenAttributes);
}
}
private void processGeneList(Session session, Element element, HashMap additionalInformation) {
String name = getAttribute(element, SessionAttribute.NAME.getText());
String txt = element.getTextContent();
String[] genes = txt.trim().split("\\s+");
GeneList gl = new GeneList(name, Arrays.asList(genes));
GeneListManager.getInstance().addGeneList(gl);
session.setCurrentGeneList(gl);
// Adjust frames
processFrames(element);
}
private void processFrames(Element element) {
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Map<String, ReferenceFrame> frames = new HashMap();
for (ReferenceFrame f : FrameManager.getFrames()) {
frames.put(f.getName(), f);
}
List<ReferenceFrame> reorderedFrames = new ArrayList();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) {
String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText());
ReferenceFrame f = frames.get(frameName);
if (f != null) {
reorderedFrames.add(f);
try {
String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText());
final String startString =
getAttribute((Element) childNode, SessionAttribute.START.getText()).replace(",", "");
final String endString =
getAttribute((Element) childNode, SessionAttribute.END.getText()).replace(",", "");
int start = ParsingUtils.parseInt(startString);
int end = ParsingUtils.parseInt(endString);
org.broad.igv.feature.Locus locus = new Locus(chr, start, end);
f.jumpTo(locus);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
if (reorderedFrames.size() > 0) {
FrameManager.setFrames(reorderedFrames);
}
}
IGV.getInstance().resetFrames();
}
private void processFilter(Session session, Element element, HashMap additionalInformation, String rootPath) {
String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText());
String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText());
String filterName = getAttribute(element, SessionAttribute.NAME.getText());
TrackFilter filter = new TrackFilter(filterName, null);
additionalInformation.put(SessionElement.FILTER, filter);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
// Save the filter
session.setFilter(filter);
// Set filter properties
if ("all".equalsIgnoreCase(match)) {
IGV.getInstance().setFilterMatchAll(true);
} else if ("any".equalsIgnoreCase(match)) {
IGV.getInstance().setFilterMatchAll(false);
}
if ("true".equalsIgnoreCase(showAllTracks)) {
IGV.getInstance().setFilterShowAllTracks(true);
} else {
IGV.getInstance().setFilterShowAllTracks(false);
}
}
private void processFilterElement(Session session, Element element,
HashMap additionalInformation, String rootPath) {
TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER);
String item = getAttribute(element, SessionAttribute.ITEM.getText());
String operator = getAttribute(element, SessionAttribute.OPERATOR.getText());
String value = getAttribute(element, SessionAttribute.VALUE.getText());
String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText());
Operator opEnum = CollUtils.findValueOf(Operator.class, operator);
BooleanOperator boolEnum = BooleanOperator.valueOf(booleanOperator.toUpperCase());
TrackFilterElement trackFilterElement = new TrackFilterElement(filter, item,
opEnum, value, boolEnum);
filter.add(trackFilterElement);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
/**
* A counter to generate unique panel names. Needed for backward-compatibility of old session files.
*/
private int panelCounter = 1;
private void processPanel(Session session, Element element, HashMap additionalInformation, String rootPath) {
panelElementPresent = true;
String panelName = element.getAttribute("name");
if (panelName == null) {
panelName = "Panel" + panelCounter++;
}
List<Track> panelTracks = new ArrayList();
NodeList elements = element.getChildNodes();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track?
childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) {
List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation, rootPath);
if (tracks != null) {
panelTracks.addAll(tracks);
}
} else {
process(session, childNode, additionalInformation, rootPath);
}
}
//We make a second pass through, resolving references to tracks which may have been processed afterwards.
//For instance if Track 2 referenced Track 4
//TODO Make this less hacky
for (Track track: panelTracks){
if(track instanceof FeatureTrack){
FeatureTrack featureTrack = (FeatureTrack) track;
featureTrack.updateTrackReferences(panelTracks);
}else if(track instanceof DataSourceTrack){
DataSourceTrack dataTrack = (DataSourceTrack) track;
dataTrack.updateTrackReferences(panelTracks);
}
}
TrackPanel panel = IGV.getInstance().getTrackPanel(panelName);
panel.addTracks(panelTracks);
}
private void processPanelLayout(Session session, Element element, HashMap additionalInformation) {
String nodeName = element.getNodeName();
String panelName = nodeName;
NamedNodeMap tNodeMap = element.getAttributes();
for (int i = 0; i < tNodeMap.getLength(); i++) {
Node node = tNodeMap.item(i);
String name = node.getNodeName();
if (name.equals("dividerFractions")) {
String value = node.getNodeValue();
String[] tokens = value.split(",");
double[] divs = new double[tokens.length];
try {
for (int j = 0; j < tokens.length; j++) {
divs[j] = Double.parseDouble(tokens[j]);
}
session.setDividerFractions(divs);
} catch (NumberFormatException e) {
log.error("Error parsing divider locations", e);
}
}
}
}
/**
* Process a track element. This should return a single track, but could return multiple tracks since the
* uniqueness of the track id is not enforced.
*
* @param session
* @param element
* @param additionalInformation
* @return
*/
private List<Track> processTrack(Session session, Element element, HashMap additionalInformation, String rootPath) {
String id = getAttribute(element, SessionAttribute.ID.getText());
// Get matching tracks.
List<Track> matchedTracks = allTracks.get(id);
if (matchedTracks == null) {
log.info("Warning. No tracks were found with id: " + id + " in session file");
String className = getAttribute(element, "clazz");
//We try anyway, some tracks can be reconstructed without a resource element
//They must have a source, though
try{
if(className != null && ( className.contains("FeatureTrack") || className.contains("DataSourceTrack") ) && element.hasChildNodes()){
Class clazz = Class.forName(className);
Unmarshaller u = getJAXBContext().createUnmarshaller();
Track track = unmarshalTrackElement(u, element, null, clazz);
matchedTracks = new ArrayList<Track>(Arrays.asList(track));
allTracks.put(track.getId(), matchedTracks);
}
} catch (JAXBException e) {
//pass
} catch (ClassNotFoundException e) {
//pass
}
} else {
try {
Unmarshaller u = getJAXBContext().createUnmarshaller();
for (final Track track : matchedTracks) {
// Special case for sequence & gene tracks, they need to be removed before being placed.
if (igv != null && version >= 4 && (track == geneTrack || track == seqTrack)) {
igv.removeTracks(Arrays.asList(track));
}
unmarshalTrackElement(u, element, (AbstractTrack) track);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
leftoverTrackDictionary.remove(id);
}
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
return matchedTracks;
}
private static void setNextTrack(AbstractTrack track){
nextTrack = track;
}
/**
* Used for unmarshalling track; JAXB needs a static no-arg factory method
* @return
*/
public static AbstractTrack getNextTrack(){
return nextTrack;
}
/**
* Unmarshal element into specified class
* @param u
* @param e
* @param track
* @return
* @throws JAXBException
*/
protected Track unmarshalTrackElement(Unmarshaller u, Element e, AbstractTrack track) throws JAXBException{
return unmarshalTrackElement(u, e, track, track.getClass());
}
/**
*
* @param u
* @param element
* @param track The track into which to unmarshal. Can be null if the relevant static factory method can handle
* creating a new instance
* @param trackClass Class of track to use for unmarshalling
* @return The unmarshalled track
* @throws JAXBException
*/
protected Track unmarshalTrackElement(Unmarshaller u, Element element, AbstractTrack track, Class trackClass) throws JAXBException{
AbstractTrack ut;
synchronized (IGVSessionReader.class){
setNextTrack(track);
ut = unmarshalTrack(u, element, trackClass, trackClass);
}
ut.restorePersistentState(element);
return ut;
}
private void processColorScales(Session session, Element element, HashMap additionalInformation, String rootPath) {
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processColorScale(Session session, Element element, HashMap additionalInformation, String rootPath) {
String trackType = getAttribute(element, SessionAttribute.TYPE.getText());
String value = getAttribute(element, SessionAttribute.VALUE.getText());
setColorScaleSet(session, trackType, value);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processPreferences(Session session, Element element, HashMap additionalInformation) {
NodeList elements = element.getChildNodes();
for (int i = 0; i < elements.getLength(); i++) {
Node child = elements.item(i);
if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) {
Element childNode = (Element) child;
String name = getAttribute(childNode, SessionAttribute.NAME.getText());
String value = getAttribute(childNode, SessionAttribute.VALUE.getText());
session.setPreference(name, value);
}
}
}
/**
* Process a list of session element nodes.
*
* @param session
* @param elements
*/
private void process(Session session, NodeList elements, HashMap additionalInformation, String rootPath) {
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
process(session, childNode, additionalInformation, rootPath);
}
}
public void setColorScaleSet(Session session, String type, String value) {
if (type == null | value == null) {
return;
}
TrackType trackType = CollUtils.valueOf(TrackType.class, type.toUpperCase(), TrackType.OTHER);
// TODO -- refactor to remove instanceof / cast. Currently only ContinuousColorScale is handled
ColorScale colorScale = ColorScaleFactory.getScaleFromString(value);
if (colorScale instanceof ContinuousColorScale) {
session.setColorScale(trackType, (ContinuousColorScale) colorScale);
}
// ColorScaleFactory.setColorScale(trackType, colorScale);
}
private String getAttribute(Element element, String key) {
String value = element.getAttribute(key);
if (value != null) {
if (value.trim().equals("")) {
value = null;
}
}
return value;
}
private static JAXBContext jc = null;
public static synchronized JAXBContext getJAXBContext() throws JAXBException {
if(jc == null){
jc = JAXBContext.newInstance(registeredClasses.toArray(new Class[0]), new HashMap<String, Object>());
}
return jc;
}
/**
* Register this class with JAXB, so it can be saved and restored to a session.
* The class must conform the JAXBs requirements (e.g. no-arg constructor or factory method)
* @param clazz
*/
//@api
public static synchronized void registerClass(Class clazz){
registeredClasses.add(clazz);
jc = null;
}
/**
* Unmarshal node. We first attempt to unmarshal into the specified {@code clazz}
* if that fails, we try the superclass, and so on up.
*
* @param node
* @param unmarshalClass Class to which to use for unmarshalling
* @param firstClass The first class used for invocation. For helpful error message only
*
* @return
*/
public static AbstractTrack unmarshalTrack(Unmarshaller u, Node node, Class unmarshalClass, Class firstClass) throws JAXBException{
if(unmarshalClass == null || unmarshalClass.equals(Object.class)){
throw new JAXBException(firstClass + " and none of its superclasses are known");
}
if(AbstractTrack.knownUnknownTrackClasses.contains(unmarshalClass)){
return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass());
}
JAXBElement el;
try {
el = u.unmarshal(node, unmarshalClass);
} catch (JAXBException e) {
AbstractTrack.knownUnknownTrackClasses.add(unmarshalClass);
return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass());
}
return (AbstractTrack) el.getValue();
}
/**
* Uses #sessionReader to lookup matching tracks by id, or
* searches allTracks if sessionReader is null
* @param trackId
* @param allTracks
* @return
*/
public static Track getMatchingTrack(String trackId, List<Track> allTracks){
IGVSessionReader reader = currentReader.get();
List<Track> matchingTracks;
if(reader != null){
matchingTracks = reader.getTracksById(trackId);
}else{
if(allTracks == null) throw new IllegalStateException("No session reader and no tracks to search to resolve Track references");
matchingTracks = new ArrayList<Track>();
for(Track track: allTracks){
if(trackId.equals(track.getId())){
matchingTracks.add(track);
break;
}
}
}
if (matchingTracks == null || matchingTracks.size() == 0) {
//Either the session file is corrupted, or we just haven't loaded the relevant track yet
return null;
}else if (matchingTracks.size() >= 2) {
log.debug("Found multiple tracks with id " + trackId + ", using the first");
}
return matchingTracks.get(0);
}
}
|
src/org/broad/igv/session/IGVSessionReader.java
|
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.session;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.RegionOfInterest;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.lists.GeneList;
import org.broad.igv.lists.GeneListManager;
import org.broad.igv.renderer.ColorScale;
import org.broad.igv.renderer.ColorScaleFactory;
import org.broad.igv.renderer.ContinuousColorScale;
import org.broad.igv.track.*;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.TrackFilter;
import org.broad.igv.ui.TrackFilterElement;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.panel.TrackPanel;
import org.broad.igv.ui.panel.TrackPanelScrollPane;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.FilterElement.BooleanOperator;
import org.broad.igv.util.FilterElement.Operator;
import org.broad.igv.util.ParsingUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.Utilities;
import org.broad.igv.util.collections.CollUtils;
import org.w3c.dom.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.List;
/**
* Class to parse an IGV session file
*/
public class IGVSessionReader implements SessionReader {
private static Logger log = Logger.getLogger(IGVSessionReader.class);
private static String INPUT_FILE_KEY = "INPUT_FILE_KEY";
// Temporary values used in processing
//package-private for unit testing
Collection<ResourceLocator> dataFiles;
private Collection<ResourceLocator> missingDataFiles;
private static Map<String, String> attributeSynonymMap = new HashMap();
private boolean panelElementPresent = false;
private int version;
private IGV igv;
private static WeakReference<IGVSessionReader> currentReader;
/**
* Classes that have been registered for use with JAXB
*/
private static List<Class> registeredClasses = new ArrayList<Class>();
/**
* Map of track id -> track. It is important to maintain the order in which tracks are added, thus
* the use of LinkedHashMap. We add tracks here when loaded and remove them when attributes are specified.
*/
private final Map<String, List<Track>> leftoverTrackDictionary = Collections.synchronizedMap(new LinkedHashMap());
/**
* Map of id -> track, for second pass through when tracks reference each other
*/
private final Map<String, List<Track>> allTracks = Collections.synchronizedMap(new LinkedHashMap<String, List<Track>>());
public List<Track> getTracksById(String trackId){
return allTracks.get(trackId);
}
/**
* Map of full path -> relative path.
*/
Map<String, String> fullToRelPathMap = new HashMap<String, String>();
private Track geneTrack = null;
private Track seqTrack = null;
private boolean hasTrackElments;
//Temporary holder for generating tracks
protected static AbstractTrack nextTrack;
static {
attributeSynonymMap.put("DATA FILE", "DATA SET");
attributeSynonymMap.put("TRACK NAME", "NAME");
registerClass(AbstractTrack.class);
}
/**
* Session Element types
*/
public static enum SessionElement {
PANEL("Panel"),
PANEL_LAYOUT("PanelLayout"),
TRACK("Track"),
COLOR_SCALE("ColorScale"),
COLOR_SCALES("ColorScales"),
DATA_TRACK("DataTrack"),
DATA_TRACKS("DataTracks"),
FEATURE_TRACKS("FeatureTracks"),
DATA_FILE("DataFile"),
RESOURCE("Resource"),
RESOURCES("Resources"),
FILES("Files"),
FILTER_ELEMENT("FilterElement"),
FILTER("Filter"),
SESSION("Session"),
GLOBAL("Global"),
REGION("Region"),
REGIONS("Regions"),
DATA_RANGE("DataRange"),
PREFERENCES("Preferences"),
PROPERTY("Property"),
GENE_LIST("GeneList"),
HIDDEN_ATTRIBUTES("HiddenAttributes"),
VISIBLE_ATTRIBUTES("VisibleAttributes"),
ATTRIBUTE("Attribute"),
VISIBLE_ATTRIBUTE("VisibleAttribute"),
FRAME("Frame");
private String name;
SessionElement(String name) {
this.name = name;
}
public String getText() {
return name;
}
@Override
public String toString() {
return getText();
}
static public SessionElement findEnum(String value) {
if (value == null) {
return null;
} else {
return SessionElement.valueOf(value);
}
}
}
/**
* Session Attribute types
*/
public static enum SessionAttribute {
BOOLEAN_OPERATOR("booleanOperator"),
COLOR("color"),
ALT_COLOR("altColor"),
COLOR_MODE("colorMode"),
CHROMOSOME("chromosome"),
END_INDEX("end"),
EXPAND("expand"),
SQUISH("squish"),
DISPLAY_MODE("displayMode"),
FILTER_MATCH("match"),
FILTER_SHOW_ALL_TRACKS("showTracks"),
GENOME("genome"),
GROUP_TRACKS_BY("groupTracksBy"),
HEIGHT("height"),
ID("id"),
ITEM("item"),
LOCUS("locus"),
NAME("name"),
SAMPLE_ID("sampleID"),
RESOURCE_TYPE("resourceType"),
OPERATOR("operator"),
RELATIVE_PATH("relativePath"),
RENDERER("renderer"),
SCALE("scale"),
START_INDEX("start"),
VALUE("value"),
VERSION("version"),
VISIBLE("visible"),
WINDOW_FUNCTION("windowFunction"),
RENDER_NAME("renderName"),
GENOTYPE_HEIGHT("genotypeHeight"),
VARIANT_HEIGHT("variantHeight"),
PREVIOUS_HEIGHT("previousHeight"),
FEATURE_WINDOW("featureVisibilityWindow"),
DISPLAY_NAME("displayName"),
COLOR_SCALE("colorScale"),
HAS_GENE_TRACK("hasGeneTrack"),
HAS_SEQ_TRACK("hasSequenceTrack"),
//RESOURCE ATTRIBUTES
PATH("path"),
LABEL("label"),
SERVER_URL("serverURL"),
HYPERLINK("hyperlink"),
INFOLINK("infolink"),
URL("url"),
FEATURE_URL("featureURL"),
DESCRIPTION("description"),
TYPE("type"),
COVERAGE("coverage"),
TRACK_LINE("trackLine"),
CHR("chr"),
START("start"),
END("end");
//TODO Add the following into the Attributes
/*
ShadeBasesOption shadeBases;
boolean shadeCenters;
boolean flagUnmappedPairs;
boolean showAllBases;
int insertSizeThreshold;
boolean colorByStrand;
boolean colorByAmpliconStrand;
*/
private String name;
SessionAttribute(String name) {
this.name = name;
}
public String getText() {
return name;
}
@Override
public String toString() {
return getText();
}
}
public IGVSessionReader(IGV igv) {
this.igv = igv;
currentReader = new WeakReference<IGVSessionReader>(this);
}
/**
* @param inputStream
* @param session
* @param sessionPath @return
* @throws RuntimeException
*/
public void loadSession(InputStream inputStream, Session session, String sessionPath) {
log.debug("Load session");
Document document = null;
try {
document = Utilities.createDOMDocumentFromXmlStream(inputStream);
} catch (Exception e) {
log.error("Load session error", e);
throw new RuntimeException(e);
}
NodeList tracks = document.getElementsByTagName("Track");
hasTrackElments = tracks.getLength() > 0;
HashMap additionalInformation = new HashMap();
additionalInformation.put(INPUT_FILE_KEY, sessionPath);
NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText());
if (nodes == null || nodes.getLength() == 0) {
nodes = document.getElementsByTagName(SessionElement.SESSION.getText());
}
processRootNode(session, nodes.item(0), additionalInformation, sessionPath);
// Add tracks not explicitly allocated to panels. It is legal to define sessions with the Resources
// section only (no Panel or Track elements).
addLeftoverTracks(leftoverTrackDictionary.values());
if (igv != null) {
if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) {
igv.setGroupByAttribute(session.getGroupTracksBy());
}
if (session.isRemoveEmptyPanels()) {
igv.getMainPanel().removeEmptyDataPanels();
}
igv.resetOverlayTracks();
}
}
private void processRootNode(Session session, Node node, HashMap additionalInformation, String rootPath) {
if ((node == null) || (session == null)) {
MessageUtils.showMessage("Invalid session file: root node not found");
return;
}
String nodeName = node.getNodeName();
if (!(nodeName.equalsIgnoreCase(SessionElement.GLOBAL.getText()) || nodeName.equalsIgnoreCase(SessionElement.SESSION.getText()))) {
MessageUtils.showMessage("Session files must begin with a \"Global\" or \"Session\" element. Found: " + nodeName);
return;
}
process(session, node, additionalInformation, rootPath);
Element element = (Element) node;
String versionString = getAttribute(element, SessionAttribute.VERSION.getText());
try {
version = Integer.parseInt(versionString);
} catch (NumberFormatException e) {
log.error("Non integer version number in session file: " + versionString);
}
// Load the genome, which can be an ID, or a path or URL to a .genome or indexed fasta file.
String genomeId = getAttribute(element, SessionAttribute.GENOME.getText());
String hasGeneTrackStr = getAttribute(element, SessionAttribute.HAS_GENE_TRACK.getText());
boolean hasGeneTrack = true;
if(hasGeneTrackStr != null){
hasGeneTrack = Boolean.parseBoolean(hasGeneTrackStr);
}
boolean hasSeqTrack = hasGeneTrack;
String hasSeqTrackStr = getAttribute(element, SessionAttribute.HAS_SEQ_TRACK.getText());
if(hasSeqTrackStr != null){
hasSeqTrack = Boolean.parseBoolean(hasSeqTrackStr);
}
if (genomeId != null && genomeId.length() > 0) {
if (genomeId.equals(GenomeManager.getInstance().getGenomeId())) {
// We don't have to reload the genome, but the gene track for the current genome should be restored.
if(hasGeneTrack || hasSeqTrack){
Genome genome = GenomeManager.getInstance().getCurrentGenome();
FeatureTrack geneTrack = hasGeneTrack ? genome.getGeneTrack() : null;
IGV.getInstance().setGenomeTracks(geneTrack);
}
} else {
// Selecting a genome will actually "reset" the session so we have to
// save the path and restore it.
String sessionPath = session.getPath();
//Loads genome from list, or from server or cache
igv.selectGenomeFromList(genomeId);
if (!GenomeManager.getInstance().getGenomeId().equals(genomeId)) {
String genomePath = genomeId;
if (!ParsingUtils.pathExists(genomePath)) {
genomePath = FileUtils.getAbsolutePath(genomeId, session.getPath());
}
if (ParsingUtils.pathExists(genomePath)) {
try {
IGV.getInstance().loadGenome(genomePath, null, hasGeneTrack);
} catch (IOException e) {
throw new RuntimeException("Error loading genome: " + genomeId);
}
} else {
MessageUtils.showMessage("Warning: Could not locate genome: " + genomeId);
}
}
session.setPath(sessionPath);
}
}
//TODO Remove these nearly identical if/then statements
if(!hasGeneTrack && igv.hasGeneTrack()){
//Need to remove gene track if it was loaded because it's not supposed to be in the session
igv.removeTracks(Arrays.<Track>asList(GenomeManager.getInstance().getCurrentGenome().getGeneTrack()));
geneTrack = null;
}else{
//For later lookup and to prevent dual adding, we keep a reference to the gene track
geneTrack = GenomeManager.getInstance().getCurrentGenome().getGeneTrack();
if(geneTrack != null){
allTracks.put(geneTrack.getId(), Arrays.asList(geneTrack));
}
}
SequenceTrack tmpSeqTrack = igv.getSequenceTrack();
if(!hasSeqTrack && igv.hasSequenceTrack()){
//Need to remove seq track if it was loaded because it's not supposed to be in the session
igv.removeTracks(Arrays.<Track>asList(tmpSeqTrack));
seqTrack = null;
}else{
//For later lookup and to prevent dual adding, we keep a reference to the sequence track
seqTrack = tmpSeqTrack;
if(seqTrack != null){
allTracks.put(seqTrack.getId(), Arrays.asList(seqTrack));
}
}
session.setLocus(getAttribute(element, SessionAttribute.LOCUS.getText()));
session.setGroupTracksBy(getAttribute(element, SessionAttribute.GROUP_TRACKS_BY.getText()));
String removeEmptyTracks = getAttribute(element, "removeEmptyTracks");
if (removeEmptyTracks != null) {
try {
Boolean b = Boolean.parseBoolean(removeEmptyTracks);
session.setRemoveEmptyPanels(b);
} catch (Exception e) {
log.error("Error parsing removeEmptyTracks string: " + removeEmptyTracks, e);
}
}
session.setVersion(version);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
// ReferenceFrame.getInstance().invalidateLocationScale();
}
//TODO Check to make sure tracks are not being created twice
//TODO -- DONT DO THIS FOR NEW SESSIONS
private void addLeftoverTracks(Collection<List<Track>> tmp) {
Map<String, TrackPanel> trackPanelCache = new HashMap();
if (version < 3 || !panelElementPresent) {
log.debug("Adding \"leftover\" tracks");
//For resetting track panels later
List<Map<TrackPanelScrollPane, Integer>> trackPanelAttrs = null;
if(IGV.hasInstance()){
trackPanelAttrs = IGV.getInstance().getTrackPanelAttrs();
}
for (List<Track> tracks : tmp) {
for (Track track : tracks) {
if (track != geneTrack && track != seqTrack && track.getResourceLocator() != null) {
TrackPanel panel = trackPanelCache.get(track.getResourceLocator().getPath());
if (panel == null) {
panel = IGV.getInstance().getPanelFor(track.getResourceLocator());
trackPanelCache.put(track.getResourceLocator().getPath(), panel);
}
panel.addTrack(track);
}
}
}
if(IGV.hasInstance()){
IGV.getInstance().resetPanelHeights(trackPanelAttrs.get(0), trackPanelAttrs.get(1));
}
}
}
/**
* Process a single session element node.
*
* @param session
* @param element
*/
private void process(Session session, Node element, HashMap additionalInformation, String rootPath) {
if ((element == null) || (session == null)) {
return;
}
String nodeName = element.getNodeName();
if (nodeName.equalsIgnoreCase(SessionElement.RESOURCES.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.FILES.getText())) {
processResources(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.RESOURCE.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.DATA_FILE.getText())) {
processResource(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.REGIONS.getText())) {
processRegions(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.REGION.getText())) {
processRegion(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.GENE_LIST.getText())) {
processGeneList(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.FILTER.getText())) {
processFilter(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.FILTER_ELEMENT.getText())) {
processFilterElement(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALES.getText())) {
processColorScales(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.COLOR_SCALE.getText())) {
processColorScale(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.PREFERENCES.getText())) {
processPreferences(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.DATA_TRACKS.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.FEATURE_TRACKS.getText()) ||
nodeName.equalsIgnoreCase(SessionElement.PANEL.getText())) {
processPanel(session, (Element) element, additionalInformation, rootPath);
} else if (nodeName.equalsIgnoreCase(SessionElement.PANEL_LAYOUT.getText())) {
processPanelLayout(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.HIDDEN_ATTRIBUTES.getText())) {
processHiddenAttributes(session, (Element) element, additionalInformation);
} else if (nodeName.equalsIgnoreCase(SessionElement.VISIBLE_ATTRIBUTES.getText())) {
processVisibleAttributes(session, (Element) element, additionalInformation);
}
}
private void processResources(Session session, Element element, HashMap additionalInformation, String rootPath) {
dataFiles = new ArrayList();
missingDataFiles = new ArrayList();
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
if (missingDataFiles.size() > 0) {
StringBuffer message = new StringBuffer();
message.append("<html>The following data file(s) could not be located.<ul>");
for (ResourceLocator file : missingDataFiles) {
if (file.getDBUrl() == null) {
message.append("<li>");
message.append(file.getPath());
message.append("</li>");
} else {
message.append("<li>Server: ");
message.append(file.getDBUrl());
message.append(" Path: ");
message.append(file.getPath());
message.append("</li>");
}
}
message.append("</ul>");
message.append("Common reasons for this include: ");
message.append("<ul><li>The session or data files have been moved.</li> ");
message.append("<li>The data files are located on a drive that is not currently accessible.</li></ul>");
message.append("</html>");
MessageUtils.showMessage(message.toString());
}
if (dataFiles.size() > 0) {
final List<String> errors = new ArrayList<String>();
// Load files concurrently -- TODO, put a limit on # of threads?
List<Thread> threads = new ArrayList(dataFiles.size());
long t0 = System.currentTimeMillis();
int i = 0;
List<Runnable> synchronousLoads = new ArrayList<Runnable>();
for (final ResourceLocator locator : dataFiles) {
final String suppliedPath = locator.getPath();
final String relPath = fullToRelPathMap.get(suppliedPath);
Runnable runnable = new Runnable() {
public void run() {
List<Track> tracks = null;
try {
tracks = igv.load(locator);
for (Track track : tracks) {
if (track == null) {
log.info("Null track for resource " + locator.getPath());
continue;
}
String id = track.getId();
if (id == null) {
log.info("Null track id for resource " + locator.getPath());
continue;
}
if (relPath != null) {
id = id.replace(suppliedPath, relPath);
}
List<Track> trackList = leftoverTrackDictionary.get(id);
if (trackList == null) {
trackList = new ArrayList();
leftoverTrackDictionary.put(id, trackList);
allTracks.put(id, trackList);
}
trackList.add(track);
}
} catch (Exception e) {
log.error("Error loading resource " + locator.getPath(), e);
String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p " + e.toString() + "<br>";
errors.add(ms);
}
}
};
boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") ||
locator.getPath().endsWith(".sam");
// Run synchronously if in batch mode or if there are no "track" elments, or if this is an alignment file
// EVERYTHING IS RUN SYNCHRONOUSLY FOR NOW UNTIL WE CAN FIGURE OUT WHAT TO DO TO PREVENT MULTIPLE
// AUTHENTICATION DIALOGS
if (isAlignment || Globals.isBatch() || !hasTrackElments) {
synchronousLoads.add(runnable);
} else {
Thread t = new Thread(runnable);
threads.add(t);
t.start();
}
i++;
}
// Wait for all threads to complete
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException ignore) {
}
}
// Now load data that must be loaded synchronously
for (Runnable runnable : synchronousLoads) {
runnable.run();
}
long dt = System.currentTimeMillis() - t0;
log.debug("Total load time = " + dt);
if (errors.size() > 0) {
StringBuffer buf = new StringBuffer();
buf.append("<html>Errors were encountered loading the session:<br>");
for (String msg : errors) {
buf.append(msg);
}
MessageUtils.showMessage(buf.toString());
}
}
dataFiles = null;
}
/**
* Load a single resource.
* <p/>
* Package private for unit testing
*
* @param session
* @param element
* @param additionalInformation
*/
void processResource(Session session, Element element, HashMap additionalInformation, String rootPath) {
String nodeName = element.getNodeName();
boolean oldSession = nodeName.equals(SessionElement.DATA_FILE.getText());
String label = getAttribute(element, SessionAttribute.LABEL.getText());
String name = getAttribute(element, SessionAttribute.NAME.getText());
String sampleId = getAttribute(element, SessionAttribute.SAMPLE_ID.getText());
String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText());
String type = getAttribute(element, SessionAttribute.TYPE.getText());
String coverage = getAttribute(element, SessionAttribute.COVERAGE.getText());
String trackLine = getAttribute(element, SessionAttribute.TRACK_LINE.getText());
String colorString = getAttribute(element, SessionAttribute.COLOR.getText());
//String relPathValue = getAttribute(element, SessionAttribute.RELATIVE_PATH.getText());
//boolean isRelativePath = ((relPathValue != null) && relPathValue.equalsIgnoreCase("true"));
String serverURL = getAttribute(element, SessionAttribute.SERVER_URL.getText());
// Older sessions used the "name" attribute for the path.
String path = getAttribute(element, SessionAttribute.PATH.getText());
if (oldSession && name != null) {
path = name;
int idx = name.lastIndexOf("/");
if (idx > 0 && idx + 1 < name.length()) {
name = name.substring(idx + 1);
}
}
if (rootPath == null) {
log.error("Null root path -- this is not expected");
MessageUtils.showMessage("Unexpected error loading session: null root path");
return;
}
String absolutePath = FileUtils.getAbsolutePath(path, rootPath);
fullToRelPathMap.put(absolutePath, path);
ResourceLocator resourceLocator = new ResourceLocator(serverURL, absolutePath);
if (coverage != null) {
String absoluteCoveragePath = FileUtils.getAbsolutePath(coverage, rootPath);
resourceLocator.setCoverage(absoluteCoveragePath);
}
String url = getAttribute(element, SessionAttribute.URL.getText());
if (url == null) {
url = getAttribute(element, SessionAttribute.FEATURE_URL.getText());
}
resourceLocator.setFeatureInfoURL(url);
String infolink = getAttribute(element, SessionAttribute.HYPERLINK.getText());
if (infolink == null) {
infolink = getAttribute(element, SessionAttribute.INFOLINK.getText());
}
resourceLocator.setTrackInforURL(infolink);
// Label is deprecated in favor of name.
if (name != null) {
resourceLocator.setName(name);
} else {
resourceLocator.setName(label);
}
resourceLocator.setSampleId(sampleId);
resourceLocator.setDescription(description);
// This test added to get around earlier bug in the writer
if (type != null && !type.equals("local")) {
resourceLocator.setType(type);
}
resourceLocator.setCoverage(coverage);
resourceLocator.setTrackLine(trackLine);
if (colorString != null) {
try {
Color c = ColorUtilities.stringToColor(colorString);
resourceLocator.setColor(c);
} catch (Exception e) {
log.error("Error setting color: ", e);
}
}
dataFiles.add(resourceLocator);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processRegions(Session session, Element element, HashMap additionalInformation, String rootPath) {
session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processRegion(Session session, Element element, HashMap additionalInformation, String rootPath) {
String chromosome = getAttribute(element, SessionAttribute.CHROMOSOME.getText());
String start = getAttribute(element, SessionAttribute.START_INDEX.getText());
String end = getAttribute(element, SessionAttribute.END_INDEX.getText());
String description = getAttribute(element, SessionAttribute.DESCRIPTION.getText());
RegionOfInterest region = new RegionOfInterest(chromosome, new Integer(start), new Integer(end), description);
IGV.getInstance().addRegionOfInterest(region);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processHiddenAttributes(Session session, Element element, HashMap additionalInformation) {
// session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Set<String> attributes = new HashSet();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.ATTRIBUTE.getText())) {
attributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText()));
}
}
session.setHiddenAttributes(attributes);
}
}
/**
* For backward compatibility
*
* @param session
* @param element
* @param additionalInformation
*/
private void processVisibleAttributes(Session session, Element element, HashMap additionalInformation) {
// session.clearRegionsOfInterest();
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Set<String> visibleAttributes = new HashSet();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equals(IGVSessionReader.SessionElement.VISIBLE_ATTRIBUTE.getText())) {
visibleAttributes.add(((Element) childNode).getAttribute(IGVSessionReader.SessionAttribute.NAME.getText()));
}
}
final List<String> attributeNames = AttributeManager.getInstance().getAttributeNames();
Set<String> hiddenAttributes = new HashSet<String>(attributeNames);
hiddenAttributes.removeAll(visibleAttributes);
session.setHiddenAttributes(hiddenAttributes);
}
}
private void processGeneList(Session session, Element element, HashMap additionalInformation) {
String name = getAttribute(element, SessionAttribute.NAME.getText());
String txt = element.getTextContent();
String[] genes = txt.trim().split("\\s+");
GeneList gl = new GeneList(name, Arrays.asList(genes));
GeneListManager.getInstance().addGeneList(gl);
session.setCurrentGeneList(gl);
// Adjust frames
processFrames(element);
}
private void processFrames(Element element) {
NodeList elements = element.getChildNodes();
if (elements.getLength() > 0) {
Map<String, ReferenceFrame> frames = new HashMap();
for (ReferenceFrame f : FrameManager.getFrames()) {
frames.put(f.getName(), f);
}
List<ReferenceFrame> reorderedFrames = new ArrayList();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equalsIgnoreCase(SessionElement.FRAME.getText())) {
String frameName = getAttribute((Element) childNode, SessionAttribute.NAME.getText());
ReferenceFrame f = frames.get(frameName);
if (f != null) {
reorderedFrames.add(f);
try {
String chr = getAttribute((Element) childNode, SessionAttribute.CHR.getText());
final String startString =
getAttribute((Element) childNode, SessionAttribute.START.getText()).replace(",", "");
final String endString =
getAttribute((Element) childNode, SessionAttribute.END.getText()).replace(",", "");
int start = ParsingUtils.parseInt(startString);
int end = ParsingUtils.parseInt(endString);
org.broad.igv.feature.Locus locus = new Locus(chr, start, end);
f.jumpTo(locus);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
if (reorderedFrames.size() > 0) {
FrameManager.setFrames(reorderedFrames);
}
}
IGV.getInstance().resetFrames();
}
private void processFilter(Session session, Element element, HashMap additionalInformation, String rootPath) {
String match = getAttribute(element, SessionAttribute.FILTER_MATCH.getText());
String showAllTracks = getAttribute(element, SessionAttribute.FILTER_SHOW_ALL_TRACKS.getText());
String filterName = getAttribute(element, SessionAttribute.NAME.getText());
TrackFilter filter = new TrackFilter(filterName, null);
additionalInformation.put(SessionElement.FILTER, filter);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
// Save the filter
session.setFilter(filter);
// Set filter properties
if ("all".equalsIgnoreCase(match)) {
IGV.getInstance().setFilterMatchAll(true);
} else if ("any".equalsIgnoreCase(match)) {
IGV.getInstance().setFilterMatchAll(false);
}
if ("true".equalsIgnoreCase(showAllTracks)) {
IGV.getInstance().setFilterShowAllTracks(true);
} else {
IGV.getInstance().setFilterShowAllTracks(false);
}
}
private void processFilterElement(Session session, Element element,
HashMap additionalInformation, String rootPath) {
TrackFilter filter = (TrackFilter) additionalInformation.get(SessionElement.FILTER);
String item = getAttribute(element, SessionAttribute.ITEM.getText());
String operator = getAttribute(element, SessionAttribute.OPERATOR.getText());
String value = getAttribute(element, SessionAttribute.VALUE.getText());
String booleanOperator = getAttribute(element, SessionAttribute.BOOLEAN_OPERATOR.getText());
Operator opEnum = CollUtils.findValueOf(Operator.class, operator);
BooleanOperator boolEnum = BooleanOperator.valueOf(booleanOperator.toUpperCase());
TrackFilterElement trackFilterElement = new TrackFilterElement(filter, item,
opEnum, value, boolEnum);
filter.add(trackFilterElement);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
/**
* A counter to generate unique panel names. Needed for backward-compatibility of old session files.
*/
private int panelCounter = 1;
private void processPanel(Session session, Element element, HashMap additionalInformation, String rootPath) {
panelElementPresent = true;
String panelName = element.getAttribute("name");
if (panelName == null) {
panelName = "Panel" + panelCounter++;
}
List<Track> panelTracks = new ArrayList();
NodeList elements = element.getChildNodes();
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track?
childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) {
List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation, rootPath);
if (tracks != null) {
panelTracks.addAll(tracks);
}
} else {
process(session, childNode, additionalInformation, rootPath);
}
}
//We make a second pass through, resolving references to tracks which may have been processed afterwards.
//For instance if Track 2 referenced Track 4
//TODO Make this less hacky
for (Track track: panelTracks){
if(track instanceof FeatureTrack){
FeatureTrack featureTrack = (FeatureTrack) track;
featureTrack.updateTrackReferences(panelTracks);
}else if(track instanceof DataSourceTrack){
DataSourceTrack dataTrack = (DataSourceTrack) track;
dataTrack.updateTrackReferences(panelTracks);
}
}
TrackPanel panel = IGV.getInstance().getTrackPanel(panelName);
panel.addTracks(panelTracks);
}
private void processPanelLayout(Session session, Element element, HashMap additionalInformation) {
String nodeName = element.getNodeName();
String panelName = nodeName;
NamedNodeMap tNodeMap = element.getAttributes();
for (int i = 0; i < tNodeMap.getLength(); i++) {
Node node = tNodeMap.item(i);
String name = node.getNodeName();
if (name.equals("dividerFractions")) {
String value = node.getNodeValue();
String[] tokens = value.split(",");
double[] divs = new double[tokens.length];
try {
for (int j = 0; j < tokens.length; j++) {
divs[j] = Double.parseDouble(tokens[j]);
}
session.setDividerFractions(divs);
} catch (NumberFormatException e) {
log.error("Error parsing divider locations", e);
}
}
}
}
/**
* Process a track element. This should return a single track, but could return multiple tracks since the
* uniqueness of the track id is not enforced.
*
* @param session
* @param element
* @param additionalInformation
* @return
*/
private List<Track> processTrack(Session session, Element element, HashMap additionalInformation, String rootPath) {
String id = getAttribute(element, SessionAttribute.ID.getText());
// Get matching tracks.
List<Track> matchedTracks = allTracks.get(id);
if (matchedTracks == null) {
log.info("Warning. No tracks were found with id: " + id + " in session file");
String className = getAttribute(element, "clazz");
//We try anyway, some tracks can be reconstructed without a resource element
//They must have a source, though
try{
if(className != null && ( className.contains("FeatureTrack") || className.contains("DataSourceTrack") ) && element.hasChildNodes()){
Class clazz = Class.forName(className);
Unmarshaller u = getJAXBContext().createUnmarshaller();
Track track = unmarshalTrackElement(u, element, null, clazz);
matchedTracks = new ArrayList<Track>(Arrays.asList(track));
allTracks.put(track.getId(), matchedTracks);
}
} catch (JAXBException e) {
//pass
} catch (ClassNotFoundException e) {
//pass
}
} else {
try {
Unmarshaller u = getJAXBContext().createUnmarshaller();
for (final Track track : matchedTracks) {
// Special case for sequence & gene tracks, they need to be removed before being placed.
if (igv != null && version >= 4 && (track == geneTrack || track == seqTrack)) {
igv.removeTracks(Arrays.asList(track));
}
unmarshalTrackElement(u, element, (AbstractTrack) track);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
leftoverTrackDictionary.remove(id);
}
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
return matchedTracks;
}
private static void setNextTrack(AbstractTrack track){
nextTrack = track;
}
/**
* Used for unmarshalling track; JAXB needs a static no-arg factory method
* @return
*/
public static AbstractTrack getNextTrack(){
return nextTrack;
}
/**
* Unmarshal element into specified class
* @param u
* @param e
* @param track
* @return
* @throws JAXBException
*/
protected Track unmarshalTrackElement(Unmarshaller u, Element e, AbstractTrack track) throws JAXBException{
return unmarshalTrackElement(u, e, track, track.getClass());
}
/**
*
* @param u
* @param element
* @param track The track into which to unmarshal. Can be null if the relevant static factory method can handle
* creating a new instance
* @param trackClass Class of track to use for unmarshalling
* @return The unmarshalled track
* @throws JAXBException
*/
protected Track unmarshalTrackElement(Unmarshaller u, Element element, AbstractTrack track, Class trackClass) throws JAXBException{
AbstractTrack ut;
synchronized (IGVSessionReader.class){
setNextTrack(track);
ut = unmarshalTrack(u, element, trackClass, trackClass);
}
ut.restorePersistentState(element);
return ut;
}
private void processColorScales(Session session, Element element, HashMap additionalInformation, String rootPath) {
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processColorScale(Session session, Element element, HashMap additionalInformation, String rootPath) {
String trackType = getAttribute(element, SessionAttribute.TYPE.getText());
String value = getAttribute(element, SessionAttribute.VALUE.getText());
setColorScaleSet(session, trackType, value);
NodeList elements = element.getChildNodes();
process(session, elements, additionalInformation, rootPath);
}
private void processPreferences(Session session, Element element, HashMap additionalInformation) {
NodeList elements = element.getChildNodes();
for (int i = 0; i < elements.getLength(); i++) {
Node child = elements.item(i);
if (child.getNodeName().equalsIgnoreCase(SessionElement.PROPERTY.getText())) {
Element childNode = (Element) child;
String name = getAttribute(childNode, SessionAttribute.NAME.getText());
String value = getAttribute(childNode, SessionAttribute.VALUE.getText());
session.setPreference(name, value);
}
}
}
/**
* Process a list of session element nodes.
*
* @param session
* @param elements
*/
private void process(Session session, NodeList elements, HashMap additionalInformation, String rootPath) {
for (int i = 0; i < elements.getLength(); i++) {
Node childNode = elements.item(i);
process(session, childNode, additionalInformation, rootPath);
}
}
public void setColorScaleSet(Session session, String type, String value) {
if (type == null | value == null) {
return;
}
TrackType trackType = CollUtils.valueOf(TrackType.class, type.toUpperCase(), TrackType.OTHER);
// TODO -- refactor to remove instanceof / cast. Currently only ContinuousColorScale is handled
ColorScale colorScale = ColorScaleFactory.getScaleFromString(value);
if (colorScale instanceof ContinuousColorScale) {
session.setColorScale(trackType, (ContinuousColorScale) colorScale);
}
// ColorScaleFactory.setColorScale(trackType, colorScale);
}
private String getAttribute(Element element, String key) {
String value = element.getAttribute(key);
if (value != null) {
if (value.trim().equals("")) {
value = null;
}
}
return value;
}
private static JAXBContext jc = null;
public static synchronized JAXBContext getJAXBContext() throws JAXBException {
if(jc == null){
jc = JAXBContext.newInstance(registeredClasses.toArray(new Class[0]), new HashMap<String, Object>());
}
return jc;
}
/**
* Register this class with JAXB, so it can be saved and restored to a session.
* The class must conform the JAXBs requirements (e.g. no-arg constructor or factory method)
* @param clazz
*/
//@api
public static synchronized void registerClass(Class clazz){
registeredClasses.add(clazz);
jc = null;
}
/**
* Unmarshal node. We first attempt to unmarshal into the specified {@code clazz}
* if that fails, we try the superclass, and so on up.
*
* @param node
* @param unmarshalClass Class to which to use for unmarshalling
* @param firstClass The first class used for invocation. For helpful error message only
*
* @return
*/
public static AbstractTrack unmarshalTrack(Unmarshaller u, Node node, Class unmarshalClass, Class firstClass) throws JAXBException{
if(unmarshalClass == null || unmarshalClass.equals(Object.class)){
throw new JAXBException(firstClass + " and none of its superclasses are known");
}
if(AbstractTrack.knownUnknownTrackClasses.contains(unmarshalClass)){
return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass());
}
JAXBElement el;
try {
el = u.unmarshal(node, unmarshalClass);
} catch (JAXBException e) {
AbstractTrack.knownUnknownTrackClasses.add(unmarshalClass);
return unmarshalTrack(u, node, firstClass, unmarshalClass.getSuperclass());
}
return (AbstractTrack) el.getValue();
}
/**
* Uses #sessionReader to lookup matching tracks by id, or
* searches allTracks if sessionReader is null
* @param trackId
* @param allTracks
* @return
*/
public static Track getMatchingTrack(String trackId, List<Track> allTracks){
IGVSessionReader reader = currentReader.get();
List<Track> matchingTracks;
if(reader != null){
matchingTracks = reader.getTracksById(trackId);
}else{
if(allTracks == null) throw new IllegalStateException("No session reader and no tracks to search to resolve Track references");
matchingTracks = new ArrayList<Track>();
for(Track track: allTracks){
if(trackId.equals(track.getId())){
matchingTracks.add(track);
break;
}
}
}
if (matchingTracks == null || matchingTracks.size() == 0) {
//Either the session file is corrupted, or we just haven't loaded the relevant track yet
return null;
}else if (matchingTracks.size() >= 2) {
log.debug("Found multiple tracks with id " + trackId + ", using the first");
}
return matchingTracks.get(0);
}
}
|
Reverse equals check.
We already guard against genomeId being null, this should handle the case of no genome loaded
IGV-2021 GH #63
|
src/org/broad/igv/session/IGVSessionReader.java
|
Reverse equals check.
|
|
Java
|
mit
|
f43039da8764d0f22d7ccb9be251e7433cf3d8c7
| 0
|
arthuralee/react-native,janicduplessis/react-native,hoangpham95/react-native,exponent/react-native,hoangpham95/react-native,exponentjs/react-native,arthuralee/react-native,hammerandchisel/react-native,facebook/react-native,hoangpham95/react-native,javache/react-native,hammerandchisel/react-native,exponent/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,janicduplessis/react-native,facebook/react-native,pandiaraj44/react-native,myntra/react-native,arthuralee/react-native,myntra/react-native,myntra/react-native,exponent/react-native,pandiaraj44/react-native,javache/react-native,hoangpham95/react-native,javache/react-native,janicduplessis/react-native,javache/react-native,hammerandchisel/react-native,arthuralee/react-native,facebook/react-native,facebook/react-native,myntra/react-native,javache/react-native,hammerandchisel/react-native,myntra/react-native,exponentjs/react-native,exponentjs/react-native,javache/react-native,janicduplessis/react-native,facebook/react-native,exponent/react-native,hammerandchisel/react-native,facebook/react-native,exponentjs/react-native,janicduplessis/react-native,hammerandchisel/react-native,pandiaraj44/react-native,exponent/react-native,exponentjs/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,hoangpham95/react-native,exponentjs/react-native,exponent/react-native,javache/react-native,pandiaraj44/react-native,janicduplessis/react-native,pandiaraj44/react-native,janicduplessis/react-native,pandiaraj44/react-native,hammerandchisel/react-native,hoangpham95/react-native,javache/react-native,pandiaraj44/react-native,arthuralee/react-native,javache/react-native,exponent/react-native,hoangpham95/react-native,exponentjs/react-native,exponent/react-native,myntra/react-native,hammerandchisel/react-native,facebook/react-native,facebook/react-native,myntra/react-native,exponentjs/react-native
|
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.fabric;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import static com.facebook.react.fabric.FabricComponents.getFabricComponentName;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMaxSize;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMinSize;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaMeasureMode;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaSize;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import android.annotation.SuppressLint;
import android.os.SystemClock;
import android.view.View;
import androidx.annotation.GuardedBy;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder;
import com.facebook.debug.tags.ReactDebugOverlayTags;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.NativeMap;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.fabric.events.EventBeatManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.events.FabricEventEmitter;
import com.facebook.react.fabric.mounting.MountingManager;
import com.facebook.react.fabric.mounting.mountitems.BatchMountItem;
import com.facebook.react.fabric.mounting.mountitems.CreateMountItem;
import com.facebook.react.fabric.mounting.mountitems.DeleteMountItem;
import com.facebook.react.fabric.mounting.mountitems.DispatchCommandMountItem;
import com.facebook.react.fabric.mounting.mountitems.InsertMountItem;
import com.facebook.react.fabric.mounting.mountitems.MountItem;
import com.facebook.react.fabric.mounting.mountitems.PreAllocateViewMountItem;
import com.facebook.react.fabric.mounting.mountitems.RemoveMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateEventEmitterMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateLayoutMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateLocalDataMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdatePropsMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateStateMountItem;
import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.uimanager.ReactRoot;
import com.facebook.react.uimanager.ReactRootViewTagGenerator;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerPropertyUpdater;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.systrace.Systrace;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@SuppressLint("MissingNativeLoadLibrary")
public class FabricUIManager implements UIManager, LifecycleEventListener {
public static final String TAG = FabricUIManager.class.getSimpleName();
public static final boolean DEBUG = ReactFeatureFlags.enableFabricLogs ||
PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER);
private static final int FRAME_TIME_MS = 16;
private static final int MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS = 8;
private static final int PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY = 250;
static {
FabricSoLoader.staticInit();
}
private Binding mBinding;
private final ReactApplicationContext mReactApplicationContext;
private final MountingManager mMountingManager;
private final EventDispatcher mEventDispatcher;
private final ConcurrentHashMap<Integer, ThemedReactContext> mReactContextForRootTag =
new ConcurrentHashMap<>();
private final EventBeatManager mEventBeatManager;
private final Object mMountItemsLock = new Object();
private final Object mPreMountItemsLock = new Object();
@GuardedBy("mMountItemsLock")
private List<MountItem> mMountItems = new ArrayList<>();
@GuardedBy("mPreMountItemsLock")
private ArrayDeque<MountItem> mPreMountItems =
new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY);
@ThreadConfined(UI)
private final DispatchUIFrameCallback mDispatchUIFrameCallback;
@ThreadConfined(UI)
private boolean mIsMountingEnabled = true;
private long mRunStartTime = 0l;
private long mBatchedExecutionTime = 0l;
private long mDispatchViewUpdatesTime = 0l;
private long mCommitStartTime = 0l;
private long mLayoutTime = 0l;
private long mFinishTransactionTime = 0l;
private long mFinishTransactionCPPTime = 0l;
public FabricUIManager(
ReactApplicationContext reactContext,
ViewManagerRegistry viewManagerRegistry,
EventDispatcher eventDispatcher,
EventBeatManager eventBeatManager) {
mDispatchUIFrameCallback = new DispatchUIFrameCallback(reactContext);
mReactApplicationContext = reactContext;
mMountingManager = new MountingManager(viewManagerRegistry);
mEventDispatcher = eventDispatcher;
mEventBeatManager = eventBeatManager;
mReactApplicationContext.addLifecycleEventListener(this);
}
@Override
public <T extends View> int addRootView(
final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) {
final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
ThemedReactContext reactContext =
new ThemedReactContext(mReactApplicationContext, rootView.getContext());
mMountingManager.addRootView(rootTag, rootView);
mReactContextForRootTag.put(rootTag, reactContext);
mBinding.startSurface(rootTag, ((ReactRoot) rootView).getJSModuleName(), (NativeMap) initialProps);
if (initialUITemplate != null) {
mBinding.renderTemplateToSurface(rootTag, initialUITemplate);
}
return rootTag;
}
public <T extends View> int addRootView(
final T rootView, final String moduleName, final WritableMap initialProps, int widthMeasureSpec, int heightMeasureSpec) {
final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
ThemedReactContext reactContext =
new ThemedReactContext(mReactApplicationContext, rootView.getContext());
mMountingManager.addRootView(rootTag, rootView);
mReactContextForRootTag.put(rootTag, reactContext);
mBinding.startSurfaceWithConstraints(rootTag, moduleName, (NativeMap) initialProps,
getMinSize(widthMeasureSpec),
getMaxSize(widthMeasureSpec),
getMinSize(heightMeasureSpec),
getMaxSize(heightMeasureSpec));
return rootTag;
}
/** Method called when an event has been dispatched on the C++ side. */
@DoNotStrip
@SuppressWarnings("unused")
public void onRequestEventBeat() {
mEventDispatcher.dispatchAllEvents();
}
@Override
public void removeRootView(int reactRootTag) {
// TODO T31905686: integrate with the unmounting of Fabric React Renderer.
mMountingManager.removeRootView(reactRootTag);
mReactContextForRootTag.remove(reactRootTag);
}
@Override
public void initialize() {
mEventDispatcher.registerEventEmitter(FABRIC, new FabricEventEmitter(this));
mEventDispatcher.addBatchEventDispatchedListener(mEventBeatManager);
}
@Override
public void onCatalystInstanceDestroy() {
mEventDispatcher.removeBatchEventDispatchedListener(mEventBeatManager);
mEventDispatcher.unregisterEventEmitter(FABRIC);
mBinding.unregister();
ViewManagerPropertyUpdater.clear();
}
@DoNotStrip
@SuppressWarnings("unused")
private void preallocateView(
int rootTag,
int reactTag,
final String componentName,
@Nullable ReadableMap props,
Object stateWrapper,
boolean isLayoutable) {
ThemedReactContext context = mReactContextForRootTag.get(rootTag);
String component = getFabricComponentName(componentName);
synchronized (mPreMountItemsLock) {
mPreMountItems.add(
new PreAllocateViewMountItem(
context,
rootTag,
reactTag,
component,
props,
(StateWrapper) stateWrapper,
isLayoutable));
}
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem createMountItem(
String componentName, int reactRootTag, int reactTag, boolean isLayoutable) {
String component = getFabricComponentName(componentName);
ThemedReactContext reactContext = mReactContextForRootTag.get(reactRootTag);
if (reactContext == null) {
throw new IllegalArgumentException("Unable to find ReactContext for root: " + reactRootTag);
}
return new CreateMountItem(reactContext, reactRootTag, reactTag, component, isLayoutable);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem removeMountItem(int reactTag, int parentReactTag, int index) {
return new RemoveMountItem(reactTag, parentReactTag, index);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem insertMountItem(int reactTag, int parentReactTag, int index) {
return new InsertMountItem(reactTag, parentReactTag, index);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem deleteMountItem(int reactTag) {
return new DeleteMountItem(reactTag);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateLayoutMountItem(int reactTag, int x, int y, int width, int height) {
return new UpdateLayoutMountItem(reactTag, x, y, width, height);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updatePropsMountItem(int reactTag, ReadableMap map) {
return new UpdatePropsMountItem(reactTag, map);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateLocalDataMountItem(int reactTag, ReadableMap newLocalData) {
return new UpdateLocalDataMountItem(reactTag, newLocalData);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateStateMountItem(int reactTag, Object stateWrapper) {
return new UpdateStateMountItem(reactTag, (StateWrapper) stateWrapper);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateEventEmitterMountItem(int reactTag, Object eventEmitter) {
return new UpdateEventEmitterMountItem(reactTag, (EventEmitterWrapper) eventEmitter);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem createBatchMountItem(MountItem[] items, int size) {
return new BatchMountItem(items, size);
}
@DoNotStrip
@SuppressWarnings("unused")
private long measure(
String componentName,
ReadableMap localData,
ReadableMap props,
ReadableMap state,
float minWidth,
float maxWidth,
float minHeight,
float maxHeight) {
return mMountingManager.measure(
mReactApplicationContext,
componentName,
localData,
props,
state,
getYogaSize(minWidth, maxWidth),
getYogaMeasureMode(minWidth, maxWidth),
getYogaSize(minHeight, maxHeight),
getYogaMeasureMode(minHeight, maxHeight));
}
@Override
public void synchronouslyUpdateViewOnUIThread(int reactTag, ReadableMap props) {
long time = SystemClock.uptimeMillis();
try {
scheduleMountItems(updatePropsMountItem(reactTag, props), time, 0, time, time);
} catch (Exception ex) {
// ignore exceptions for now
// TODO T42943890: Fix animations in Fabric and remove this try/catch
}
}
/**
* This method enqueues UI operations directly to the UI thread. This might change in the future
* to enforce execution order using {@link ReactChoreographer#CallbackType}.
*/
@DoNotStrip
@SuppressWarnings("unused")
private void scheduleMountItems(
final MountItem mountItems,
long commitStartTime,
long layoutTime,
long finishTransactionStartTime,
long finishTransactionEndTime) {
// TODO T31905686: support multithreading
mCommitStartTime = commitStartTime;
mLayoutTime = layoutTime;
mFinishTransactionCPPTime = finishTransactionEndTime - finishTransactionStartTime;
mFinishTransactionTime = SystemClock.uptimeMillis() - finishTransactionStartTime;
mDispatchViewUpdatesTime = SystemClock.uptimeMillis();
synchronized (mMountItemsLock) {
mMountItems.add(mountItems);
}
if (UiThreadUtil.isOnUiThread()) {
dispatchMountItems();
}
}
@UiThread
private void dispatchMountItems() {
mRunStartTime = SystemClock.uptimeMillis();
List<MountItem> mountItemsToDispatch;
synchronized (mMountItemsLock) {
if (mMountItems.isEmpty()) {
return;
}
mountItemsToDispatch = mMountItems;
mMountItems = new ArrayList<>();
}
// If there are MountItems to dispatch, we make sure all the "pre mount items" are executed
ArrayDeque<MountItem> mPreMountItemsToDispatch = null;
synchronized (mPreMountItemsLock) {
if (!mPreMountItems.isEmpty()) {
mPreMountItemsToDispatch = mPreMountItems;
mPreMountItems = new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY);
}
}
if (mPreMountItemsToDispatch != null) {
Systrace.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
"FabricUIManager::mountViews preMountItems to execute: "
+ mPreMountItemsToDispatch.size());
while (!mPreMountItemsToDispatch.isEmpty()) {
mPreMountItemsToDispatch.pollFirst().execute(mMountingManager);
}
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
Systrace.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
"FabricUIManager::mountViews mountItems to execute: " + mountItemsToDispatch.size());
long batchedExecutionStartTime = SystemClock.uptimeMillis();
for (MountItem mountItem : mountItemsToDispatch) {
mountItem.execute(mMountingManager);
}
mBatchedExecutionTime = SystemClock.uptimeMillis() - batchedExecutionStartTime;
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
@UiThread
private void dispatchPreMountItems(long frameTimeNanos) {
Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::premountViews");
while (true) {
long timeLeftInFrame = FRAME_TIME_MS - ((System.nanoTime() - frameTimeNanos) / 1000000);
if (timeLeftInFrame < MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS) {
break;
}
MountItem preMountItemsToDispatch;
synchronized (mPreMountItemsLock) {
if (mPreMountItems.isEmpty()) {
break;
}
preMountItemsToDispatch = mPreMountItems.pollFirst();
}
preMountItemsToDispatch.execute(mMountingManager);
}
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
public void setBinding(Binding binding) {
mBinding = binding;
}
/**
* Updates the layout metrics of the root view based on the Measure specs received by parameters.
*/
@Override
public void updateRootLayoutSpecs(
final int rootTag, final int widthMeasureSpec, final int heightMeasureSpec) {
mReactApplicationContext.runOnJSQueueThread(new Runnable() {
@Override
public void run() {
mBinding.setConstraints(
rootTag,
getMinSize(widthMeasureSpec),
getMaxSize(widthMeasureSpec),
getMinSize(heightMeasureSpec),
getMaxSize(heightMeasureSpec));
}
});
}
public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap params) {
EventEmitterWrapper eventEmitter = mMountingManager.getEventEmitter(reactTag);
if (eventEmitter == null) {
// This can happen if the view has disappeared from the screen (because of async events)
FLog.d(TAG, "Unable to invoke event: " + eventName + " for reactTag: " + reactTag);
return;
}
eventEmitter.invoke(eventName, params);
}
@Override
public void onHostResume() {
ReactChoreographer.getInstance()
.postFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
@Override
public void onHostPause() {
ReactChoreographer.getInstance()
.removeFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
@Override
public void onHostDestroy() {}
@Override
public void dispatchCommand(
final int reactTag, final int commandId, @Nullable final ReadableArray commandArgs) {
synchronized (mMountItemsLock) {
mMountItems.add(new DispatchCommandMountItem(reactTag, commandId, commandArgs));
}
}
@Override
public void setJSResponder(int reactTag, boolean blockNativeResponder) {
// do nothing for now.
}
@Override
public void clearJSResponder() {
// do nothing for now.
}
@Override
public void profileNextBatch() {
// TODO T31905686: Remove this method and add support for multi-threading performance counters
}
@Override
public Map<String, Long> getPerformanceCounters() {
HashMap<String, Long> performanceCounters = new HashMap<>();
performanceCounters.put("CommitStartTime", mCommitStartTime);
performanceCounters.put("LayoutTime", mLayoutTime);
performanceCounters.put("DispatchViewUpdatesTime", mDispatchViewUpdatesTime);
performanceCounters.put("RunStartTime", mRunStartTime);
performanceCounters.put("BatchedExecutionTime", mBatchedExecutionTime);
performanceCounters.put("FinishFabricTransactionTime", mFinishTransactionTime);
performanceCounters.put("FinishFabricTransactionCPPTime", mFinishTransactionCPPTime);
return performanceCounters;
}
private class DispatchUIFrameCallback extends GuardedFrameCallback {
private DispatchUIFrameCallback(ReactContext reactContext) {
super(reactContext);
}
@Override
public void doFrameGuarded(long frameTimeNanos) {
if (!mIsMountingEnabled) {
FLog.w(
ReactConstants.TAG,
"Not flushing pending UI operations because of previously thrown Exception");
return;
}
try {
dispatchPreMountItems(frameTimeNanos);
dispatchMountItems();
} catch (Exception ex) {
FLog.i(ReactConstants.TAG, "Exception thrown when executing UIFrameGuarded", ex);
mIsMountingEnabled = false;
throw ex;
} finally {
ReactChoreographer.getInstance()
.postFrameCallback(
ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
}
}
}
|
ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
|
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.fabric;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import static com.facebook.react.fabric.FabricComponents.getFabricComponentName;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMaxSize;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMinSize;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaMeasureMode;
import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaSize;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import android.annotation.SuppressLint;
import android.os.SystemClock;
import android.view.View;
import androidx.annotation.GuardedBy;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder;
import com.facebook.debug.tags.ReactDebugOverlayTags;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.NativeMap;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.fabric.events.EventBeatManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.events.FabricEventEmitter;
import com.facebook.react.fabric.mounting.MountingManager;
import com.facebook.react.fabric.mounting.mountitems.BatchMountItem;
import com.facebook.react.fabric.mounting.mountitems.CreateMountItem;
import com.facebook.react.fabric.mounting.mountitems.DeleteMountItem;
import com.facebook.react.fabric.mounting.mountitems.DispatchCommandMountItem;
import com.facebook.react.fabric.mounting.mountitems.InsertMountItem;
import com.facebook.react.fabric.mounting.mountitems.MountItem;
import com.facebook.react.fabric.mounting.mountitems.PreAllocateViewMountItem;
import com.facebook.react.fabric.mounting.mountitems.RemoveMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateEventEmitterMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateLayoutMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateLocalDataMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdatePropsMountItem;
import com.facebook.react.fabric.mounting.mountitems.UpdateStateMountItem;
import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.uimanager.ReactRoot;
import com.facebook.react.uimanager.ReactRootViewTagGenerator;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerPropertyUpdater;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.systrace.Systrace;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@SuppressLint("MissingNativeLoadLibrary")
public class FabricUIManager implements UIManager, LifecycleEventListener {
public static final String TAG = FabricUIManager.class.getSimpleName();
public static final boolean DEBUG = ReactFeatureFlags.enableFabricLogs ||
PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER);
private static final int FRAME_TIME_MS = 16;
private static final int MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS = 8;
private static final int PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY = 250;
static {
FabricSoLoader.staticInit();
}
private Binding mBinding;
private final ReactApplicationContext mReactApplicationContext;
private final MountingManager mMountingManager;
private final EventDispatcher mEventDispatcher;
private final ConcurrentHashMap<Integer, ThemedReactContext> mReactContextForRootTag =
new ConcurrentHashMap<>();
private final EventBeatManager mEventBeatManager;
private final Object mMountItemsLock = new Object();
private final Object mPreMountItemsLock = new Object();
@GuardedBy("mMountItemsLock")
private List<MountItem> mMountItems = new ArrayList<>();
@GuardedBy("mPreMountItemsLock")
private ArrayDeque<MountItem> mPreMountItems =
new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY);
@ThreadConfined(UI)
private final DispatchUIFrameCallback mDispatchUIFrameCallback;
@ThreadConfined(UI)
private boolean mIsMountingEnabled = true;
private long mRunStartTime = 0l;
private long mBatchedExecutionTime = 0l;
private long mDispatchViewUpdatesTime = 0l;
private long mCommitStartTime = 0l;
private long mLayoutTime = 0l;
private long mFinishTransactionTime = 0l;
private long mFinishTransactionCPPTime = 0l;
public FabricUIManager(
ReactApplicationContext reactContext,
ViewManagerRegistry viewManagerRegistry,
EventDispatcher eventDispatcher,
EventBeatManager eventBeatManager) {
mDispatchUIFrameCallback = new DispatchUIFrameCallback(reactContext);
mReactApplicationContext = reactContext;
mMountingManager = new MountingManager(viewManagerRegistry);
mEventDispatcher = eventDispatcher;
mEventBeatManager = eventBeatManager;
mReactApplicationContext.addLifecycleEventListener(this);
}
@Override
public <T extends View> int addRootView(
final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) {
final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
ThemedReactContext reactContext =
new ThemedReactContext(mReactApplicationContext, rootView.getContext());
mMountingManager.addRootView(rootTag, rootView);
mReactContextForRootTag.put(rootTag, reactContext);
mBinding.startSurface(rootTag, ((ReactRoot) rootView).getJSModuleName(), (NativeMap) initialProps);
if (initialUITemplate != null) {
mBinding.renderTemplateToSurface(rootTag, initialUITemplate);
}
return rootTag;
}
public <T extends View> int addRootView(
final T rootView, final String moduleName, final WritableMap initialProps, int widthMeasureSpec, int heightMeasureSpec) {
final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag();
ThemedReactContext reactContext =
new ThemedReactContext(mReactApplicationContext, rootView.getContext());
mMountingManager.addRootView(rootTag, rootView);
mReactContextForRootTag.put(rootTag, reactContext);
mBinding.startSurfaceWithConstraints(rootTag, moduleName, (NativeMap) initialProps,
getMinSize(widthMeasureSpec),
getMaxSize(widthMeasureSpec),
getMinSize(heightMeasureSpec),
getMaxSize(heightMeasureSpec));
return rootTag;
}
/** Method called when an event has been dispatched on the C++ side. */
@DoNotStrip
@SuppressWarnings("unused")
public void onRequestEventBeat() {
mEventDispatcher.dispatchAllEvents();
}
@Override
public void removeRootView(int reactRootTag) {
// TODO T31905686: integrate with the unmounting of Fabric React Renderer.
mMountingManager.removeRootView(reactRootTag);
mReactContextForRootTag.remove(reactRootTag);
}
@Override
public void initialize() {
mEventDispatcher.registerEventEmitter(FABRIC, new FabricEventEmitter(this));
mEventDispatcher.addBatchEventDispatchedListener(mEventBeatManager);
}
@Override
public void onCatalystInstanceDestroy() {
mEventDispatcher.removeBatchEventDispatchedListener(mEventBeatManager);
mEventDispatcher.unregisterEventEmitter(FABRIC);
mBinding.unregister();
ViewManagerPropertyUpdater.clear();
}
@DoNotStrip
@SuppressWarnings("unused")
private void preallocateView(
int rootTag,
int reactTag,
final String componentName,
@Nullable ReadableMap props,
Object stateWrapper,
boolean isLayoutable) {
ThemedReactContext context = mReactContextForRootTag.get(rootTag);
String component = getFabricComponentName(componentName);
synchronized (mPreMountItemsLock) {
mPreMountItems.add(
new PreAllocateViewMountItem(
context,
rootTag,
reactTag,
component,
props,
(StateWrapper) stateWrapper,
isLayoutable));
}
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem createMountItem(
String componentName, int reactRootTag, int reactTag, boolean isLayoutable) {
String component = getFabricComponentName(componentName);
ThemedReactContext reactContext = mReactContextForRootTag.get(reactRootTag);
if (reactContext == null) {
throw new IllegalArgumentException("Unable to find ReactContext for root: " + reactRootTag);
}
return new CreateMountItem(reactContext, reactRootTag, reactTag, component, isLayoutable);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem removeMountItem(int reactTag, int parentReactTag, int index) {
return new RemoveMountItem(reactTag, parentReactTag, index);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem insertMountItem(int reactTag, int parentReactTag, int index) {
return new InsertMountItem(reactTag, parentReactTag, index);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem deleteMountItem(int reactTag) {
return new DeleteMountItem(reactTag);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateLayoutMountItem(int reactTag, int x, int y, int width, int height) {
return new UpdateLayoutMountItem(reactTag, x, y, width, height);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updatePropsMountItem(int reactTag, ReadableMap map) {
return new UpdatePropsMountItem(reactTag, map);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateLocalDataMountItem(int reactTag, ReadableMap newLocalData) {
return new UpdateLocalDataMountItem(reactTag, newLocalData);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateStateMountItem(int reactTag, Object stateWrapper) {
return new UpdateStateMountItem(reactTag, (StateWrapper) stateWrapper);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem updateEventEmitterMountItem(int reactTag, Object eventEmitter) {
return new UpdateEventEmitterMountItem(reactTag, (EventEmitterWrapper) eventEmitter);
}
@DoNotStrip
@SuppressWarnings("unused")
private MountItem createBatchMountItem(MountItem[] items, int size) {
return new BatchMountItem(items, size);
}
@DoNotStrip
@SuppressWarnings("unused")
private long measure(
String componentName,
ReadableMap localData,
ReadableMap props,
ReadableMap state,
float minWidth,
float maxWidth,
float minHeight,
float maxHeight) {
return mMountingManager.measure(
mReactApplicationContext,
componentName,
localData,
props,
state,
getYogaSize(minWidth, maxWidth),
getYogaMeasureMode(minWidth, maxWidth),
getYogaSize(minHeight, maxHeight),
getYogaMeasureMode(minHeight, maxHeight));
}
@Override
public void synchronouslyUpdateViewOnUIThread(int reactTag, ReadableMap props) {
long time = SystemClock.uptimeMillis();
try {
scheduleMountItems(updatePropsMountItem(reactTag, props), time, 0, time, time);
} catch (Exception ex) {
// ignore exceptions for now
// TODO T42943890: Fix animations in Fabric and remove this try/catch
}
}
/**
* This method enqueues UI operations directly to the UI thread. This might change in the future
* to enforce execution order using {@link ReactChoreographer#CallbackType}.
*/
@DoNotStrip
@SuppressWarnings("unused")
private void scheduleMountItems(
final MountItem mountItems,
long commitStartTime,
long layoutTime,
long finishTransactionStartTime,
long finishTransactionEndTime) {
// TODO T31905686: support multithreading
mCommitStartTime = commitStartTime;
mLayoutTime = layoutTime;
mFinishTransactionCPPTime = finishTransactionEndTime - finishTransactionStartTime;
mFinishTransactionTime = SystemClock.uptimeMillis() - finishTransactionStartTime;
mDispatchViewUpdatesTime = SystemClock.uptimeMillis();
synchronized (mMountItemsLock) {
mMountItems.add(mountItems);
}
if (UiThreadUtil.isOnUiThread()) {
dispatchMountItems();
}
}
@UiThread
private void dispatchMountItems() {
mRunStartTime = SystemClock.uptimeMillis();
List<MountItem> mountItemsToDispatch;
synchronized (mMountItemsLock) {
if (mMountItems.isEmpty()) {
return;
}
mountItemsToDispatch = mMountItems;
mMountItems = new ArrayList<>();
}
// If there are MountItems to dispatch, we make sure all the "pre mount items" are executed
ArrayDeque<MountItem> mPreMountItemsToDispatch = null;
synchronized (mPreMountItemsLock) {
if (!mPreMountItems.isEmpty()) {
mPreMountItemsToDispatch = mPreMountItems;
mPreMountItems = new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY);
}
}
if (mPreMountItemsToDispatch != null) {
Systrace.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
"FabricUIManager::mountViews preMountItems to execute: "
+ mPreMountItemsToDispatch.size());
while (!mPreMountItemsToDispatch.isEmpty()) {
mPreMountItemsToDispatch.pollFirst().execute(mMountingManager);
}
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
Systrace.beginSection(
Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
"FabricUIManager::mountViews mountItems to execute: " + mountItemsToDispatch.size());
long batchedExecutionStartTime = SystemClock.uptimeMillis();
for (MountItem mountItem : mountItemsToDispatch) {
mountItem.execute(mMountingManager);
}
mBatchedExecutionTime = SystemClock.uptimeMillis() - batchedExecutionStartTime;
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
@UiThread
private void dispatchPreMountItems(long frameTimeNanos) {
Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::premountViews");
while (true) {
long timeLeftInFrame = FRAME_TIME_MS - ((System.nanoTime() - frameTimeNanos) / 1000000);
if (timeLeftInFrame < MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS) {
break;
}
MountItem preMountItemsToDispatch;
synchronized (mPreMountItemsLock) {
if (mPreMountItems.isEmpty()) {
break;
}
preMountItemsToDispatch = mPreMountItems.pollFirst();
}
preMountItemsToDispatch.execute(mMountingManager);
}
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
public void setBinding(Binding binding) {
mBinding = binding;
}
/**
* Updates the layout metrics of the root view based on the Measure specs received by parameters.
*/
@Override
public void updateRootLayoutSpecs(
final int rootTag, final int widthMeasureSpec, final int heightMeasureSpec) {
mBinding.setConstraints(
rootTag,
getMinSize(widthMeasureSpec),
getMaxSize(widthMeasureSpec),
getMinSize(heightMeasureSpec),
getMaxSize(heightMeasureSpec));
}
public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap params) {
EventEmitterWrapper eventEmitter = mMountingManager.getEventEmitter(reactTag);
if (eventEmitter == null) {
// This can happen if the view has disappeared from the screen (because of async events)
FLog.d(TAG, "Unable to invoke event: " + eventName + " for reactTag: " + reactTag);
return;
}
eventEmitter.invoke(eventName, params);
}
@Override
public void onHostResume() {
ReactChoreographer.getInstance()
.postFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
@Override
public void onHostPause() {
ReactChoreographer.getInstance()
.removeFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
@Override
public void onHostDestroy() {}
@Override
public void dispatchCommand(
final int reactTag, final int commandId, @Nullable final ReadableArray commandArgs) {
synchronized (mMountItemsLock) {
mMountItems.add(new DispatchCommandMountItem(reactTag, commandId, commandArgs));
}
}
@Override
public void setJSResponder(int reactTag, boolean blockNativeResponder) {
// do nothing for now.
}
@Override
public void clearJSResponder() {
// do nothing for now.
}
@Override
public void profileNextBatch() {
// TODO T31905686: Remove this method and add support for multi-threading performance counters
}
@Override
public Map<String, Long> getPerformanceCounters() {
HashMap<String, Long> performanceCounters = new HashMap<>();
performanceCounters.put("CommitStartTime", mCommitStartTime);
performanceCounters.put("LayoutTime", mLayoutTime);
performanceCounters.put("DispatchViewUpdatesTime", mDispatchViewUpdatesTime);
performanceCounters.put("RunStartTime", mRunStartTime);
performanceCounters.put("BatchedExecutionTime", mBatchedExecutionTime);
performanceCounters.put("FinishFabricTransactionTime", mFinishTransactionTime);
performanceCounters.put("FinishFabricTransactionCPPTime", mFinishTransactionCPPTime);
return performanceCounters;
}
private class DispatchUIFrameCallback extends GuardedFrameCallback {
private DispatchUIFrameCallback(ReactContext reactContext) {
super(reactContext);
}
@Override
public void doFrameGuarded(long frameTimeNanos) {
if (!mIsMountingEnabled) {
FLog.w(
ReactConstants.TAG,
"Not flushing pending UI operations because of previously thrown Exception");
return;
}
try {
dispatchPreMountItems(frameTimeNanos);
dispatchMountItems();
} catch (Exception ex) {
FLog.i(ReactConstants.TAG, "Exception thrown when executing UIFrameGuarded", ex);
mIsMountingEnabled = false;
throw ex;
} finally {
ReactChoreographer.getInstance()
.postFrameCallback(
ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback);
}
}
}
}
|
Force setConstraints to run in the JS Thread
Summary: This diff forces the method: scheduler.constraintSurfaceLayout to run on the JS thread.
Reviewed By: JoshuaGross
Differential Revision: D15845768
fbshipit-source-id: de2aa69f301770aaf6cb7c3f5670548a3b6110df
|
ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
|
Force setConstraints to run in the JS Thread
|
|
Java
|
mit
|
8cfb7c8d7af52603a8b8ae7f7f4007cadba56e33
| 0
|
igm-team/atav,igm-team/atav,igm-team/atav,igm-team/atav
|
package function.cohort.vargeno;
import function.annotation.base.Annotation;
import function.annotation.base.PolyphenManager;
import function.cohort.base.GenotypeLevelFilterCommand;
import function.external.exac.ExACCommand;
import function.external.exac.ExACManager;
import function.external.gnomad.GnomADCommand;
import function.external.gnomad.GnomADManager;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.StringJoiner;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.ArrayUtils;
import utils.CommonCommand;
import utils.ErrorManager;
import utils.FormatManager;
import utils.LogManager;
/**
*
* @author nick
*/
public class ListVarGenoLite {
public static BufferedWriter bwGenotypes = null;
public static final String genotypeFilePath = CommonCommand.outputPath + "genotypes.csv";
public static final String VARIANT_ID_HEADER = "Variant ID";
public static final String STABLE_ID_HEADER = "Transcript Stable Id";
public static int STABLE_ID_HEADER_INDEX;
public static final String EFFECT_HEADER = "Effect";
public static int EFFECT_HEADER_INDEX;
public static final String HAS_CCDS_HEADER = "Has CCDS Transcript";
public static int HAS_CCDS_HEADER_INDEX;
public static final String HGVS_c_HEADER = "HGVS_c";
public static int HGVS_c_HEADER_INDEX;
public static final String HGVS_p_HEADER = "HGVS_p";
public static int HGVS_p_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_SCORE_HEADER = "Polyphen Humdiv Score";
public static int POLYPHEN_HUMDIV_SCORE_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_PREDICTION_HEADER = "Polyphen Humdiv Prediction";
public static int POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_SCORE_CCDS_HEADER = "Polyphen Humdiv Score (CCDS)";
public static int POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER = "Polyphen Humdiv Prediction (CCDS)";
public static int POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_SCORE_HEADER = "Polyphen Humvar Score";
public static int POLYPHEN_HUMVAR_SCORE_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_PREDICTION_HEADER = "Polyphen Humvar Prediction";
public static int POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_SCORE_CCDS_HEADER = "Polyphen Humvar Score (CCDS)";
public static int POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER = "Polyphen Humvar Prediction (CCDS)";
public static int POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX;
public static final String GENE_NAME_HEADER = "Gene Name";
public static int GENE_NAME_HEADER_INDEX;
public static final String ALL_ANNOTATION_HEADER = "All Effect Gene Transcript HGVS_c HGVS_p Polyphen_Humdiv Polyphen_Humvar";
public static int ALL_ANNOTATION_HEADER_INDEX;
public static final String SAMPLE_NAME_HEADER = "Sample Name";
public static final String QC_FAIL_CASE_HEADER = "QC Fail Case";
public static final String QC_FAIL_CTRL_HEADER = "QC Fail Ctrl";
public static final String LOO_AF_HEADER = "LOO AF";
public void initOutput() {
try {
bwGenotypes = new BufferedWriter(new FileWriter(genotypeFilePath));
} catch (IOException ex) {
ErrorManager.send(ex);
}
}
public void closeOutput() {
try {
bwGenotypes.flush();
bwGenotypes.close();
} catch (IOException ex) {
ErrorManager.send(ex);
}
}
public void run() {
try {
LogManager.writeAndPrint("Start running list var geno lite function");
initOutput();
boolean isHeaderOutput = false;
Iterable<CSVRecord> records = getRecords();
for (CSVRecord record : records) {
if (!isHeaderOutput) {
outputHeader(record);
isHeaderOutput = true;
}
VariantLite variantLite = new VariantLite(record);
// output qualifed record to genotypes file
if (variantLite.isValid()) {
outputGenotype(variantLite);
}
}
closeOutput();
} catch (Exception e) {
ErrorManager.send(e);
}
}
private static String[] getHeaders() {
String[] headers = {
VARIANT_ID_HEADER,
STABLE_ID_HEADER,
EFFECT_HEADER,
HAS_CCDS_HEADER,
HGVS_c_HEADER,
HGVS_p_HEADER,
POLYPHEN_HUMDIV_SCORE_HEADER,
POLYPHEN_HUMDIV_PREDICTION_HEADER,
POLYPHEN_HUMDIV_SCORE_CCDS_HEADER,
POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER,
POLYPHEN_HUMVAR_SCORE_HEADER,
POLYPHEN_HUMVAR_PREDICTION_HEADER,
POLYPHEN_HUMVAR_SCORE_CCDS_HEADER,
POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER,
GENE_NAME_HEADER,
ALL_ANNOTATION_HEADER,
SAMPLE_NAME_HEADER,
QC_FAIL_CASE_HEADER,
QC_FAIL_CTRL_HEADER,
LOO_AF_HEADER
};
if (ExACCommand.isIncludeExac) {
headers = (String[]) ArrayUtils.addAll(headers, ExACManager.getTitle().split(","));
}
if (GnomADCommand.isIncludeGnomADExome) {
headers = (String[]) ArrayUtils.addAll(headers, GnomADManager.getExomeTitle().split(","));
}
if (GnomADCommand.isIncludeGnomADGenome) {
headers = (String[]) ArrayUtils.addAll(headers, GnomADManager.getGenomeTitle().split(","));
}
return headers;
}
public Iterable<CSVRecord> getRecords() throws FileNotFoundException, IOException {
Reader in = new FileReader(GenotypeLevelFilterCommand.genotypeFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(getHeaders())
.withFirstRecordAsHeader()
.parse(in);
return records;
}
public void outputHeader(CSVRecord record) throws IOException {
StringJoiner sj = new StringJoiner(",");
for (int headerIndex = 0; headerIndex < record.getParser().getHeaderNames().size(); headerIndex++) {
String value = record.getParser().getHeaderNames().get(headerIndex);
switch (value) {
case STABLE_ID_HEADER:
STABLE_ID_HEADER_INDEX = headerIndex;
break;
case EFFECT_HEADER:
EFFECT_HEADER_INDEX = headerIndex;
break;
case HAS_CCDS_HEADER:
HAS_CCDS_HEADER_INDEX = headerIndex;
break;
case HGVS_c_HEADER:
HGVS_c_HEADER_INDEX = headerIndex;
break;
case HGVS_p_HEADER:
HGVS_p_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_SCORE_HEADER:
POLYPHEN_HUMDIV_SCORE_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_PREDICTION_HEADER:
POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_SCORE_CCDS_HEADER:
POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER:
POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_SCORE_HEADER:
POLYPHEN_HUMVAR_SCORE_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_PREDICTION_HEADER:
POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_SCORE_CCDS_HEADER:
POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER:
POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX = headerIndex;
break;
case GENE_NAME_HEADER:
GENE_NAME_HEADER_INDEX = headerIndex;
break;
case ALL_ANNOTATION_HEADER:
ALL_ANNOTATION_HEADER_INDEX = headerIndex;
break;
default:
break;
}
sj.add(value);
}
bwGenotypes.write(sj.toString());
bwGenotypes.newLine();
}
public void outputGenotype(VariantLite variantLite) throws IOException {
CSVRecord record = variantLite.getRecord();
Annotation mostDamagingAnnotation = variantLite.getMostDamagingAnnotation();
String allAnnotation = variantLite.getAllAnnotation();
StringJoiner sj = new StringJoiner(",");
for (int headerIndex = 0; headerIndex < record.size(); headerIndex++) {
String value = "";
if (headerIndex == STABLE_ID_HEADER_INDEX) {
value = mostDamagingAnnotation.getStableId();
} else if (headerIndex == EFFECT_HEADER_INDEX) {
value = mostDamagingAnnotation.effect;
} else if (headerIndex == HAS_CCDS_HEADER_INDEX) {
value = Boolean.toString(mostDamagingAnnotation.hasCCDS);
} else if (headerIndex == HGVS_c_HEADER_INDEX) {
value = mostDamagingAnnotation.HGVS_c;
} else if (headerIndex == HGVS_p_HEADER_INDEX) {
value = mostDamagingAnnotation.HGVS_p;
} else if (headerIndex == POLYPHEN_HUMDIV_SCORE_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumdiv);
} else if (headerIndex == POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumdiv, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumdivCCDS);
} else if (headerIndex == POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumdivCCDS, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMVAR_SCORE_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumvar);
} else if (headerIndex == POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumvar, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumvarCCDS);
} else if (headerIndex == POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumvarCCDS, mostDamagingAnnotation.effect);
} else if (headerIndex == GENE_NAME_HEADER_INDEX) {
value = "'" + mostDamagingAnnotation.geneName + "'";
} else if (headerIndex == ALL_ANNOTATION_HEADER_INDEX) {
value = allAnnotation;
} else {
value = record.get(headerIndex);
}
if (value.contains(",")) {
value = FormatManager.appendDoubleQuote(value);
}
sj.add(value);
}
bwGenotypes.write(sj.toString());
bwGenotypes.newLine();
}
}
|
src/main/java/function/cohort/vargeno/ListVarGenoLite.java
|
package function.cohort.vargeno;
import function.annotation.base.Annotation;
import function.annotation.base.PolyphenManager;
import function.cohort.base.GenotypeLevelFilterCommand;
import function.external.exac.ExACCommand;
import function.external.exac.ExACManager;
import function.external.gnomad.GnomADCommand;
import function.external.gnomad.GnomADManager;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.StringJoiner;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.ArrayUtils;
import utils.CommonCommand;
import utils.ErrorManager;
import utils.FormatManager;
import utils.LogManager;
/**
*
* @author nick
*/
public class ListVarGenoLite {
public static BufferedWriter bwGenotypes = null;
public static final String genotypeFilePath = CommonCommand.outputPath + "genotypes.csv";
public static final String VARIANT_ID_HEADER = "Variant ID";
public static final String STABLE_ID_HEADER = "Transcript Stable Id";
public static int STABLE_ID_HEADER_INDEX;
public static final String EFFECT_HEADER = "Effect";
public static int EFFECT_HEADER_INDEX;
public static final String HAS_CCDS_HEADER = "Has CCDS Transcript";
public static int HAS_CCDS_HEADER_INDEX;
public static final String HGVS_c_HEADER = "HGVS_c";
public static int HGVS_c_HEADER_INDEX;
public static final String HGVS_p_HEADER = "HGVS_p";
public static int HGVS_p_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_SCORE_HEADER = "Polyphen Humdiv Score";
public static int POLYPHEN_HUMDIV_SCORE_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_PREDICTION_HEADER = "Polyphen Humdiv Prediction";
public static int POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_SCORE_CCDS_HEADER = "Polyphen Humdiv Score (CCDS)";
public static int POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER = "Polyphen Humdiv Prediction (CCDS)";
public static int POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_SCORE_HEADER = "Polyphen Humvar Score";
public static int POLYPHEN_HUMVAR_SCORE_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_PREDICTION_HEADER = "Polyphen Humvar Prediction";
public static int POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_SCORE_CCDS_HEADER = "Polyphen Humvar Score (CCDS)";
public static int POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX;
public static final String POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER = "Polyphen Humvar Prediction (CCDS)";
public static int POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX;
public static final String GENE_NAME_HEADER = "Gene Name";
public static int GENE_NAME_HEADER_INDEX;
public static final String ALL_ANNOTATION_HEADER = "All Effect Gene Transcript HGVS_c HGVS_p Polyphen_Humdiv Polyphen_Humvar";
public static int ALL_ANNOTATION_HEADER_INDEX;
public static final String SAMPLE_NAME_HEADER = "Sample Name";
public static final String QC_FAIL_CASE_HEADER = "QC Fail Case";
public static final String QC_FAIL_CTRL_HEADER = "QC Fail Ctrl";
public static final String LOO_AF_HEADER = "LOO AF";
public void initOutput() {
try {
bwGenotypes = new BufferedWriter(new FileWriter(genotypeFilePath));
} catch (IOException ex) {
ErrorManager.send(ex);
}
}
public void closeOutput() {
try {
bwGenotypes.flush();
bwGenotypes.close();
} catch (IOException ex) {
ErrorManager.send(ex);
}
}
public void run() {
try {
LogManager.writeAndPrint("Start running list var geno lite function");
initOutput();
boolean isHeaderOutput = false;
Iterable<CSVRecord> records = getRecords();
for (CSVRecord record : records) {
if (!isHeaderOutput) {
outputHeader(record);
isHeaderOutput = true;
}
VariantLite variantLite = new VariantLite(record);
// output qualifed record to genotypes file
if (variantLite.isValid()) {
outputGenotype(variantLite);
}
}
closeOutput();
} catch (Exception e) {
ErrorManager.send(e);
}
}
private static String[] getHeaders() {
String[] headers = {
VARIANT_ID_HEADER,
STABLE_ID_HEADER,
EFFECT_HEADER,
HAS_CCDS_HEADER,
HGVS_c_HEADER,
HGVS_p_HEADER,
POLYPHEN_HUMDIV_SCORE_HEADER,
POLYPHEN_HUMDIV_PREDICTION_HEADER,
POLYPHEN_HUMDIV_SCORE_CCDS_HEADER,
POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER,
POLYPHEN_HUMVAR_SCORE_HEADER,
POLYPHEN_HUMVAR_PREDICTION_HEADER,
POLYPHEN_HUMVAR_SCORE_CCDS_HEADER,
POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER,
GENE_NAME_HEADER,
ALL_ANNOTATION_HEADER,
SAMPLE_NAME_HEADER,
QC_FAIL_CASE_HEADER,
QC_FAIL_CTRL_HEADER,
LOO_AF_HEADER
};
if (ExACCommand.isIncludeExac) {
headers = (String[]) ArrayUtils.addAll(headers, ExACManager.getTitle().split(","));
}
if (GnomADCommand.isIncludeGnomADExome) {
headers = (String[]) ArrayUtils.addAll(headers, GnomADManager.getExomeTitle().split(","));
}
if (GnomADCommand.isIncludeGnomADGenome) {
headers = (String[]) ArrayUtils.addAll(headers, GnomADManager.getGenomeTitle().split(","));
}
return headers;
}
public Iterable<CSVRecord> getRecords() throws FileNotFoundException, IOException {
Reader in = new FileReader(GenotypeLevelFilterCommand.genotypeFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(getHeaders())
.withFirstRecordAsHeader()
.parse(in);
return records;
}
public void outputHeader(CSVRecord record) throws IOException {
StringJoiner sj = new StringJoiner(",");
for (int headerIndex = 0; headerIndex < record.getParser().getHeaderNames().size(); headerIndex++) {
String value = record.getParser().getHeaderNames().get(headerIndex);
switch (value) {
case STABLE_ID_HEADER:
STABLE_ID_HEADER_INDEX = headerIndex;
break;
case EFFECT_HEADER:
EFFECT_HEADER_INDEX = headerIndex;
break;
case HAS_CCDS_HEADER:
HAS_CCDS_HEADER_INDEX = headerIndex;
break;
case HGVS_c_HEADER:
HGVS_c_HEADER_INDEX = headerIndex;
break;
case HGVS_p_HEADER:
HGVS_p_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_SCORE_HEADER:
POLYPHEN_HUMDIV_SCORE_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_PREDICTION_HEADER:
POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_SCORE_CCDS_HEADER:
POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER:
POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_SCORE_HEADER:
POLYPHEN_HUMVAR_SCORE_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_PREDICTION_HEADER:
POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_SCORE_CCDS_HEADER:
POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX = headerIndex;
break;
case POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER:
POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX = headerIndex;
break;
case GENE_NAME_HEADER:
GENE_NAME_HEADER_INDEX = headerIndex;
break;
case ALL_ANNOTATION_HEADER:
ALL_ANNOTATION_HEADER_INDEX = headerIndex;
break;
default:
break;
}
sj.add(value);
}
bwGenotypes.write(sj.toString());
bwGenotypes.newLine();
}
public void outputGenotype(VariantLite variantLite) throws IOException {
CSVRecord record = variantLite.getRecord();
Annotation mostDamagingAnnotation = variantLite.getMostDamagingAnnotation();
String allAnnotation = variantLite.getAllAnnotation();
StringJoiner sj = new StringJoiner(",");
for (int headerIndex = 0; headerIndex < record.size(); headerIndex++) {
String value = "";
if (headerIndex == STABLE_ID_HEADER_INDEX) {
value = mostDamagingAnnotation.getStableId();
} else if (headerIndex == EFFECT_HEADER_INDEX) {
value = mostDamagingAnnotation.effect;
} else if (headerIndex == HAS_CCDS_HEADER_INDEX) {
value = Boolean.toString(mostDamagingAnnotation.hasCCDS);
} else if (headerIndex == HGVS_c_HEADER_INDEX) {
value = mostDamagingAnnotation.HGVS_c;
} else if (headerIndex == HGVS_p_HEADER_INDEX) {
value = mostDamagingAnnotation.HGVS_p;
} else if (headerIndex == POLYPHEN_HUMDIV_SCORE_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumdiv);
} else if (headerIndex == POLYPHEN_HUMDIV_PREDICTION_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumdiv, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMDIV_SCORE_CCDS_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumdivCCDS);
} else if (headerIndex == POLYPHEN_HUMDIV_PREDICTION_CCDS_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumdivCCDS, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMVAR_SCORE_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumvar);
} else if (headerIndex == POLYPHEN_HUMVAR_PREDICTION_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumvar, mostDamagingAnnotation.effect);
} else if (headerIndex == POLYPHEN_HUMVAR_SCORE_CCDS_HEADER_INDEX) {
value = FormatManager.getFloat(mostDamagingAnnotation.polyphenHumvarCCDS);
} else if (headerIndex == POLYPHEN_HUMVAR_PREDICTION_CCDS_HEADER_INDEX) {
value = PolyphenManager.getPrediction(mostDamagingAnnotation.polyphenHumvarCCDS, mostDamagingAnnotation.effect);
} else if (headerIndex == GENE_NAME_HEADER_INDEX) {
value = "'" + mostDamagingAnnotation.geneName + "'";
} else if (headerIndex == ALL_ANNOTATION_HEADER_INDEX) {
value = allAnnotation;
} else {
value = record.get(headerIndex);
}
sj.add(value);
}
bwGenotypes.write(sj.toString());
bwGenotypes.newLine();
}
}
|
append double quote when ouput value include comma
|
src/main/java/function/cohort/vargeno/ListVarGenoLite.java
|
append double quote when ouput value include comma
|
|
Java
|
mit
|
0ca4c0588f75fd8f8c1c29ddd994cde2ce799efd
| 0
|
nsnjson/nsnjson-java-driver
|
package com.github.nsnjson.decoding;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
public class Decoder {
private static final Decoding DEFAULT_DECODING = new DefaultDecoding();
public static Optional<JsonNode> decode(JsonNode presentation) {
return DEFAULT_DECODING.decode(presentation);
}
public static Optional<JsonNode> decode(JsonNode presentation, Decoding decoding) {
return Optional.ofNullable(decoding).orElse(DEFAULT_DECODING).decode(presentation);
}
}
|
src/main/java/com/github/nsnjson/decoding/Decoder.java
|
package com.github.nsnjson.decoding;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Optional;
public class Decoder {
private static final Decoding DEFAULT_DECODING = new DefaultDecoding();
public static Optional<JsonNode> decode(JsonNode presentation) {
return DEFAULT_DECODING.decode(presentation);
}
public static Optional<JsonNode> decode(JsonNode json, Decoding decoding) {
return Optional.ofNullable(decoding).orElse(DEFAULT_DECODING).decode(json);
}
}
|
Refactor method { Decoder @ decode(JsonNode, Encoding) }
|
src/main/java/com/github/nsnjson/decoding/Decoder.java
|
Refactor method { Decoder @ decode(JsonNode, Encoding) }
|
|
Java
|
mit
|
05d27ada4ca82a22904050fa9a3e80f1f54a709d
| 0
|
CS2103JAN2017-W13-B2/main,CS2103JAN2017-W13-B2/main
|
package seedu.address.model.util;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyTaskManager;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Deadline;
import seedu.address.model.task.Description;
import seedu.address.model.task.IdentificationNumber;
import seedu.address.model.task.Name;
import seedu.address.model.task.Task;
import seedu.address.model.TaskManager;
public class SampleDataUtil {
public static Task[] getSampleTasks() {
try {
return new Task[] {
new Task(new Name("Go fly kite"), new Deadline("27/02/2017"),
new Description("Flying kite at park"),
new IdentificationNumber("1"),
new UniqueTagList("meet with friends")),
new Task(new Name("Buy christmas presents"), new Deadline("23/12/2017"),
new Description("Buy presents for Familiy and Friends"),
new IdentificationNumber("2"),
new UniqueTagList("presents", "christmas")),
new Task(new Name("Meeting with Charlotte Oliveiro"), new Deadline("02/02/2017"),
new Description("Prepare for Meeting with Charlotte"),
new IdentificationNumber("3"),
new UniqueTagList("important","meeting")),
new Task(new Name("Dinner outing with family"), new Deadline("17/12/2017"),
new Description("Going to the zoo with family"),
new IdentificationNumber("4"),
new UniqueTagList("family", "zoo")),
new Task(new Name("Class reunion"), new Deadline("15/01/2018"),
new Description("Secondary school class reunion"),
new IdentificationNumber("5"),
new UniqueTagList("classmates")),
new Task(new Name("Company meeting"), new Deadline("04/05/2017"),
new Description("Prepare for company meeting"),
new IdentificationNumber("6"),
new UniqueTagList("important", "meeting"))
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyTaskManager getSampleTaskManager() {
TaskManager sampleAB = new TaskManager();
for (Task samplePerson : getSampleTasks()) {
sampleAB.addTask(samplePerson);
}
return sampleAB;
}
}
|
src/main/java/seedu/address/model/util/SampleDataUtil.java
|
package seedu.address.model.util;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyTaskManager;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Deadline;
import seedu.address.model.task.Description;
import seedu.address.model.task.IdentificationNumber;
import seedu.address.model.task.Name;
import seedu.address.model.task.Task;
import seedu.address.model.TaskManager;
public class SampleDataUtil {
public static Task[] getSampleTasks() {
try {
return new Task[] {
new Task(new Name("Go fly kite"), new Deadline("27/02/2017"),
new Description("Flying kite at park"),
new IdentificationNumber("1"),
new UniqueTagList("meet with friends")),
new Task(new Name("Buy christmas presents"), new Deadline("23/12/2017"),
new Description("Buy presents for Familiy and Friends"),
new IdentificationNumber("2"),
new UniqueTagList("presents", "christmas")),
new Task(new Name("Meeting with Charlotte Oliveiro"), new Deadline("02/02/2017"),
new Description("Prepare for Meeting with Charlotte"),
new IdentificationNumber("3"),
new UniqueTagList("important","meeting")),
new Task(new Name("Dinner outing with family"), new Deadline("17/12/2017"),
new Description("Going to the zoo with family"),
new IdentificationNumber("4"),
new UniqueTagList("family", "zoo")),
new Task(new Name("Class reunion"), new Deadline("15/01/2018"),
new Description("Secondary school class reunion"),
new IdentificationNumber("5"),
new UniqueTagList("classmates")),
new Task(new Name("Company meeting"), new Deadline("04/05/2017"),
new Description("Prepare for company meeting"),
new IdentificationNumber("6"),
new UniqueTagList("important", "meeting"))
};
} catch (IllegalValueException e) {
throw new AssertionError("sample data cannot be invalid", e);
}
}
public static ReadOnlyTaskManager getSampleTaskManager() {
TaskManager sampleAB = new TaskManager();
for (Task samplePerson : getSampleTasks()) {
sampleAB.addTask(samplePerson);
}
return sampleAB;
}
}
|
Fix typo
|
src/main/java/seedu/address/model/util/SampleDataUtil.java
|
Fix typo
|
|
Java
|
mit
|
8f7818425c9951c97307544870eea366c9cba4ff
| 0
|
poser3/Prove-It
|
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import acm.graphics.GCompound;
import acm.graphics.GLabel;
import acm.graphics.GOval;
@SuppressWarnings("serial")
public class PPoint extends GCompound implements Drawable, Selectable {
public static final double POINT_DIAMETER = 10;
public static final double EPSILON = 1;
public static final byte FREE_POINT = 0;
public static final byte MIDPOINT = 1;
public static final byte INTERSECTION_OF_LINES = 2;
public static final byte LEFT_INTERSECTION_OF_CIRCLES = 3;
public static final byte RIGHT_INTERSECTION_OF_CIRCLES = 4;
public static final byte LEFT_INTERSECTION_OF_CIRCLE_AND_LINE = 5;
public static final byte RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE = 6;
public static double distance(PPoint p1, PPoint p2) {
double x1 = p1.getPointX();
double y1 = p1.getPointY();
double x2 = p2.getPointX();
double y2 = p2.getPointY();
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
private GOval dot_;
private double x_;
private double y_;
private byte constructedAs_;
private ArrayList<Drawable> parents_;
private final String label_;
private boolean selected_;
private GLabel gLabel_;
public PPoint(double x, double y, String label) {
this.setLocation(x,y);
dot_ = new GOval(-POINT_DIAMETER / 2.0, -POINT_DIAMETER / 2.0, POINT_DIAMETER, POINT_DIAMETER);
dot_.setFilled(true);
dot_.setFillColor(Color.BLACK);
this.add(dot_);
label_ = label;
gLabel_ = new GLabel(label_, 10, -10);
this.add(gLabel_);
constructedAs_ = FREE_POINT;
x_ = x;
y_ = y;
}
public PPoint(byte constructedAs, Collection<? extends Drawable> parents, String label) {
dot_ = new GOval(0, 0, POINT_DIAMETER, POINT_DIAMETER);
dot_.setFilled(true);
dot_.setFillColor(Color.BLACK);
parents_ = new Drawables(parents);
label_ = label;
constructedAs_ = constructedAs;
update();
}
@Override
public void move(double dx, double dy) {
switch (constructedAs_) {
case FREE_POINT : //move the point itself
x_ += dx;
y_ += dy;
super.move(dx, dy);
break;
case MIDPOINT : //move the point itself
x_ += dx;
y_ += dy;
super.move(dx, dy);
//now move the parents
for (int i=0; i < parents_.size(); i++) {
parents_.get(i).move(dx, dy);
}
break;
}
}
public void update() {
//scratch variables to improve readability of calculations...
double x0,y0,x1,y1,x2,y2,xj,yj,a1,a2,b1,b2,t1,rj,r1,r2,d,h,xm,xn,yn,a,b,f,g,t,sign;
PLine pL1, pL2;
PCircle c1, c2;
switch (constructedAs_) {
case FREE_POINT :
setLocation(x_, y_);
break;
case MIDPOINT :
PPoint p1 = (PPoint) parents_.get(0);
PPoint p2 = (PPoint) parents_.get(1);
x_ = (p1.getPointX() + p2.getPointX()) / 2.0;
y_ = (p1.getPointY() + p2.getPointY()) / 2.0;
setLocation(x_, y_);
break;
case INTERSECTION_OF_LINES :
pL1 = (PLine) parents_.get(0);
pL2 = (PLine) parents_.get(1);
x1 = pL1.get1stPoint().getPointX();
y1 = pL1.get1stPoint().getPointY();
x2 = pL2.get1stPoint().getPointX();
y2 = pL2.get1stPoint().getPointY();
a1 = pL1.get2ndPoint().getPointX() - x1;
a2 = pL2.get2ndPoint().getPointX() - x2;
b1 = pL1.get2ndPoint().getPointY() - y1;
b2 = pL2.get2ndPoint().getPointY() - y2;
t1 = (b2*(x1-x2) + a2*(y2-y1))/(a2*b1-a1*b2);
x_ = x1 + a1*t1;
y_ = y1 + b1*t1;
setLocation(x_, y_);
break;
case LEFT_INTERSECTION_OF_CIRCLE_AND_LINE :
case RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE :
c1 = (PCircle) parents_.get(0);
pL2 = (PLine) parents_.get(1);
rj = c1.getRadius();
xj = c1.getCenter().getPointX();
yj = c1.getCenter().getPointY();
x0 = pL2.get1stPoint().getPointX();
y0 = pL2.get1stPoint().getPointY();
x1 = pL2.get2ndPoint().getPointX();
y1 = pL2.get2ndPoint().getPointY();
f = x1-x0;
g = y1-y0;
sign = (constructedAs_ == RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE ? 1 : -1);
t = (f*(xj - x0) + g*(yj-y0) + sign * Math.sqrt(rj*rj * (f*f + g*g) -
(f*(y0 - yj) - g*(x0-xj))*(f*(y0 - yj) - g*(x0-xj))))/(f*f+g*g);
x_ = x0 + f*t;
y_ = y0 + g*t;
setLocation(x_, y_);
break;
case RIGHT_INTERSECTION_OF_CIRCLES :
case LEFT_INTERSECTION_OF_CIRCLES :
c1 = (PCircle) parents_.get(0);
c2 = (PCircle) parents_.get(1);
r1 = c1.getRadius();
r2 = c2.getRadius();
x1 = c1.getCenter().getPointX();
y1 = c1.getCenter().getPointY();
x2 = c2.getCenter().getPointX();
y2 = c2.getCenter().getPointY();
p1 = c1.getCenter();
p2 = c2.getCenter();
d = distance(p1, p2); //d is distance between centers
xm = (d*d + r1*r1 - r2*r2)/(2*d);
//xm is the distance from p1 to the closest point
//on the segment connecting their centers to the intersection
h = Math.sqrt((4*d*d*r1*r1 - Math.pow(d*d-r2*r2+r1*r1,2))/(4*d*d));
//h is the distance from the pt of intersection to the line
//connectingthe centers
xn = (y2-y1) / d; //(xn,yn) is a unit vector normal to the
yn = -(x2-x1) / d; //segment connecting the centers
a = x1 + (x2-x1)*xm/d;
b = y1 + (y2-y1)*xm/d;
sign = (constructedAs_ == RIGHT_INTERSECTION_OF_CIRCLES ? 1 : -1);
x_ = a + sign*h*xn;
y_ = b + sign*h*yn;
setLocation(x_, y_);
break;
}
}
public void setSelected(boolean selected) {
selected_ = selected;
dot_.setFillColor(selected ? Color.MAGENTA : Color.BLACK);
}
public boolean isSelected() {
return selected_;
}
public String getLabel() {
return label_;
}
public double distanceTo(double x, double y) {
return Math.sqrt( (x-this.getPointX())*(x-this.getPointX()) +
(y-this.getPointY())*(y-this.getPointY()) );
}
@Override
public boolean equals(Object o) {
if (o instanceof PPoint) {
return label_.equals(((PPoint) o).getLabel());
}
else {
return false;
}
}
public double getPointX() {
return this.getX();
//return x_;
}
public double getPointY() {
return this.getY();
//return y_;
}
public double getDistanceTo(double x, double y) {
return Math.sqrt((x-x_)*(x-x_) + (y-y_)*(y-y_));
}
@Override
public String toString() {
return "Point " + this.getLabel() + " at (" + getPointX() + ", " + getPointY() + ")";
}
}
|
src/PPoint.java
|
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import acm.graphics.GOval;
@SuppressWarnings("serial")
public class PPoint extends GOval implements Drawable, Selectable {
public static final double POINT_DIAMETER = 10;
public static final double EPSILON = 1;
public static final byte FREE_POINT = 0;
public static final byte MIDPOINT = 1;
public static final byte INTERSECTION_OF_LINES = 2;
public static final byte LEFT_INTERSECTION_OF_CIRCLES = 3;
public static final byte RIGHT_INTERSECTION_OF_CIRCLES = 4;
public static final byte LEFT_INTERSECTION_OF_CIRCLE_AND_LINE = 5;
public static final byte RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE = 6;
public static double distance(PPoint p1, PPoint p2) {
double x1 = p1.getPointX();
double y1 = p1.getPointY();
double x2 = p2.getPointX();
double y2 = p2.getPointY();
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
private double x_;
private double y_;
private byte constructedAs_;
private ArrayList<Drawable> parents_;
private final String label_;
private boolean selected_;
public PPoint(double x, double y, String label) {
super(x - POINT_DIAMETER/2, y - POINT_DIAMETER/2, POINT_DIAMETER, POINT_DIAMETER);
x_ = x;
y_ = y;
constructedAs_ = FREE_POINT;
setFilled(true);
setFillColor(Color.BLACK);
label_ = label;
}
public PPoint(byte constructedAs, Collection<? extends Drawable> parents, String label) {
super(0, 0, POINT_DIAMETER, POINT_DIAMETER);
parents_ = new Drawables(parents);
setFilled(true);
setFillColor(Color.BLACK);
label_ = label;
constructedAs_ = constructedAs;
update();
}
@Override
public void move(double dx, double dy) {
switch (constructedAs_) {
case FREE_POINT : //move the point itself
x_ += dx;
y_ += dy;
super.move(dx, dy);
break;
case MIDPOINT : //move the point itself
x_ += dx;
y_ += dy;
super.move(dx, dy);
//now move the parents
for (int i=0; i < parents_.size(); i++) {
parents_.get(i).move(dx, dy);
}
break;
}
}
public void update() {
//scratch variables to improve readability of calculations...
double x0,y0,x1,y1,x2,y2,xj,yj,a1,a2,b1,b2,t1,rj,r1,r2,d,h,xm,xn,yn,a,b,f,g,t,sign;
PLine pL1, pL2;
PCircle c1, c2;
switch (constructedAs_) {
case FREE_POINT :
setLocation(x_ - POINT_DIAMETER/2, y_ - POINT_DIAMETER/2);
break;
case MIDPOINT :
PPoint p1 = (PPoint) parents_.get(0);
PPoint p2 = (PPoint) parents_.get(1);
x_ = (p1.getPointX() + p2.getPointX()) / 2.0;
y_ = (p1.getPointY() + p2.getPointY()) / 2.0;
setLocation(x_ - POINT_DIAMETER/2, y_ - POINT_DIAMETER/2);
break;
case INTERSECTION_OF_LINES :
pL1 = (PLine) parents_.get(0);
pL2 = (PLine) parents_.get(1);
x1 = pL1.get1stPoint().getPointX();
y1 = pL1.get1stPoint().getPointY();
x2 = pL2.get1stPoint().getPointX();
y2 = pL2.get1stPoint().getPointY();
a1 = pL1.get2ndPoint().getPointX() - x1;
a2 = pL2.get2ndPoint().getPointX() - x2;
b1 = pL1.get2ndPoint().getPointY() - y1;
b2 = pL2.get2ndPoint().getPointY() - y2;
t1 = (b2*(x1-x2) + a2*(y2-y1))/(a2*b1-a1*b2);
x_ = x1 + a1*t1;
y_ = y1 + b1*t1;
setLocation(x_ - POINT_DIAMETER/2, y_ - POINT_DIAMETER/2);
break;
case LEFT_INTERSECTION_OF_CIRCLE_AND_LINE :
case RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE :
c1 = (PCircle) parents_.get(0);
pL2 = (PLine) parents_.get(1);
rj = c1.getRadius();
xj = c1.getCenter().getPointX();
yj = c1.getCenter().getPointY();
x0 = pL2.get1stPoint().getPointX();
y0 = pL2.get1stPoint().getPointY();
x1 = pL2.get2ndPoint().getPointX();
y1 = pL2.get2ndPoint().getPointY();
f = x1-x0;
g = y1-y0;
sign = (constructedAs_ == RIGHT_INTERSECTION_OF_CIRCLE_AND_LINE ? 1 : -1);
t = (f*(xj - x0) + g*(yj-y0) + sign * Math.sqrt(rj*rj * (f*f + g*g) -
(f*(y0 - yj) - g*(x0-xj))*(f*(y0 - yj) - g*(x0-xj))))/(f*f+g*g);
x_ = x0 + f*t;
y_ = y0 + g*t;
setLocation(x_ - POINT_DIAMETER/2, y_ - POINT_DIAMETER/2);
break;
case RIGHT_INTERSECTION_OF_CIRCLES :
case LEFT_INTERSECTION_OF_CIRCLES :
c1 = (PCircle) parents_.get(0);
c2 = (PCircle) parents_.get(1);
r1 = c1.getRadius();
r2 = c2.getRadius();
x1 = c1.getCenter().getPointX();
y1 = c1.getCenter().getPointY();
x2 = c2.getCenter().getPointX();
y2 = c2.getCenter().getPointY();
p1 = c1.getCenter();
p2 = c2.getCenter();
d = distance(p1, p2); //d is distance between centers
xm = (d*d + r1*r1 - r2*r2)/(2*d);
//xm is the distance from p1 to the closest point
//on the segment connecting their centers to the intersection
h = Math.sqrt((4*d*d*r1*r1 - Math.pow(d*d-r2*r2+r1*r1,2))/(4*d*d));
//h is the distance from the pt of intersection to the line
//connectingthe centers
xn = (y2-y1) / d; //(xn,yn) is a unit vector normal to the
yn = -(x2-x1) / d; //segment connecting the centers
a = x1 + (x2-x1)*xm/d;
b = y1 + (y2-y1)*xm/d;
sign = (constructedAs_ == RIGHT_INTERSECTION_OF_CIRCLES ? 1 : -1);
x_ = a + sign*h*xn;
y_ = b + sign*h*yn;
setLocation(x_ - POINT_DIAMETER/2, y_ - POINT_DIAMETER/2);
break;
}
}
public void setSelected(boolean selected) {
selected_ = selected;
setFillColor(selected ? Color.MAGENTA : Color.BLACK);
}
public boolean isSelected() {
return selected_;
}
public String getLabel() {
return label_;
}
public double distanceTo(double x, double y) {
return Math.sqrt( (x-this.getPointX())*(x-this.getPointX()) +
(y-this.getPointY())*(y-this.getPointY()) );
}
@Override
public boolean equals(Object o) {
if (o instanceof PPoint) {
return label_.equals(((PPoint) o).getLabel());
}
else {
return false;
}
}
public double getPointX() {
return x_;
}
public double getPointY() {
return y_;
}
public double getDistanceTo(double x, double y) {
return Math.sqrt((x-x_)*(x-x_) + (y-y_)*(y-y_));
}
@Override
public String toString() {
return "Point " + this.getLabel() + " at (" + getPointX() + ", " + getPointY() + ")";
}
}
|
added point labels (first pass)
|
src/PPoint.java
|
added point labels (first pass)
|
|
Java
|
mit
|
4ffe3c7b4c4b8bd7a3034b74f5ec617175f8396a
| 0
|
jpbriend/jenkins,mattclark/jenkins,iterate/coding-dojo,everyonce/jenkins,jenkinsci/jenkins,escoem/jenkins,pselle/jenkins,protazy/jenkins,SebastienGllmt/jenkins,mcanthony/jenkins,KostyaSha/jenkins,liorhson/jenkins,petermarcoen/jenkins,tangkun75/jenkins,hashar/jenkins,ydubreuil/jenkins,akshayabd/jenkins,paulmillar/jenkins,singh88/jenkins,Jimilian/jenkins,deadmoose/jenkins,ErikVerheul/jenkins,wangyikai/jenkins,christ66/jenkins,fbelzunc/jenkins,ikedam/jenkins,paulwellnerbou/jenkins,everyonce/jenkins,damianszczepanik/jenkins,oleg-nenashev/jenkins,sathiya-mit/jenkins,jzjzjzj/jenkins,singh88/jenkins,aldaris/jenkins,elkingtonmcb/jenkins,tangkun75/jenkins,bpzhang/jenkins,hplatou/jenkins,jtnord/jenkins,wangyikai/jenkins,christ66/jenkins,dbroady1/jenkins,lindzh/jenkins,292388900/jenkins,mdonohue/jenkins,jglick/jenkins,mattclark/jenkins,amruthsoft9/Jenkis,h4ck3rm1k3/jenkins,FarmGeek4Life/jenkins,292388900/jenkins,duzifang/my-jenkins,AustinKwang/jenkins,gorcz/jenkins,lvotypko/jenkins3,Jochen-A-Fuerbacher/jenkins,akshayabd/jenkins,AustinKwang/jenkins,fbelzunc/jenkins,vijayto/jenkins,ajshastri/jenkins,abayer/jenkins,chbiel/jenkins,scoheb/jenkins,shahharsh/jenkins,Jochen-A-Fuerbacher/jenkins,SebastienGllmt/jenkins,ChrisA89/jenkins,albers/jenkins,msrb/jenkins,recena/jenkins,daniel-beck/jenkins,FTG-003/jenkins,6WIND/jenkins,fbelzunc/jenkins,hemantojhaa/jenkins,lvotypko/jenkins,jenkinsci/jenkins,ns163/jenkins,duzifang/my-jenkins,rsandell/jenkins,guoxu0514/jenkins,stephenc/jenkins,ErikVerheul/jenkins,akshayabd/jenkins,christ66/jenkins,amruthsoft9/Jenkis,huybrechts/hudson,hashar/jenkins,MarkEWaite/jenkins,MadsNielsen/jtemp,vlajos/jenkins,my7seven/jenkins,Jochen-A-Fuerbacher/jenkins,petermarcoen/jenkins,ikedam/jenkins,github-api-test-org/jenkins,jtnord/jenkins,lvotypko/jenkins2,amruthsoft9/Jenkis,mrooney/jenkins,gusreiber/jenkins,jenkinsci/jenkins,singh88/jenkins,tfennelly/jenkins,DanielWeber/jenkins,jzjzjzj/jenkins,noikiy/jenkins,pantheon-systems/jenkins,jcsirot/jenkins,viqueen/jenkins,mpeltonen/jenkins,jglick/jenkins,AustinKwang/jenkins,paulmillar/jenkins,jpederzolli/jenkins-1,aheritier/jenkins,jcarrothers-sap/jenkins,KostyaSha/jenkins,v1v/jenkins,jpbriend/jenkins,rlugojr/jenkins,seanlin816/jenkins,iqstack/jenkins,DoctorQ/jenkins,gorcz/jenkins,iqstack/jenkins,ns163/jenkins,pjanouse/jenkins,ajshastri/jenkins,luoqii/jenkins,github-api-test-org/jenkins,AustinKwang/jenkins,mpeltonen/jenkins,godfath3r/jenkins,lvotypko/jenkins2,liupugong/jenkins,rsandell/jenkins,stefanbrausch/hudson-main,khmarbaise/jenkins,morficus/jenkins,goldchang/jenkins,sathiya-mit/jenkins,nandan4/Jenkins,csimons/jenkins,rsandell/jenkins,SenolOzer/jenkins,FTG-003/jenkins,Krasnyanskiy/jenkins,DoctorQ/jenkins,jcarrothers-sap/jenkins,Jimilian/jenkins,escoem/jenkins,kzantow/jenkins,liorhson/jenkins,arcivanov/jenkins,jcsirot/jenkins,lvotypko/jenkins2,aquarellian/jenkins,chbiel/jenkins,arcivanov/jenkins,bpzhang/jenkins,jcsirot/jenkins,samatdav/jenkins,v1v/jenkins,daniel-beck/jenkins,dbroady1/jenkins,NehemiahMi/jenkins,christ66/jenkins,keyurpatankar/hudson,rlugojr/jenkins,duzifang/my-jenkins,my7seven/jenkins,damianszczepanik/jenkins,dennisjlee/jenkins,svanoort/jenkins,godfath3r/jenkins,deadmoose/jenkins,mrooney/jenkins,aldaris/jenkins,paulwellnerbou/jenkins,christ66/jenkins,ikedam/jenkins,mdonohue/jenkins,elkingtonmcb/jenkins,jzjzjzj/jenkins,Krasnyanskiy/jenkins,hemantojhaa/jenkins,intelchen/jenkins,gitaccountforprashant/gittest,godfath3r/jenkins,abayer/jenkins,mcanthony/jenkins,protazy/jenkins,vijayto/jenkins,wuwen5/jenkins,jenkinsci/jenkins,jzjzjzj/jenkins,shahharsh/jenkins,Vlatombe/jenkins,bkmeneguello/jenkins,ns163/jenkins,DanielWeber/jenkins,gusreiber/jenkins,elkingtonmcb/jenkins,duzifang/my-jenkins,jpbriend/jenkins,keyurpatankar/hudson,liorhson/jenkins,jzjzjzj/jenkins,amruthsoft9/Jenkis,Vlatombe/jenkins,lindzh/jenkins,singh88/jenkins,aduprat/jenkins,ikedam/jenkins,iterate/coding-dojo,samatdav/jenkins,abayer/jenkins,arcivanov/jenkins,daniel-beck/jenkins,brunocvcunha/jenkins,Krasnyanskiy/jenkins,gorcz/jenkins,h4ck3rm1k3/jenkins,hemantojhaa/jenkins,wuwen5/jenkins,wuwen5/jenkins,vjuranek/jenkins,scoheb/jenkins,dennisjlee/jenkins,vijayto/jenkins,pselle/jenkins,morficus/jenkins,Jimilian/jenkins,wuwen5/jenkins,protazy/jenkins,recena/jenkins,ikedam/jenkins,csimons/jenkins,gitaccountforprashant/gittest,liupugong/jenkins,stephenc/jenkins,h4ck3rm1k3/jenkins,synopsys-arc-oss/jenkins,nandan4/Jenkins,liorhson/jenkins,scoheb/jenkins,amuniz/jenkins,albers/jenkins,tfennelly/jenkins,aheritier/jenkins,mdonohue/jenkins,noikiy/jenkins,kohsuke/hudson,batmat/jenkins,yonglehou/jenkins,aquarellian/jenkins,recena/jenkins,KostyaSha/jenkins,6WIND/jenkins,godfath3r/jenkins,Vlatombe/jenkins,seanlin816/jenkins,MichaelPranovich/jenkins_sc,1and1/jenkins,tangkun75/jenkins,pjanouse/jenkins,ChrisA89/jenkins,MichaelPranovich/jenkins_sc,svanoort/jenkins,oleg-nenashev/jenkins,AustinKwang/jenkins,brunocvcunha/jenkins,dennisjlee/jenkins,jhoblitt/jenkins,ndeloof/jenkins,andresrc/jenkins,thomassuckow/jenkins,sathiya-mit/jenkins,deadmoose/jenkins,dariver/jenkins,lvotypko/jenkins3,CodeShane/jenkins,DanielWeber/jenkins,liupugong/jenkins,verbitan/jenkins,SebastienGllmt/jenkins,alvarolobato/jenkins,evernat/jenkins,intelchen/jenkins,azweb76/jenkins,khmarbaise/jenkins,guoxu0514/jenkins,jpbriend/jenkins,Ykus/jenkins,msrb/jenkins,vvv444/jenkins,evernat/jenkins,nandan4/Jenkins,amuniz/jenkins,maikeffi/hudson,nandan4/Jenkins,lindzh/jenkins,elkingtonmcb/jenkins,github-api-test-org/jenkins,tastatur/jenkins,CodeShane/jenkins,Wilfred/jenkins,huybrechts/hudson,patbos/jenkins,noikiy/jenkins,jenkinsci/jenkins,mpeltonen/jenkins,ikedam/jenkins,gusreiber/jenkins,rsandell/jenkins,maikeffi/hudson,samatdav/jenkins,mattclark/jenkins,shahharsh/jenkins,seanlin816/jenkins,jk47/jenkins,vvv444/jenkins,alvarolobato/jenkins,kzantow/jenkins,jpbriend/jenkins,ydubreuil/jenkins,pselle/jenkins,KostyaSha/jenkins,godfath3r/jenkins,luoqii/jenkins,arunsingh/jenkins,MichaelPranovich/jenkins_sc,verbitan/jenkins,albers/jenkins,aduprat/jenkins,ydubreuil/jenkins,damianszczepanik/jenkins,vvv444/jenkins,protazy/jenkins,daspilker/jenkins,vlajos/jenkins,iterate/coding-dojo,wuwen5/jenkins,Wilfred/jenkins,ErikVerheul/jenkins,jglick/jenkins,pantheon-systems/jenkins,mcanthony/jenkins,paulmillar/jenkins,daniel-beck/jenkins,msrb/jenkins,luoqii/jenkins,mattclark/jenkins,fbelzunc/jenkins,lvotypko/jenkins,1and1/jenkins,andresrc/jenkins,Jochen-A-Fuerbacher/jenkins,keyurpatankar/hudson,luoqii/jenkins,csimons/jenkins,batmat/jenkins,andresrc/jenkins,keyurpatankar/hudson,stephenc/jenkins,svanoort/jenkins,amuniz/jenkins,varmenise/jenkins,gorcz/jenkins,arcivanov/jenkins,kzantow/jenkins,SebastienGllmt/jenkins,wangyikai/jenkins,paulwellnerbou/jenkins,viqueen/jenkins,MichaelPranovich/jenkins_sc,shahharsh/jenkins,akshayabd/jenkins,guoxu0514/jenkins,hemantojhaa/jenkins,arunsingh/jenkins,kohsuke/hudson,shahharsh/jenkins,keyurpatankar/hudson,mrobinet/jenkins,sathiya-mit/jenkins,singh88/jenkins,stephenc/jenkins,huybrechts/hudson,tastatur/jenkins,amuniz/jenkins,SenolOzer/jenkins,shahharsh/jenkins,lilyJi/jenkins,MadsNielsen/jtemp,guoxu0514/jenkins,paulmillar/jenkins,hplatou/jenkins,shahharsh/jenkins,damianszczepanik/jenkins,SenolOzer/jenkins,aldaris/jenkins,christ66/jenkins,gitaccountforprashant/gittest,Ykus/jenkins,bkmeneguello/jenkins,mdonohue/jenkins,noikiy/jenkins,MarkEWaite/jenkins,iqstack/jenkins,jpbriend/jenkins,rlugojr/jenkins,tastatur/jenkins,Jimilian/jenkins,aldaris/jenkins,alvarolobato/jenkins,FarmGeek4Life/jenkins,olivergondza/jenkins,Vlatombe/jenkins,gorcz/jenkins,lvotypko/jenkins,tastatur/jenkins,v1v/jenkins,maikeffi/hudson,soenter/jenkins,FarmGeek4Life/jenkins,kzantow/jenkins,synopsys-arc-oss/jenkins,FarmGeek4Life/jenkins,azweb76/jenkins,lvotypko/jenkins,lilyJi/jenkins,chbiel/jenkins,v1v/jenkins,jcarrothers-sap/jenkins,iterate/coding-dojo,Jimilian/jenkins,goldchang/jenkins,liupugong/jenkins,alvarolobato/jenkins,stephenc/jenkins,jk47/jenkins,dennisjlee/jenkins,rlugojr/jenkins,dbroady1/jenkins,arcivanov/jenkins,huybrechts/hudson,rlugojr/jenkins,mrooney/jenkins,bkmeneguello/jenkins,nandan4/Jenkins,vjuranek/jenkins,rashmikanta-1984/jenkins,wangyikai/jenkins,intelchen/jenkins,gusreiber/jenkins,dbroady1/jenkins,jhoblitt/jenkins,MadsNielsen/jtemp,guoxu0514/jenkins,andresrc/jenkins,elkingtonmcb/jenkins,singh88/jenkins,msrb/jenkins,dariver/jenkins,h4ck3rm1k3/jenkins,tangkun75/jenkins,lordofthejars/jenkins,batmat/jenkins,jcsirot/jenkins,FarmGeek4Life/jenkins,Wilfred/jenkins,batmat/jenkins,liorhson/jenkins,aduprat/jenkins,pselle/jenkins,NehemiahMi/jenkins,hudson/hudson-2.x,synopsys-arc-oss/jenkins,ErikVerheul/jenkins,ns163/jenkins,amruthsoft9/Jenkis,ndeloof/jenkins,dariver/jenkins,jpederzolli/jenkins-1,andresrc/jenkins,ErikVerheul/jenkins,noikiy/jenkins,MadsNielsen/jtemp,andresrc/jenkins,mrooney/jenkins,wangyikai/jenkins,FTG-003/jenkins,viqueen/jenkins,hudson/hudson-2.x,hplatou/jenkins,arunsingh/jenkins,292388900/jenkins,arunsingh/jenkins,Krasnyanskiy/jenkins,Ykus/jenkins,escoem/jenkins,svanoort/jenkins,vvv444/jenkins,msrb/jenkins,vvv444/jenkins,verbitan/jenkins,FTG-003/jenkins,mdonohue/jenkins,daspilker/jenkins,viqueen/jenkins,viqueen/jenkins,DoctorQ/jenkins,pjanouse/jenkins,liupugong/jenkins,scoheb/jenkins,olivergondza/jenkins,synopsys-arc-oss/jenkins,kohsuke/hudson,vlajos/jenkins,rsandell/jenkins,soenter/jenkins,abayer/jenkins,stephenc/jenkins,thomassuckow/jenkins,abayer/jenkins,noikiy/jenkins,batmat/jenkins,brunocvcunha/jenkins,aduprat/jenkins,lvotypko/jenkins2,Wilfred/jenkins,wangyikai/jenkins,aheritier/jenkins,tfennelly/jenkins,nandan4/Jenkins,stefanbrausch/hudson-main,recena/jenkins,seanlin816/jenkins,brunocvcunha/jenkins,lilyJi/jenkins,mpeltonen/jenkins,arunsingh/jenkins,scoheb/jenkins,vjuranek/jenkins,SenolOzer/jenkins,vjuranek/jenkins,recena/jenkins,jcarrothers-sap/jenkins,bpzhang/jenkins,gorcz/jenkins,jk47/jenkins,lvotypko/jenkins,amuniz/jenkins,thomassuckow/jenkins,Krasnyanskiy/jenkins,wuwen5/jenkins,wangyikai/jenkins,MadsNielsen/jtemp,jpederzolli/jenkins-1,ChrisA89/jenkins,iqstack/jenkins,daspilker/jenkins,samatdav/jenkins,rashmikanta-1984/jenkins,DoctorQ/jenkins,aquarellian/jenkins,patbos/jenkins,varmenise/jenkins,stefanbrausch/hudson-main,kohsuke/hudson,Ykus/jenkins,MarkEWaite/jenkins,lordofthejars/jenkins,DanielWeber/jenkins,h4ck3rm1k3/jenkins,pantheon-systems/jenkins,olivergondza/jenkins,petermarcoen/jenkins,oleg-nenashev/jenkins,vlajos/jenkins,goldchang/jenkins,azweb76/jenkins,tfennelly/jenkins,daniel-beck/jenkins,aheritier/jenkins,azweb76/jenkins,lindzh/jenkins,evernat/jenkins,yonglehou/jenkins,kohsuke/hudson,lindzh/jenkins,chbiel/jenkins,svanoort/jenkins,jhoblitt/jenkins,intelchen/jenkins,hemantojhaa/jenkins,1and1/jenkins,varmenise/jenkins,ydubreuil/jenkins,ikedam/jenkins,bkmeneguello/jenkins,lordofthejars/jenkins,vjuranek/jenkins,brunocvcunha/jenkins,SenolOzer/jenkins,dariver/jenkins,jpederzolli/jenkins-1,gusreiber/jenkins,hashar/jenkins,christ66/jenkins,DoctorQ/jenkins,jcarrothers-sap/jenkins,shahharsh/jenkins,jtnord/jenkins,rsandell/jenkins,ChrisA89/jenkins,hplatou/jenkins,6WIND/jenkins,evernat/jenkins,lvotypko/jenkins3,hplatou/jenkins,albers/jenkins,lordofthejars/jenkins,mcanthony/jenkins,verbitan/jenkins,github-api-test-org/jenkins,stefanbrausch/hudson-main,MarkEWaite/jenkins,mdonohue/jenkins,ChrisA89/jenkins,hashar/jenkins,github-api-test-org/jenkins,scoheb/jenkins,MarkEWaite/jenkins,kzantow/jenkins,varmenise/jenkins,kohsuke/hudson,DoctorQ/jenkins,huybrechts/hudson,my7seven/jenkins,pjanouse/jenkins,rlugojr/jenkins,wuwen5/jenkins,thomassuckow/jenkins,SenolOzer/jenkins,rashmikanta-1984/jenkins,CodeShane/jenkins,batmat/jenkins,jtnord/jenkins,ns163/jenkins,lordofthejars/jenkins,pselle/jenkins,iterate/coding-dojo,guoxu0514/jenkins,MichaelPranovich/jenkins_sc,aquarellian/jenkins,daspilker/jenkins,akshayabd/jenkins,brunocvcunha/jenkins,kzantow/jenkins,deadmoose/jenkins,morficus/jenkins,SebastienGllmt/jenkins,NehemiahMi/jenkins,everyonce/jenkins,gorcz/jenkins,Vlatombe/jenkins,soenter/jenkins,Jimilian/jenkins,scoheb/jenkins,gitaccountforprashant/gittest,synopsys-arc-oss/jenkins,vijayto/jenkins,escoem/jenkins,ndeloof/jenkins,azweb76/jenkins,aheritier/jenkins,deadmoose/jenkins,tfennelly/jenkins,pantheon-systems/jenkins,jk47/jenkins,yonglehou/jenkins,liupugong/jenkins,pjanouse/jenkins,soenter/jenkins,deadmoose/jenkins,MarkEWaite/jenkins,mcanthony/jenkins,SenolOzer/jenkins,thomassuckow/jenkins,goldchang/jenkins,amuniz/jenkins,ajshastri/jenkins,mrooney/jenkins,KostyaSha/jenkins,luoqii/jenkins,msrb/jenkins,keyurpatankar/hudson,chbiel/jenkins,andresrc/jenkins,petermarcoen/jenkins,CodeShane/jenkins,gitaccountforprashant/gittest,patbos/jenkins,Ykus/jenkins,jenkinsci/jenkins,vlajos/jenkins,DanielWeber/jenkins,paulwellnerbou/jenkins,MadsNielsen/jtemp,khmarbaise/jenkins,DanielWeber/jenkins,khmarbaise/jenkins,lvotypko/jenkins2,6WIND/jenkins,keyurpatankar/hudson,jtnord/jenkins,mattclark/jenkins,KostyaSha/jenkins,seanlin816/jenkins,bkmeneguello/jenkins,stephenc/jenkins,goldchang/jenkins,liorhson/jenkins,github-api-test-org/jenkins,nandan4/Jenkins,noikiy/jenkins,evernat/jenkins,hudson/hudson-2.x,6WIND/jenkins,SebastienGllmt/jenkins,mcanthony/jenkins,ydubreuil/jenkins,samatdav/jenkins,verbitan/jenkins,kohsuke/hudson,1and1/jenkins,evernat/jenkins,aquarellian/jenkins,ajshastri/jenkins,pjanouse/jenkins,luoqii/jenkins,lordofthejars/jenkins,maikeffi/hudson,verbitan/jenkins,ns163/jenkins,jglick/jenkins,oleg-nenashev/jenkins,mpeltonen/jenkins,oleg-nenashev/jenkins,hudson/hudson-2.x,pjanouse/jenkins,arunsingh/jenkins,Jochen-A-Fuerbacher/jenkins,everyonce/jenkins,MarkEWaite/jenkins,jk47/jenkins,ns163/jenkins,github-api-test-org/jenkins,huybrechts/hudson,paulmillar/jenkins,292388900/jenkins,aldaris/jenkins,Jimilian/jenkins,elkingtonmcb/jenkins,jpbriend/jenkins,vvv444/jenkins,CodeShane/jenkins,github-api-test-org/jenkins,yonglehou/jenkins,amruthsoft9/Jenkis,yonglehou/jenkins,ChrisA89/jenkins,fbelzunc/jenkins,dbroady1/jenkins,akshayabd/jenkins,arcivanov/jenkins,viqueen/jenkins,MichaelPranovich/jenkins_sc,gusreiber/jenkins,tastatur/jenkins,hashar/jenkins,NehemiahMi/jenkins,my7seven/jenkins,petermarcoen/jenkins,1and1/jenkins,FarmGeek4Life/jenkins,vlajos/jenkins,arcivanov/jenkins,ikedam/jenkins,jcarrothers-sap/jenkins,aheritier/jenkins,Jochen-A-Fuerbacher/jenkins,NehemiahMi/jenkins,pantheon-systems/jenkins,escoem/jenkins,mcanthony/jenkins,MichaelPranovich/jenkins_sc,sathiya-mit/jenkins,goldchang/jenkins,dbroady1/jenkins,aquarellian/jenkins,albers/jenkins,ajshastri/jenkins,stefanbrausch/hudson-main,everyonce/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,1and1/jenkins,jhoblitt/jenkins,ndeloof/jenkins,rashmikanta-1984/jenkins,vjuranek/jenkins,iterate/coding-dojo,MadsNielsen/jtemp,jglick/jenkins,daniel-beck/jenkins,keyurpatankar/hudson,fbelzunc/jenkins,rlugojr/jenkins,jenkinsci/jenkins,patbos/jenkins,jcarrothers-sap/jenkins,lvotypko/jenkins3,stefanbrausch/hudson-main,damianszczepanik/jenkins,jk47/jenkins,patbos/jenkins,mrooney/jenkins,patbos/jenkins,v1v/jenkins,csimons/jenkins,godfath3r/jenkins,msrb/jenkins,hemantojhaa/jenkins,hudson/hudson-2.x,gitaccountforprashant/gittest,damianszczepanik/jenkins,tfennelly/jenkins,paulwellnerbou/jenkins,ajshastri/jenkins,petermarcoen/jenkins,jglick/jenkins,mrobinet/jenkins,olivergondza/jenkins,vvv444/jenkins,chbiel/jenkins,Ykus/jenkins,azweb76/jenkins,aduprat/jenkins,FTG-003/jenkins,yonglehou/jenkins,varmenise/jenkins,verbitan/jenkins,paulmillar/jenkins,FarmGeek4Life/jenkins,lvotypko/jenkins,kzantow/jenkins,arunsingh/jenkins,daspilker/jenkins,jk47/jenkins,chbiel/jenkins,DanielWeber/jenkins,CodeShane/jenkins,lilyJi/jenkins,lvotypko/jenkins2,SebastienGllmt/jenkins,jpederzolli/jenkins-1,svanoort/jenkins,dennisjlee/jenkins,jpederzolli/jenkins-1,paulwellnerbou/jenkins,CodeShane/jenkins,vijayto/jenkins,tangkun75/jenkins,jenkinsci/jenkins,ErikVerheul/jenkins,ydubreuil/jenkins,jglick/jenkins,tangkun75/jenkins,lvotypko/jenkins3,bpzhang/jenkins,duzifang/my-jenkins,thomassuckow/jenkins,hplatou/jenkins,ydubreuil/jenkins,lvotypko/jenkins3,lindzh/jenkins,h4ck3rm1k3/jenkins,DoctorQ/jenkins,dariver/jenkins,aquarellian/jenkins,alvarolobato/jenkins,vijayto/jenkins,mrobinet/jenkins,jcsirot/jenkins,KostyaSha/jenkins,lordofthejars/jenkins,aduprat/jenkins,my7seven/jenkins,maikeffi/hudson,varmenise/jenkins,rashmikanta-1984/jenkins,Wilfred/jenkins,morficus/jenkins,morficus/jenkins,lilyJi/jenkins,pantheon-systems/jenkins,mpeltonen/jenkins,gusreiber/jenkins,Krasnyanskiy/jenkins,thomassuckow/jenkins,hudson/hudson-2.x,recena/jenkins,duzifang/my-jenkins,oleg-nenashev/jenkins,batmat/jenkins,daspilker/jenkins,mattclark/jenkins,NehemiahMi/jenkins,soenter/jenkins,jhoblitt/jenkins,ndeloof/jenkins,lvotypko/jenkins2,mrobinet/jenkins,vijayto/jenkins,dariver/jenkins,dbroady1/jenkins,deadmoose/jenkins,bpzhang/jenkins,vjuranek/jenkins,akshayabd/jenkins,Vlatombe/jenkins,daniel-beck/jenkins,samatdav/jenkins,jpederzolli/jenkins-1,amuniz/jenkins,mrobinet/jenkins,maikeffi/hudson,intelchen/jenkins,duzifang/my-jenkins,ndeloof/jenkins,alvarolobato/jenkins,seanlin816/jenkins,csimons/jenkins,jcarrothers-sap/jenkins,yonglehou/jenkins,daniel-beck/jenkins,mpeltonen/jenkins,bpzhang/jenkins,hemantojhaa/jenkins,huybrechts/hudson,mrooney/jenkins,fbelzunc/jenkins,hashar/jenkins,protazy/jenkins,jzjzjzj/jenkins,khmarbaise/jenkins,petermarcoen/jenkins,protazy/jenkins,sathiya-mit/jenkins,brunocvcunha/jenkins,azweb76/jenkins,FTG-003/jenkins,sathiya-mit/jenkins,gorcz/jenkins,goldchang/jenkins,tangkun75/jenkins,alvarolobato/jenkins,hplatou/jenkins,daspilker/jenkins,maikeffi/hudson,AustinKwang/jenkins,iterate/coding-dojo,rsandell/jenkins,tastatur/jenkins,FTG-003/jenkins,kohsuke/hudson,viqueen/jenkins,jhoblitt/jenkins,everyonce/jenkins,escoem/jenkins,khmarbaise/jenkins,6WIND/jenkins,paulwellnerbou/jenkins,iqstack/jenkins,jzjzjzj/jenkins,Vlatombe/jenkins,damianszczepanik/jenkins,liorhson/jenkins,elkingtonmcb/jenkins,abayer/jenkins,jtnord/jenkins,seanlin816/jenkins,luoqii/jenkins,Ykus/jenkins,oleg-nenashev/jenkins,csimons/jenkins,NehemiahMi/jenkins,hashar/jenkins,v1v/jenkins,292388900/jenkins,synopsys-arc-oss/jenkins,tastatur/jenkins,goldchang/jenkins,abayer/jenkins,jhoblitt/jenkins,morficus/jenkins,synopsys-arc-oss/jenkins,my7seven/jenkins,lindzh/jenkins,iqstack/jenkins,mrobinet/jenkins,albers/jenkins,aldaris/jenkins,morficus/jenkins,ErikVerheul/jenkins,stefanbrausch/hudson-main,Wilfred/jenkins,rashmikanta-1984/jenkins,singh88/jenkins,patbos/jenkins,dariver/jenkins,ajshastri/jenkins,v1v/jenkins,aheritier/jenkins,lvotypko/jenkins3,lilyJi/jenkins,maikeffi/hudson,aduprat/jenkins,pselle/jenkins,soenter/jenkins,ChrisA89/jenkins,pselle/jenkins,svanoort/jenkins,jcsirot/jenkins,gitaccountforprashant/gittest,albers/jenkins,intelchen/jenkins,soenter/jenkins,samatdav/jenkins,evernat/jenkins,khmarbaise/jenkins,Wilfred/jenkins,h4ck3rm1k3/jenkins,bkmeneguello/jenkins,KostyaSha/jenkins,lilyJi/jenkins,lvotypko/jenkins,bpzhang/jenkins,liupugong/jenkins,olivergondza/jenkins,Jochen-A-Fuerbacher/jenkins,DoctorQ/jenkins,damianszczepanik/jenkins,mattclark/jenkins,paulmillar/jenkins,tfennelly/jenkins,ndeloof/jenkins,everyonce/jenkins,mrobinet/jenkins,amruthsoft9/Jenkis,Krasnyanskiy/jenkins,mdonohue/jenkins,jzjzjzj/jenkins,1and1/jenkins,dennisjlee/jenkins,escoem/jenkins,rashmikanta-1984/jenkins,6WIND/jenkins,varmenise/jenkins,292388900/jenkins,olivergondza/jenkins,292388900/jenkins,rsandell/jenkins,aldaris/jenkins,jtnord/jenkins,csimons/jenkins,recena/jenkins,iqstack/jenkins,bkmeneguello/jenkins,guoxu0514/jenkins,intelchen/jenkins,pantheon-systems/jenkins,AustinKwang/jenkins,olivergondza/jenkins,dennisjlee/jenkins,jcsirot/jenkins,vlajos/jenkins,my7seven/jenkins,protazy/jenkins
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Tom Huybrechts, Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks.test;
import hudson.Util;
import hudson.Functions;
import hudson.model.*;
import hudson.tasks.junit.History;
import hudson.tasks.junit.TestAction;
import hudson.tasks.junit.TestResultAction;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.export.ExportedBean;
import com.google.common.collect.MapMaker;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;
/**
* Base class for all test result objects.
* For compatibility with code that expects this class to be in hudson.tasks.junit,
* we've created a pure-abstract class, hudson.tasks.junit.TestObject. That
* stub class is deprecated; instead, people should use this class.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public abstract class TestObject extends hudson.tasks.junit.TestObject {
private static final Logger LOGGER = Logger.getLogger(TestObject.class.getName());
private volatile transient String id;
public abstract AbstractBuild<?, ?> getOwner();
/**
* Reverse pointer of {@link TabulatedResult#getChildren()}.
*/
public abstract TestObject getParent();
@Override
public final String getId() {
if (id == null) {
StringBuilder buf = new StringBuilder();
buf.append(getSafeName());
TestObject parent = getParent();
if (parent != null) {
String parentId = parent.getId();
if ((parentId != null) && (parentId.length() > 0)) {
buf.insert(0, '/');
buf.insert(0, parent.getId());
}
}
id = buf.toString();
}
return id;
}
/**
* Returns url relative to TestResult
*/
@Override
public String getUrl() {
return '/' + getId();
}
/**
* Returns the top level test result data.
*
* @deprecated This method returns a JUnit specific class. Use
* {@link #getTopLevelTestResult()} instead for a more general interface.
* @return
*/
@Override
public hudson.tasks.junit.TestResult getTestResult() {
TestObject parent = getParent();
return (parent == null ? null : getParent().getTestResult());
}
/**
* Returns the top level test result data.
*
* @return
*/
public TestResult getTopLevelTestResult() {
TestObject parent = getParent();
return (parent == null ? null : getParent().getTopLevelTestResult());
}
/**
* Computes the relative path to get to this test object from <code>it</code>. If
* <code>it</code> does not appear in the parent chain for this object, a
* relative path from the server root will be returned.
*
* @return A relative path to this object, potentially from the top of the
* Hudson object model
*/
public String getRelativePathFrom(TestObject it) {
// if (it is one of my ancestors) {
// return a relative path from it
// } else {
// return a complete path starting with "/"
// }
if (it==this) {
return ".";
}
StringBuilder buf = new StringBuilder();
TestObject next = this;
TestObject cur = this;
// Walk up my ancesotors from leaf to root, looking for "it"
// and accumulating a relative url as I go
while (next!=null && it!=next) {
cur = next;
buf.insert(0,'/');
buf.insert(0,cur.getSafeName());
next = cur.getParent();
}
if (it==next) {
return buf.toString();
} else {
// Keep adding on to the string we've built so far
// Start with the test result action
AbstractTestResultAction action = getTestResultAction();
if (action==null) {
LOGGER.warning("trying to get relative path, but we can't determine the action that owns this result.");
return ""; // this won't take us to the right place, but it also won't 404.
}
buf.insert(0,'/');
buf.insert(0,action.getUrlName());
// Now the build
AbstractBuild<?,?> myBuild = cur.getOwner();
if (myBuild ==null) {
LOGGER.warning("trying to get relative path, but we can't determine the build that owns this result.");
return ""; // this won't take us to the right place, but it also won't 404.
}
buf.insert(0,'/');
buf.insert(0,myBuild.getUrl());
// If we're inside a stapler request, just delegate to Hudson.Functions to get the relative path!
StaplerRequest req = Stapler.getCurrentRequest();
if (req!=null && myBuild instanceof Item) {
buf.insert(0, '/');
// Ugly but I don't see how else to convince the compiler that myBuild is an Item
Item myBuildAsItem = (Item) myBuild;
buf.insert(0, Functions.getRelativeLinkTo(myBuildAsItem));
} else {
// We're not in a stapler request. Okay, give up.
LOGGER.info("trying to get relative path, but it is not my ancestor, and we're not in a stapler request. Trying absolute hudson url...");
String hudsonRootUrl = Hudson.getInstance().getRootUrl();
if (hudsonRootUrl==null||hudsonRootUrl.length()==0) {
LOGGER.warning("Can't find anything like a decent hudson url. Punting, returning empty string.");
return "";
}
buf.insert(0, '/');
buf.insert(0, hudsonRootUrl);
}
LOGGER.info("Here's our relative path: " + buf.toString());
return buf.toString();
}
}
/**
* Subclasses may override this method if they are
* associated with a particular subclass of
* AbstractTestResultAction.
*
* @return the test result action that connects this test result to a particular build
*/
@Override
public AbstractTestResultAction getTestResultAction() {
AbstractBuild<?, ?> owner = getOwner();
if (owner != null) {
return owner.getAction(AbstractTestResultAction.class);
} else {
LOGGER.warning("owner is null when trying to getTestResultAction.");
return null;
}
}
/**
* Get a list of all TestActions associated with this TestObject.
* @return
*/
@Override
public List<TestAction> getTestActions() {
AbstractTestResultAction atra = getTestResultAction();
if ((atra != null) && (atra instanceof TestResultAction)) {
TestResultAction tra = (TestResultAction) atra;
return tra.getActions(this);
} else {
return new ArrayList<TestAction>();
}
}
/**
* Gets a test action of the class passed in.
* @param klazz
* @param <T> an instance of the class passed in
* @return
*/
@Override
public <T> T getTestAction(Class<T> klazz) {
for (TestAction action : getTestActions()) {
if (klazz.isAssignableFrom(action.getClass())) {
return klazz.cast(action);
}
}
return null;
}
/**
* Gets the counterpart of this {@link TestResult} in the previous run.
*
* @return null if no such counter part exists.
*/
public abstract TestResult getPreviousResult();
/**
* Gets the counterpart of this {@link TestResult} in the specified run.
*
* @return null if no such counter part exists.
*/
public abstract TestResult getResultInBuild(AbstractBuild<?, ?> build);
/**
* Find the test result corresponding to the one identified by <code>id></code>
* withint this test result.
*
* @param id The path to the original test result
* @return A corresponding test result, or null if there is no corresponding
* result.
*/
public abstract TestResult findCorrespondingResult(String id);
/**
* Time took to run this test. In seconds.
*/
public abstract float getDuration();
/**
* Returns the string representation of the {@link #getDuration()}, in a
* human readable format.
*/
@Override
public String getDurationString() {
return Util.getTimeSpanString((long) (getDuration() * 1000));
}
@Override
public String getDescription() {
AbstractTestResultAction action = getTestResultAction();
if (action != null) {
return action.getDescription(this);
}
return "";
}
@Override
public void setDescription(String description) {
AbstractTestResultAction action = getTestResultAction();
if (action != null) {
action.setDescription(this, description);
}
}
/**
* Exposes this object through the remote API.
*/
@Override
public Api getApi() {
return new Api(this);
}
/**
* Gets the name of this object.
*/
@Override
public/* abstract */ String getName() {
return "";
}
/**
* Gets the version of {@link #getName()} that's URL-safe.
*/
@Override
public String getSafeName() {
return safe(getName());
}
@Override
public String getSearchUrl() {
return getSafeName();
}
/**
* #2988: uniquifies a {@link #getSafeName} amongst children of the parent.
*/
protected final synchronized String uniquifyName(
Collection<? extends TestObject> siblings, String base) {
String uniquified = base;
int sequence = 1;
for (TestObject sibling : siblings) {
if (sibling != this && uniquified.equals(UNIQUIFIED_NAMES.get(sibling))) {
uniquified = base + '_' + ++sequence;
}
}
UNIQUIFIED_NAMES.put(this, uniquified);
return uniquified;
}
private static final Map<TestObject, String> UNIQUIFIED_NAMES = new MapMaker().weakKeys().makeMap();
/**
* Replaces URL-unsafe characters.
*/
public static String safe(String s) {
// 3 replace calls is still 2-3x faster than a regex replaceAll
return s.replace('/', '_').replace('\\', '_').replace(':', '_');
}
/**
* Gets the total number of passed tests.
*/
public abstract int getPassCount();
/**
* Gets the total number of failed tests.
*/
public abstract int getFailCount();
/**
* Gets the total number of skipped tests.
*/
public abstract int getSkipCount();
/**
* Gets the total number of tests.
*/
@Override
public int getTotalCount() {
return getPassCount() + getFailCount() + getSkipCount();
}
@Override
public History getHistory() {
return new History(this);
}
public Object getDynamic(String token, StaplerRequest req,
StaplerResponse rsp) {
for (Action a : getTestActions()) {
if (a == null) {
continue; // be defensive
}
String urlName = a.getUrlName();
if (urlName == null) {
continue;
}
if (urlName.equals(token)) {
return a;
}
}
return null;
}
public synchronized HttpResponse doSubmitDescription(
@QueryParameter String description) throws IOException,
ServletException {
if (getOwner() == null) {
LOGGER.severe("getOwner() is null, can't save description.");
} else {
getOwner().checkPermission(Run.UPDATE);
setDescription(description);
getOwner().save();
}
return new HttpRedirect(".");
}
private static final long serialVersionUID = 1L;
}
|
core/src/main/java/hudson/tasks/test/TestObject.java
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Tom Huybrechts, Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks.test;
import hudson.Util;
import hudson.Functions;
import hudson.model.*;
import hudson.tasks.junit.History;
import hudson.tasks.junit.TestAction;
import hudson.tasks.junit.TestResultAction;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.export.ExportedBean;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;
/**
* Base class for all test result objects.
* For compatibility with code that expects this class to be in hudson.tasks.junit,
* we've created a pure-abstract class, hudson.tasks.junit.TestObject. That
* stub class is deprecated; instead, people should use this class.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public abstract class TestObject extends hudson.tasks.junit.TestObject {
private static final Logger LOGGER = Logger.getLogger(TestObject.class.getName());
private volatile transient String id;
public abstract AbstractBuild<?, ?> getOwner();
/**
* Reverse pointer of {@link TabulatedResult#getChildren()}.
*/
public abstract TestObject getParent();
@Override
public final String getId() {
if (id == null) {
StringBuilder buf = new StringBuilder();
buf.append(getSafeName());
TestObject parent = getParent();
if (parent != null) {
String parentId = parent.getId();
if ((parentId != null) && (parentId.length() > 0)) {
buf.insert(0, '/');
buf.insert(0, parent.getId());
}
}
id = buf.toString();
}
return id;
}
/**
* Returns url relative to TestResult
*/
@Override
public String getUrl() {
return '/' + getId();
}
/**
* Returns the top level test result data.
*
* @deprecated This method returns a JUnit specific class. Use
* {@link #getTopLevelTestResult()} instead for a more general interface.
* @return
*/
@Override
public hudson.tasks.junit.TestResult getTestResult() {
TestObject parent = getParent();
return (parent == null ? null : getParent().getTestResult());
}
/**
* Returns the top level test result data.
*
* @return
*/
public TestResult getTopLevelTestResult() {
TestObject parent = getParent();
return (parent == null ? null : getParent().getTopLevelTestResult());
}
/**
* Computes the relative path to get to this test object from <code>it</code>. If
* <code>it</code> does not appear in the parent chain for this object, a
* relative path from the server root will be returned.
*
* @return A relative path to this object, potentially from the top of the
* Hudson object model
*/
public String getRelativePathFrom(TestObject it) {
// if (it is one of my ancestors) {
// return a relative path from it
// } else {
// return a complete path starting with "/"
// }
if (it==this) {
return ".";
}
StringBuilder buf = new StringBuilder();
TestObject next = this;
TestObject cur = this;
// Walk up my ancesotors from leaf to root, looking for "it"
// and accumulating a relative url as I go
while (next!=null && it!=next) {
cur = next;
buf.insert(0,'/');
buf.insert(0,cur.getSafeName());
next = cur.getParent();
}
if (it==next) {
return buf.toString();
} else {
// Keep adding on to the string we've built so far
// Start with the test result action
AbstractTestResultAction action = getTestResultAction();
if (action==null) {
LOGGER.warning("trying to get relative path, but we can't determine the action that owns this result.");
return ""; // this won't take us to the right place, but it also won't 404.
}
buf.insert(0,'/');
buf.insert(0,action.getUrlName());
// Now the build
AbstractBuild<?,?> myBuild = cur.getOwner();
if (myBuild ==null) {
LOGGER.warning("trying to get relative path, but we can't determine the build that owns this result.");
return ""; // this won't take us to the right place, but it also won't 404.
}
buf.insert(0,'/');
buf.insert(0,myBuild.getUrl());
// If we're inside a stapler request, just delegate to Hudson.Functions to get the relative path!
StaplerRequest req = Stapler.getCurrentRequest();
if (req!=null && myBuild instanceof Item) {
buf.insert(0, '/');
// Ugly but I don't see how else to convince the compiler that myBuild is an Item
Item myBuildAsItem = (Item) myBuild;
buf.insert(0, Functions.getRelativeLinkTo(myBuildAsItem));
} else {
// We're not in a stapler request. Okay, give up.
LOGGER.info("trying to get relative path, but it is not my ancestor, and we're not in a stapler request. Trying absolute hudson url...");
String hudsonRootUrl = Hudson.getInstance().getRootUrl();
if (hudsonRootUrl==null||hudsonRootUrl.length()==0) {
LOGGER.warning("Can't find anything like a decent hudson url. Punting, returning empty string.");
return "";
}
buf.insert(0, '/');
buf.insert(0, hudsonRootUrl);
}
LOGGER.info("Here's our relative path: " + buf.toString());
return buf.toString();
}
}
/**
* Subclasses may override this method if they are
* associated with a particular subclass of
* AbstractTestResultAction.
*
* @return the test result action that connects this test result to a particular build
*/
@Override
public AbstractTestResultAction getTestResultAction() {
AbstractBuild<?, ?> owner = getOwner();
if (owner != null) {
return owner.getAction(AbstractTestResultAction.class);
} else {
LOGGER.warning("owner is null when trying to getTestResultAction.");
return null;
}
}
/**
* Get a list of all TestActions associated with this TestObject.
* @return
*/
@Override
public List<TestAction> getTestActions() {
AbstractTestResultAction atra = getTestResultAction();
if ((atra != null) && (atra instanceof TestResultAction)) {
TestResultAction tra = (TestResultAction) atra;
return tra.getActions(this);
} else {
return new ArrayList<TestAction>();
}
}
/**
* Gets a test action of the class passed in.
* @param klazz
* @param <T> an instance of the class passed in
* @return
*/
@Override
public <T> T getTestAction(Class<T> klazz) {
for (TestAction action : getTestActions()) {
if (klazz.isAssignableFrom(action.getClass())) {
return klazz.cast(action);
}
}
return null;
}
/**
* Gets the counterpart of this {@link TestResult} in the previous run.
*
* @return null if no such counter part exists.
*/
public abstract TestResult getPreviousResult();
/**
* Gets the counterpart of this {@link TestResult} in the specified run.
*
* @return null if no such counter part exists.
*/
public abstract TestResult getResultInBuild(AbstractBuild<?, ?> build);
/**
* Find the test result corresponding to the one identified by <code>id></code>
* withint this test result.
*
* @param id The path to the original test result
* @return A corresponding test result, or null if there is no corresponding
* result.
*/
public abstract TestResult findCorrespondingResult(String id);
/**
* Time took to run this test. In seconds.
*/
public abstract float getDuration();
/**
* Returns the string representation of the {@link #getDuration()}, in a
* human readable format.
*/
@Override
public String getDurationString() {
return Util.getTimeSpanString((long) (getDuration() * 1000));
}
@Override
public String getDescription() {
AbstractTestResultAction action = getTestResultAction();
if (action != null) {
return action.getDescription(this);
}
return "";
}
@Override
public void setDescription(String description) {
AbstractTestResultAction action = getTestResultAction();
if (action != null) {
action.setDescription(this, description);
}
}
/**
* Exposes this object through the remote API.
*/
@Override
public Api getApi() {
return new Api(this);
}
/**
* Gets the name of this object.
*/
@Override
public/* abstract */ String getName() {
return "";
}
/**
* Gets the version of {@link #getName()} that's URL-safe.
*/
@Override
public String getSafeName() {
return safe(getName());
}
@Override
public String getSearchUrl() {
return getSafeName();
}
/**
* #2988: uniquifies a {@link #getSafeName} amongst children of the parent.
*/
protected final synchronized String uniquifyName(
Collection<? extends TestObject> siblings, String base) {
String uniquified = base;
int sequence = 1;
for (TestObject sibling : siblings) {
if (sibling != this && uniquified.equals(UNIQUIFIED_NAMES.get(sibling))) {
uniquified = base + '_' + ++sequence;
}
}
UNIQUIFIED_NAMES.put(this, uniquified);
return uniquified;
}
private static final Map<TestObject, String> UNIQUIFIED_NAMES = new WeakHashMap<TestObject, String>();
/**
* Replaces URL-unsafe characters.
*/
public static String safe(String s) {
// 3 replace calls is still 2-3x faster than a regex replaceAll
return s.replace('/', '_').replace('\\', '_').replace(':', '_');
}
/**
* Gets the total number of passed tests.
*/
public abstract int getPassCount();
/**
* Gets the total number of failed tests.
*/
public abstract int getFailCount();
/**
* Gets the total number of skipped tests.
*/
public abstract int getSkipCount();
/**
* Gets the total number of tests.
*/
@Override
public int getTotalCount() {
return getPassCount() + getFailCount() + getSkipCount();
}
@Override
public History getHistory() {
return new History(this);
}
public Object getDynamic(String token, StaplerRequest req,
StaplerResponse rsp) {
for (Action a : getTestActions()) {
if (a == null) {
continue; // be defensive
}
String urlName = a.getUrlName();
if (urlName == null) {
continue;
}
if (urlName.equals(token)) {
return a;
}
}
return null;
}
public synchronized HttpResponse doSubmitDescription(
@QueryParameter String description) throws IOException,
ServletException {
if (getOwner() == null) {
LOGGER.severe("getOwner() is null, can't save description.");
} else {
getOwner().checkPermission(Run.UPDATE);
setDescription(description);
getOwner().save();
}
return new HttpRedirect(".");
}
private static final long serialVersionUID = 1L;
}
|
WeakHashMap TestObject.UNIQUIFIED_NAMES was being used from multiple threads.
Replacement with google-collections MapMaker
|
core/src/main/java/hudson/tasks/test/TestObject.java
|
WeakHashMap TestObject.UNIQUIFIED_NAMES was being used from multiple threads. Replacement with google-collections MapMaker
|
|
Java
|
mit
|
a9644452c69a35c7126a99b02589a54dd8410a0d
| 0
|
CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw
|
/*
* Copyright (C) 2017 CenturyLink, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.mdw.util.log;
import com.centurylink.mdw.common.service.WebSocketMessenger;
import com.centurylink.mdw.config.PropertyManager;
import com.centurylink.mdw.constant.PropertyNames;
import com.centurylink.mdw.model.JsonObject;
import com.centurylink.mdw.model.workflow.TransitionStatus;
import com.centurylink.mdw.model.workflow.WorkStatus;
import com.centurylink.mdw.soccom.SoccomClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class AbstractStandardLoggerBase implements StandardLogger {
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 7181;
protected static String dateFormat = "yyyyMMdd.HH:mm:ss.SSS";
private static final String MESSAGE_REG_EX = "\\[\\(.\\)([0-9.:]+) p([0-9]+)\\.([0-9]+) ([a-z])([0-9]+)?\\.([^]]+)] (.*)";
private static Pattern pattern = Pattern.compile(MESSAGE_REG_EX, Pattern.DOTALL);
protected static String watcher = null;
public String getDefaultHost() {
return DEFAULT_HOST;
}
public int getDefaultPort() {
return DEFAULT_PORT;
}
public void refreshWatcher() {
watcher = PropertyManager.getProperty(PropertyNames.MDW_LOGGING_WATCHER);
}
protected String generateLogLine(char type, String tag, String message) {
StringBuffer sb = new StringBuffer();
sb.append("[(");
sb.append(type);
sb.append(")");
sb.append(new SimpleDateFormat(dateFormat).format(new Date()));
if (tag!=null) {
sb.append(" ");
sb.append(tag);
} else {
sb.append(" ~");
sb.append(Thread.currentThread().getId());
}
sb.append("] ");
sb.append(message);
return sb.toString();
}
public boolean watching() {
return watcher != null;
}
protected JSONObject buildJSONLogMessage(String message) throws JSONException, ParseException {
JSONObject obj = null;
Matcher matcher = pattern.matcher(message);
String subtype = null;
String msg = null;
if (matcher.matches()) {
obj = new JsonObject();
obj.put("name", "LogWatcher");
String t = matcher.group(1);
obj.put("time", new SimpleDateFormat(dateFormat).parse(t).toInstant());
obj.put("procId", new Long(matcher.group(2)));
obj.put("procInstId", new Long(matcher.group(3)));
subtype = matcher.group(4);
obj.put("subtype", subtype);
String id = matcher.group(5);
if (id != null)
obj.put("id", Long.parseLong(id));
String instId = matcher.group(6);
if (instId != null) {
try {
obj.put("instId", Long.parseLong(instId));
}
catch (NumberFormatException ex) {
// master request id needn't be numeric
obj.put("instId", instId);
}
}
msg = matcher.group(7);
obj.put("msg", msg);
}
if ("a".equals(subtype) && msg != null) {
if (msg.startsWith(WorkStatus.LOGMSG_COMPLETE)) {
obj.put("status", WorkStatus.STATUS_COMPLETED);
} else if (msg.startsWith(WorkStatus.LOGMSG_START)) {
obj.put("status", WorkStatus.STATUS_IN_PROGRESS);
} else if (msg.startsWith(WorkStatus.LOGMSG_FAILED)) {
obj.put("status", WorkStatus.STATUS_FAILED);
} else if (msg.startsWith(WorkStatus.LOGMSG_SUSPEND)) {
obj.put("status", WorkStatus.STATUS_WAITING);
} else if (msg.startsWith(WorkStatus.LOGMSG_HOLD)) {
obj.put("status", WorkStatus.STATUS_HOLD);
}
}
else if ("t".equals(subtype)) {
obj.put("status", TransitionStatus.STATUS_COMPLETED);
}
else if ("m".equals(subtype)) {
}
return obj;
}
protected void sendToWatchers(String message) {
if (watching())
sendToWatcher(message);
try {
JSONObject jsonObj = buildJSONLogMessage(message);
if (jsonObj != null && jsonObj.has("procInstId") && jsonObj.has("procId")) {
sendToWebWatcher(String.valueOf(jsonObj.get("procInstId")), jsonObj);
sendToWebWatcher(String.valueOf(jsonObj.get("procId")), jsonObj);
}
else if (jsonObj != null && jsonObj.has("masterRequestId")) {
sendToWebWatcher(jsonObj.getString("masterRequestId"), jsonObj);
}
}
catch (Throwable e) {
System.out.println("Error building log watcher json for: '" + message + "' -> " + e);
e.printStackTrace();
};
}
protected void sendToWatcher(String message) {
SoccomClient client = null;
try {
String[] spec = watcher.split(":");
String host = spec.length > 0 ? spec[0] : getDefaultHost();
int port = spec.length > 1 ? Integer.parseInt(spec[1]) : getDefaultPort();
client = new SoccomClient(host, port, null);
client.putreq(message);
} catch (Exception e) {
watcher = null;
System.out.println("Exception when sending log messages to watcher - turn it off");
e.printStackTrace();
} finally {
if (client!=null) client.close();
}
}
protected void sendToWebWatcher(String topic, JSONObject message) throws JSONException, IOException {
WebSocketMessenger.getInstance().send(topic, message.toString());
}
@Override
public boolean isInfoEnabled() {
return isEnabledFor(LogLevel.INFO);
}
@Override
public boolean isDebugEnabled() {
return isEnabledFor(LogLevel.DEBUG);
}
@Override
public boolean isTraceEnabled() {
return isEnabledFor(LogLevel.TRACE);
}
@Override
public boolean isMdwDebugEnabled() {
return isEnabledFor(LogLevel.TRACE);
}
private void logIt(LogLevel level, String message, Throwable t) {
String origMsg = message;
int index = message.indexOf(" ");
if (index > 0 && message.startsWith("[("))
message = "[" + message.substring(index+1);
switch (level.toString()) {
case "INFO":
if (t == null)
info(message);
else
info(message, t);
break;
case "ERROR":
if (t == null)
error(message);
else
error(message, t);
break;
case "DEBUG":
if (t == null)
debug(message);
else
debug(message, t);
break;
case "WARN":
if (t == null)
warn(message);
else
warn(message, t);
break;
case "TRACE":
if (t == null)
trace(message);
else
trace(message, t);
break;
default: break;
}
sendToWatchers(origMsg);
}
@Override
public void exception(String tag, String message, Throwable e) {
String line = generateLogLine('e', tag, message);
logIt(LogLevel.ERROR, line, e);
}
public void info(String tag, String message) {
if (isInfoEnabled()) {
String line = generateLogLine('i', tag, message);
logIt(LogLevel.INFO, line, null);
}
}
public void debug(String tag, String message) {
if (isDebugEnabled()) {
String line = generateLogLine('d', tag, message);
logIt(LogLevel.DEBUG, line, null);
}
}
public void warn(String tag, String message) {
String line = generateLogLine('w', tag, message);
logIt(LogLevel.WARN, line, null);
}
public void severe(String tag, String message) {
String line = generateLogLine('s', tag, message);
logIt(LogLevel.ERROR, line, null);
}
public void trace(String tag, String message) {
if (isTraceEnabled()) {
String line = generateLogLine('t', tag, message);
logIt(LogLevel.TRACE, line, null);
}
}
}
|
mdw-common/src/com/centurylink/mdw/util/log/AbstractStandardLoggerBase.java
|
/*
* Copyright (C) 2017 CenturyLink, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.mdw.util.log;
import com.centurylink.mdw.common.service.WebSocketMessenger;
import com.centurylink.mdw.config.PropertyManager;
import com.centurylink.mdw.constant.PropertyNames;
import com.centurylink.mdw.model.JsonObject;
import com.centurylink.mdw.model.workflow.TransitionStatus;
import com.centurylink.mdw.model.workflow.WorkStatus;
import com.centurylink.mdw.soccom.SoccomClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class AbstractStandardLoggerBase implements StandardLogger {
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 7181;
protected static String dateFormat = "yyyyMMdd.HH:mm:ss.SSS";
private static final String MESSAGE_REG_EX = "\\[\\(.\\)([0-9.:]+) p([0-9]+)\\.([0-9]+) ([a-z])([0-9]+)?\\.([^]]+)] (.*)";
private static Pattern pattern = Pattern.compile(MESSAGE_REG_EX, Pattern.DOTALL);
protected static String watcher = null;
public String getDefaultHost() {
return DEFAULT_HOST;
}
public int getDefaultPort() {
return DEFAULT_PORT;
}
public void refreshWatcher() {
watcher = PropertyManager.getProperty(PropertyNames.MDW_LOGGING_WATCHER);
}
protected String generateLogLine(char type, String tag, String message) {
StringBuffer sb = new StringBuffer();
sb.append("[(");
sb.append(type);
sb.append(")");
sb.append(new SimpleDateFormat(dateFormat).format(new Date()));
if (tag!=null) {
sb.append(" ");
sb.append(tag);
} else {
sb.append(" ~");
sb.append(Thread.currentThread().getId());
}
sb.append("] ");
sb.append(message);
return sb.toString();
}
public boolean watching() {
return watcher != null;
}
protected JSONObject buildJSONLogMessage(String message) throws JSONException, ParseException {
JSONObject obj = null;
Matcher matcher = pattern.matcher(message);
String subtype = null;
String msg = null;
if (matcher.matches()) {
obj = new JsonObject();
obj.put("name", "LogWatcher");
String t = matcher.group(1);
obj.put("time", new SimpleDateFormat(dateFormat).parse(t).toInstant());
obj.put("procId", new Long(matcher.group(2)));
obj.put("procInstId", new Long(matcher.group(3)));
subtype = matcher.group(4);
obj.put("subtype", subtype);
String id = matcher.group(5);
if (id != null)
obj.put("id", Long.parseLong(id));
String instId = matcher.group(6);
if (instId != null) {
try {
obj.put("instId", Long.parseLong(instId));
}
catch (NumberFormatException ex) {
// master request id needn't be numeric
obj.put("instId", instId);
}
}
msg = matcher.group(7);
obj.put("msg", msg);
}
if ("a".equals(subtype) && msg != null) {
if (msg.startsWith(WorkStatus.LOGMSG_COMPLETE)) {
obj.put("status", WorkStatus.STATUS_COMPLETED);
} else if (msg.startsWith(WorkStatus.LOGMSG_START)) {
obj.put("status", WorkStatus.STATUS_IN_PROGRESS);
} else if (msg.startsWith(WorkStatus.LOGMSG_FAILED)) {
obj.put("status", WorkStatus.STATUS_FAILED);
} else if (msg.startsWith(WorkStatus.LOGMSG_SUSPEND)) {
obj.put("status", WorkStatus.STATUS_WAITING);
} else if (msg.startsWith(WorkStatus.LOGMSG_HOLD)) {
obj.put("status", WorkStatus.STATUS_HOLD);
}
}
else if ("t".equals(subtype)) {
obj.put("status", TransitionStatus.STATUS_COMPLETED);
}
else if ("m".equals(subtype)) {
}
return obj;
}
protected void sendToWatchers(String message) {
if (watching())
sendToWatcher(message);
try {
JSONObject jsonObj = buildJSONLogMessage(message);
if (jsonObj != null && jsonObj.has("procInstId") && jsonObj.has("procId")) {
sendToWebWatcher(String.valueOf(jsonObj.get("procInstId")), jsonObj);
sendToWebWatcher(String.valueOf(jsonObj.get("procId")), jsonObj);
}
else if (jsonObj != null && jsonObj.has("masterRequestId")) {
sendToWebWatcher(jsonObj.getString("masterRequestId"), jsonObj);
}
}
catch (Throwable e) {
System.out.println("Error building log watcher json for: '" + message + "' -> " + e);
e.printStackTrace();
};
}
protected void sendToWatcher(String message) {
SoccomClient client = null;
try {
String[] spec = watcher.split(":");
String host = spec.length > 0 ? spec[0] : getDefaultHost();
int port = spec.length > 1 ? Integer.parseInt(spec[1]) : getDefaultPort();
client = new SoccomClient(host, port, null);
client.putreq(message);
} catch (Exception e) {
watcher = null;
System.out.println("Exception when sending log messages to watcher - turn it off");
e.printStackTrace();
} finally {
if (client!=null) client.close();
}
}
protected void sendToWebWatcher(String topic, JSONObject message) throws JSONException, IOException {
WebSocketMessenger.getInstance().send(topic, message.toString());
}
@Override
public boolean isInfoEnabled() {
return isEnabledFor(LogLevel.INFO);
}
@Override
public boolean isDebugEnabled() {
return isEnabledFor(LogLevel.DEBUG);
}
@Override
public boolean isTraceEnabled() {
return isEnabledFor(LogLevel.TRACE);
}
@Override
public boolean isMdwDebugEnabled() {
return isEnabledFor(LogLevel.TRACE);
}
private void logIt(LogLevel level, String message, Throwable t) {
switch (level.toString()) {
case "INFO":
if (t == null)
info(message);
else
info(message, t);
break;
case "ERROR":
if (t == null)
error(message);
else
error(message, t);
break;
case "DEBUG":
if (t == null)
debug(message);
else
debug(message, t);
break;
case "WARN":
if (t == null)
warn(message);
else
warn(message, t);
break;
case "TRACE":
if (t == null)
trace(message);
else
trace(message, t);
break;
default: break;
}
sendToWatchers(message);
}
@Override
public void exception(String tag, String message, Throwable e) {
String line = generateLogLine('e', tag, message);
logIt(LogLevel.ERROR, line, e);
}
public void info(String tag, String message) {
if (isInfoEnabled()) {
String line = generateLogLine('i', tag, message);
logIt(LogLevel.INFO, line, null);
}
}
public void debug(String tag, String message) {
if (isDebugEnabled()) {
String line = generateLogLine('d', tag, message);
logIt(LogLevel.DEBUG, line, null);
}
}
public void warn(String tag, String message) {
String line = generateLogLine('w', tag, message);
logIt(LogLevel.WARN, line, null);
}
public void severe(String tag, String message) {
String line = generateLogLine('w', tag, message);
logIt(LogLevel.ERROR, line, null);
}
public void trace(String tag, String message) {
if (isTraceEnabled()) {
String line = generateLogLine('t', tag, message);
logIt(LogLevel.TRACE, line, null);
}
}
}
|
Issue #571
|
mdw-common/src/com/centurylink/mdw/util/log/AbstractStandardLoggerBase.java
|
Issue #571
|
|
Java
|
epl-1.0
|
b7873e2f9674ac63c8c271bb52d92959c4365e69
| 0
|
Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt
|
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.metadata;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.metadata.IElementDefn;
import org.eclipse.birt.report.model.api.metadata.IPropertyType;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.metadata.validators.SimpleValueValidator;
import org.eclipse.birt.report.model.util.AbstractParseState;
import org.eclipse.birt.report.model.util.ErrorHandler;
import org.eclipse.birt.report.model.util.XMLParserException;
import org.eclipse.birt.report.model.util.XMLParserHandler;
import org.eclipse.birt.report.model.validators.AbstractSemanticValidator;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* SAX handler for reading the XML meta data definition file.
*/
public class MetaDataHandlerImpl extends XMLParserHandler
{
/**
* Cache the singleton instance of the meta-data dictionary.
*/
MetaDataDictionary dictionary = MetaDataDictionary.getInstance( );
protected static final String PROPERTY_TAG = "Property"; //$NON-NLS-1$
protected static final String ELEMENT_TAG = "Element"; //$NON-NLS-1$
protected static final String NAME_ATTRIB = "name"; //$NON-NLS-1$
protected static final String METHOD_TAG = "Method"; //$NON-NLS-1$
protected static final String PROPERTY_GROUP_TAG = "PropertyGroup"; //$NON-NLS-1$
private static final String ROOT_TAG = "ReportMetaData"; //$NON-NLS-1$
private static final String STYLE_TAG = "Style"; //$NON-NLS-1$
private static final String STYLE_PROPERTY_TAG = "StyleProperty"; //$NON-NLS-1$
private static final String SLOT_TAG = "Slot"; //$NON-NLS-1$
private static final String TYPE_TAG = "Type"; //$NON-NLS-1$
private static final String DEFAULT_TAG = "Default"; //$NON-NLS-1$
private static final String CHOICE_TAG = "Choice"; //$NON-NLS-1$
private static final String CHOICE_TYPE_TAG = "ChoiceType"; //$NON-NLS-1$
private static final String STRUCTURE_TAG = "Structure"; //$NON-NLS-1$
private static final String ALLOWED_TAG = "Allowed"; //$NON-NLS-1$
private static final String ALLOWED_UNITS_TAG = "AllowedUnits"; //$NON-NLS-1$
private static final String MEMBER_TAG = "Member"; //$NON-NLS-1$
private static final String VALUE_VALIDATOR_TAG = "ValueValidator"; //$NON-NLS-1$
private static final String VALIDATORS_TAG = "Validators"; //$NON-NLS-1$
private static final String ARGUMENT_TAG = "Argument"; //$NON-NLS-1$
private static final String CLASS_TAG = "Class"; //$NON-NLS-1$
private static final String CONSTRUCTOR_TAG = "Constructor"; //$NON-NLS-1$
private static final String SEMANTIC_VALIDATOR_TAG = "SemanticValidator"; //$NON-NLS-1$
private static final String TRIGGER_TAG = "Trigger"; //$NON-NLS-1$
private static final String DEFAULT_UNIT_TAG = "DefaultUnit"; //$NON-NLS-1$
private static final String PROPERTY_VISIBILITY_TAG = "PropertyVisibility"; //$NON-NLS-1$
private static final String DISPLAY_NAME_ID_ATTRIB = "displayNameID"; //$NON-NLS-1$
private static final String EXTENDS_ATTRIB = "extends"; //$NON-NLS-1$
private static final String TYPE_ATTRIB = "type"; //$NON-NLS-1$
private static final String SUB_TYPE_ATTRIB = "subType"; //$NON-NLS-1$
private static final String HAS_STYLE_ATTRIB = "hasStyle"; //$NON-NLS-1$
private static final String SELECTOR_ATTRIB = "selector"; //$NON-NLS-1$
private static final String ALLOWS_USER_PROPERTIES_ATTRIB = "allowsUserProperties"; //$NON-NLS-1$
private static final String CAN_EXTEND_ATTRIB = "canExtend"; //$NON-NLS-1$
private static final String MULTIPLE_CARDINALITY_ATTRIB = "multipleCardinality"; //$NON-NLS-1$
private static final String IS_MANAGED_BY_NAME_SPACE_ATTRIB = "isManagedByNameSpace"; //$NON-NLS-1$
private static final String CAN_INHERIT_ATTRIBUTE = "canInherit"; //$NON-NLS-1$
private static final String IS_INTRINSIC_ATTRIB = "isIntrinsic"; //$NON-NLS-1$
private static final String IS_STYLE_PROPERTY_ATTRIB = "isStyleProperty"; //$NON-NLS-1$
private static final String IS_LIST_ATTRIB = "isList"; //$NON-NLS-1$
private static final String NAME_SPACE_ATTRIB = "nameSpace"; //$NON-NLS-1$
private static final String IS_NAME_REQUIRED_ATTRIB = "isNameRequired"; //$NON-NLS-1$
private static final String IS_ABSTRACT_ATTRIB = "isAbstract"; //$NON-NLS-1$
private static final String DETAIL_TYPE_ATTRIB = "detailType"; //$NON-NLS-1$
private static final String JAVA_CLASS_ATTRIB = "javaClass"; //$NON-NLS-1$
private static final String TOOL_TIP_ID_ATTRIB = "toolTipID"; //$NON-NLS-1$
private static final String RETURN_TYPE_ATTRIB = "returnType"; //$NON-NLS-1$
private static final String TAG_ID_ATTRIB = "tagID"; //$NON-NLS-1$
private static final String DATA_TYPE_ATTRIB = "dataType"; //$NON-NLS-1$
private static final String IS_STATIC_ATTRIB = "isStatic"; //$NON-NLS-1$
private static final String VALIDATOR_ATTRIB = "validator"; //$NON-NLS-1$
private static final String CLASS_ATTRIB = "class"; //$NON-NLS-1$
private static final String NATIVE_ATTRIB = "native"; //$NON-NLS-1$
private static final String PRE_REQUISITE_ATTRIB = "preRequisite"; //$NON-NLS-1$
private static final String TARGET_ELEMENT_ATTRIB = "targetElement"; //$NON-NLS-1$
private static final String VALUE_REQUIRED_ATTRIB = "valueRequired"; //$NON-NLS-1$
private static final String PROPERTY_VISIBILITY_ATTRIB = "visibility"; //$NON-NLS-1$
private static final String SINCE_ATTRIB = "since"; //$NON-NLS-1$
private static final String XML_NAME_ATTRIB = "xmlName"; //$NON-NLS-1$
private static final String RUNTIME_SETTABLE_ATTRIB = "runtimeSettable"; //$NON-NLS-1$
private static final String TRIM_OPTION_ATTRIB = "trimOption"; //$NON-NLS-1$
private static final String CONTEXT_ATTRIB = "context"; //$NON-NLS-1$
private static final String MODULES_ATTRIB = "modules"; //$NON-NLS-1$
private static final String IS_BIDI_PROPERTY_ATTRIB = "isBidiProperty"; //$NON-NLS-1$
private static final String ALLOW_EXPRESSION_ATTRIB = "allowExpression"; //$NON-NLS-1$
/**
* The unique id for the slot.
*/
private static final String ID_ATTRIB = "id"; //$NON-NLS-1$
private static final String THIS_KEYWORD = "this"; //$NON-NLS-1$
private String groupNameID;
// Cached state. Can be done here because nothing in this grammar is
// recursive.
protected ElementDefn elementDefn = null;
protected SlotDefn slotDefn = null;
protected SystemPropertyDefn propDefn = null;
protected StructureDefn struct = null;
protected ArrayList<Choice> choices = new ArrayList<Choice>( );
/**
* The input string will not be trimmed.
*/
private static final String NO_TRIM = "noTrim"; //$NON-NLS-1$
/**
* The space will be trimmed.
*/
private static final String TRIM_SPACE = "trimSpace"; //$NON-NLS-1$
/**
* If the input string is empty, normalizes the string to an null string.
*/
private static final String TRIM_EMPTY_TO_NULL = "trimEmptyToNull"; //$NON-NLS-1$
/**
* if the display ID could be empty
*/
protected boolean checkDisplayNameID = true;
protected MetaDataBuilder builder;
/**
* Constructor.
*/
public MetaDataHandlerImpl( )
{
this( new MetaDataErrorHandler( ), new MetaDataBuilder( ) );
}
/**
* Constructs the meta data handler implementation with the specified error
* handler.
*
* @param errorHandler
* @param builder
*/
public MetaDataHandlerImpl( ErrorHandler errorHandler,
MetaDataBuilder builder )
{
super( errorHandler );
this.builder = builder;
}
public AbstractParseState createStartState( )
{
return new StartState( );
}
/**
* Convert the array list of choices to an array.
*
* @return an array of the choices.
*/
private Choice[] getChoiceArray( )
{
Choice[] choiceArray = new Choice[choices.size( )];
for ( int i = 0; i < choices.size( ); i++ )
choiceArray[i] = choices.get( i );
return choiceArray;
}
class StartState extends InnerParseState
{
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( ROOT_TAG ) )
return new RootState( );
return super.startElement( tagName );
}
}
class RootState extends InnerParseState
{
public AbstractParseState startElement( String tagName )
{
if ( CHOICE_TYPE_TAG.equalsIgnoreCase( tagName ) )
return new ChoiceTypeState( );
if ( STRUCTURE_TAG.equalsIgnoreCase( tagName ) )
return new StructDefnState( );
if ( ELEMENT_TAG.equalsIgnoreCase( tagName ) )
return new ElementDefnState( );
if ( STYLE_TAG.equalsIgnoreCase( tagName ) )
return new StyleState( );
if ( CLASS_TAG.equalsIgnoreCase( tagName ) )
return new ClassState( );
if ( VALIDATORS_TAG.equalsIgnoreCase( tagName ) )
return new ValidatorsState( );
return super.startElement( tagName );
}
}
public class ChoiceTypeState extends InnerParseState
{
ChoiceSet choiceSet = null;
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
choices.clear( );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
else
{
choiceSet = builder.createChoiceSet( );
choiceSet.setName( name );;
try
{
builder.addChoiceSet( choiceSet );
}
catch ( MetaDataException e )
{
choiceSet = null;
errorHandler.semanticError( e );
}
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( CHOICE_TAG ) )
return new ChoiceState( );
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( !choices.isEmpty( ) && choiceSet != null )
choiceSet.setChoices( getChoiceArray( ) );
}
}
protected class StyleState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String type = attrs.getValue( TYPE_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
}
else if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else
{
PredefinedStyle style = new PredefinedStyle( );
style.setName( name );
style.setDisplayNameKey( displayNameID );
style.setType( type );
try
{
dictionary.addPredefinedStyle( style );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
protected class StructDefnState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
}
if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else
{
struct = new StructureDefn( name );
struct.setDisplayNameKey( attrs
.getValue( DISPLAY_NAME_ID_ATTRIB ) );
struct.setSince( attrs.getValue( SINCE_ATTRIB ) );
try
{
dictionary.addStructure( struct );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
struct = null;
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( MEMBER_TAG ) )
return new MemberState( );
return super.startElement( tagName );
}
}
protected class MemberState extends InnerParseState
{
StructPropertyDefn memberDefn = null;
public void parseAttrs( Attributes attrs )
{
String name = getAttrib( attrs, NAME_ATTRIB );
String displayNameID = getAttrib( attrs, DISPLAY_NAME_ID_ATTRIB );
String type = getAttrib( attrs, TYPE_ATTRIB );
String validator = getAttrib( attrs, VALIDATOR_ATTRIB );
String subType = getAttrib( attrs, SUB_TYPE_ATTRIB );
boolean ok = ( struct != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( StringUtil.isBlank( type ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
PropertyType typeDefn = dictionary.getPropertyType( type );
if ( typeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
if ( !ok )
return;
String detailName = getAttrib( attrs, DETAIL_TYPE_ATTRIB );
ChoiceSet choiceSet = null;
String structDefn = null;
PropertyType subTypeDefn = null;
switch ( typeDefn.getTypeCode( ) )
{
case IPropertyType.DIMENSION_TYPE :
case IPropertyType.DATE_TIME_TYPE :
case IPropertyType.STRING_TYPE :
case IPropertyType.LITERAL_STRING_TYPE :
case IPropertyType.FLOAT_TYPE :
case IPropertyType.INTEGER_TYPE :
case IPropertyType.NUMBER_TYPE :
if ( detailName != null )
{
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
}
break;
case IPropertyType.CHOICE_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CHOICE_TYPE_REQUIRED ) );
return;
}
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
break;
case IPropertyType.COLOR_TYPE :
choiceSet = validateChoiceSet( ColorPropertyType.COLORS_CHOICE_SET );
if ( choiceSet == null )
return;
break;
case IPropertyType.STRUCT_TYPE :
case IPropertyType.STRUCT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_STRUCT_TYPE_REQUIRED ) );
return;
}
structDefn = detailName;
break;
case IPropertyType.ELEMENT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
break;
case IPropertyType.LIST_TYPE :
if ( subType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MISSING_SUB_TYPE ) );
}
else
{
subTypeDefn = dictionary.getPropertyType( subType );
if ( subTypeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
else if ( subTypeDefn.getTypeCode( ) == IPropertyType.ELEMENT_REF_TYPE )
{
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
}
}
break;
}
memberDefn = new StructPropertyDefn( );
memberDefn.setName( name );
memberDefn.setType( typeDefn );
if ( subTypeDefn != null
&& typeDefn.getTypeCode( ) == IPropertyType.LIST_TYPE )
memberDefn.setSubType( subTypeDefn );
memberDefn.setDisplayNameID( displayNameID );
memberDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
memberDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
memberDefn.setRuntimeSettable( getBooleanAttrib( attrs,
RUNTIME_SETTABLE_ATTRIB, true ) );
String trimOption = attrs.getValue( TRIM_OPTION_ATTRIB );
if ( trimOption != null )
{
try
{
int value = handleTrimOption( trimOption );
memberDefn.setTrimOption( value );
}
catch ( MetaDataParserException e )
{
errorHandler.semanticError( e );
}
}
memberDefn.setAllowExpression( getBooleanAttrib( attrs,
ALLOW_EXPRESSION_ATTRIB, false ) );
if ( memberDefn.getTypeCode( ) == IPropertyType.EXPRESSION_TYPE )
{
memberDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
memberDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
}
if ( !StringUtil.isBlank( validator ) )
{
memberDefn.setValueValidator( validator );
}
if ( typeDefn.getTypeCode( ) == IPropertyType.STRUCT_TYPE )
memberDefn.setIsList( getBooleanAttrib( attrs, IS_LIST_ATTRIB,
false ) );
if ( choiceSet != null )
memberDefn.setDetails( choiceSet );
else if ( structDefn != null )
memberDefn.setDetails( structDefn );
else if ( detailName != null )
memberDefn.setDetails( detailName );
memberDefn.setIntrinsic( getBooleanAttrib( attrs,
IS_INTRINSIC_ATTRIB, false ) );
try
{
struct.addProperty( memberDefn );
}
catch ( MetaDataException e )
{
errorHandler.semanticError( e );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( DEFAULT_TAG ) )
return new DefaultValueState( memberDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_TAG ) )
return new AllowedState( memberDefn );
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( propDefn == null )
{
return;
}
// validate the default value. The default value must be validate
// here as it needs choice set.
if ( propDefn != null && propDefn.getDefault( ) != null )
{
try
{
Object value = propDefn.validateXml( null, null,
propDefn.getDefault( ) );
propDefn.setDefault( value );
}
catch ( PropertyValueException e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_DEFAULT ) );
}
}
propDefn = null;
}
}
public class ElementDefnState extends InnerParseState
{
protected ElementDefn createElementDefn( )
{
return builder.createElementDefn( );
}
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// use this method to create element definition instance and handle
// the name, this will help to override and change the behavior for
// different requirements
elementDefn = createElementDefn( );
elementDefn.setName( name );
elementDefn.setAbstract( getBooleanAttrib( attrs,
IS_ABSTRACT_ATTRIB, false ) );
elementDefn.setDisplayNameKey( displayNameID );
elementDefn.setExtends( attrs.getValue( EXTENDS_ATTRIB ) );
elementDefn.setHasStyle( getBooleanAttrib( attrs, HAS_STYLE_ATTRIB,
false ) );
elementDefn.setSelector( attrs.getValue( SELECTOR_ATTRIB ) );
elementDefn.setAllowsUserProperties( getBooleanAttrib( attrs,
ALLOWS_USER_PROPERTIES_ATTRIB, true ) );
elementDefn.setJavaClass( attrs.getValue( JAVA_CLASS_ATTRIB ) );
elementDefn.setCanExtend( getBooleanAttrib( attrs,
CAN_EXTEND_ATTRIB, true ) );
elementDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
elementDefn.setXmlName( attrs.getValue( XML_NAME_ATTRIB ) );
String nameRequired = attrs.getValue( IS_NAME_REQUIRED_ATTRIB );
if ( nameRequired != null )
{
boolean flag = parseBoolean( nameRequired, false );
elementDefn.setNameOption( flag
? MetaDataConstants.REQUIRED_NAME
: MetaDataConstants.OPTIONAL_NAME );
}
String ns = attrs.getValue( NAME_SPACE_ATTRIB );
IElementDefn moduleDefn = dictionary
.getElement( ReportDesignConstants.MODULE_ELEMENT );
if ( ns == null || ns.trim( ).length( ) == 0 )
{
// Inherit default name space
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.STYLE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.STYLE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.THEME_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.THEME_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.DATA_SET_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DATA_SET_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.DATA_SOURCE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DATA_SOURCE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.ELEMENT_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.ELEMENT_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.PARAMETER_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.PARAMETER_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.MASTER_PAGE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.PAGE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.CUBE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.CUBE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.TEMPLATE_PARAMETER_DEFINITION_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.TEMPLATE_PARAMETER_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.DIMENSION_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DIMENSION_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.NO_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = MetaDataConstants.NO_NAME_SPACE;
}
else if ( ns.startsWith( "(" ) && ns.endsWith( ")" ) ) //$NON-NLS-1$//$NON-NLS-2$
{
String nsValue = ns.substring( 1, ns.length( ) - 1 );
String[] splitStrings = nsValue.split( "," ); //$NON-NLS-1$
if ( splitStrings == null
|| !( splitStrings.length == 2 || splitStrings.length == 3 ) )
{
errorHandler
.semanticError( new MetaDataException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
}
else
{
int length = splitStrings.length;
assert length == 2 || length == 3;
String holderName = StringUtil.trimString( splitStrings[0] );
String nameSpace = StringUtil.trimString( splitStrings[1] );
ElementDefn holderDefn = (ElementDefn) dictionary
.getElement( holderName );
if ( holderDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
}
else
{
// the name holder must be existing and name
// required element or the module type
elementDefn.nameConfig.holder = holderDefn;
elementDefn.nameConfig.nameSpaceID = NameSpaceFactory
.getInstance( ).getNameSpaceID( holderName,
nameSpace );
if ( length == 3 )
{
elementDefn.nameConfig.targetPropertyName = StringUtil
.trimString( splitStrings[2] );
}
}
}
}
else
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
try
{
builder.addElementDefn( elementDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( PROPERTY_TAG ) )
return new PropertyState( );
if ( tagName.equalsIgnoreCase( PROPERTY_GROUP_TAG ) )
return new PropertyGroupState( );
if ( tagName.equalsIgnoreCase( STYLE_PROPERTY_TAG ) )
return new StylePropertyState( );
if ( tagName.equalsIgnoreCase( SLOT_TAG ) )
return new SlotState( );
if ( tagName.equalsIgnoreCase( METHOD_TAG ) )
return new ElementMethodState( elementDefn );
if ( tagName.equalsIgnoreCase( SEMANTIC_VALIDATOR_TAG ) )
return new TriggerState( );
if ( tagName.equalsIgnoreCase( PROPERTY_VISIBILITY_TAG ) )
return new PropertyVisibilityState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
elementDefn = null;
}
/**
* Parses the property visiblity.
*/
private class PropertyVisibilityState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String visible = attrs.getValue( PROPERTY_VISIBILITY_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
return;
}
elementDefn.addPropertyVisibility( name, visible );
}
}
}
class PropertyGroupState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
groupNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
if ( StringUtil.isBlank( groupNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_GROUP_NAME_ID_REQUIRED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( PROPERTY_TAG ) )
return new PropertyState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
groupNameID = null;
}
}
protected class PropertyState extends InnerParseState
{
List<String> propertyTypes = new ArrayList<String>( );
public void parseAttrs( Attributes attrs )
{
choices.clear( );
propDefn = null;
String name = getAttrib( attrs, NAME_ATTRIB );
String displayNameID = getAttrib( attrs, DISPLAY_NAME_ID_ATTRIB );
String type = getAttrib( attrs, TYPE_ATTRIB );
String validator = getAttrib( attrs, VALIDATOR_ATTRIB );
String subType = getAttrib( attrs, SUB_TYPE_ATTRIB );
boolean isList = getBooleanAttrib( attrs, IS_LIST_ATTRIB, false );
String detailName = getAttrib( attrs, DETAIL_TYPE_ATTRIB );
boolean ok = ( elementDefn != null );
if ( name == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( type == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// Look up the choice set name, if any.
PropertyType typeDefn = dictionary.getPropertyType( type );
if ( typeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
//list type only support types in supportedSubTypes
//isList only support element/content/structure
//here we convert isList to listType for simple properties
int typeCode = typeDefn.getTypeCode( );
if ( isList && typeCode != IPropertyType.LIST_TYPE )
{
if ( PropertyDefn.isSupportedSubType( typeDefn ) )
{
subType = type;
}
}
ChoiceSet choiceSet = null;
StructureDefn struct = null;
PropertyType subTypeDefn = null;
switch ( typeDefn.getTypeCode( ) )
{
case IPropertyType.DIMENSION_TYPE :
case IPropertyType.DATE_TIME_TYPE :
case IPropertyType.STRING_TYPE :
case IPropertyType.LITERAL_STRING_TYPE :
case IPropertyType.FLOAT_TYPE :
case IPropertyType.INTEGER_TYPE :
case IPropertyType.NUMBER_TYPE :
if ( detailName != null )
{
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
}
break;
case IPropertyType.CHOICE_TYPE :
// the user can define the detail type either in detailType
// attribute or type element, so valid it at the end of element
if ( detailName != null )
{
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
}
break;
case IPropertyType.COLOR_TYPE :
choiceSet = validateChoiceSet( ColorPropertyType.COLORS_CHOICE_SET );
if ( choiceSet == null )
return;
break;
case IPropertyType.STRUCT_TYPE :
case IPropertyType.STRUCT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_STRUCT_TYPE_REQUIRED ) );
return;
}
struct = (StructureDefn) dictionary
.getStructure( detailName );
if ( struct == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_STRUCT_TYPE ) );
return;
}
break;
case IPropertyType.ELEMENT_TYPE :
case IPropertyType.CONTENT_ELEMENT_TYPE :
case IPropertyType.ELEMENT_REF_TYPE :
// the user can define the detail type either in detailType attribute or type element.
if ( THIS_KEYWORD.equals( detailName ) )
{
detailName = elementDefn.getName( );
}
break;
case IPropertyType.LIST_TYPE :
if ( subType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MISSING_SUB_TYPE ) );
}
else
{
subTypeDefn = dictionary.getPropertyType( subType );
if ( subTypeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
else if ( subTypeDefn.getTypeCode( ) == IPropertyType.ELEMENT_REF_TYPE )
{
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
}
}
break;
default :
// Ignore the detail name for other types.
detailName = null;
}
// call the method to create property definition rather than create
// it using constructor directly to satisfy different requirements
// in different use-cases
propDefn = builder.createPropertyDefn( );
propDefn.setName( name );
propDefn.setDisplayNameID( displayNameID );
propDefn.setType( typeDefn );
if ( typeDefn.getTypeCode( ) == IPropertyType.LIST_TYPE )
propDefn.setSubType( subTypeDefn );
propDefn.setGroupNameKey( groupNameID );
propDefn.setCanInherit( getBooleanAttrib( attrs,
CAN_INHERIT_ATTRIBUTE, true ) );
propDefn.setIntrinsic( getBooleanAttrib( attrs,
IS_INTRINSIC_ATTRIB, false ) );
propDefn.setStyleProperty( getBooleanAttrib( attrs,
IS_STYLE_PROPERTY_ATTRIB, false ) );
propDefn.setBidiProperty( getBooleanAttrib( attrs,
IS_BIDI_PROPERTY_ATTRIB, false ) );
propDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
propDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
propDefn.setRuntimeSettable( getBooleanAttrib( attrs,
RUNTIME_SETTABLE_ATTRIB, true ) );
String trimOption = attrs.getValue( TRIM_OPTION_ATTRIB );
if ( trimOption != null )
{
try
{
int value = handleTrimOption( trimOption );
propDefn.setTrimOption( value );
}
catch ( MetaDataParserException e )
{
errorHandler.semanticError( e );
}
}
propDefn.setAllowExpression( getBooleanAttrib( attrs,
ALLOW_EXPRESSION_ATTRIB, false ) );
if ( propDefn.getTypeCode( ) == IPropertyType.EXPRESSION_TYPE )
{
propDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
propDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
}
if ( !StringUtil.isBlank( validator ) )
{
propDefn.setValueValidator( validator );
}
if ( typeCode == IPropertyType.STRUCT_TYPE
|| propDefn.isElementType( ) )
propDefn.setIsList( isList );
if ( choiceSet != null )
propDefn.setDetails( choiceSet );
else if ( struct != null )
propDefn.setDetails( struct );
else if ( detailName != null )
propDefn.setDetails( detailName );
// add it to dictionary
try
{
builder.addPropertyDefn( elementDefn, propDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( DEFAULT_TAG ) )
return new DefaultValueState( propDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_TAG ) )
return new AllowedState( propDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_UNITS_TAG ) )
return new AllowedUnitsState( propDefn );
else if ( tagName.equalsIgnoreCase( TRIGGER_TAG ) )
return new TriggerState( );
else if ( tagName.equalsIgnoreCase( DEFAULT_UNIT_TAG ) )
return new DefaultUnitState( );
else if ( tagName.equalsIgnoreCase( TYPE_TAG ) )
return new PropertyTypeState( propertyTypes );
else
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( propDefn == null )
{
return;
}
// if property is element or choice type, then set list of allowed
// type names to the details
int typeCode = propDefn.getTypeCode( );
if ( !propertyTypes.isEmpty( ) )
{
if ( typeCode == IPropertyType.ELEMENT_TYPE
|| typeCode == IPropertyType.STRUCT_TYPE
|| typeCode == IPropertyType.CONTENT_ELEMENT_TYPE )
{
propDefn.setDetails( propertyTypes );
}
if ( typeCode == IPropertyType.CHOICE_TYPE
&& propDefn.getDetails( ) == null )
{
IChoiceSet choiceSet = validateChoiceSet( propertyTypes
.get( 0 ) );
if ( choiceSet != null )
{
propDefn.setDetails( choiceSet );
}
}
}
// validate the default value. The default value must be validate
// here as it needs choice set.
if ( propDefn.getDefault( ) != null )
{
try
{
Object value = propDefn.validateXml( null, null,
propDefn.getDefault( ) );
propDefn.setDefault( value );
}
catch ( PropertyValueException e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_DEFAULT ) );
}
}
propDefn = null;
}
}
class DefaultUnitState extends InnerParseState
{
public void end( ) throws SAXException
{
if ( propDefn == null )
return;
int type = propDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DEFAULT_UNIT_NOT_ALLOWED ) );
return;
}
propDefn.setDefaultUnit( text.toString( ) );
}
}
class AllowedState extends InnerParseState
{
PropertyDefn tmpPropDefn;
AllowedState( PropertyDefn tmpPropDefn )
{
this.tmpPropDefn = tmpPropDefn;
}
public void end( ) throws SAXException
{
if ( tmpPropDefn == null )
return;
int type = tmpPropDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE
&& type != IPropertyType.CHOICE_TYPE )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_RESTRICTION_NOT_ALLOWED ) );
return;
}
ChoiceSet allowedChoices = builder.createChoiceSet( );
ArrayList<IChoice> allowedList = new ArrayList<IChoice>( );
String choicesStr = StringUtil.trimString( text.toString( ) );
// blank string.
if ( choicesStr == null )
return;
String[] nameArray = choicesStr.split( "," ); //$NON-NLS-1$
if ( type == IPropertyType.DIMENSION_TYPE )
{
// units restriction on a dimension property.
IChoiceSet units = dictionary
.getChoiceSet( DesignChoiceConstants.CHOICE_UNITS );
assert units != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice unit = units.findChoice( nameArray[i].trim( ) );
if ( unit != null )
{
allowedList.add( unit );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
}
else
{
// choices type restriction.
IChoiceSet choices = tmpPropDefn.getChoices( );
assert choices != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice choice = choices.findChoice( nameArray[i].trim( ) );
if ( choice != null )
{
allowedList.add( choice );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
}
allowedChoices.setChoices( allowedList
.toArray( new Choice[allowedList.size( )] ) );
tmpPropDefn.setAllowedChoices( allowedChoices );
}
}
private class AllowedUnitsState extends InnerParseState
{
PropertyDefn tmpPropDefn;
AllowedUnitsState( PropertyDefn tmpPropDefn )
{
this.tmpPropDefn = tmpPropDefn;
}
public void end( ) throws SAXException
{
if ( tmpPropDefn == null )
return;
int type = tmpPropDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE
&& !( type == IPropertyType.LIST_TYPE && tmpPropDefn
.getSubTypeCode( ) == IPropertyType.DIMENSION_TYPE ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_RESTRICTION_NOT_ALLOWED ) );
return;
}
ChoiceSet allowedChoices = builder.createChoiceSet( );
ArrayList<IChoice> allowedList = new ArrayList<IChoice>( );
String choicesStr = StringUtil.trimString( text.toString( ) );
// blank string.
if ( choicesStr == null )
return;
String[] nameArray = choicesStr.split( "," ); //$NON-NLS-1$
// units restriction on a dimension property.
IChoiceSet units = dictionary
.getChoiceSet( DesignChoiceConstants.CHOICE_UNITS );
assert units != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice unit = units.findChoice( nameArray[i].trim( ) );
if ( unit != null )
{
allowedList.add( unit );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
allowedChoices.setChoices( allowedList
.toArray( new Choice[allowedList.size( )] ) );
tmpPropDefn.setAllowedUnits( allowedChoices );
}
}
class ValidatorsState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#startElement
* (java.lang.String)
*/
public AbstractParseState startElement( String tagName )
{
if ( VALUE_VALIDATOR_TAG.equalsIgnoreCase( tagName ) )
return new ValueValidatorState( );
if ( SEMANTIC_VALIDATOR_TAG.equalsIgnoreCase( tagName ) )
return new SemanticValidatorState( );
return super.startElement( tagName );
}
}
class ValueValidatorState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = getAttrib( attrs, NAME_ATTRIB );
String className = getAttrib( attrs, CLASS_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
return;
}
if ( StringUtil.isBlank( className ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CLASS_NAME_REQUIRED ) );
return;
}
try
{
Class<? extends Object> c = Class.forName( className );
SimpleValueValidator validator = (SimpleValueValidator) c
.newInstance( );
validator.setName( name );
try
{
dictionary.addValueValidator( validator );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
catch ( Exception e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_META_VALIDATOR ) );
}
}
}
class SemanticValidatorState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = getAttrib( attrs, NAME_ATTRIB );
String modules = getAttrib( attrs, MODULES_ATTRIB );
String className = getAttrib( attrs, CLASS_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
return;
}
if ( StringUtil.isBlank( className ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CLASS_NAME_REQUIRED ) );
return;
}
try
{
Class<? extends Object> c = Class.forName( className );
Method m = c.getMethod( "getInstance", (Class[]) null ); //$NON-NLS-1$
AbstractSemanticValidator validator = (AbstractSemanticValidator) m
.invoke( null, (Object[]) null );
validator.setName( name );
validator.setModules( modules );
try
{
dictionary.addSemanticValidator( validator );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
catch ( Exception e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_META_VALIDATOR ) );
}
}
}
class DefaultValueState extends InnerParseState
{
/**
* Reference to a member or a property.
*/
PropertyDefn propertyDefn = null;
DefaultValueState( PropertyDefn propDefn )
{
this.propertyDefn = propDefn;
}
public void end( ) throws SAXException
{
if ( this.propertyDefn == null )
return;
// validation should be done in property.end or member.end as
// the choice set may not defined yet
propertyDefn.setDefault( text.toString( ) );
}
}
class ChoiceState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String xmlName = attrs.getValue( NAME_ATTRIB );
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else if ( StringUtil.isBlank( xmlName ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_XML_NAME_REQUIRED ) );
}
else
{
Choice choice = builder.createChoice( );
choice.setName( xmlName );
choice.setDisplayNameKey( displayNameID );
boolean found = false;
Iterator<Choice> iter = choices.iterator( );
while ( iter.hasNext( ) )
{
Choice tmpChoice = iter.next( );
if ( tmpChoice.getName( ).equalsIgnoreCase(
choice.getName( ) ) )
{
found = true;
break;
}
}
if ( found )
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_DUPLICATE_CHOICE_NAME ) );
else
choices.add( choice );
}
}
}
class StylePropertyState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
boolean ok = ( elementDefn != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
elementDefn.addStyleProperty( name );
}
}
class SlotState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String multipleCardinality = attrs
.getValue( MULTIPLE_CARDINALITY_ATTRIB );
String tmpID = attrs.getValue( ID_ATTRIB );
boolean ok = ( elementDefn != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
else if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
else if ( StringUtil.isBlank( multipleCardinality ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MULTIPLE_CARDINALITY_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
slotDefn = new SlotDefn( );
slotDefn.setName( name );
slotDefn.setDisplayNameID( displayNameID );
slotDefn.setManagedByNameSpace( getBooleanAttrib( attrs,
IS_MANAGED_BY_NAME_SPACE_ATTRIB, true ) );
slotDefn.setMultipleCardinality( parseBoolean( multipleCardinality,
true ) );
slotDefn.setSelector( attrs.getValue( SELECTOR_ATTRIB ) );
slotDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
slotDefn.setXmlName( attrs.getValue( XML_NAME_ATTRIB ) );
if ( !StringUtil.isBlank( tmpID ) )
{
try
{
slotDefn.setSlotID( Integer.parseInt( tmpID ) );
}
catch ( NumberFormatException e )
{
// just ignore the error. the slot id is reset later.
}
}
elementDefn.addSlot( slotDefn );
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( TYPE_TAG ) )
return new SlotTypeState( );
if ( tagName.equalsIgnoreCase( TRIGGER_TAG ) )
return new TriggerState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
slotDefn = null;
}
}
class PropertyTypeState extends InnerParseState
{
protected List<String> types = null;
/**
* Constructs the property type state with a list to hold all the type
* names.
*
* @param propertyTypes
*/
public PropertyTypeState( List<String> propertyTypes )
{
this.types = propertyTypes;
}
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
boolean ok = ( propDefn != null );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
types.add( name );
}
}
class SlotTypeState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
boolean ok = ( slotDefn != null );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
slotDefn.addType( name );
}
}
/**
* The state to parse a method under a class.
*/
class ClassMethodState extends AbstractMethodState
{
private boolean isConstructor = false;
ClassMethodState( Object obj, boolean isConstructor )
{
super( obj );
this.isConstructor = isConstructor;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#getMethodInfo()
*/
MethodInfo getMethodInfo( String name )
{
ClassInfo classInfo = (ClassInfo) owner;
if ( classInfo != null )
{
if ( isConstructor )
methodInfo = (MethodInfo) classInfo.getConstructor( );
else
methodInfo = classInfo.findMethod( name );
}
if ( methodInfo == null )
methodInfo = builder.createMethodInfo( isConstructor );
return methodInfo;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#addDefnTo()
*/
void addDefnTo( )
{
assert owner instanceof ClassInfo;
ClassInfo classInfo = (ClassInfo) owner;
try
{
builder.addMethodInfo( classInfo, methodInfo );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/**
* The state to parse a method under an element.
*/
class ElementMethodState extends AbstractMethodState
{
SystemPropertyDefn localPropDefn = null;;
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#getMethodInfo()
*/
MethodInfo getMethodInfo( String name )
{
return new MethodInfo( false );
}
ElementMethodState( Object obj )
{
super( obj );
localPropDefn = builder.createPropertyDefn( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs )
{
super.parseAttrs( attrs );
localPropDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
localPropDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
localPropDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
localPropDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#addDefnTo()
*/
final void addDefnTo( )
{
assert owner instanceof ElementDefn;
PropertyType typeDefn = dictionary
.getPropertyType( IPropertyType.SCRIPT_TYPE );
String name = methodInfo.getName( );
String displayNameID = methodInfo.getDisplayNameKey( );
localPropDefn.setName( name );
localPropDefn.setDisplayNameID( displayNameID );
localPropDefn.setType( typeDefn );
localPropDefn.setGroupNameKey( null );
localPropDefn.setCanInherit( true );
localPropDefn.setIntrinsic( false );
localPropDefn.setStyleProperty( false );
localPropDefn.setDetails( methodInfo );
try
{
builder.addPropertyDefn( (ElementDefn) owner, localPropDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/**
* Parses an method state either under an element or class tag.
*/
abstract class AbstractMethodState extends InnerParseState
{
/**
* The element contains this state. Can be either a
* <code>ElementDefn</code> or <code>ClassInfo</code>.
*/
protected Object owner = null;
/**
* The cached <code>MethodInfo</code> for the state.
*/
protected MethodInfo methodInfo = null;
/**
* The cached argument list.
*/
private ArgumentInfoList argumentList = null;
/**
* Constructs a <code>MethodState</code> with the given owner.
*
* @param obj
* the parent object of this state
*/
AbstractMethodState( Object obj )
{
assert obj != null;
this.owner = obj;
}
/**
* Adds method information to the ElementDefn or ClassInfo.
*/
abstract void addDefnTo( );
/**
* Returns method information with the given method name.
*
* @param name
* the method name
* @return the <code>MethodInfo</code> object
*/
abstract MethodInfo getMethodInfo( String name );
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String returnType = attrs.getValue( RETURN_TYPE_ATTRIB );
boolean isStatic = getBooleanAttrib( attrs, IS_STATIC_ATTRIB, false );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// Note that here ROM supports overloadding, while JavaScript not.
// finds the method info if it has been parsed.
methodInfo = getMethodInfo( name );
methodInfo.setName( name );
methodInfo.setDisplayNameKey( displayNameID );
methodInfo.setReturnType( returnType );
methodInfo.setToolTipKey( toolTipID );
methodInfo.setStatic( isStatic );
addDefnTo( );
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( ARGUMENT_TAG ) )
return new ArgumentState( );
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( argumentList == null )
argumentList = new ArgumentInfoList( );
methodInfo.addArgumentList( argumentList );
methodInfo = null;
propDefn = null;
}
class ArgumentState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String tagID = attrs.getValue( TAG_ID_ATTRIB );
String type = attrs.getValue( TYPE_ATTRIB );
// for class member, we use data type, support dataType to make it consistent
if ( type == null )
{
type = attrs.getValue( DATA_TYPE_ATTRIB );
}
if ( name == null )
return;
ArgumentInfo argument = builder.createArgumentInfo( );
argument.setName( name );
argument.setType( type );
argument.setDisplayNameKey( tagID );
if ( argumentList == null )
argumentList = new ArgumentInfoList( );
try
{
argumentList.addArgument( argument );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
protected class ClassState extends InnerParseState
{
protected ClassInfo classInfo = null;
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String isNative = attrs.getValue( NATIVE_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
classInfo = builder.createClassInfo( );
classInfo.setName( name );
classInfo.setDisplayNameKey( displayNameID );
classInfo.setToolTipKey( toolTipID );
if ( Boolean.TRUE.toString( ).equalsIgnoreCase( isNative ) )
classInfo.setNative( true );
else if ( Boolean.FALSE.toString( ).equalsIgnoreCase( isNative ) )
classInfo.setNative( false );
try
{
builder.addClassInfo(classInfo );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( CONSTRUCTOR_TAG ) )
return new ClassMethodState( classInfo, true );
if ( tagName.equalsIgnoreCase( MEMBER_TAG ) )
return new MemberState( );
if ( tagName.equalsIgnoreCase( METHOD_TAG ) )
return new ClassMethodState( classInfo, false );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
classInfo = null;
}
protected class MemberState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String dataType = attrs.getValue( DATA_TYPE_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ))
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( dataType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DATA_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
MemberInfo memberDefn = builder.createMemberInfo( );
memberDefn.setName( name );
memberDefn.setDisplayNameKey( displayNameID );
memberDefn.setToolTipKey( toolTipID );
memberDefn.setDataType( dataType );
memberDefn.setStatic( getBooleanAttrib( attrs,
IS_STATIC_ATTRIB, false ) );
try
{
builder.addMemberInfo( classInfo, memberDefn);
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
class TriggerState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
assert propDefn != null || slotDefn != null;
String validatorName = attrs.getValue( VALIDATOR_ATTRIB );
String targetElement = attrs.getValue( TARGET_ELEMENT_ATTRIB );
if ( !StringUtil.isBlank( validatorName ) )
{
SemanticTriggerDefn triggerDefn = new SemanticTriggerDefn(
validatorName );
triggerDefn.setPreRequisite( getBooleanAttrib( attrs,
PRE_REQUISITE_ATTRIB, false ) );
if ( !StringUtil.isBlank( targetElement ) )
triggerDefn.setTargetElement( targetElement );
if ( propDefn != null )
propDefn.getTriggerDefnSet( ).add( triggerDefn );
if ( slotDefn != null )
slotDefn.getTriggerDefnSet( ).add( triggerDefn );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
}
}
}
/**
* Checks if dictionary contains a specified ChoiceSet with the name
* <code>choiceSetName</code>.
*
* @param choiceSetName
* the name of ChoiceSet to be checked.
* @return the validated choiceSet. If not found, return null.
*/
private ChoiceSet validateChoiceSet( String choiceSetName )
{
IChoiceSet choiceSet = dictionary.getChoiceSet( choiceSetName );
if ( choiceSet == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_CHOICE_TYPE ) );
return null;
}
return (ChoiceSet) choiceSet;
}
/**
* Transfers trim option string to trim option value. The input value is
* defined in <code>ModelUtil</code> and can be one of:
*
* <ul>
* <li>NO_TRIM</li>
* <li>TRIM_EMPTY</li>
* <li>TRIM_NULL</li>
* <li>TRIM_EMPTY&TRIM_NULL</li>
* <li>NULL</li>
* </ul>
*
* @param trimOption
* the trim option.
* @return the trim option value.
*/
private int handleTrimOption( String trimOption )
throws MetaDataParserException
{
// TODO: do some enhancement to enable textualPropertyType could
// not trim, trim string space or trim empty space to null according to
// the trim option.
String[] options = trimOption.split( ";" ); //$NON-NLS-1$
int value = XMLPropertyType.NO_VALUE;
for ( int i = 0; i < options.length; i++ )
{
String option = options[i];
if ( NO_TRIM.equals( option ) )
{
value |= XMLPropertyType.NO_TRIM_VALUE;
}
else if ( TRIM_SPACE.equals( option ) )
{
value |= XMLPropertyType.TRIM_SPACE_VALUE;
}
else if ( TRIM_EMPTY_TO_NULL.equals( option ) )
{
value |= XMLPropertyType.TRIM_EMPTY_TO_NULL_VALUE;
}
else
{
// invalid trim option.
throw new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TRIM_OPTION );
}
}
return value;
}
/**
* Does some actions when the meta data file is end.
*
* @throws MetaDataParserException
*/
public void endDocument( ) throws MetaDataParserException
{
//
if ( !errorHandler.getErrors( ).isEmpty( ) )
{
throw new MetaDataParserException( errorHandler.getErrors( ) );
}
try
{
dictionary.build( );
}
catch ( MetaDataException e )
{
errorHandler.semanticError( new MetaDataParserException( e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
throw new MetaDataParserException( errorHandler.getErrors( ) );
}
}
}
|
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/metadata/MetaDataHandlerImpl.java
|
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.metadata;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.metadata.IElementDefn;
import org.eclipse.birt.report.model.api.metadata.IPropertyType;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.metadata.validators.SimpleValueValidator;
import org.eclipse.birt.report.model.util.AbstractParseState;
import org.eclipse.birt.report.model.util.ErrorHandler;
import org.eclipse.birt.report.model.util.XMLParserException;
import org.eclipse.birt.report.model.util.XMLParserHandler;
import org.eclipse.birt.report.model.validators.AbstractSemanticValidator;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* SAX handler for reading the XML meta data definition file.
*/
public class MetaDataHandlerImpl extends XMLParserHandler
{
/**
* Cache the singleton instance of the meta-data dictionary.
*/
MetaDataDictionary dictionary = MetaDataDictionary.getInstance( );
protected static final String PROPERTY_TAG = "Property"; //$NON-NLS-1$
protected static final String ELEMENT_TAG = "Element"; //$NON-NLS-1$
protected static final String NAME_ATTRIB = "name"; //$NON-NLS-1$
protected static final String METHOD_TAG = "Method"; //$NON-NLS-1$
protected static final String PROPERTY_GROUP_TAG = "PropertyGroup"; //$NON-NLS-1$
private static final String ROOT_TAG = "ReportMetaData"; //$NON-NLS-1$
private static final String STYLE_TAG = "Style"; //$NON-NLS-1$
private static final String STYLE_PROPERTY_TAG = "StyleProperty"; //$NON-NLS-1$
private static final String SLOT_TAG = "Slot"; //$NON-NLS-1$
private static final String TYPE_TAG = "Type"; //$NON-NLS-1$
private static final String DEFAULT_TAG = "Default"; //$NON-NLS-1$
private static final String CHOICE_TAG = "Choice"; //$NON-NLS-1$
private static final String CHOICE_TYPE_TAG = "ChoiceType"; //$NON-NLS-1$
private static final String STRUCTURE_TAG = "Structure"; //$NON-NLS-1$
private static final String ALLOWED_TAG = "Allowed"; //$NON-NLS-1$
private static final String ALLOWED_UNITS_TAG = "AllowedUnits"; //$NON-NLS-1$
private static final String MEMBER_TAG = "Member"; //$NON-NLS-1$
private static final String VALUE_VALIDATOR_TAG = "ValueValidator"; //$NON-NLS-1$
private static final String VALIDATORS_TAG = "Validators"; //$NON-NLS-1$
private static final String ARGUMENT_TAG = "Argument"; //$NON-NLS-1$
private static final String CLASS_TAG = "Class"; //$NON-NLS-1$
private static final String CONSTRUCTOR_TAG = "Constructor"; //$NON-NLS-1$
private static final String SEMANTIC_VALIDATOR_TAG = "SemanticValidator"; //$NON-NLS-1$
private static final String TRIGGER_TAG = "Trigger"; //$NON-NLS-1$
private static final String DEFAULT_UNIT_TAG = "DefaultUnit"; //$NON-NLS-1$
private static final String PROPERTY_VISIBILITY_TAG = "PropertyVisibility"; //$NON-NLS-1$
private static final String DISPLAY_NAME_ID_ATTRIB = "displayNameID"; //$NON-NLS-1$
private static final String EXTENDS_ATTRIB = "extends"; //$NON-NLS-1$
private static final String TYPE_ATTRIB = "type"; //$NON-NLS-1$
private static final String SUB_TYPE_ATTRIB = "subType"; //$NON-NLS-1$
private static final String HAS_STYLE_ATTRIB = "hasStyle"; //$NON-NLS-1$
private static final String SELECTOR_ATTRIB = "selector"; //$NON-NLS-1$
private static final String ALLOWS_USER_PROPERTIES_ATTRIB = "allowsUserProperties"; //$NON-NLS-1$
private static final String CAN_EXTEND_ATTRIB = "canExtend"; //$NON-NLS-1$
private static final String MULTIPLE_CARDINALITY_ATTRIB = "multipleCardinality"; //$NON-NLS-1$
private static final String IS_MANAGED_BY_NAME_SPACE_ATTRIB = "isManagedByNameSpace"; //$NON-NLS-1$
private static final String CAN_INHERIT_ATTRIBUTE = "canInherit"; //$NON-NLS-1$
private static final String IS_INTRINSIC_ATTRIB = "isIntrinsic"; //$NON-NLS-1$
private static final String IS_STYLE_PROPERTY_ATTRIB = "isStyleProperty"; //$NON-NLS-1$
private static final String IS_LIST_ATTRIB = "isList"; //$NON-NLS-1$
private static final String NAME_SPACE_ATTRIB = "nameSpace"; //$NON-NLS-1$
private static final String IS_NAME_REQUIRED_ATTRIB = "isNameRequired"; //$NON-NLS-1$
private static final String IS_ABSTRACT_ATTRIB = "isAbstract"; //$NON-NLS-1$
private static final String DETAIL_TYPE_ATTRIB = "detailType"; //$NON-NLS-1$
private static final String JAVA_CLASS_ATTRIB = "javaClass"; //$NON-NLS-1$
private static final String TOOL_TIP_ID_ATTRIB = "toolTipID"; //$NON-NLS-1$
private static final String RETURN_TYPE_ATTRIB = "returnType"; //$NON-NLS-1$
private static final String TAG_ID_ATTRIB = "tagID"; //$NON-NLS-1$
private static final String DATA_TYPE_ATTRIB = "dataType"; //$NON-NLS-1$
private static final String IS_STATIC_ATTRIB = "isStatic"; //$NON-NLS-1$
private static final String VALIDATOR_ATTRIB = "validator"; //$NON-NLS-1$
private static final String CLASS_ATTRIB = "class"; //$NON-NLS-1$
private static final String NATIVE_ATTRIB = "native"; //$NON-NLS-1$
private static final String PRE_REQUISITE_ATTRIB = "preRequisite"; //$NON-NLS-1$
private static final String TARGET_ELEMENT_ATTRIB = "targetElement"; //$NON-NLS-1$
private static final String VALUE_REQUIRED_ATTRIB = "valueRequired"; //$NON-NLS-1$
private static final String PROPERTY_VISIBILITY_ATTRIB = "visibility"; //$NON-NLS-1$
private static final String SINCE_ATTRIB = "since"; //$NON-NLS-1$
private static final String XML_NAME_ATTRIB = "xmlName"; //$NON-NLS-1$
private static final String RUNTIME_SETTABLE_ATTRIB = "runtimeSettable"; //$NON-NLS-1$
private static final String TRIM_OPTION_ATTRIB = "trimOption"; //$NON-NLS-1$
private static final String CONTEXT_ATTRIB = "context"; //$NON-NLS-1$
private static final String MODULES_ATTRIB = "modules"; //$NON-NLS-1$
private static final String IS_BIDI_PROPERTY_ATTRIB = "isBidiProperty"; //$NON-NLS-1$
private static final String ALLOW_EXPRESSION_ATTRIB = "allowExpression"; //$NON-NLS-1$
/**
* The unique id for the slot.
*/
private static final String ID_ATTRIB = "id"; //$NON-NLS-1$
private static final String THIS_KEYWORD = "this"; //$NON-NLS-1$
private String groupNameID;
// Cached state. Can be done here because nothing in this grammar is
// recursive.
protected ElementDefn elementDefn = null;
protected SlotDefn slotDefn = null;
protected SystemPropertyDefn propDefn = null;
protected StructureDefn struct = null;
protected ArrayList<Choice> choices = new ArrayList<Choice>( );
/**
* The input string will not be trimmed.
*/
private static final String NO_TRIM = "noTrim"; //$NON-NLS-1$
/**
* The space will be trimmed.
*/
private static final String TRIM_SPACE = "trimSpace"; //$NON-NLS-1$
/**
* If the input string is empty, normalizes the string to an null string.
*/
private static final String TRIM_EMPTY_TO_NULL = "trimEmptyToNull"; //$NON-NLS-1$
/**
* if the display ID could be empty
*/
protected boolean checkDisplayNameID = true;
protected MetaDataBuilder builder;
/**
* Constructor.
*/
public MetaDataHandlerImpl( )
{
this( new MetaDataErrorHandler( ), new MetaDataBuilder( ) );
}
/**
* Constructs the meta data handler implementation with the specified error
* handler.
*
* @param errorHandler
* @param builder
*/
public MetaDataHandlerImpl( ErrorHandler errorHandler,
MetaDataBuilder builder )
{
super( errorHandler );
this.builder = builder;
}
public AbstractParseState createStartState( )
{
return new StartState( );
}
/**
* Convert the array list of choices to an array.
*
* @return an array of the choices.
*/
private Choice[] getChoiceArray( )
{
Choice[] choiceArray = new Choice[choices.size( )];
for ( int i = 0; i < choices.size( ); i++ )
choiceArray[i] = choices.get( i );
return choiceArray;
}
class StartState extends InnerParseState
{
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( ROOT_TAG ) )
return new RootState( );
return super.startElement( tagName );
}
}
class RootState extends InnerParseState
{
public AbstractParseState startElement( String tagName )
{
if ( CHOICE_TYPE_TAG.equalsIgnoreCase( tagName ) )
return new ChoiceTypeState( );
if ( STRUCTURE_TAG.equalsIgnoreCase( tagName ) )
return new StructDefnState( );
if ( ELEMENT_TAG.equalsIgnoreCase( tagName ) )
return new ElementDefnState( );
if ( STYLE_TAG.equalsIgnoreCase( tagName ) )
return new StyleState( );
if ( CLASS_TAG.equalsIgnoreCase( tagName ) )
return new ClassState( );
if ( VALIDATORS_TAG.equalsIgnoreCase( tagName ) )
return new ValidatorsState( );
return super.startElement( tagName );
}
}
public class ChoiceTypeState extends InnerParseState
{
ChoiceSet choiceSet = null;
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
choices.clear( );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
else
{
choiceSet = builder.createChoiceSet( );
choiceSet.setName( name );;
try
{
builder.addChoiceSet( choiceSet );
}
catch ( MetaDataException e )
{
choiceSet = null;
errorHandler.semanticError( e );
}
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( CHOICE_TAG ) )
return new ChoiceState( );
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( !choices.isEmpty( ) && choiceSet != null )
choiceSet.setChoices( getChoiceArray( ) );
}
}
protected class StyleState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String type = attrs.getValue( TYPE_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
}
else if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else
{
PredefinedStyle style = new PredefinedStyle( );
style.setName( name );
style.setDisplayNameKey( displayNameID );
style.setType( type );
try
{
dictionary.addPredefinedStyle( style );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
protected class StructDefnState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
}
if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else
{
struct = new StructureDefn( name );
struct.setDisplayNameKey( attrs
.getValue( DISPLAY_NAME_ID_ATTRIB ) );
struct.setSince( attrs.getValue( SINCE_ATTRIB ) );
try
{
dictionary.addStructure( struct );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
struct = null;
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( MEMBER_TAG ) )
return new MemberState( );
return super.startElement( tagName );
}
}
protected class MemberState extends InnerParseState
{
StructPropertyDefn memberDefn = null;
public void parseAttrs( Attributes attrs )
{
String name = getAttrib( attrs, NAME_ATTRIB );
String displayNameID = getAttrib( attrs, DISPLAY_NAME_ID_ATTRIB );
String type = getAttrib( attrs, TYPE_ATTRIB );
String validator = getAttrib( attrs, VALIDATOR_ATTRIB );
String subType = getAttrib( attrs, SUB_TYPE_ATTRIB );
boolean ok = ( struct != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( StringUtil.isBlank( type ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
PropertyType typeDefn = dictionary.getPropertyType( type );
if ( typeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
if ( !ok )
return;
String detailName = getAttrib( attrs, DETAIL_TYPE_ATTRIB );
ChoiceSet choiceSet = null;
String structDefn = null;
PropertyType subTypeDefn = null;
switch ( typeDefn.getTypeCode( ) )
{
case IPropertyType.DIMENSION_TYPE :
case IPropertyType.DATE_TIME_TYPE :
case IPropertyType.STRING_TYPE :
case IPropertyType.LITERAL_STRING_TYPE :
case IPropertyType.FLOAT_TYPE :
case IPropertyType.INTEGER_TYPE :
case IPropertyType.NUMBER_TYPE :
if ( detailName != null )
{
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
}
break;
case IPropertyType.CHOICE_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CHOICE_TYPE_REQUIRED ) );
return;
}
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
break;
case IPropertyType.COLOR_TYPE :
choiceSet = validateChoiceSet( ColorPropertyType.COLORS_CHOICE_SET );
if ( choiceSet == null )
return;
break;
case IPropertyType.STRUCT_TYPE :
case IPropertyType.STRUCT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_STRUCT_TYPE_REQUIRED ) );
return;
}
structDefn = detailName;
break;
case IPropertyType.ELEMENT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
break;
case IPropertyType.LIST_TYPE :
if ( subType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MISSING_SUB_TYPE ) );
}
else
{
subTypeDefn = dictionary.getPropertyType( subType );
if ( subTypeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
else if ( subTypeDefn.getTypeCode( ) == IPropertyType.ELEMENT_REF_TYPE )
{
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
}
}
break;
}
memberDefn = new StructPropertyDefn( );
memberDefn.setName( name );
memberDefn.setType( typeDefn );
if ( subTypeDefn != null
&& typeDefn.getTypeCode( ) == IPropertyType.LIST_TYPE )
memberDefn.setSubType( subTypeDefn );
memberDefn.setDisplayNameID( displayNameID );
memberDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
memberDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
memberDefn.setRuntimeSettable( getBooleanAttrib( attrs,
RUNTIME_SETTABLE_ATTRIB, true ) );
String trimOption = attrs.getValue( TRIM_OPTION_ATTRIB );
if ( trimOption != null )
{
try
{
int value = handleTrimOption( trimOption );
memberDefn.setTrimOption( value );
}
catch ( MetaDataParserException e )
{
errorHandler.semanticError( e );
}
}
memberDefn.setAllowExpression( getBooleanAttrib( attrs,
ALLOW_EXPRESSION_ATTRIB, false ) );
if ( memberDefn.getTypeCode( ) == IPropertyType.EXPRESSION_TYPE )
{
memberDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
memberDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
}
if ( !StringUtil.isBlank( validator ) )
{
memberDefn.setValueValidator( validator );
}
if ( typeDefn.getTypeCode( ) == IPropertyType.STRUCT_TYPE )
memberDefn.setIsList( getBooleanAttrib( attrs, IS_LIST_ATTRIB,
false ) );
if ( choiceSet != null )
memberDefn.setDetails( choiceSet );
else if ( structDefn != null )
memberDefn.setDetails( structDefn );
else if ( detailName != null )
memberDefn.setDetails( detailName );
memberDefn.setIntrinsic( getBooleanAttrib( attrs,
IS_INTRINSIC_ATTRIB, false ) );
try
{
struct.addProperty( memberDefn );
}
catch ( MetaDataException e )
{
errorHandler.semanticError( e );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( DEFAULT_TAG ) )
return new DefaultValueState( memberDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_TAG ) )
return new AllowedState( memberDefn );
return super.startElement( tagName );
}
}
public class ElementDefnState extends InnerParseState
{
protected ElementDefn createElementDefn( )
{
return builder.createElementDefn( );
}
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// use this method to create element definition instance and handle
// the name, this will help to override and change the behavior for
// different requirements
elementDefn = createElementDefn( );
elementDefn.setName( name );
elementDefn.setAbstract( getBooleanAttrib( attrs,
IS_ABSTRACT_ATTRIB, false ) );
elementDefn.setDisplayNameKey( displayNameID );
elementDefn.setExtends( attrs.getValue( EXTENDS_ATTRIB ) );
elementDefn.setHasStyle( getBooleanAttrib( attrs, HAS_STYLE_ATTRIB,
false ) );
elementDefn.setSelector( attrs.getValue( SELECTOR_ATTRIB ) );
elementDefn.setAllowsUserProperties( getBooleanAttrib( attrs,
ALLOWS_USER_PROPERTIES_ATTRIB, true ) );
elementDefn.setJavaClass( attrs.getValue( JAVA_CLASS_ATTRIB ) );
elementDefn.setCanExtend( getBooleanAttrib( attrs,
CAN_EXTEND_ATTRIB, true ) );
elementDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
elementDefn.setXmlName( attrs.getValue( XML_NAME_ATTRIB ) );
String nameRequired = attrs.getValue( IS_NAME_REQUIRED_ATTRIB );
if ( nameRequired != null )
{
boolean flag = parseBoolean( nameRequired, false );
elementDefn.setNameOption( flag
? MetaDataConstants.REQUIRED_NAME
: MetaDataConstants.OPTIONAL_NAME );
}
String ns = attrs.getValue( NAME_SPACE_ATTRIB );
IElementDefn moduleDefn = dictionary
.getElement( ReportDesignConstants.MODULE_ELEMENT );
if ( ns == null || ns.trim( ).length( ) == 0 )
{
// Inherit default name space
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.STYLE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.STYLE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.THEME_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.THEME_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.DATA_SET_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DATA_SET_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.DATA_SOURCE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DATA_SOURCE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.ELEMENT_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.ELEMENT_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.PARAMETER_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.PARAMETER_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.MASTER_PAGE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.PAGE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.CUBE_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.CUBE_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns
.equalsIgnoreCase( NameSpaceFactory.TEMPLATE_PARAMETER_DEFINITION_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.TEMPLATE_PARAMETER_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.DIMENSION_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = Module.DIMENSION_NAME_SPACE;
elementDefn.nameConfig.holder = moduleDefn;
}
else if ( ns.equalsIgnoreCase( NameSpaceFactory.NO_NS_NAME ) )
{
elementDefn.nameConfig.nameSpaceID = MetaDataConstants.NO_NAME_SPACE;
}
else if ( ns.startsWith( "(" ) && ns.endsWith( ")" ) ) //$NON-NLS-1$//$NON-NLS-2$
{
String nsValue = ns.substring( 1, ns.length( ) - 1 );
String[] splitStrings = nsValue.split( "," ); //$NON-NLS-1$
if ( splitStrings == null
|| !( splitStrings.length == 2 || splitStrings.length == 3 ) )
{
errorHandler
.semanticError( new MetaDataException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
}
else
{
int length = splitStrings.length;
assert length == 2 || length == 3;
String holderName = StringUtil.trimString( splitStrings[0] );
String nameSpace = StringUtil.trimString( splitStrings[1] );
ElementDefn holderDefn = (ElementDefn) dictionary
.getElement( holderName );
if ( holderDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
}
else
{
// the name holder must be existing and name
// required element or the module type
elementDefn.nameConfig.holder = holderDefn;
elementDefn.nameConfig.nameSpaceID = NameSpaceFactory
.getInstance( ).getNameSpaceID( holderName,
nameSpace );
if ( length == 3 )
{
elementDefn.nameConfig.targetPropertyName = StringUtil
.trimString( splitStrings[2] );
}
}
}
}
else
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_INVALID_NAME_SPACE ) );
try
{
builder.addElementDefn( elementDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( PROPERTY_TAG ) )
return new PropertyState( );
if ( tagName.equalsIgnoreCase( PROPERTY_GROUP_TAG ) )
return new PropertyGroupState( );
if ( tagName.equalsIgnoreCase( STYLE_PROPERTY_TAG ) )
return new StylePropertyState( );
if ( tagName.equalsIgnoreCase( SLOT_TAG ) )
return new SlotState( );
if ( tagName.equalsIgnoreCase( METHOD_TAG ) )
return new ElementMethodState( elementDefn );
if ( tagName.equalsIgnoreCase( SEMANTIC_VALIDATOR_TAG ) )
return new TriggerState( );
if ( tagName.equalsIgnoreCase( PROPERTY_VISIBILITY_TAG ) )
return new PropertyVisibilityState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
elementDefn = null;
}
/**
* Parses the property visiblity.
*/
private class PropertyVisibilityState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String visible = attrs.getValue( PROPERTY_VISIBILITY_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
return;
}
elementDefn.addPropertyVisibility( name, visible );
}
}
}
class PropertyGroupState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
groupNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
if ( StringUtil.isBlank( groupNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_GROUP_NAME_ID_REQUIRED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( PROPERTY_TAG ) )
return new PropertyState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
groupNameID = null;
}
}
protected class PropertyState extends InnerParseState
{
List<String> propertyTypes = new ArrayList<String>( );
public void parseAttrs( Attributes attrs )
{
choices.clear( );
propDefn = null;
String name = getAttrib( attrs, NAME_ATTRIB );
String displayNameID = getAttrib( attrs, DISPLAY_NAME_ID_ATTRIB );
String type = getAttrib( attrs, TYPE_ATTRIB );
String validator = getAttrib( attrs, VALIDATOR_ATTRIB );
String subType = getAttrib( attrs, SUB_TYPE_ATTRIB );
boolean isList = getBooleanAttrib( attrs, IS_LIST_ATTRIB, false );
String detailName = getAttrib( attrs, DETAIL_TYPE_ATTRIB );
boolean ok = ( elementDefn != null );
if ( name == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( type == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// Look up the choice set name, if any.
PropertyType typeDefn = dictionary.getPropertyType( type );
if ( typeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
//list type only support types in supportedSubTypes
//isList only support element/content/structure
//here we convert isList to listType for simple properties
int typeCode = typeDefn.getTypeCode( );
if ( isList && typeCode != IPropertyType.LIST_TYPE )
{
if ( PropertyDefn.isSupportedSubType( typeDefn ) )
{
subType = type;
}
}
ChoiceSet choiceSet = null;
StructureDefn struct = null;
PropertyType subTypeDefn = null;
switch ( typeDefn.getTypeCode( ) )
{
case IPropertyType.DIMENSION_TYPE :
case IPropertyType.DATE_TIME_TYPE :
case IPropertyType.STRING_TYPE :
case IPropertyType.LITERAL_STRING_TYPE :
case IPropertyType.FLOAT_TYPE :
case IPropertyType.INTEGER_TYPE :
case IPropertyType.NUMBER_TYPE :
if ( detailName != null )
{
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
}
break;
case IPropertyType.CHOICE_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CHOICE_TYPE_REQUIRED ) );
return;
}
choiceSet = validateChoiceSet( detailName );
if ( choiceSet == null )
return;
break;
case IPropertyType.COLOR_TYPE :
choiceSet = validateChoiceSet( ColorPropertyType.COLORS_CHOICE_SET );
if ( choiceSet == null )
return;
break;
case IPropertyType.STRUCT_TYPE :
case IPropertyType.STRUCT_REF_TYPE :
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_STRUCT_TYPE_REQUIRED ) );
return;
}
struct = (StructureDefn) dictionary
.getStructure( detailName );
if ( struct == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_STRUCT_TYPE ) );
return;
}
break;
case IPropertyType.ELEMENT_TYPE :
case IPropertyType.CONTENT_ELEMENT_TYPE :
case IPropertyType.ELEMENT_REF_TYPE :
// the user can define the detail type either in detailType attribute or type element.
if ( THIS_KEYWORD.equals( detailName ) )
{
detailName = elementDefn.getName( );
}
break;
case IPropertyType.LIST_TYPE :
if ( subType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MISSING_SUB_TYPE ) );
}
else
{
subTypeDefn = dictionary.getPropertyType( subType );
if ( subTypeDefn == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TYPE ) );
return;
}
else if ( subTypeDefn.getTypeCode( ) == IPropertyType.ELEMENT_REF_TYPE )
{
if ( detailName == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_ELEMENT_REF_TYPE_REQUIRED ) );
return;
}
if ( detailName.equals( THIS_KEYWORD ) )
detailName = elementDefn.getName( );
}
}
break;
default :
// Ignore the detail name for other types.
detailName = null;
}
// call the method to create property definition rather than create
// it using constructor directly to satisfy different requirements
// in different use-cases
propDefn = builder.createPropertyDefn( );
propDefn.setName( name );
propDefn.setDisplayNameID( displayNameID );
propDefn.setType( typeDefn );
if ( typeDefn.getTypeCode( ) == IPropertyType.LIST_TYPE )
propDefn.setSubType( subTypeDefn );
propDefn.setGroupNameKey( groupNameID );
propDefn.setCanInherit( getBooleanAttrib( attrs,
CAN_INHERIT_ATTRIBUTE, true ) );
propDefn.setIntrinsic( getBooleanAttrib( attrs,
IS_INTRINSIC_ATTRIB, false ) );
propDefn.setStyleProperty( getBooleanAttrib( attrs,
IS_STYLE_PROPERTY_ATTRIB, false ) );
propDefn.setBidiProperty( getBooleanAttrib( attrs,
IS_BIDI_PROPERTY_ATTRIB, false ) );
propDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
propDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
propDefn.setRuntimeSettable( getBooleanAttrib( attrs,
RUNTIME_SETTABLE_ATTRIB, true ) );
String trimOption = attrs.getValue( TRIM_OPTION_ATTRIB );
if ( trimOption != null )
{
try
{
int value = handleTrimOption( trimOption );
propDefn.setTrimOption( value );
}
catch ( MetaDataParserException e )
{
errorHandler.semanticError( e );
}
}
propDefn.setAllowExpression( getBooleanAttrib( attrs,
ALLOW_EXPRESSION_ATTRIB, false ) );
if ( propDefn.getTypeCode( ) == IPropertyType.EXPRESSION_TYPE )
{
propDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
propDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
}
if ( !StringUtil.isBlank( validator ) )
{
propDefn.setValueValidator( validator );
}
if ( typeCode == IPropertyType.STRUCT_TYPE
|| propDefn.isElementType( ) )
propDefn.setIsList( isList );
if ( choiceSet != null )
propDefn.setDetails( choiceSet );
else if ( struct != null )
propDefn.setDetails( struct );
else if ( detailName != null )
propDefn.setDetails( detailName );
// add it to dictionary
try
{
builder.addPropertyDefn( elementDefn, propDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( DEFAULT_TAG ) )
return new DefaultValueState( propDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_TAG ) )
return new AllowedState( propDefn );
else if ( tagName.equalsIgnoreCase( ALLOWED_UNITS_TAG ) )
return new AllowedUnitsState( propDefn );
else if ( tagName.equalsIgnoreCase( TRIGGER_TAG ) )
return new TriggerState( );
else if ( tagName.equalsIgnoreCase( DEFAULT_UNIT_TAG ) )
return new DefaultUnitState( );
else if ( tagName.equalsIgnoreCase( TYPE_TAG ) )
return new PropertyTypeState( propertyTypes );
else
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
// if property is element type, then set list of allowed type names
// to the details
if ( propDefn != null && !propertyTypes.isEmpty( ) )
{
int typeCode = propDefn.getTypeCode( );
if ( typeCode == IPropertyType.ELEMENT_TYPE
|| typeCode == IPropertyType.STRUCT_TYPE
|| typeCode == IPropertyType.CONTENT_ELEMENT_TYPE )
{
propDefn.setDetails( propertyTypes );
}
}
propDefn = null;
}
}
class DefaultUnitState extends InnerParseState
{
public void end( ) throws SAXException
{
if ( propDefn == null )
return;
int type = propDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DEFAULT_UNIT_NOT_ALLOWED ) );
return;
}
propDefn.setDefaultUnit( text.toString( ) );
}
}
class AllowedState extends InnerParseState
{
PropertyDefn tmpPropDefn;
AllowedState( PropertyDefn tmpPropDefn )
{
this.tmpPropDefn = tmpPropDefn;
}
public void end( ) throws SAXException
{
if ( tmpPropDefn == null )
return;
int type = tmpPropDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE
&& type != IPropertyType.CHOICE_TYPE )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_RESTRICTION_NOT_ALLOWED ) );
return;
}
ChoiceSet allowedChoices = builder.createChoiceSet( );
ArrayList<IChoice> allowedList = new ArrayList<IChoice>( );
String choicesStr = StringUtil.trimString( text.toString( ) );
// blank string.
if ( choicesStr == null )
return;
String[] nameArray = choicesStr.split( "," ); //$NON-NLS-1$
if ( type == IPropertyType.DIMENSION_TYPE )
{
// units restriction on a dimension property.
IChoiceSet units = dictionary
.getChoiceSet( DesignChoiceConstants.CHOICE_UNITS );
assert units != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice unit = units.findChoice( nameArray[i].trim( ) );
if ( unit != null )
{
allowedList.add( unit );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
}
else
{
// choices type restriction.
IChoiceSet choices = tmpPropDefn.getChoices( );
assert choices != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice choice = choices.findChoice( nameArray[i].trim( ) );
if ( choice != null )
{
allowedList.add( choice );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
}
allowedChoices.setChoices( allowedList
.toArray( new Choice[allowedList.size( )] ) );
tmpPropDefn.setAllowedChoices( allowedChoices );
}
}
private class AllowedUnitsState extends InnerParseState
{
PropertyDefn tmpPropDefn;
AllowedUnitsState( PropertyDefn tmpPropDefn )
{
this.tmpPropDefn = tmpPropDefn;
}
public void end( ) throws SAXException
{
if ( tmpPropDefn == null )
return;
int type = tmpPropDefn.getTypeCode( );
if ( type != IPropertyType.DIMENSION_TYPE
&& !( type == IPropertyType.LIST_TYPE && tmpPropDefn
.getSubTypeCode( ) == IPropertyType.DIMENSION_TYPE ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_RESTRICTION_NOT_ALLOWED ) );
return;
}
ChoiceSet allowedChoices = builder.createChoiceSet( );
ArrayList<IChoice> allowedList = new ArrayList<IChoice>( );
String choicesStr = StringUtil.trimString( text.toString( ) );
// blank string.
if ( choicesStr == null )
return;
String[] nameArray = choicesStr.split( "," ); //$NON-NLS-1$
// units restriction on a dimension property.
IChoiceSet units = dictionary
.getChoiceSet( DesignChoiceConstants.CHOICE_UNITS );
assert units != null;
for ( int i = 0; i < nameArray.length; i++ )
{
IChoice unit = units.findChoice( nameArray[i].trim( ) );
if ( unit != null )
{
allowedList.add( unit );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_RESTRICTION ) );
return;
}
}
allowedChoices.setChoices( allowedList
.toArray( new Choice[allowedList.size( )] ) );
tmpPropDefn.setAllowedUnits( allowedChoices );
}
}
class ValidatorsState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#startElement
* (java.lang.String)
*/
public AbstractParseState startElement( String tagName )
{
if ( VALUE_VALIDATOR_TAG.equalsIgnoreCase( tagName ) )
return new ValueValidatorState( );
if ( SEMANTIC_VALIDATOR_TAG.equalsIgnoreCase( tagName ) )
return new SemanticValidatorState( );
return super.startElement( tagName );
}
}
class ValueValidatorState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = getAttrib( attrs, NAME_ATTRIB );
String className = getAttrib( attrs, CLASS_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
return;
}
if ( StringUtil.isBlank( className ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CLASS_NAME_REQUIRED ) );
return;
}
try
{
Class<? extends Object> c = Class.forName( className );
SimpleValueValidator validator = (SimpleValueValidator) c
.newInstance( );
validator.setName( name );
try
{
dictionary.addValueValidator( validator );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
catch ( Exception e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_META_VALIDATOR ) );
}
}
}
class SemanticValidatorState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = getAttrib( attrs, NAME_ATTRIB );
String modules = getAttrib( attrs, MODULES_ATTRIB );
String className = getAttrib( attrs, CLASS_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
return;
}
if ( StringUtil.isBlank( className ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_CLASS_NAME_REQUIRED ) );
return;
}
try
{
Class<? extends Object> c = Class.forName( className );
Method m = c.getMethod( "getInstance", (Class[]) null ); //$NON-NLS-1$
AbstractSemanticValidator validator = (AbstractSemanticValidator) m
.invoke( null, (Object[]) null );
validator.setName( name );
validator.setModules( modules );
try
{
dictionary.addSemanticValidator( validator );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
catch ( Exception e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_META_VALIDATOR ) );
}
}
}
class DefaultValueState extends InnerParseState
{
/**
* Reference to a member or a property.
*/
PropertyDefn propertyDefn = null;
DefaultValueState( PropertyDefn propDefn )
{
this.propertyDefn = propDefn;
}
public void end( ) throws SAXException
{
if ( this.propertyDefn == null )
return;
try
{
Object value = propertyDefn.validateXml( null, null, text
.toString( ) );
propertyDefn.setDefault( value );
}
catch ( PropertyValueException e )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_DEFAULT ) );
}
}
}
class ChoiceState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String xmlName = attrs.getValue( NAME_ATTRIB );
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
}
else if ( StringUtil.isBlank( xmlName ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_XML_NAME_REQUIRED ) );
}
else
{
Choice choice = builder.createChoice( );
choice.setName( xmlName );
choice.setDisplayNameKey( displayNameID );
boolean found = false;
Iterator<Choice> iter = choices.iterator( );
while ( iter.hasNext( ) )
{
Choice tmpChoice = iter.next( );
if ( tmpChoice.getName( ).equalsIgnoreCase(
choice.getName( ) ) )
{
found = true;
break;
}
}
if ( found )
errorHandler
.semanticError( new MetaDataParserException(
MetaDataException.DESIGN_EXCEPTION_DUPLICATE_CHOICE_NAME ) );
else
choices.add( choice );
}
}
}
class StylePropertyState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
boolean ok = ( elementDefn != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
elementDefn.addStyleProperty( name );
}
}
class SlotState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String multipleCardinality = attrs
.getValue( MULTIPLE_CARDINALITY_ATTRIB );
String tmpID = attrs.getValue( ID_ATTRIB );
boolean ok = ( elementDefn != null );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
else if ( StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
else if ( StringUtil.isBlank( multipleCardinality ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_MULTIPLE_CARDINALITY_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
slotDefn = new SlotDefn( );
slotDefn.setName( name );
slotDefn.setDisplayNameID( displayNameID );
slotDefn.setManagedByNameSpace( getBooleanAttrib( attrs,
IS_MANAGED_BY_NAME_SPACE_ATTRIB, true ) );
slotDefn.setMultipleCardinality( parseBoolean( multipleCardinality,
true ) );
slotDefn.setSelector( attrs.getValue( SELECTOR_ATTRIB ) );
slotDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
slotDefn.setXmlName( attrs.getValue( XML_NAME_ATTRIB ) );
if ( !StringUtil.isBlank( tmpID ) )
{
try
{
slotDefn.setSlotID( Integer.parseInt( tmpID ) );
}
catch ( NumberFormatException e )
{
// just ignore the error. the slot id is reset later.
}
}
elementDefn.addSlot( slotDefn );
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( TYPE_TAG ) )
return new SlotTypeState( );
if ( tagName.equalsIgnoreCase( TRIGGER_TAG ) )
return new TriggerState( );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
slotDefn = null;
}
}
class PropertyTypeState extends InnerParseState
{
protected List<String> types = null;
/**
* Constructs the property type state with a list to hold all the type
* names.
*
* @param propertyTypes
*/
public PropertyTypeState( List<String> propertyTypes )
{
this.types = propertyTypes;
}
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
boolean ok = ( propDefn != null );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
types.add( name );
}
}
class SlotTypeState extends InnerParseState
{
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
boolean ok = ( slotDefn != null );
String name = attrs.getValue( NAME_ATTRIB );
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( ok )
slotDefn.addType( name );
}
}
/**
* The state to parse a method under a class.
*/
class ClassMethodState extends AbstractMethodState
{
private boolean isConstructor = false;
ClassMethodState( Object obj, boolean isConstructor )
{
super( obj );
this.isConstructor = isConstructor;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#getMethodInfo()
*/
MethodInfo getMethodInfo( String name )
{
ClassInfo classInfo = (ClassInfo) owner;
if ( classInfo != null )
{
if ( isConstructor )
methodInfo = (MethodInfo) classInfo.getConstructor( );
else
methodInfo = classInfo.findMethod( name );
}
if ( methodInfo == null )
methodInfo = builder.createMethodInfo( isConstructor );
return methodInfo;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#addDefnTo()
*/
void addDefnTo( )
{
assert owner instanceof ClassInfo;
ClassInfo classInfo = (ClassInfo) owner;
try
{
builder.addMethodInfo( classInfo, methodInfo );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/**
* The state to parse a method under an element.
*/
class ElementMethodState extends AbstractMethodState
{
SystemPropertyDefn localPropDefn = null;;
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#getMethodInfo()
*/
MethodInfo getMethodInfo( String name )
{
return new MethodInfo( false );
}
ElementMethodState( Object obj )
{
super( obj );
localPropDefn = builder.createPropertyDefn( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs )
{
super.parseAttrs( attrs );
localPropDefn.setValueRequired( getBooleanAttrib( attrs,
VALUE_REQUIRED_ATTRIB, false ) );
localPropDefn.setSince( attrs.getValue( SINCE_ATTRIB ) );
localPropDefn.setContext( attrs.getValue( CONTEXT_ATTRIB ) );
localPropDefn.setReturnType( attrs.getValue( RETURN_TYPE_ATTRIB ) );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.model.metadata.MetaDataHandler.
* AbstractMethodState#addDefnTo()
*/
final void addDefnTo( )
{
assert owner instanceof ElementDefn;
PropertyType typeDefn = dictionary
.getPropertyType( IPropertyType.SCRIPT_TYPE );
String name = methodInfo.getName( );
String displayNameID = methodInfo.getDisplayNameKey( );
localPropDefn.setName( name );
localPropDefn.setDisplayNameID( displayNameID );
localPropDefn.setType( typeDefn );
localPropDefn.setGroupNameKey( null );
localPropDefn.setCanInherit( true );
localPropDefn.setIntrinsic( false );
localPropDefn.setStyleProperty( false );
localPropDefn.setDetails( methodInfo );
try
{
builder.addPropertyDefn( (ElementDefn) owner, localPropDefn );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
/**
* Parses an method state either under an element or class tag.
*/
abstract class AbstractMethodState extends InnerParseState
{
/**
* The element contains this state. Can be either a
* <code>ElementDefn</code> or <code>ClassInfo</code>.
*/
protected Object owner = null;
/**
* The cached <code>MethodInfo</code> for the state.
*/
protected MethodInfo methodInfo = null;
/**
* The cached argument list.
*/
private ArgumentInfoList argumentList = null;
/**
* Constructs a <code>MethodState</code> with the given owner.
*
* @param obj
* the parent object of this state
*/
AbstractMethodState( Object obj )
{
assert obj != null;
this.owner = obj;
}
/**
* Adds method information to the ElementDefn or ClassInfo.
*/
abstract void addDefnTo( );
/**
* Returns method information with the given method name.
*
* @param name
* the method name
* @return the <code>MethodInfo</code> object
*/
abstract MethodInfo getMethodInfo( String name );
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String returnType = attrs.getValue( RETURN_TYPE_ATTRIB );
boolean isStatic = getBooleanAttrib( attrs, IS_STATIC_ATTRIB, false );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
// Note that here ROM supports overloadding, while JavaScript not.
// finds the method info if it has been parsed.
methodInfo = getMethodInfo( name );
methodInfo.setName( name );
methodInfo.setDisplayNameKey( displayNameID );
methodInfo.setReturnType( returnType );
methodInfo.setToolTipKey( toolTipID );
methodInfo.setStatic( isStatic );
addDefnTo( );
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( ARGUMENT_TAG ) )
return new ArgumentState( );
return super.startElement( tagName );
}
public void end( ) throws SAXException
{
if ( argumentList == null )
argumentList = new ArgumentInfoList( );
methodInfo.addArgumentList( argumentList );
methodInfo = null;
propDefn = null;
}
class ArgumentState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String tagID = attrs.getValue( TAG_ID_ATTRIB );
String type = attrs.getValue( TYPE_ATTRIB );
// for class member, we use data type, support dataType to make it consistent
if ( type == null )
{
type = attrs.getValue( DATA_TYPE_ATTRIB );
}
if ( name == null )
return;
ArgumentInfo argument = builder.createArgumentInfo( );
argument.setName( name );
argument.setType( type );
argument.setDisplayNameKey( tagID );
if ( argumentList == null )
argumentList = new ArgumentInfoList( );
try
{
argumentList.addArgument( argument );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
protected class ClassState extends InnerParseState
{
protected ClassInfo classInfo = null;
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String isNative = attrs.getValue( NATIVE_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
classInfo = builder.createClassInfo( );
classInfo.setName( name );
classInfo.setDisplayNameKey( displayNameID );
classInfo.setToolTipKey( toolTipID );
if ( Boolean.TRUE.toString( ).equalsIgnoreCase( isNative ) )
classInfo.setNative( true );
else if ( Boolean.FALSE.toString( ).equalsIgnoreCase( isNative ) )
classInfo.setNative( false );
try
{
builder.addClassInfo(classInfo );
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
public AbstractParseState startElement( String tagName )
{
if ( tagName.equalsIgnoreCase( CONSTRUCTOR_TAG ) )
return new ClassMethodState( classInfo, true );
if ( tagName.equalsIgnoreCase( MEMBER_TAG ) )
return new MemberState( );
if ( tagName.equalsIgnoreCase( METHOD_TAG ) )
return new ClassMethodState( classInfo, false );
return super.startElement( tagName );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
super.end( );
classInfo = null;
}
protected class MemberState extends InnerParseState
{
public void parseAttrs( Attributes attrs )
{
String name = attrs.getValue( NAME_ATTRIB );
String displayNameID = attrs.getValue( DISPLAY_NAME_ID_ATTRIB );
String toolTipID = attrs.getValue( TOOL_TIP_ID_ATTRIB );
String dataType = attrs.getValue( DATA_TYPE_ATTRIB );
boolean ok = true;
if ( StringUtil.isBlank( name ))
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_NAME_REQUIRED ) );
ok = false;
}
if ( checkDisplayNameID && StringUtil.isBlank( displayNameID) )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DISPLAY_NAME_ID_REQUIRED ) );
ok = false;
}
if ( dataType == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_DATA_TYPE_REQUIRED ) );
ok = false;
}
if ( !ok )
return;
MemberInfo memberDefn = builder.createMemberInfo( );
memberDefn.setName( name );
memberDefn.setDisplayNameKey( displayNameID );
memberDefn.setToolTipKey( toolTipID );
memberDefn.setDataType( dataType );
memberDefn.setStatic( getBooleanAttrib( attrs,
IS_STATIC_ATTRIB, false ) );
try
{
builder.addMemberInfo( classInfo, memberDefn);
}
catch ( MetaDataException e )
{
errorHandler
.semanticError( new MetaDataParserException(
e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
}
}
}
}
class TriggerState extends InnerParseState
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(
* org.xml.sax.Attributes)
*/
public void parseAttrs( Attributes attrs ) throws XMLParserException
{
assert propDefn != null || slotDefn != null;
String validatorName = attrs.getValue( VALIDATOR_ATTRIB );
String targetElement = attrs.getValue( TARGET_ELEMENT_ATTRIB );
if ( !StringUtil.isBlank( validatorName ) )
{
SemanticTriggerDefn triggerDefn = new SemanticTriggerDefn(
validatorName );
triggerDefn.setPreRequisite( getBooleanAttrib( attrs,
PRE_REQUISITE_ATTRIB, false ) );
if ( !StringUtil.isBlank( targetElement ) )
triggerDefn.setTargetElement( targetElement );
if ( propDefn != null )
propDefn.getTriggerDefnSet( ).add( triggerDefn );
if ( slotDefn != null )
slotDefn.getTriggerDefnSet( ).add( triggerDefn );
}
else
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_VALIDATOR_NAME_REQUIRED ) );
}
}
}
/**
* Checks if dictionary contains a specified ChoiceSet with the name
* <code>choiceSetName</code>.
*
* @param choiceSetName
* the name of ChoiceSet to be checked.
* @return the validated choiceSet. If not found, return null.
*/
private ChoiceSet validateChoiceSet( String choiceSetName )
{
IChoiceSet choiceSet = dictionary.getChoiceSet( choiceSetName );
if ( choiceSet == null )
{
errorHandler
.semanticError( new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_CHOICE_TYPE ) );
return null;
}
return (ChoiceSet) choiceSet;
}
/**
* Transfers trim option string to trim option value. The input value is
* defined in <code>ModelUtil</code> and can be one of:
*
* <ul>
* <li>NO_TRIM</li>
* <li>TRIM_EMPTY</li>
* <li>TRIM_NULL</li>
* <li>TRIM_EMPTY&TRIM_NULL</li>
* <li>NULL</li>
* </ul>
*
* @param trimOption
* the trim option.
* @return the trim option value.
*/
private int handleTrimOption( String trimOption )
throws MetaDataParserException
{
// TODO: do some enhancement to enable textualPropertyType could
// not trim, trim string space or trim empty space to null according to
// the trim option.
String[] options = trimOption.split( ";" ); //$NON-NLS-1$
int value = XMLPropertyType.NO_VALUE;
for ( int i = 0; i < options.length; i++ )
{
String option = options[i];
if ( NO_TRIM.equals( option ) )
{
value |= XMLPropertyType.NO_TRIM_VALUE;
}
else if ( TRIM_SPACE.equals( option ) )
{
value |= XMLPropertyType.TRIM_SPACE_VALUE;
}
else if ( TRIM_EMPTY_TO_NULL.equals( option ) )
{
value |= XMLPropertyType.TRIM_EMPTY_TO_NULL_VALUE;
}
else
{
// invalid trim option.
throw new MetaDataParserException(
MetaDataParserException.DESIGN_EXCEPTION_INVALID_TRIM_OPTION );
}
}
return value;
}
/**
* Does some actions when the meta data file is end.
*
* @throws MetaDataParserException
*/
public void endDocument( ) throws MetaDataParserException
{
//
if ( !errorHandler.getErrors( ).isEmpty( ) )
{
throw new MetaDataParserException( errorHandler.getErrors( ) );
}
try
{
dictionary.build( );
}
catch ( MetaDataException e )
{
errorHandler.semanticError( new MetaDataParserException( e,
MetaDataParserException.DESIGN_EXCEPTION_BUILD_FAILED ) );
throw new MetaDataParserException( errorHandler.getErrors( ) );
}
}
}
|
Enhance ROM syntax to define choice type in type element
|
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/metadata/MetaDataHandlerImpl.java
|
Enhance ROM syntax to define choice type in type element
|
|
Java
|
epl-1.0
|
885d8f2c2f14a803c0dac2d8ddb34e07fc7eba27
| 0
|
briandealwis/gwt-eclipse-plugin,gwt-plugins/gwt-eclipse-plugin,briandealwis/gwt-eclipse-plugin,briandealwis/gwt-eclipse-plugin,gwt-plugins/gwt-eclipse-plugin,gwt-plugins/gwt-eclipse-plugin
|
/*******************************************************************************
* Copyright 2011 Google Inc. All Rights Reserved.
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.google.gdt.eclipse.managedapis;
import com.google.gdt.eclipse.core.AbstractGooglePlugin;
import com.google.gdt.eclipse.core.extensions.ExtensionQuery;
import com.google.gdt.eclipse.core.extensiontypes.IManagedApiProjectStateTest;
import com.google.gdt.eclipse.core.natures.NatureUtils;
import com.google.gdt.eclipse.managedapis.directory.ApiDirectory;
import com.google.gdt.eclipse.managedapis.directory.ApiDirectoryFactory;
import com.google.gdt.eclipse.managedapis.extensiontypes.IManagedApiProjectInitializationCallback;
import com.google.gdt.eclipse.managedapis.impl.IconCache;
import com.google.gdt.eclipse.managedapis.impl.ManagedApiChecker;
import com.google.gdt.eclipse.managedapis.impl.RemoteApiDirectory;
import com.google.gdt.eclipse.managedapis.platform.PluginResources;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IRegistryChangeEvent;
import org.eclipse.core.runtime.IRegistryChangeListener;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jdt.core.JavaCore;
import org.osgi.framework.BundleContext;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
* Entrypoint for the ManagedApi plugin and container of contants used by the
* plugin as a whole.
*/
public class ManagedApiPlugin extends AbstractGooglePlugin {
public static final boolean SINGLE_CLASSPATH_CONTAINER = false;
public static final String DEPENDENCIES_FOLDER_NAME = "dependencies";
public static final String PLUGIN_ID = "com.google.gdt.eclipse.managedapis";
public static final String API_CONTAINER_PATH_ID = PLUGIN_ID
+ ".MANAGED_API_CONTAINER";
public static final Path API_CONTAINER_PATH = new Path(API_CONTAINER_PATH_ID);
public static final
String COPY_CLASSPATH_ENTRIES_TARGET_PATH_KEY = "COPY_CLASSPATH_ENTRIES_TARGET_PATH";
public static final
String DEFAULT_MANAGED_API_DIRECTORY_HREF = "http://api-directory.googleapis.com/5935";
public static final
String DEFAULT_MANAGED_API_ICON_PREFETCH_HREF = "http://api-directory.googleapis.com/icons";
public static final String ICON_KEY_CLASSPATH_CONTAINER = "x16";
public static final String ICON_KEY_API_IMPORT = "x32";
public static final QualifiedName MANAGED_API_FLAG_QNAME = new QualifiedName(
PLUGIN_ID, "PROJECT_FLAG");
public static final String
MANAGED_API_ROOT_FOLDER_DEFAULT_PATH = ".google_apis";
public static final String SWARM_LIB_FOLDER_NAME = "endpoint-libs";
public static final String
MANAGED_API_ROOT_FOLDER_PATH_KEY = "MANAGED_API_ROOT_FOLDER_PATH";
public static final QualifiedName
MANAGED_API_SESSION_KEY_QNAME = new QualifiedName(
PLUGIN_ID, "MANAGED_API_SESSION_KEY");
// Latest in the 1.14 series
public static final String API_CLIENT_LANG_VERSION = "1.16.x";
public static final long API_DIRECTORY_CACHE_TTL = 4 * 60 * 60 * 1000; // 4HRS
public static final long CHECK_MANAGED_APIS_FREQ = 2 * 60 * 60 * 1000;// 2 HRS
public static final boolean DO_DELETES = false;
private static ManagedApiPlugin plugin;
/**
* Provide access to updated set of initialization callbacks configured for
* this workspace.
*
* @return the callbacks
*/
public static IManagedApiProjectInitializationCallback[] findProjectInitializationCallbacks() {
IManagedApiProjectInitializationCallback[] callbacks;
getDefault().extensionsLock.lock();
try {
callbacks = getDefault().projectInitializationCallbacks;
} finally {
getDefault().extensionsLock.unlock();
}
return callbacks;
}
public static ManagedApiPlugin getDefault() {
return plugin;
}
public static String getManagedApiDirectoryHref() {
String overrideHref = System.getenv("MANAGED_API_DIRECTORY_HREF");
if (overrideHref == null) {
return DEFAULT_MANAGED_API_DIRECTORY_HREF;
} else {
return overrideHref;
}
}
public static String getManagedApiIconBundleHref() {
String overrideHref = System.getenv("MANAGED_API_ICON_PREFETCH_HREF");
if (overrideHref == null) {
return DEFAULT_MANAGED_API_ICON_PREFETCH_HREF;
} else {
return overrideHref;
}
}
public static boolean isManagedApiClasspathContainer(IPath containerPath) {
return containerPath.segment(0).equals(API_CONTAINER_PATH_ID);
}
public static boolean isValidToAddManagedApiProjectState(IProject project) {
try {
if (NatureUtils.hasNature(project, JavaCore.NATURE_ID)) {
boolean isValid = true;
getDefault().extensionsLock.lock();
try {
for (IManagedApiProjectStateTest tester :
getDefault().managedApiProjectStateTests) {
isValid &= tester.isValidToAddManagedApiProjectState(project);
}
} finally {
getDefault().extensionsLock.unlock();
}
return isValid;
}
} catch (CoreException e) {
ManagedApiLogger.info(e,
"Caught core exception while testing project nature for project "
+ project.getProject().getName());
}
return false;
}
private RemoteApiDirectory apiDirectory = new RemoteApiDirectory(
getManagedApiDirectoryHref());
/**
* Access to this array of extensions should be protected by the
* extensionsLock.
*/
private IManagedApiProjectStateTest[] managedApiProjectStateTests = null;
/**
* Access to this array of extensions should be protected by the
* extensionsLock.
*/
private IManagedApiProjectInitializationCallback[]
projectInitializationCallbacks = null;
private ReentrantLock extensionsLock = new ReentrantLock();
private ApiDirectoryFactory apiDirectoryFactory = new ApiDirectoryFactory() {
public ApiDirectory buildApiDirectory() {
return apiDirectory;
}
};
private ManagedApiChecker checker;
private IconCache iconCache = null;
private IRegistryChangeListener registryChangeListener;
public ApiDirectoryFactory getApiDirectoryFactory() {
return apiDirectoryFactory;
}
public IconCache getIconCache() {
return iconCache;
}
public Resources getResources() {
return new PluginResources(getWorkbench().getDisplay());
}
public void setIconCache(IconCache iconCache) {
this.iconCache = iconCache;
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
loadExtensions();
registryChangeListener = new IRegistryChangeListener() {
public void registryChanged(IRegistryChangeEvent event) {
loadExtensions();
}
};
Platform.getExtensionRegistry()
.addRegistryChangeListener(registryChangeListener);
checker = new ManagedApiChecker(apiDirectoryFactory,
CHECK_MANAGED_APIS_FREQ,
"Google Managed APIs Plugin: check APIs for updates", this);
checker.startChecking();
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
if (checker != null) {
checker.stopChecking();
}
if (registryChangeListener != null) {
Platform.getExtensionRegistry()
.removeRegistryChangeListener(registryChangeListener);
}
}
private void loadExtensions() {
ExtensionQuery<IManagedApiProjectStateTest> testExtQuery = new ExtensionQuery<IManagedApiProjectStateTest>(
ManagedApiPlugin.PLUGIN_ID, "managedApiProjectStateTest", "class");
List<ExtensionQuery.Data<IManagedApiProjectStateTest>> testExtensions = testExtQuery.getData();
List<IManagedApiProjectStateTest> tests = new ArrayList<
IManagedApiProjectStateTest>();
for (ExtensionQuery.Data<IManagedApiProjectStateTest> testExtension :
testExtensions) {
if (testExtension.getExtensionPointData() != null) {
tests.add(testExtension.getExtensionPointData());
}
}
ExtensionQuery<IManagedApiProjectInitializationCallback>
projectInitCallbackExtQuery = new ExtensionQuery<
IManagedApiProjectInitializationCallback>(ManagedApiPlugin.PLUGIN_ID,
"managedApiProjectInitializationCallback", "class");
List<ExtensionQuery.Data<IManagedApiProjectInitializationCallback>>
projectInitCallbackExtensions = projectInitCallbackExtQuery.getData();
List<IManagedApiProjectInitializationCallback> initCallbacks = new ArrayList<IManagedApiProjectInitializationCallback>();
for (ExtensionQuery.Data<IManagedApiProjectInitializationCallback>
testCallback : projectInitCallbackExtensions) {
if (testCallback.getExtensionPointData() != null) {
initCallbacks.add(testCallback.getExtensionPointData());
}
}
try {
extensionsLock.lock();
managedApiProjectStateTests = tests.toArray(
new IManagedApiProjectStateTest[tests.size()]);
projectInitializationCallbacks = initCallbacks.toArray(
new IManagedApiProjectInitializationCallback[initCallbacks.size()]);
} finally {
extensionsLock.unlock();
}
}
}
|
plugins/com.google.gdt.eclipse.managedapis/src/com/google/gdt/eclipse/managedapis/ManagedApiPlugin.java
|
/*******************************************************************************
* Copyright 2011 Google Inc. All Rights Reserved.
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.google.gdt.eclipse.managedapis;
import com.google.gdt.eclipse.core.AbstractGooglePlugin;
import com.google.gdt.eclipse.core.extensions.ExtensionQuery;
import com.google.gdt.eclipse.core.extensiontypes.IManagedApiProjectStateTest;
import com.google.gdt.eclipse.core.natures.NatureUtils;
import com.google.gdt.eclipse.managedapis.directory.ApiDirectory;
import com.google.gdt.eclipse.managedapis.directory.ApiDirectoryFactory;
import com.google.gdt.eclipse.managedapis.extensiontypes.IManagedApiProjectInitializationCallback;
import com.google.gdt.eclipse.managedapis.impl.IconCache;
import com.google.gdt.eclipse.managedapis.impl.ManagedApiChecker;
import com.google.gdt.eclipse.managedapis.impl.RemoteApiDirectory;
import com.google.gdt.eclipse.managedapis.platform.PluginResources;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IRegistryChangeEvent;
import org.eclipse.core.runtime.IRegistryChangeListener;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jdt.core.JavaCore;
import org.osgi.framework.BundleContext;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
* Entrypoint for the ManagedApi plugin and container of contants used by the
* plugin as a whole.
*/
public class ManagedApiPlugin extends AbstractGooglePlugin {
public static final boolean SINGLE_CLASSPATH_CONTAINER = false;
public static final String DEPENDENCIES_FOLDER_NAME = "dependencies";
public static final String PLUGIN_ID = "com.google.gdt.eclipse.managedapis";
public static final String API_CONTAINER_PATH_ID = PLUGIN_ID
+ ".MANAGED_API_CONTAINER";
public static final Path API_CONTAINER_PATH = new Path(API_CONTAINER_PATH_ID);
public static final
String COPY_CLASSPATH_ENTRIES_TARGET_PATH_KEY = "COPY_CLASSPATH_ENTRIES_TARGET_PATH";
public static final
String DEFAULT_MANAGED_API_DIRECTORY_HREF = "http://api-directory.googleapis.com/5935";
public static final
String DEFAULT_MANAGED_API_ICON_PREFETCH_HREF = "http://api-directory.googleapis.com/icons";
public static final String ICON_KEY_CLASSPATH_CONTAINER = "x16";
public static final String ICON_KEY_API_IMPORT = "x32";
public static final QualifiedName MANAGED_API_FLAG_QNAME = new QualifiedName(
PLUGIN_ID, "PROJECT_FLAG");
public static final String
MANAGED_API_ROOT_FOLDER_DEFAULT_PATH = ".google_apis";
public static final String SWARM_LIB_FOLDER_NAME = "endpoint-libs";
public static final String
MANAGED_API_ROOT_FOLDER_PATH_KEY = "MANAGED_API_ROOT_FOLDER_PATH";
public static final QualifiedName
MANAGED_API_SESSION_KEY_QNAME = new QualifiedName(
PLUGIN_ID, "MANAGED_API_SESSION_KEY");
// Latest in the 1.14 series
public static final String API_CLIENT_LANG_VERSION = "1.15.x";
public static final long API_DIRECTORY_CACHE_TTL = 4 * 60 * 60 * 1000; // 4HRS
public static final long CHECK_MANAGED_APIS_FREQ = 2 * 60 * 60 * 1000;// 2 HRS
public static final boolean DO_DELETES = false;
private static ManagedApiPlugin plugin;
/**
* Provide access to updated set of initialization callbacks configured for
* this workspace.
*
* @return the callbacks
*/
public static IManagedApiProjectInitializationCallback[] findProjectInitializationCallbacks() {
IManagedApiProjectInitializationCallback[] callbacks;
getDefault().extensionsLock.lock();
try {
callbacks = getDefault().projectInitializationCallbacks;
} finally {
getDefault().extensionsLock.unlock();
}
return callbacks;
}
public static ManagedApiPlugin getDefault() {
return plugin;
}
public static String getManagedApiDirectoryHref() {
String overrideHref = System.getenv("MANAGED_API_DIRECTORY_HREF");
if (overrideHref == null) {
return DEFAULT_MANAGED_API_DIRECTORY_HREF;
} else {
return overrideHref;
}
}
public static String getManagedApiIconBundleHref() {
String overrideHref = System.getenv("MANAGED_API_ICON_PREFETCH_HREF");
if (overrideHref == null) {
return DEFAULT_MANAGED_API_ICON_PREFETCH_HREF;
} else {
return overrideHref;
}
}
public static boolean isManagedApiClasspathContainer(IPath containerPath) {
return containerPath.segment(0).equals(API_CONTAINER_PATH_ID);
}
public static boolean isValidToAddManagedApiProjectState(IProject project) {
try {
if (NatureUtils.hasNature(project, JavaCore.NATURE_ID)) {
boolean isValid = true;
getDefault().extensionsLock.lock();
try {
for (IManagedApiProjectStateTest tester :
getDefault().managedApiProjectStateTests) {
isValid &= tester.isValidToAddManagedApiProjectState(project);
}
} finally {
getDefault().extensionsLock.unlock();
}
return isValid;
}
} catch (CoreException e) {
ManagedApiLogger.info(e,
"Caught core exception while testing project nature for project "
+ project.getProject().getName());
}
return false;
}
private RemoteApiDirectory apiDirectory = new RemoteApiDirectory(
getManagedApiDirectoryHref());
/**
* Access to this array of extensions should be protected by the
* extensionsLock.
*/
private IManagedApiProjectStateTest[] managedApiProjectStateTests = null;
/**
* Access to this array of extensions should be protected by the
* extensionsLock.
*/
private IManagedApiProjectInitializationCallback[]
projectInitializationCallbacks = null;
private ReentrantLock extensionsLock = new ReentrantLock();
private ApiDirectoryFactory apiDirectoryFactory = new ApiDirectoryFactory() {
public ApiDirectory buildApiDirectory() {
return apiDirectory;
}
};
private ManagedApiChecker checker;
private IconCache iconCache = null;
private IRegistryChangeListener registryChangeListener;
public ApiDirectoryFactory getApiDirectoryFactory() {
return apiDirectoryFactory;
}
public IconCache getIconCache() {
return iconCache;
}
public Resources getResources() {
return new PluginResources(getWorkbench().getDisplay());
}
public void setIconCache(IconCache iconCache) {
this.iconCache = iconCache;
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
loadExtensions();
registryChangeListener = new IRegistryChangeListener() {
public void registryChanged(IRegistryChangeEvent event) {
loadExtensions();
}
};
Platform.getExtensionRegistry()
.addRegistryChangeListener(registryChangeListener);
checker = new ManagedApiChecker(apiDirectoryFactory,
CHECK_MANAGED_APIS_FREQ,
"Google Managed APIs Plugin: check APIs for updates", this);
checker.startChecking();
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
if (checker != null) {
checker.stopChecking();
}
if (registryChangeListener != null) {
Platform.getExtensionRegistry()
.removeRegistryChangeListener(registryChangeListener);
}
}
private void loadExtensions() {
ExtensionQuery<IManagedApiProjectStateTest> testExtQuery = new ExtensionQuery<IManagedApiProjectStateTest>(
ManagedApiPlugin.PLUGIN_ID, "managedApiProjectStateTest", "class");
List<ExtensionQuery.Data<IManagedApiProjectStateTest>> testExtensions = testExtQuery.getData();
List<IManagedApiProjectStateTest> tests = new ArrayList<
IManagedApiProjectStateTest>();
for (ExtensionQuery.Data<IManagedApiProjectStateTest> testExtension :
testExtensions) {
if (testExtension.getExtensionPointData() != null) {
tests.add(testExtension.getExtensionPointData());
}
}
ExtensionQuery<IManagedApiProjectInitializationCallback>
projectInitCallbackExtQuery = new ExtensionQuery<
IManagedApiProjectInitializationCallback>(ManagedApiPlugin.PLUGIN_ID,
"managedApiProjectInitializationCallback", "class");
List<ExtensionQuery.Data<IManagedApiProjectInitializationCallback>>
projectInitCallbackExtensions = projectInitCallbackExtQuery.getData();
List<IManagedApiProjectInitializationCallback> initCallbacks = new ArrayList<IManagedApiProjectInitializationCallback>();
for (ExtensionQuery.Data<IManagedApiProjectInitializationCallback>
testCallback : projectInitCallbackExtensions) {
if (testCallback.getExtensionPointData() != null) {
initCallbacks.add(testCallback.getExtensionPointData());
}
}
try {
extensionsLock.lock();
managedApiProjectStateTests = tests.toArray(
new IManagedApiProjectStateTest[tests.size()]);
projectInitializationCallbacks = initCallbacks.toArray(
new IManagedApiProjectInitializationCallback[initCallbacks.size()]);
} finally {
extensionsLock.unlock();
}
}
}
|
Update client library version to 1.16.x.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=51775388
|
plugins/com.google.gdt.eclipse.managedapis/src/com/google/gdt/eclipse/managedapis/ManagedApiPlugin.java
|
Update client library version to 1.16.x. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=51775388
|
|
Java
|
epl-1.0
|
c7c8e2afd7290b446dbb0fc48d1067eadffe5207
| 0
|
oehme/sobula,kuniss/sobula
|
package com.github.oehme.sobula;
import java.util.regex.Pattern;
public enum License {
EPL_V1_0(
"EPL-1.0",
"Eclipse Public License, Version 1.0",
"https://www.eclipse.org/legal/epl-v10.html",
"Eclipse Public License\\s+-\\s+v 1.0"
),
MIT(
"MIT",
"The MIT License",
"http://opensource.org/licenses/MIT",
Pattern.quote(
"Permission is hereby granted, free of charge, to any person obtaining a copy\n" +
"of this software and associated documentation files (the \"Software\"), to deal\n" +
"in the Software without restriction, including without limitation the rights\n" +
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +
"copies of the Software, and to permit persons to whom the Software is\n" +
"furnished to do so, subject to the following conditions:\n" +
"\n\n" +
"The above copyright notice and this permission notice shall be included in\n" +
"all copies or substantial portions of the Software.\n" +
"\n\n" +
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" +
"THE SOFTWARE.")
),
APACHE_V2_0(
"Apache-2.0",
"Apache License, Version 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
"Apache License\\s+Version 2.0, January 2004"
),
GPL_V2_0(
"GPL-2.0",
"GNU General Public License Version 2, June 1991",
"http://www.gnu.org/licenses/gpl-2.0",
"GNU GENERAL PUBLIC LICENSE\\s+Version 2, June 1991"
),
LGPL_V2_1(
"LGPL-2.1",
"GNU Lesser General Public License Version 2.1, February 1999",
"http://www.gnu.org/licenses/lgpl-2.1",
"GNU LESSER GENERAL PUBLIC LICENSE\\s+Version 2.1, February 1999"
),
GPL_V3_0(
"GPL-3.0",
"GNU General Public License Version 3, 29 June 2007",
"http://www.gnu.org/licenses/gpl-3.0",
"GNU GENERAL PUBLIC LICENSE\\s+Version 3, 29 June 2007"
),
LGPL_V3_0(
"LGPL-3.0",
"GNU Lesser General Public License Version 3, 29 June 2007",
"http://www.gnu.org/licenses/lgpl-3.0",
"GNU LESSER GENERAL PUBLIC LICENSE\\s+Version 3, 29 June 2007"
),
AGPL_V3_0(
"AGPL-3.0",
"GNU Affero General Public License Version 3, 19 November 2007",
"http://www.gnu.org/licenses/agpl-3.0.html",
"GNU AFFERO GENERAL PUBLIC LICENSE\\s+Version 3, 19 November 2007"
),
CPL_V1_0(
"CPL-1.0",
"Common Public License (CPL) -- V1.0",
"http://www.ibm.com/developerworks/library/os-cpl.html",
"Common Public License\\s+(\\(CPL\\)\\s+)?(--\\s+)?V1.0"
);
private String id;
private String longName;
private String url;
private String[] recognitionPatterns;
public String getId() {
return id;
}
public String getLongName() {
return longName;
}
public String getUrl() {
return url;
}
public boolean matches(String licenseText) {
if (licenseText.contains(longName))
return true;
licenseText = normalizeEOL(licenseText);
for (String recognitionPattern : recognitionPatterns) {
Pattern pattern = Pattern.compile(recognitionPattern);
if (pattern.matcher(licenseText).find())
return true;
}
return false;
}
/**
* Normalizes Windows and Mac EOL to Linux EOL.
* @param originalText the original text
* @return the normalized text
*/
private String normalizeEOL(String originalText) {
// for Windows
String result = originalText.replaceAll("\\r\\n", "\n");
// for Mac
return result.replaceAll("\\r", "\n");
}
private License(String id, String longName, String url, String... recognitionPatterns) {
this.id = id;
this.longName = longName;
this.url = url;
this.recognitionPatterns = recognitionPatterns;
}
}
|
src/main/java/com/github/oehme/sobula/License.java
|
package com.github.oehme.sobula;
import java.util.regex.Pattern;
public enum License {
EPL_V1_0(
"EPL-1.0",
"Eclipse Public License, Version 1.0",
"https://www.eclipse.org/legal/epl-v10.html",
"Eclipse Public License\\s+-\\s+v 1.0"
),
MIT(
"MIT",
"The MIT License",
"http://opensource.org/licenses/MIT",
Pattern.quote(
"Permission is hereby granted, free of charge, to any person obtaining a copy\n" +
"of this software and associated documentation files (the \"Software\"), to deal\n" +
"in the Software without restriction, including without limitation the rights\n" +
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" +
"copies of the Software, and to permit persons to whom the Software is\n" +
"furnished to do so, subject to the following conditions:\n" +
"\n\n" +
"The above copyright notice and this permission notice shall be included in\n" +
"all copies or substantial portions of the Software.\n" +
"\n\n" +
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" +
"THE SOFTWARE.")
),
APACHE_V2_0(
"Apache-2.0",
"Apache License, Version 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
"Apache License\\s+Version 2.0, January 2004"
),
GPL_V2_0(
"GPL-2.0",
"GNU General Public License Version 2, June 1991",
"http://www.gnu.org/licenses/gpl-2.0",
"GNU GENERAL PUBLIC LICENSE\\s+Version 2, June 1991"
),
LGPL_V2_1(
"LGPL-2.1",
"GNU Lesser General Public License Version 2.1, February 1999",
"http://www.gnu.org/licenses/lgpl-2.1",
"GNU LESSER GENERAL PUBLIC LICENSE\\s+Version 2.1, February 1999"
),
GPL_V3_0(
"GPL-3.0",
"GNU General Public License Version 3, 29 June 2007",
"http://www.gnu.org/licenses/gpl-3.0",
"GNU GENERAL PUBLIC LICENSE\\s+Version 3, 29 June 2007"
),
LGPL_V3_0(
"LGPL-3.0",
"GNU Lesser General Public License Version 3, 29 June 2007",
"http://www.gnu.org/licenses/lgpl-3.0",
"GNU LESSER GENERAL PUBLIC LICENSE\\s+Version 3, 29 June 2007"
),
AGPL_V3_0(
"AGPL-3.0",
"GNU Affero General Public License Version 3, 19 November 2007",
"http://www.gnu.org/licenses/agpl-3.0.html",
"GNU AFFERO GENERAL PUBLIC LICENSE\\s+Version 3, 19 November 2007"
),
CPL_V1_0(
"CPL-1.0",
"Common Public License (CPL) -- V1.0",
"http://www.ibm.com/developerworks/library/os-cpl.html",
"Common Public License\\s+(\\(CPL\\)\\s+)?(--\\s+)?V1.0"
);
private String id;
private String longName;
private String url;
private String[] recognitionPatterns;
public String getId() {
return id;
}
public String getLongName() {
return longName;
}
public String getUrl() {
return url;
}
public boolean matches(String licenseText) {
if (licenseText.contains(longName))
return true;
for (String recognitionPattern : recognitionPatterns) {
Pattern pattern = Pattern.compile(recognitionPattern);
if (pattern.matcher(licenseText).find())
return true;
}
return false;
}
private License(String id, String longName, String url, String... recognitionPatterns) {
this.id = id;
this.longName = longName;
this.url = url;
this.recognitionPatterns = recognitionPatterns;
}
}
|
added EOL normalization for license texts
as a tests failed after having run first time on Windows - EOL in
license texts did not match the Linux like EOLs in the matching pattern
|
src/main/java/com/github/oehme/sobula/License.java
|
added EOL normalization for license texts
|
|
Java
|
mpl-2.0
|
60ec5a4b5d36ba609862ffbb604b7056ca5e2c5d
| 0
|
ajschult/etomica,etomica/etomica,ajschult/etomica,etomica/etomica,etomica/etomica,ajschult/etomica
|
package etomica.atom.iterator;
import etomica.action.AtomsetAction;
import etomica.atom.Atom;
import etomica.atom.AtomArrayList;
import etomica.atom.AtomList;
import etomica.atom.AtomSet;
import etomica.atom.AtomToArrayList;
import etomica.atom.AtomToIndex;
import etomica.atom.AtomToIndexOrdinal;
import etomica.atom.AtomToParentChildList;
import etomica.atom.iterator.IteratorDirective.Direction;
/**
* Returns one or both of the atoms adjacent to a specified atom in
* its sequence list (i.e., the AtomList containing its seq linker).
* If adjacent linker has no atom (is a tab or header) no corresponding
* atom is given as an iterate; thus iterator may give 0, 1, or 2 iterates
* depending on presence of adjacent atoms and specification of iteration
* direction.
*/
public class AtomIteratorArrayListAdjacent implements AtomIteratorAtomDependent, java.io.Serializable {
/**
* Constructor gives iterator not ready for iteration. Must
* set an atom and reset before using. Default direction is
* null, meaning that both adjacent atoms (if there are two)
* will be given by iterator.
*/
public AtomIteratorArrayListAdjacent(IteratorDirective.Direction direction) {
this(direction,new AtomToIndexOrdinal(), new AtomToParentChildList());
}
public AtomIteratorArrayListAdjacent(IteratorDirective.Direction direction,
AtomToIndex atomToIndex, AtomToArrayList atomToArrayList) {
super();
this.direction = direction;
this.atomToIndex = atomToIndex;
this.atomToArrayList = atomToArrayList;
unset();
}
/**
* Returns true if the given AtomSet has count == 1 and
* its atom is one of the iterates for the current condition
* of the iterator (independent of hasNext status).
*/
public boolean contains(AtomSet atom) {
if(atom == null || atom.count() != 1) return false;
Atom testAtom = atom.getAtom(0);
if(testAtom == null) return false;
if(direction != IteratorDirective.DOWN && firstCursor < list.size()-1 && list.get(firstCursor+1) == testAtom) {
return true;
}
if(direction != IteratorDirective.UP && firstCursor > 0 && list.get(firstCursor-1) == testAtom) {
return true;
}
return false;
}
/**
* Returns the number of iterates that iterator would give
* if reset and iterated in its current condition. Does not
* depend on or affect iteration state.
*/
public int size() {
int size = 0;
if(direction != IteratorDirective.DOWN && (firstCursor < list.size()-1)) {
size++;
}
if(direction != IteratorDirective.UP && (firstCursor > 0)) {
size++;
}
return size;
}
/**
* Performs action on all iterates for current condition of iterator.
*/
public void allAtoms(AtomsetAction action) {
if(direction != IteratorDirective.DOWN) {
if (firstCursor < list.size()-1) {
action.actionPerformed(list.get(firstCursor+1));
}
}
if (direction != IteratorDirective.UP) {
if (firstCursor > 0) {
action.actionPerformed(list.get(firstCursor-1));
}
}
}
/**
* Returns true if another iterate is forthcoming, false otherwise.
*/
public boolean hasNext() {
return hasNext;
}
/**
* Returns 1, indicating that this is an atom AtomSet iterator.
*/
public int nBody() {
return 1;
}
/**
* Same as nextAtom.
*/
public AtomSet next() {
return nextAtom();
}
/**
* Returns the next iterator, or null if hasNext is false.
*/
public Atom nextAtom() {
if (!hasNext) {
return null;
}
if(upListNow) {
upListNow = false;
if (direction == IteratorDirective.UP || firstCursor == 0) {
hasNext = false;
}
return list.get(firstCursor+1);
}
hasNext = false;
return list.get(firstCursor-1);
}
/**
* Returns the next iterate without advancing the iterator.
*/
public AtomSet peek() {
if (!hasNext) {
return null;
}
if(upListNow) {
return list.get(firstCursor+1);
}
return list.get(firstCursor-1);
}
/**
* Readies the iterator to begin iteration.
*/
public void reset() {
upListNow = false;
hasNext = true;
if ((direction != IteratorDirective.DOWN) && (firstCursor < list.size()-1)) {
upListNow = true;
return;
}
if ((direction != IteratorDirective.UP) && (firstCursor > 0)) {
return;
}
hasNext = false;
}
/**
* Puts iterator in a state where hasNext is false.
*/
public void unset() {
hasNext = false;
}
/**
* Sets the first atom for iteration. Iteration proceeds from this atom up
* and/or down the list, depending on how iterator was configured at
* construction.
*/
public void setAtom(Atom atom) {
list = atomToArrayList.getArrayList(atom);
firstCursor = atomToIndex.getIndex(atom);
}
private int firstCursor;
private final Direction direction;
private boolean upListNow;
private AtomArrayList list;
private boolean hasNext;
private final AtomToIndex atomToIndex;
private final AtomToArrayList atomToArrayList;
}
|
etomica/atom/iterator/AtomIteratorArrayListAdjacent.java
|
package etomica.atom.iterator;
import etomica.action.AtomsetAction;
import etomica.atom.Atom;
import etomica.atom.AtomLinker;
import etomica.atom.AtomList;
import etomica.atom.AtomSet;
import etomica.atom.iterator.IteratorDirective.Direction;
/**
* Returns one or both of the atoms adjacent to a specified atom in
* its sequence list (i.e., the AtomList containing its seq linker).
* If adjacent linker has no atom (is a tab or header) no corresponding
* atom is given as an iterate; thus iterator may give 0, 1, or 2 iterates
* depending on presence of adjacent atoms and specification of iteration
* direction.
*/
public class AtomIteratorArrayListAdjacent implements AtomIteratorAtomDependent, java.io.Serializable {
/**
* Constructor gives iterator not ready for iteration. Must
* set an atom and reset before using. Default direction is
* null, meaning that both adjacent atoms (if there are two)
* will be given by iterator.
*/
public AtomIteratorArrayListAdjacent(IteratorDirective.Direction direction) {
super();
this.direction = direction;
setAtom(null);
unset();
}
/**
* Returns true if the given AtomSet has count == 1 and
* its atom is one of the iterates for the current condition
* of the iterator (independent of hasNext status).
*/
public boolean contains(AtomSet atom) {
if(atom == null || atom.count() != 1) return false;
Atom testAtom = atom.getAtom(0);
if(testAtom == null) return false;
if(direction == IteratorDirective.UP && (atomSeq.next.atom == testAtom)) {
return true;
}
if(direction == IteratorDirective.DOWN && (atomSeq.previous.atom == testAtom)) {
return true;
}
return false;
}
/**
* Returns the number of iterates that iterator would give
* if reset and iterated in its current condition. Does not
* depend on or affect iteration state.
*/
public int size() {
if(direction == IteratorDirective.UP && (atomSeq.next.atom != null)) {
return 1;
}
if(direction == IteratorDirective.DOWN && (atomSeq.previous.atom != null)) {
return 1;
}
return 0;
}
/**
* Performs action on all iterates for current condition of iterator.
*/
public void allAtoms(AtomsetAction action) {
if(direction == IteratorDirective.UP) {
Atom atom = atomSeq.next.atom;
if(atom != null) action.actionPerformed(atom);
}
else {
Atom atom = atomSeq.previous.atom;
if(atom != null) action.actionPerformed(atom);
}
}
/**
* Returns true if another iterate is forthcoming, false otherwise.
*/
public boolean hasNext() {
return hasNext;
}
/**
* Returns 1, indicating that this is an atom AtomSet iterator.
*/
public int nBody() {
return 1;
}
/**
* Same as nextAtom.
*/
public AtomSet next() {
return nextAtom();
}
/**
* Returns the next iterator, or null if hasNext is false.
*/
public Atom nextAtom() {
if (!hasNext) {
return null;
}
hasNext = false;
if(direction == IteratorDirective.UP) {
return atomSeq.next.atom;
}
return atomSeq.previous.atom;
}
/**
* Returns the next iterate without advancing the iterator.
*/
public AtomSet peek() {
if (!hasNext) {
return null;
}
if(direction == IteratorDirective.UP) {
return atomSeq.next.atom;
}
return atomSeq.previous.atom;
}
/**
* Readies the iterator to begin iteration.
*/
public void reset() {
hasNext = ((direction != IteratorDirective.DOWN) && (atomSeq.next.atom != null)) ||
((direction != IteratorDirective.UP) && (atomSeq.previous.atom != null));
}
/**
* Puts iterator in a state where hasNext is false.
*/
public void unset() {
hasNext = false;
}
/**
* Sets the central atom. Iterates will be those atoms (if not null) at
* atom.seq.next.atom and atom.seq.previous.atom, as indicated
* by the direction field.
*/
public void setAtom(Atom atom) {
atomSeq = (atom != null) ? atom.seq : emptyList.header;
}
private AtomLinker atomSeq;
private final Direction direction;
private final AtomList emptyList = new AtomList();
private boolean hasNext;
}
|
actually implement this class
|
etomica/atom/iterator/AtomIteratorArrayListAdjacent.java
|
actually implement this class
|
|
Java
|
mpl-2.0
|
72757ceb128df82b1db49028b46592b9662bc2cb
| 0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
/*************************************************************************
*
* $RCSfile: SystemProxySettings.java,v $
*
* $Revision: 1.2 $
*
* last change:$Date: 2003-05-27 12:57:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package mod._proxyset;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import java.util.Hashtable;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
/**
* Test for object which is represented by service
* <code>com.sun.star.system.SystemProxySettings</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::lang::XServiceInfo</code></li>
* <li> <code>com::sun::star::system::XProxySettings</code></li>
* <li> <code>com::sun::star::lang::XTypeProvider</code></li>
* </ul> <p>
*
* This object test <b> is NOT </b> designed to be run in several
* threads concurently.
*
* @see com.sun.star.lang.XServiceInfo
* @see com.sun.star.system.XProxySettings
* @see com.sun.star.lang.XTypeProvider
* @see ifc.lang._XServiceInfo
* @see ifc.system._XProxySettings
* @see ifc.lang._XTypeProvider
*/
public class SystemProxySettings extends TestCase {
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of
* <code>com.sun.star.system.SystemProxySettings</code>,for testing.
*
* Object relations created :
* <ul>
* <li> <code>'XProxySettings.proxySettings'</code> for
* {@link ifc.system._XProxySettings} : </li>
* <p>It passes a Hashtable with expected proxy settings as object
* relation "XProxySettings.proxySettings", to verify results. The expected
* settings are taken from parameters. The following parameters are recognized:
* <ul>
* <li>test.proxy.soffice52.ftpProxyAddress</li>
* <li>test.proxy.soffice52.ftpProxyPort</li>
* <li>test.proxy.soffice52.gopherProxyAddress</li>
* <li>test.proxy.soffice52.gopherProxyPort</li>
* <li>test.proxy.soffice52.httpProxyAddress</li>
* <li>test.proxy.soffice52.httpProxyPort</li>
* <li>test.proxy.soffice52.httpsProxyAddress</li>
* <li>test.proxy.soffice52.httpsProxyPort</li>
* <li>test.proxy.soffice52.socksProxyAddress</li>
* <li>test.proxy.soffice52.socksProxyPort</li>
* <li>test.proxy.soffice52.proxyBypassAddress</li>
* <li>test.proxy.soffice52.proxyEnabled</li>
* </ul>.
* </ul>
*/
protected TestEnvironment createTestEnvironment
(TestParameters tParam, PrintWriter log) {
XInterface oObj = null;
Object oInterface = null;
try {
XMultiServiceFactory xMSF = (XMultiServiceFactory)tParam.getMSF();
oInterface = xMSF.createInstance
( "com.sun.star.system.SystemProxySettings" );
}
catch( com.sun.star.uno.Exception e ) {
log.println("Service not available" );
}
oObj = (XInterface) oInterface;
log.println( " creating a new environment for object" );
TestEnvironment tEnv = new TestEnvironment( oObj );
// extracting parameters to proxy settings
Hashtable proxySettings = new Hashtable(12);
String prefix = "test.proxy.system.";
final String[] names = {
"ftpProxyAddress",
"ftpProxyPort",
"gopherProxyAddress",
"gopherProxyPort",
"httpProxyAddress",
"httpProxyPort",
"httpsProxyAddress",
"httpsProxyPort",
"socksProxyAddress",
"socksProxyPort",
"proxyBypassAddress",
"proxyEnabled"
};
for (int i = 0; i < names.length; i++) {
String name = prefix + names[i];
String value = (String) tParam.get(name);
if (value == null) {
value = "";
}
proxySettings.put(names[i], value);
}
tEnv.addObjRelation("XProxySettings.proxySettings", proxySettings);
return tEnv;
}
}
|
qadevOOo/tests/java/mod/_proxyset/SystemProxySettings.java
|
/*************************************************************************
*
* $RCSfile: SystemProxySettings.java,v $
*
* $Revision: 1.1 $
*
* last change:$Date: 2003-01-27 18:16:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
package mod._proxyset;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import java.util.Hashtable;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
/**
* Test for object which is represented by service
* <code>com.sun.star.system.SystemProxySettings</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::lang::XServiceInfo</code></li>
* <li> <code>com::sun::star::system::XProxySettings</code></li>
* <li> <code>com::sun::star::lang::XTypeProvider</code></li>
* </ul> <p>
*
* This object test <b> is NOT </b> designed to be run in several
* threads concurently.
*
* @see com.sun.star.lang.XServiceInfo
* @see com.sun.star.system.XProxySettings
* @see com.sun.star.lang.XTypeProvider
* @see ifc.lang._XServiceInfo
* @see ifc.system._XProxySettings
* @see ifc.lang._XTypeProvider
*/
public class SystemProxySettings extends TestCase {
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of
* <code>com.sun.star.system.SystemProxySettings</code>,for testing.
*
* Object relations created :
* <ul>
* <li> <code>'XProxySettings.proxySettings'</code> for
* {@link ifc.system._XProxySettings} : </li>
* <p>It passes a Hashtable with expected proxy settings as object
* relation "XProxySettings.proxySettings", to verify results. The expected
* settings are taken from parameters. The following parameters are recognized:
* <ul>
* <li>test.proxy.soffice52.ftpProxyAddress</li>
* <li>test.proxy.soffice52.ftpProxyPort</li>
* <li>test.proxy.soffice52.gopherProxyAddress</li>
* <li>test.proxy.soffice52.gopherProxyPort</li>
* <li>test.proxy.soffice52.httpProxyAddress</li>
* <li>test.proxy.soffice52.httpProxyPort</li>
* <li>test.proxy.soffice52.httpsProxyAddress</li>
* <li>test.proxy.soffice52.httpsProxyPort</li>
* <li>test.proxy.soffice52.socksProxyAddress</li>
* <li>test.proxy.soffice52.socksProxyPort</li>
* <li>test.proxy.soffice52.proxyBypassAddress</li>
* <li>test.proxy.soffice52.proxyEnabled</li>
* </ul>.
* </ul>
*/
protected TestEnvironment createTestEnvironment
(TestParameters tParam, PrintWriter log) {
XInterface oObj = null;
Object oInterface = null;
try {
XMultiServiceFactory xMSF = tParam.getMSF();
oInterface = xMSF.createInstance
( "com.sun.star.system.SystemProxySettings" );
}
catch( com.sun.star.uno.Exception e ) {
log.println("Service not available" );
}
oObj = (XInterface) oInterface;
log.println( " creating a new environment for object" );
TestEnvironment tEnv = new TestEnvironment( oObj );
// extracting parameters to proxy settings
Hashtable proxySettings = new Hashtable(12);
String prefix = "test.proxy.system.";
final String[] names = {
"ftpProxyAddress",
"ftpProxyPort",
"gopherProxyAddress",
"gopherProxyPort",
"httpProxyAddress",
"httpProxyPort",
"httpsProxyAddress",
"httpsProxyPort",
"socksProxyAddress",
"socksProxyPort",
"proxyBypassAddress",
"proxyEnabled"
};
for (int i = 0; i < names.length; i++) {
String name = prefix + names[i];
String value = (String) tParam.get(name);
if (value == null) {
value = "";
}
proxySettings.put(names[i], value);
}
tEnv.addObjRelation("XProxySettings.proxySettings", proxySettings);
return tEnv;
}
}
|
INTEGRATION: CWS qadev6 (1.1.8); FILE MERGED
2003/05/21 10:56:34 sg 1.1.8.1: #109819# prepare devide of runner
|
qadevOOo/tests/java/mod/_proxyset/SystemProxySettings.java
|
INTEGRATION: CWS qadev6 (1.1.8); FILE MERGED 2003/05/21 10:56:34 sg 1.1.8.1: #109819# prepare devide of runner
|
|
Java
|
agpl-3.0
|
757a030a065ce46e31e114cb988f0eb3419b0995
| 0
|
duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot,duncte123/SkyBot
|
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot;
import ml.duncte123.skybot.commands.essentials.eval.EvalCommand;
import ml.duncte123.skybot.objects.guild.GuildSettings;
import ml.duncte123.skybot.parsers.CommandParser;
import ml.duncte123.skybot.utils.*;
import net.dv8tion.jda.bot.sharding.ShardManager;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.WebSocketCode;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ShutdownEvent;
import net.dv8tion.jda.core.events.guild.GuildJoinEvent;
import net.dv8tion.jda.core.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.managers.Presence;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONObject;
import org.slf4j.event.Level;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class BotListener extends ListenerAdapter {
/**
* This is the command parser
*/
private static CommandParser parser = new CommandParser();
/**
* This filter helps us to fiter out swearing
*/
private BadWordFilter filter = new BadWordFilter();
/**
* When a command gets ran, it'll be stored in here
*/
private static Map<Guild, TextChannel> lastGuildChannel = new HashMap<>();
/**
* This timer is for checking unbans
*/
public Timer unbanTimer = new Timer();
/**
* This tells us if the {@link #unbanTimer unbanTimer} is running
*/
public boolean unbanTimerRunning = false;
/**
* This timer is for checking new quotes
*/
public Timer settingsUpdateTimer = new Timer();
/**
* This tells us if the {@link #settingsUpdateTimer settingsUpdateTimer} is running
*/
public boolean settingsUpdateTimerRunning = false;
/**
* Listen for messages send to the bot
* @param event The corresponding {@link net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent GuildMessageReceivedEvent}
*/
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event){
//We only want to respond to members/users
if(event.getAuthor().isFake() || event.getAuthor().isBot() || event.getMember()==null){
return;
}
GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
if(event.getMessage().getContent().equals(Settings.prefix + "shutdown") && Arrays.asList(Settings.wbkxwkZPaG4ni5lm8laY).contains(event.getAuthor().getId()) ){
AirUtils.log(Level.INFO,"Initialising shutdown!!!");
ShardManager manager = event.getJDA().asBot().getShardManager();
for(JDA shard : manager.getShards()) {
AirUtils.log(Level.INFO,"Shard " + shard.getShardInfo().getShardId() + " has been shut down");
shard.shutdown();
}
System.exit(0);
return;
}
Permission[] adminPerms = {
Permission.MESSAGE_MANAGE
};
if(event.getGuild().getSelfMember().hasPermission(adminPerms) && AirUtils.guildSettings.get(event.getGuild().getId()).isEnableSwearFilter()) {
if (!event.getMember().hasPermission(adminPerms)) {
Message messageToCheck = event.getMessage();
if (filter.filterText(messageToCheck.getRawContent())) {
messageToCheck.delete().reason("Blocked for bad swearing: " + messageToCheck.getContent()).queue();
event.getChannel().sendMessage("Hello there, " + event.getAuthor().getAsMention() + " please do not use cursive language within this Discord.").queue(
m -> m.delete().queueAfter(10, TimeUnit.SECONDS));
return;
}
}
}
//If the topic contains -commands ignore it
if(event.getChannel().getTopic().contains("-commands")) {
return;
}
if(!event.getMessage().getRawContent().startsWith(Settings.prefix) && !event.getMessage().getRawContent().startsWith(settings.getCustomPrefix())){
return;
} else if(event.getMessage().getMentionedUsers().contains(event.getJDA().getSelfUser()) && event.getChannel().canTalk()) {
if (!event.getMessage().getRawContent().startsWith(event.getJDA().getSelfUser().getAsMention())) {
event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, try `" + Settings.prefix + "help` for a list of commands. If it doesn't work scream at _duncte123#1245_").queue();
return;
}
}
// run the a command
lastGuildChannel.put(event.getGuild(), event.getChannel());
String rw = event.getMessage().getRawContent();
if(!Settings.prefix.equals(settings.getCustomPrefix())) {
rw = rw.replaceFirst(
Pattern.quote(settings.getCustomPrefix()),
Settings.prefix);
}
AirUtils.commandManager.runCommand(parser.parse(rw.replaceFirst("<@" + event.getJDA().getSelfUser().getId() + "> ", Settings.prefix)
,
event
));
}
/**
* When the bot is ready to go
* @param event The corresponding {@link net.dv8tion.jda.core.events.ReadyEvent ReadyEvent}
*/
@Override
public void onReady(ReadyEvent event){
setWatchingStatus(event.getJDA());
AirUtils.log(Level.INFO, "Logged in as " + String.format("%#s", event.getJDA().getSelfUser()) + " (Shard #" + event.getJDA().getShardInfo().getShardId() + ")");
AirUtils.spoopyScaryVariable = event.getJDA().getSelfUser().getId().equals(
new String(Settings.iyqrektunkyhuwul3dx0b[0]))
| event.getJDA().getSelfUser().getId().equals(
new String(Settings.iyqrektunkyhuwul3dx0b[1]));
//Start the timers if they have not been started yet
if(!unbanTimerRunning && AirUtils.nonsqlite) {
AirUtils.log(Level.INFO, "Starting the unban timer.");
//Register the timer for the auto unbans
//I moved the timer here to make sure that every running jar has this only once
TimerTask unbanTask = new TimerTask() {
@Override
public void run() {
AirUtils.checkUnbans(event.getJDA().asBot().getShardManager());
}
};
unbanTimer.schedule(unbanTask, DateUtils.MILLIS_PER_MINUTE * 10, DateUtils.MILLIS_PER_MINUTE * 10);
unbanTimerRunning = true;
}
if(!settingsUpdateTimerRunning && AirUtils.nonsqlite) {
AirUtils.log(Level.INFO, "Starting the settings timer.");
//This handles the updating from the setting and quotes
TimerTask settingsTask = new TimerTask() {
@Override
public void run() {
GuildSettingsUtils.loadAllSettings();
}
};
settingsUpdateTimer.schedule(settingsTask, DateUtils.MILLIS_PER_HOUR, DateUtils.MILLIS_PER_HOUR);
settingsUpdateTimerRunning = true;
}
}
@Override
public void onShutdown(ShutdownEvent event) {
((EvalCommand) AirUtils.commandManager.getCommand("eval")).shutdown();
if(unbanTimerRunning) {
this.unbanTimer.cancel();
this.unbanTimer.purge();
}
if(settingsUpdateTimerRunning) {
this.settingsUpdateTimer.cancel();
this.settingsUpdateTimer.purge();
}
}
/**
* This will fire when a new member joins
* @param event The corresponding {@link net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent GuildMemberJoinEvent}
*/
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event){
/*
{{USER_MENTION}} = mention user
{{USER_NAME}} = return username
{{GUILD_NAME}} = the name of the guild
{{GUILD_USER_COUNT}} = member count
{{GUILD_OWNER_MENTION}} = mention the guild owner
{{GUILD_OWNER_NAME}} = return the name form the owner
*/
GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
if (settings.isEnableJoinMessage()) {
TextChannel publicChannel = AirUtils.getPublicChannel(event.getGuild());
String msg = settings.getCustomJoinMessage()
.replaceAll("\\{\\{USER_MENTION}}", event.getUser().getAsMention())
.replaceAll("\\{\\{USER_NAME}}", event.getUser().getName())
.replaceAll("\\{\\{GUILD_NAME}}", event.getGuild().getName())
.replaceAll("\\{\\{GUILD_USER_COUNT}}", event.getGuild().getMemberCache().size() + "");
publicChannel.sendMessage(msg).queue();
}
}
/**
* This will fire when the bot joins a guild and we check if we are allowed to join this guild
* @param event The corresponding {@link net.dv8tion.jda.core.events.guild.GuildJoinEvent GuildJoinEvent}
*/
@Override
public void onGuildJoin(GuildJoinEvent event) {
//if 60 of a guild is bots, we'll leave it
double[] botToUserRatio = AirUtils.getBotRatio(event.getGuild());
if(botToUserRatio[1] > 60) {
AirUtils.getPublicChannel(event.getGuild()).sendMessage("Hey " +
event.getGuild().getOwner().getAsMention() + ", "+botToUserRatio[1]+"% of this guild are bots ("+event.getGuild().getMemberCache().size()+" is the total btw). " +
"I'm outta here").queue(
message -> message.getGuild().leave().queue()
);
AirUtils.log(Settings.defaultName + "GuildJoin", Level.INFO, "Joining guild: " + event.getGuild().getName() + ", and leaving it after. BOT ALERT");
return;
}
AirUtils.log(Settings.defaultName + "GuildJoin", Level.INFO, "Joining guild: " + event.getGuild().getName() + ".");
GuildSettingsUtils.registerNewGuild(event.getGuild());
AirUtils.updateGuildCount(event.getJDA(), event.getJDA().asBot().getShardManager().getGuildCache().size());
}
@Override
public void onGuildLeave(GuildLeaveEvent event) {
GuildSettingsUtils.deleteGuild(event.getGuild());
AirUtils.updateGuildCount(event.getJDA(), event.getJDA().asBot().getShardManager().getGuildCache().size());
}
/**
* This will fire when a member leaves a channel in a guild, we check if the channel is empty and if it is we leave it
* @param event {@link net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent GuildVoiceLeaveEvent}
*/
@Override
public void onGuildVoiceLeave(GuildVoiceLeaveEvent event){
if(!event.getVoiceState().getMember().getUser().getId().equals(event.getJDA().getSelfUser().getId()) && event.getGuild().getAudioManager().isConnected()){
if (!event.getChannelLeft().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelLeft().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().closeAudioConnection();
event.getGuild().getAudioManager().setSendingHandler(null);
}
}
}
}
/**
* This will fire when a member moves from channel, if a member moves we will check if our channel is empty
* @param event {@link net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent GuildVoiceMoveEvent}
*/
@Override
public void onGuildVoiceMove(GuildVoiceMoveEvent event) {
if(!event.getVoiceState().getMember().getUser().getId().equals(event.getJDA().getSelfUser().getId()) && event.getGuild().getAudioManager().isConnected()) {
if(event.getChannelLeft()!=null) {
if (!event.getChannelLeft().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelLeft().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().closeAudioConnection();
event.getGuild().getAudioManager().setSendingHandler(null);
}
}
}
if(event.getChannelJoined()!=null) {
if (!event.getChannelJoined().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelJoined().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().setSendingHandler(null);
event.getGuild().getAudioManager().closeAudioConnection();
}
}
}
}
}
private boolean temp = true;
//We're beeing sneaky here because we are setting the game to something called "Listening to"
//b1nzy if you see this, please don't b4nzy me
private void setWatchingStatus(JDA jda) {
System.out.println("checking");
System.out.println("shards is " + jda.asBot().getShardManager().getShards().size());
if(temp && (jda.asBot().getShardManager().getShards().size() != 2) ) {
System.out.println("not setting");
return;
}
System.out.println("Setting game for all shards");
Presence p = jda.getPresence();
JSONObject gameObj = new JSONObject();
gameObj.put("name", "Danny Phantom");
gameObj.put("type", 3);
JSONObject object = new JSONObject();
object.put("game", gameObj);
object.put("afk", p.isIdle());
object.put("status", p.getStatus().getKey());
object.put("since", System.currentTimeMillis());
for (JDA shard : jda.asBot().getShardManager().getShards())
((JDAImpl) shard).getClient().send(new JSONObject()
.put("d", object)
.put("op", WebSocketCode.PRESENCE).toString()
);
temp = false;
}
}
|
src/main/java/ml/duncte123/skybot/BotListener.java
|
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot;
import ml.duncte123.skybot.commands.essentials.eval.EvalCommand;
import ml.duncte123.skybot.objects.guild.GuildSettings;
import ml.duncte123.skybot.parsers.CommandParser;
import ml.duncte123.skybot.utils.*;
import net.dv8tion.jda.bot.sharding.ShardManager;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.WebSocketCode;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ShutdownEvent;
import net.dv8tion.jda.core.events.guild.GuildJoinEvent;
import net.dv8tion.jda.core.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.managers.Presence;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONObject;
import org.slf4j.event.Level;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class BotListener extends ListenerAdapter {
/**
* This is the command parser
*/
private static CommandParser parser = new CommandParser();
/**
* This filter helps us to fiter out swearing
*/
private BadWordFilter filter = new BadWordFilter();
/**
* When a command gets ran, it'll be stored in here
*/
private static Map<Guild, TextChannel> lastGuildChannel = new HashMap<>();
/**
* This timer is for checking unbans
*/
public Timer unbanTimer = new Timer();
/**
* This tells us if the {@link #unbanTimer unbanTimer} is running
*/
public boolean unbanTimerRunning = false;
/**
* This timer is for checking new quotes
*/
public Timer settingsUpdateTimer = new Timer();
/**
* This tells us if the {@link #settingsUpdateTimer settingsUpdateTimer} is running
*/
public boolean settingsUpdateTimerRunning = false;
/**
* Listen for messages send to the bot
* @param event The corresponding {@link net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent GuildMessageReceivedEvent}
*/
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event){
//We only want to respond to members/users
if(event.getAuthor().isFake() || event.getAuthor().isBot() || event.getMember()==null){
return;
}
GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
if(event.getMessage().getContent().equals(Settings.prefix + "shutdown") && Arrays.asList(Settings.wbkxwkZPaG4ni5lm8laY).contains(event.getAuthor().getId()) ){
AirUtils.log(Level.INFO,"Initialising shutdown!!!");
ShardManager manager = event.getJDA().asBot().getShardManager();
for(JDA shard : manager.getShards()) {
AirUtils.log(Level.INFO,"Shard " + shard.getShardInfo().getShardId() + " has been shut down");
shard.shutdown();
}
System.exit(0);
return;
}
Permission[] adminPerms = {
Permission.MESSAGE_MANAGE
};
if(event.getGuild().getSelfMember().hasPermission(adminPerms) && AirUtils.guildSettings.get(event.getGuild().getId()).isEnableSwearFilter()) {
if (!event.getMember().hasPermission(adminPerms)) {
Message messageToCheck = event.getMessage();
if (filter.filterText(messageToCheck.getRawContent())) {
messageToCheck.delete().reason("Blocked for bad swearing: " + messageToCheck.getContent()).queue();
event.getChannel().sendMessage("Hello there, " + event.getAuthor().getAsMention() + " please do not use cursive language within this Discord.").queue(
m -> m.delete().queueAfter(10, TimeUnit.SECONDS));
return;
}
}
}
if(!event.getMessage().getRawContent().startsWith(Settings.prefix) && !event.getMessage().getRawContent().startsWith(settings.getCustomPrefix())){
return;
} else if(event.getMessage().getMentionedUsers().contains(event.getJDA().getSelfUser()) && event.getChannel().canTalk()) {
if (!event.getMessage().getRawContent().startsWith(event.getJDA().getSelfUser().getAsMention())) {
event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, try `" + Settings.prefix + "help` for a list of commands. If it doesn't work scream at _duncte123#1245_").queue();
return;
}
}
// run the a command
lastGuildChannel.put(event.getGuild(), event.getChannel());
String rw = event.getMessage().getRawContent();
if(!Settings.prefix.equals(settings.getCustomPrefix())) {
rw = rw.replaceFirst(
Pattern.quote(settings.getCustomPrefix()),
Settings.prefix);
}
AirUtils.commandManager.runCommand(parser.parse(rw.replaceFirst("<@" + event.getJDA().getSelfUser().getId() + "> ", Settings.prefix)
,
event
));
}
/**
* When the bot is ready to go
* @param event The corresponding {@link net.dv8tion.jda.core.events.ReadyEvent ReadyEvent}
*/
@Override
public void onReady(ReadyEvent event){
setWatchingStatus(event.getJDA());
AirUtils.log(Level.INFO, "Logged in as " + String.format("%#s", event.getJDA().getSelfUser()) + " (Shard #" + event.getJDA().getShardInfo().getShardId() + ")");
AirUtils.spoopyScaryVariable = event.getJDA().getSelfUser().getId().equals(
new String(Settings.iyqrektunkyhuwul3dx0b[0]))
| event.getJDA().getSelfUser().getId().equals(
new String(Settings.iyqrektunkyhuwul3dx0b[1]));
//Start the timers if they have not been started yet
if(!unbanTimerRunning && AirUtils.nonsqlite) {
AirUtils.log(Level.INFO, "Starting the unban timer.");
//Register the timer for the auto unbans
//I moved the timer here to make sure that every running jar has this only once
TimerTask unbanTask = new TimerTask() {
@Override
public void run() {
AirUtils.checkUnbans(event.getJDA().asBot().getShardManager());
}
};
unbanTimer.schedule(unbanTask, DateUtils.MILLIS_PER_MINUTE * 10, DateUtils.MILLIS_PER_MINUTE * 10);
unbanTimerRunning = true;
}
if(!settingsUpdateTimerRunning && AirUtils.nonsqlite) {
AirUtils.log(Level.INFO, "Starting the settings timer.");
//This handles the updating from the setting and quotes
TimerTask settingsTask = new TimerTask() {
@Override
public void run() {
GuildSettingsUtils.loadAllSettings();
}
};
settingsUpdateTimer.schedule(settingsTask, DateUtils.MILLIS_PER_HOUR, DateUtils.MILLIS_PER_HOUR);
settingsUpdateTimerRunning = true;
}
}
@Override
public void onShutdown(ShutdownEvent event) {
((EvalCommand) AirUtils.commandManager.getCommand("eval")).shutdown();
if(unbanTimerRunning) {
this.unbanTimer.cancel();
this.unbanTimer.purge();
}
if(settingsUpdateTimerRunning) {
this.settingsUpdateTimer.cancel();
this.settingsUpdateTimer.purge();
}
}
/**
* This will fire when a new member joins
* @param event The corresponding {@link net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent GuildMemberJoinEvent}
*/
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event){
/*
{{USER_MENTION}} = mention user
{{USER_NAME}} = return username
{{GUILD_NAME}} = the name of the guild
{{GUILD_USER_COUNT}} = member count
{{GUILD_OWNER_MENTION}} = mention the guild owner
{{GUILD_OWNER_NAME}} = return the name form the owner
*/
GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
if (settings.isEnableJoinMessage()) {
TextChannel publicChannel = AirUtils.getPublicChannel(event.getGuild());
String msg = settings.getCustomJoinMessage()
.replaceAll("\\{\\{USER_MENTION}}", event.getUser().getAsMention())
.replaceAll("\\{\\{USER_NAME}}", event.getUser().getName())
.replaceAll("\\{\\{GUILD_NAME}}", event.getGuild().getName())
.replaceAll("\\{\\{GUILD_USER_COUNT}}", event.getGuild().getMemberCache().size() + "");
publicChannel.sendMessage(msg).queue();
}
}
/**
* This will fire when the bot joins a guild and we check if we are allowed to join this guild
* @param event The corresponding {@link net.dv8tion.jda.core.events.guild.GuildJoinEvent GuildJoinEvent}
*/
@Override
public void onGuildJoin(GuildJoinEvent event) {
//if 60 of a guild is bots, we'll leave it
double[] botToUserRatio = AirUtils.getBotRatio(event.getGuild());
if(botToUserRatio[1] > 60) {
AirUtils.getPublicChannel(event.getGuild()).sendMessage("Hey " +
event.getGuild().getOwner().getAsMention() + ", "+botToUserRatio[1]+"% of this guild are bots ("+event.getGuild().getMemberCache().size()+" is the total btw). " +
"I'm outta here").queue(
message -> message.getGuild().leave().queue()
);
AirUtils.log(Settings.defaultName + "GuildJoin", Level.INFO, "Joining guild: " + event.getGuild().getName() + ", and leaving it after. BOT ALERT");
return;
}
AirUtils.log(Settings.defaultName + "GuildJoin", Level.INFO, "Joining guild: " + event.getGuild().getName() + ".");
GuildSettingsUtils.registerNewGuild(event.getGuild());
AirUtils.updateGuildCount(event.getJDA(), event.getJDA().asBot().getShardManager().getGuildCache().size());
}
@Override
public void onGuildLeave(GuildLeaveEvent event) {
GuildSettingsUtils.deleteGuild(event.getGuild());
AirUtils.updateGuildCount(event.getJDA(), event.getJDA().asBot().getShardManager().getGuildCache().size());
}
/**
* This will fire when a member leaves a channel in a guild, we check if the channel is empty and if it is we leave it
* @param event {@link net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent GuildVoiceLeaveEvent}
*/
@Override
public void onGuildVoiceLeave(GuildVoiceLeaveEvent event){
if(!event.getVoiceState().getMember().getUser().getId().equals(event.getJDA().getSelfUser().getId()) && event.getGuild().getAudioManager().isConnected()){
if (!event.getChannelLeft().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelLeft().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().closeAudioConnection();
event.getGuild().getAudioManager().setSendingHandler(null);
}
}
}
}
/**
* This will fire when a member moves from channel, if a member moves we will check if our channel is empty
* @param event {@link net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent GuildVoiceMoveEvent}
*/
@Override
public void onGuildVoiceMove(GuildVoiceMoveEvent event) {
if(!event.getVoiceState().getMember().getUser().getId().equals(event.getJDA().getSelfUser().getId()) && event.getGuild().getAudioManager().isConnected()) {
if(event.getChannelLeft()!=null) {
if (!event.getChannelLeft().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelLeft().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().closeAudioConnection();
event.getGuild().getAudioManager().setSendingHandler(null);
}
}
}
if(event.getChannelJoined()!=null) {
if (!event.getChannelJoined().getId().equals(event.getGuild().getAudioManager().getConnectedChannel().getId())) { return; }
if(event.getChannelJoined().getMembers().size() <= 1){
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.stopTrack();
AirUtils.audioUtils.getMusicManager(event.getGuild()).player.setPaused(false);
AirUtils.audioUtils.getMusicManager(event.getGuild()).scheduler.queue.clear();
lastGuildChannel.get(event.getGuild()).sendMessage(EmbedUtils.embedMessage("Leaving voice channel because all the members have left it.")).queue();
if(event.getGuild().getAudioManager().isConnected()){
event.getGuild().getAudioManager().setSendingHandler(null);
event.getGuild().getAudioManager().closeAudioConnection();
}
}
}
}
}
private boolean temp = true;
//We're beeing sneaky here because we are setting the game to something called "Listening to"
//b1nzy if you see this, please don't b4nzy me
private void setWatchingStatus(JDA jda) {
System.out.println("checking");
System.out.println("shards is " + jda.asBot().getShardManager().getShards().size());
if(temp && (jda.asBot().getShardManager().getShards().size() != 2) ) {
System.out.println("not setting");
return;
}
System.out.println("Setting game for all shards");
Presence p = jda.getPresence();
JSONObject gameObj = new JSONObject();
gameObj.put("name", "Danny Phantom");
gameObj.put("type", 3);
JSONObject object = new JSONObject();
object.put("game", gameObj);
object.put("afk", p.isIdle());
object.put("status", p.getStatus().getKey());
object.put("since", System.currentTimeMillis());
for (JDA shard : jda.asBot().getShardManager().getShards())
((JDAImpl) shard).getClient().send(new JSONObject()
.put("d", object)
.put("op", WebSocketCode.PRESENCE).toString()
);
temp = false;
}
}
|
Make the bot ignore commands in channels that have -commands in the topic
|
src/main/java/ml/duncte123/skybot/BotListener.java
|
Make the bot ignore commands in channels that have -commands in the topic
|
|
Java
|
lgpl-2.1
|
55284b17937629ada0366cc90227aae9609407a7
| 0
|
JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,joshkh/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,joshkh/intermine,tomck/intermine,joshkh/intermine,justincc/intermine,zebrafishmine/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,kimrutherford/intermine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,tomck/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,drhee/toxoMine,elsiklab/intermine,elsiklab/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,justincc/intermine,zebrafishmine/intermine,kimrutherford/intermine,JoeCarlson/intermine,elsiklab/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,joshkh/intermine,zebrafishmine/intermine,kimrutherford/intermine,justincc/intermine,elsiklab/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,drhee/toxoMine
|
package org.intermine.webservice.client.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
import org.intermine.webservice.client.template.TemplateParameter;
import org.intermine.webservice.client.util.TestUtil;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
/**
* Tests functionality of TemplateService - client class, implementing easy
* access to InterMine web service. That's why it tests the web service itself
* as well.
*
* @author Jakub Kulaviak
**/
public class TemplateServiceTest extends TestCase
{
/**
* Checks Java client and that default parameters of template are replaced with
* parameters provided by client.
*/
public void testNonDefaultParameters() {
DummyTemplateService service = TestUtil.getTemplateService();
service.setFakeResponse("EmployeeA1\t10\t1\ttrue\nEmployeeA2\t20\t2\ttrue");
//service.setExpectedRequest("http://localhost:8080/intermine-test/service/template/results?value3=60&value4=true&value1=EmployeeA&size=10&value2=10&op1=contains&constraint2=Employee.age&constraint1=Employee.name&op2=gt&constraint4=Employee.fullTime&op3=lt&op4=eq&constraint3=Employee.age&name=fourConstraints&code2=B&code3=C");
service.setExpectedRequest("http://localhost:8080/intermine-test/service/template/results?op1=contains&code2=B&constraint4=Employee.fullTime&constraint1=Employee.name&value2=10&op2=gt&constraint3=Employee.age&op3=lt&value1=EmployeeA&constraint2=Employee.age&op4=eq&value4=true&code3=C&size=10&name=fourConstraints&value3=60");
List<TemplateParameter> parameters = new ArrayList<TemplateParameter>();
parameters.add(new TemplateParameter("Employee.name", "contains", "EmployeeA"));
TemplateParameter par1 = new TemplateParameter("Employee.age", "gt", "10");
par1.setCode("B");
parameters.add(par1);
TemplateParameter par2 = new TemplateParameter("Employee.age", "lt", "60");
par2.setCode("C");
parameters.add(par2);
parameters.add(new TemplateParameter("Employee.fullTime", "eq", "true"));
List<List<String>> results = service.getResult("fourConstraints", parameters, 10);
assertEquals(2, results.size());
// returns 2 results, notice that the logic for constraints B and C is OR -> returns Employee of age 10
TestUtil.checkRow(results.get(0), "EmployeeA1", "10", "1", "true");
TestUtil.checkRow(results.get(1), "EmployeeA2", "20", "2", "true");
}
}
|
intermine/webservice/client/test/src/org/intermine/webservice/client/services/TemplateServiceTest.java
|
package org.intermine.webservice.client.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
import org.intermine.webservice.client.template.TemplateParameter;
import org.intermine.webservice.client.util.TestUtil;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
/**
* Tests functionality of TemplateService - client class, implementing easy
* access to InterMine web service. That's why it tests the web service itself
* as well.
*
* @author Jakub Kulaviak
**/
public class TemplateServiceTest extends TestCase
{
/**
* Checks Java client and that default parameters of template are replaced with
* parameters provided by client.
*/
public void testNonDefaultParameters() {
DummyTemplateService service = TestUtil.getTemplateService();
service.setFakeResponse("EmployeeA1\t10\t1\ttrue\nEmployeeA2\t20\t2\ttrue");
service.setExpectedRequest("http://localhost:8080/intermine-test/service/template/results?value3=60&value4=true&value1=EmployeeA&size=10&value2=10&op1=contains&constraint2=Employee.age&constraint1=Employee.name&op2=gt&constraint4=Employee.fullTime&op3=lt&op4=eq&constraint3=Employee.age&name=fourConstraints&code2=B&code3=C");
List<TemplateParameter> parameters = new ArrayList<TemplateParameter>();
parameters.add(new TemplateParameter("Employee.name", "contains", "EmployeeA"));
TemplateParameter par1 = new TemplateParameter("Employee.age", "gt", "10");
par1.setCode("B");
parameters.add(par1);
TemplateParameter par2 = new TemplateParameter("Employee.age", "lt", "60");
par2.setCode("C");
parameters.add(par2);
parameters.add(new TemplateParameter("Employee.fullTime", "eq", "true"));
List<List<String>> results = service.getResult("fourConstraints", parameters, 10);
assertEquals(2, results.size());
// returns 2 results, notice that the logic for constraints B and C is OR -> returns Employee of age 10
TestUtil.checkRow(results.get(0), "EmployeeA1", "10", "1", "true");
TestUtil.checkRow(results.get(1), "EmployeeA2", "20", "2", "true");
}
}
|
update webservice url
|
intermine/webservice/client/test/src/org/intermine/webservice/client/services/TemplateServiceTest.java
|
update webservice url
|
|
Java
|
lgpl-2.1
|
8bd8fbd7b300f33f7cd6be29656fe3ba3b049d1f
| 0
|
serrapos/opencms-core,victos/opencms-core,gallardo/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,serrapos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,victos/opencms-core,gallardo/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,victos/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,alkacon/opencms-core,alkacon/opencms-core,victos/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,MenZil/opencms-core
|
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsNewExplorerFileList.java,v $
* Date : $Date: 2001/09/13 10:21:08 $
* Version: $Revision: 1.39 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2001 The OpenCms Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about OpenCms, please see the
* OpenCms Website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.opencms.workplace;
import java.util.*;
import com.opencms.launcher.*;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.template.*;
import com.opencms.template.cache.*;
import com.opencms.util.*;
import java.util.*;
import org.w3c.dom.*;
import org.xml.sax.*;
/**
* Template class for dumping files to the output without further
* interpreting or processing.
* This can be used for plain text files or files containing graphics.
*
* @author Alexander Lucas
* @version $Revision: 1.39 $ $Date: 2001/09/13 10:21:08 $
*/
public class CmsNewExplorerFileList implements I_CmsDumpTemplate,I_CmsLogChannels,I_CmsConstants,I_CmsWpConstants {
/**
* Template cache is not used here since we don't include
* any subtemplates.
*/
private static I_CmsTemplateCache m_cache = null;
/**
* This is the nummber of resources that are shown on one page.
* If a folder contains more than this we have to split the entrys
* on more than one page.
* TODO: this should be saved iin the usersettiings, so each user
* can say how much he wants to see at once(and how long he has to wait for it)
*/
private final static int C_ENTRYS_PER_PAGE = 50;
// the session key for the current page
private final static String C_SESSION_CURRENT_PAGE = "explorerFilelistCurrentPage";
/** Boolean for additional debug output control */
private static final boolean C_DEBUG = false;
public CmsNewExplorerFileList() {
}
/**
* gets the caching information from the current template class.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if this class may stream it's results, <EM>false</EM> otherwise.
*/
public CmsCacheDirectives getCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
// First build our own cache directives.
return new CmsCacheDirectives(false);
}
/**
* Insert the method's description here.
* Creation date: (29.11.00 14:05:21)
* @return boolean
* @param cms com.opencms.file.CmsObject
* @param path java.lang.String
*/
private boolean folderExists(CmsObject cms, String path) {
try {
CmsFolder test = cms.readFolder(path);
if (test.isFile()){
return false;
}
}
catch(Exception e) {
return false;
}
return true;
}
/**
* Insert the method's description here.
* Creation date: (07.12.00 17:08:30)
* @return java.lang.String
* @param value java.lang.String
*/
private String getChars(String value) {
String ret = "";
int num;
for(int i = 0;i < value.length();i++) {
num = value.charAt(i);
if((num > 122) || (num < 48)) {
ret += "&#" + num + ";";
}
else {
ret += value.charAt(i);
}
}
return ret + "";
}
/**
* Gets the content of a given template file.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName <em>not used here</em>.
* @param parameters <em>not used here</em>.
* @return Unprocessed content of the given template file.
* @exception CmsException
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters) throws CmsException {
if(A_OpenCms.isLogging() && I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && C_DEBUG) {
A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsDumpTemplate] Now dumping contents of file "
+ templateFile);
}
I_CmsSession session = cms.getRequestContext().getSession(true);
CmsXmlWpTemplateFile templateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
CmsXmlLanguageFile lang = templateDocument.getLanguageFile();
// get the right folder
String currentFolder = (String)parameters.get("folder");
if((currentFolder != null) && (!"".equals(currentFolder)) && folderExists(cms,
currentFolder)) {
session.putValue(C_PARA_FILELIST, currentFolder);
}else {
currentFolder = (String)session.getValue(C_PARA_FILELIST);
if((currentFolder == null) || (!folderExists(cms, currentFolder))) {
currentFolder = cms.rootFolder().getAbsolutePath();
session.putValue(C_PARA_FILELIST, currentFolder);
}
}
// if the parameter mode=listonly is set, only the list will be shown
boolean listonly = "listonly".equals(parameters.get("mode"));
// if the parameter mode=projectview is set, all changed files in that project will be shown
boolean projectView = "projectview".equals(parameters.get("mode"));
// the flaturl to use for changing folders
String flaturl = (String) parameters.get("flaturl");
// get the checksum
String checksum = (String)parameters.get("check");
boolean newTreePlease = true;
long check = -1;
try {
check = Long.parseLong(checksum);
if(check == cms.getFileSystemFolderChanges()) {
newTreePlease = false;
}
}catch(Exception e) {
}
check = cms.getFileSystemFolderChanges();
// get the currentFolder Id
int currentFolderId = (cms.readFolder(currentFolder)).getResourceId();
// start creating content
StringBuffer content = new StringBuffer();
content.append("<html> \n<head> \n<script language=JavaScript>\n");
content.append("function initialize() {\n");
if(listonly) {
content.append("top.openfolderMethod='openthisfolderflat';\n");
} else {
content.append("top.openfolderMethod='openthisfolder';\n");
}
if(projectView) {
content.append("top.projectView=true;\n");
} else {
content.append("top.projectView=false;\n");
}
// the flaturl
if(flaturl != null) {
content.append("top.flaturl='" + flaturl + "';\n");
} else if (!listonly){
content.append("top.flaturl='';\n");
}
// the help_url
content.append("top.help_url='ExplorerAnsicht/index.html';\n");
// the project
content.append("top.setProject(" + cms.getRequestContext().currentProject().getId() + ");\n");
// the onlineProject
content.append("top.setOnlineProject(" + cms.onlineProject().getId() + ");\n");
// set the checksum for the tree
content.append("top.setChecksum(" + check + ");\n");
// set the writeAccess for the current Folder
CmsFolder test = cms.readFolder(currentFolder);
boolean writeAccess = test.getProjectId() == cms.getRequestContext().currentProject().getId();
content.append("top.enableNewButton(" + writeAccess + ");\n");
// the folder
content.append("top.setDirectory(" + currentFolderId + ",\"" + currentFolder + "\");\n");
content.append("top.rD();\n\n");
// now look which filelist colums we want to show
int filelist = getDefaultPreferences(cms);
boolean showTitle = (filelist & C_FILELIST_TITLE) > 0;
boolean showDateChanged = (filelist & C_FILELIST_CHANGED) > 0;
boolean showOwner = (filelist & C_FILELIST_OWNER) > 0;
boolean showGroup = (filelist & C_FILELIST_GROUP) > 0;
boolean showSize = (filelist & C_FILELIST_SIZE) > 0;
// now get the entries for the filelist
Vector resources = getRessources(cms, currentFolder, projectView);
// if a folder contains to much entrys we split them to pages of C_ENTRYS_PER_PAGE
// but only in the explorer view
int startat = 0;
int stopat = resources.size();
int selectedPage = 1;
int numberOfPages = 0;
int maxEntrys = C_ENTRYS_PER_PAGE; // later this comes from the usersettings
if(!(listonly || projectView)){
String selPage = (String)parameters.get("selPage");
if(selPage == null || "".equals(selPage)){
selPage = (String)session.getValue(C_SESSION_CURRENT_PAGE);
}
if(selPage != null && !"".equals(selPage)){
try{
selectedPage = Integer.parseInt(selPage);
session.putValue(C_SESSION_CURRENT_PAGE, selPage);
}catch(Exception e){
}
}
if(stopat > maxEntrys){
// we have to splitt
numberOfPages = (stopat / maxEntrys) +1;
if(selectedPage > numberOfPages){
// the user has changed the folder and then selected a page for the old folder
selectedPage =1;
}
startat = (selectedPage -1) * maxEntrys;
if((startat + maxEntrys) < stopat){
stopat = startat + maxEntrys;
}
}
}
for(int i = startat;i < stopat;i++) {
CmsResource res = (CmsResource)resources.elementAt(i);
content.append("top.aF(");
// the name
content.append("\"" + res.getName() + "\",");
// the path
if(projectView){
content.append("\"" + res.getPath() + "\",");
}else{
//is taken from top.setDirectory
content.append("\"\",");
}
// the title
if(showTitle){
String title = "";
try {
title = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_TITLE);
}catch(CmsException e) {
}
if(title == null) {
title = "";
}
content.append("\"" + getChars(title) + "\",");
}else{
content.append("\"\",");
}
// the type
content.append(res.getType() + ",");
// date of last change
if(showDateChanged){
content.append("\"" + Utils.getNiceDate(res.getDateLastModified()) + "\",");
}else{
content.append("\"\",");
}
// TODO:user who changed it: content.append("\"" + "TODO" + "\",");
content.append("\"\",");
// date
// not yet used: content.append("\"" + Utils.getNiceDate(res.getDateCreated()) + "\",");
content.append("\"\",");
// size
if(res.isFolder() || (!showSize)) {
content.append("\"\",");
}else {
content.append( res.getLength() + ",");
}
// state
content.append(res.getState() + ",");
// project
content.append(res.getProjectId() + ",");
// owner
if(showOwner){
content.append("\"" + cms.readUser(res.getOwnerId()).getName() + "\",");
}else{
content.append("\"\",");
}
// group
if(showGroup){
content.append("\"" + cms.readGroup(res).getName() + "\",");
}else{
content.append("\"\",");
}
// accessFlags
content.append(res.getAccessFlags() + ",");
// locked by
if(res.isLockedBy() == C_UNKNOWN_ID) {
content.append("\"\",");
}else {
content.append("\"" + cms.lockedBy(res).getName() + "\",");
}
// locked in project
int lockedInProject = res.getLockedInProject();
String lockedInProjectName = "";
try {
lockedInProjectName = cms.readProject(lockedInProject).getName();
} catch(CmsException exc) {
// ignore the exception - this is an old project so ignore it
}
content.append("\"" + lockedInProjectName + "\"," + lockedInProject + ");\n");
}
// now the tree, only if changed
if(newTreePlease && (!listonly)) {
content.append("\n top.rT();\n");
Vector tree = cms.getFolderTree();
int startAt = 1;
int parentId;
boolean grey = false;
int onlineProjectId = cms.onlineProject().getId();
if(onlineProjectId == cms.getRequestContext().currentProject().getId()) {
// all easy: we are in the onlineProject
CmsFolder rootFolder = (CmsFolder)tree.elementAt(0);
content.append("top.aC(");
content.append(rootFolder.getResourceId() + ", ");
content.append("\"" + lang.getDataValue("title.rootfolder") + "\", ");
content.append(rootFolder.getParentId() + ", false);\n");
for(int i = startAt;i < tree.size();i++) {
CmsFolder folder = (CmsFolder)tree.elementAt(i);
content.append("top.aC(");
// id
content.append(folder.getResourceId() + ", ");
// name
content.append("\"" + folder.getName() + "\", ");
// parentId
content.append(folder.getParentId() + ", false);\n");
}
}else {
// offline Project
Hashtable idMixer = new Hashtable();
CmsFolder rootFolder = (CmsFolder)tree.elementAt(0);
String folderToIgnore = null;
if(rootFolder.getProjectId() != onlineProjectId) {
startAt = 2;
grey = false;
idMixer.put(new Integer(((CmsFolder)tree.elementAt(1)).getResourceId()),
new Integer(rootFolder.getResourceId()));
}else {
grey = true;
}
content.append("top.aC(");
content.append(rootFolder.getResourceId() + ", ");
content.append("\"" + lang.getDataValue("title.rootfolder") + "\", ");
content.append(rootFolder.getParentId() + ", " + grey + ");\n");
for(int i = startAt;i < tree.size();i++) {
CmsFolder folder = (CmsFolder)tree.elementAt(i);
if((folder.getState() == C_STATE_DELETED) || (folder.getAbsolutePath().equals(folderToIgnore))) {
// if the folder is deleted - ignore it and the following online res
folderToIgnore = folder.getAbsolutePath();
}else {
if(folder.getProjectId() != onlineProjectId) {
grey = false;
parentId = folder.getParentId();
try {
// the next res is the same res in the online-project: ignore it!
if(folder.getAbsolutePath().equals(((CmsFolder)tree.elementAt(i + 1)).getAbsolutePath())) {
i++;
idMixer.put(new Integer(((CmsFolder)tree.elementAt(i)).getResourceId()),
new Integer(folder.getResourceId()));
}
}catch(IndexOutOfBoundsException exc) {
// ignore the exception, this was the last resource
}
}else {
grey = true;
parentId = folder.getParentId();
if(idMixer.containsKey(new Integer(parentId))) {
parentId = ((Integer)idMixer.get(new Integer(parentId))).intValue();
}
}
content.append("top.aC(");
// id
content.append(folder.getResourceId() + ", ");
// name
content.append("\"" + folder.getName() + "\", ");
// parentId
content.append(parentId + ", " + grey + ");\n");
}
}
}
}
if(listonly || projectView) {
// only show the filelist
content.append(" top.dUL(document); \n");
} else {
// update all frames
content.append(" top.dU(document,"+numberOfPages+","+selectedPage+"); \n");
}
content.append("}\n");
content.append("</script>\n</head> \n<BODY onLoad=\"initialize()\"></BODY> \n</html>\n");
return (content.toString()).getBytes();
}
/**
* Gets the content of a given template file.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName <em>not used here</em>.
* @param parameters <em>not used here</em>.
* @param templateSelector <em>not used here</em>.
* @return Unprocessed content of the given template file.
* @exception CmsException
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
// ignore the templateSelector since we only dump the template
return getContent(cms, templateFile, elementName, parameters);
}
/**
* Sets the default preferences for the current user if those values are not available.
* @return Hashtable with default preferences.
*/
private int getDefaultPreferences(CmsObject cms) {
int filelist;
String explorerSettings = (String)cms.getRequestContext().currentUser().getAdditionalInfo(C_ADDITIONAL_INFO_EXPLORERSETTINGS);
if(explorerSettings != null) {
filelist = new Integer(explorerSettings).intValue();
}else {
filelist = C_FILELIST_NAME + C_FILELIST_TITLE + C_FILELIST_TYPE + C_FILELIST_CHANGED;
}
return filelist;
}
/**
* Gets the key that should be used to cache the results of
* this template class.
* <P>
* Since this class is quite simple it's okay to return
* just the name of the template file here.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return key that can be used for caching
*/
public Object getKey(CmsObject cms, String templateFile, Hashtable parameter,
String templateSelector) {
//return templateFile.getAbsolutePath();
//Vector v = new Vector();
CmsRequestContext reqContext = cms.getRequestContext();
//v.addElement(reqContext.currentProject().getName());
//v.addElement(templateFile);
//return v;
return "" + reqContext.currentProject().getId() + ":" + templateFile;
}
/**
* Template cache is not used here since we don't include
* any subtemplates. So we can always return <code>true</code> here.
* @return <code>true</code>
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
public boolean isProxyPrivateCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isProxyPublicCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isExportable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isStreamable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public CmsCacheDirectives collectCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
CmsCacheDirectives myCd = new CmsCacheDirectives(false);
return myCd;
}
/**
* Any results of this class are cacheable since we don't include
* any subtemplates. So we can always return <code>true</code> here.
* @return <code>true</code>
*/
public boolean isTemplateCacheSet() {
return true;
}
/**
* Template cache is not used here since we don't include
* any subtemplates <em>(not implemented)</em>.
*/
public void setTemplateCache(I_CmsTemplateCache c) {
// do nothing.
}
/**
* Template cache is not used here since we don't include
* any subtemplates. So we can always return <code>false</code> here.
* @return <code>false</code>
*/
public boolean shouldReload(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
public A_CmsElement createElement(CmsObject cms, String templateFile, Hashtable parameters) {
return new CmsElementDump(getClass().getName(), templateFile, null, getCacheDirectives(cms, templateFile, null, parameters, null),
cms.getRequestContext().getElementCache().getVariantCachesize());
}
/**
* Get the resources in the folder stored in parameter param
* or in the project shown in the projectview
*
* @param cms The CmsObject
* @param param The name of the folder
* @param projectView True if the projectview is shown
* @return The vector with all ressources
*/
private Vector getRessources(CmsObject cms, String param, boolean projectView) throws CmsException {
if(projectView) {
I_CmsSession session = cms.getRequestContext().getSession(true);
String filter = new String();
filter = (String) session.getValue("filter");
String projectId = (String) session.getValue("projectid");
int currentProjectId;
if(projectId == null || "".equals(projectId)){
currentProjectId = cms.getRequestContext().currentProject().getId();
} else {
currentProjectId = Integer.parseInt(projectId);
}
session.removeValue("filter");
return cms.readProjectView(currentProjectId, filter);
} else {
return cms.getResourcesInFolder(param);
}
}
}
|
src/com/opencms/workplace/CmsNewExplorerFileList.java
|
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsNewExplorerFileList.java,v $
* Date : $Date: 2001/09/13 09:55:50 $
* Version: $Revision: 1.38 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2001 The OpenCms Group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about OpenCms, please see the
* OpenCms Website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.opencms.workplace;
import java.util.*;
import com.opencms.launcher.*;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.template.*;
import com.opencms.template.cache.*;
import com.opencms.util.*;
import java.util.*;
import org.w3c.dom.*;
import org.xml.sax.*;
/**
* Template class for dumping files to the output without further
* interpreting or processing.
* This can be used for plain text files or files containing graphics.
*
* @author Alexander Lucas
* @version $Revision: 1.38 $ $Date: 2001/09/13 09:55:50 $
*/
public class CmsNewExplorerFileList implements I_CmsDumpTemplate,I_CmsLogChannels,I_CmsConstants,I_CmsWpConstants {
/**
* Template cache is not used here since we don't include
* any subtemplates.
*/
private static I_CmsTemplateCache m_cache = null;
/**
* This is the nummber of resources that are shown on one page.
* If a folder contains more than this we have to split the entrys
* on more than one page.
* TODO: this should be saved iin the usersettiings, so each user
* can say how much he wants to see at once(and how long he has to wait for it)
*/
private final static int C_ENTRYS_PER_PAGE = 50;
/** Boolean for additional debug output control */
private static final boolean C_DEBUG = false;
public CmsNewExplorerFileList() {
}
/**
* gets the caching information from the current template class.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if this class may stream it's results, <EM>false</EM> otherwise.
*/
public CmsCacheDirectives getCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
// First build our own cache directives.
return new CmsCacheDirectives(false);
}
/**
* Insert the method's description here.
* Creation date: (29.11.00 14:05:21)
* @return boolean
* @param cms com.opencms.file.CmsObject
* @param path java.lang.String
*/
private boolean folderExists(CmsObject cms, String path) {
try {
CmsFolder test = cms.readFolder(path);
if (test.isFile()){
return false;
}
}
catch(Exception e) {
return false;
}
return true;
}
/**
* Insert the method's description here.
* Creation date: (07.12.00 17:08:30)
* @return java.lang.String
* @param value java.lang.String
*/
private String getChars(String value) {
String ret = "";
int num;
for(int i = 0;i < value.length();i++) {
num = value.charAt(i);
if((num > 122) || (num < 48)) {
ret += "&#" + num + ";";
}
else {
ret += value.charAt(i);
}
}
return ret + "";
}
/**
* Gets the content of a given template file.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName <em>not used here</em>.
* @param parameters <em>not used here</em>.
* @return Unprocessed content of the given template file.
* @exception CmsException
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters) throws CmsException {
if(A_OpenCms.isLogging() && I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && C_DEBUG) {
A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsDumpTemplate] Now dumping contents of file "
+ templateFile);
}
I_CmsSession session = cms.getRequestContext().getSession(true);
CmsXmlWpTemplateFile templateDocument = new CmsXmlWpTemplateFile(cms, templateFile);
CmsXmlLanguageFile lang = templateDocument.getLanguageFile();
// get the right folder
String currentFolder = (String)parameters.get("folder");
if((currentFolder != null) && (!"".equals(currentFolder)) && folderExists(cms,
currentFolder)) {
session.putValue(C_PARA_FILELIST, currentFolder);
}else {
currentFolder = (String)session.getValue(C_PARA_FILELIST);
if((currentFolder == null) || (!folderExists(cms, currentFolder))) {
currentFolder = cms.rootFolder().getAbsolutePath();
session.putValue(C_PARA_FILELIST, currentFolder);
}
}
// if the parameter mode=listonly is set, only the list will be shown
boolean listonly = "listonly".equals(parameters.get("mode"));
// if the parameter mode=projectview is set, all changed files in that project will be shown
boolean projectView = "projectview".equals(parameters.get("mode"));
// the flaturl to use for changing folders
String flaturl = (String) parameters.get("flaturl");
// get the checksum
String checksum = (String)parameters.get("check");
boolean newTreePlease = true;
long check = -1;
try {
check = Long.parseLong(checksum);
if(check == cms.getFileSystemFolderChanges()) {
newTreePlease = false;
}
}catch(Exception e) {
}
check = cms.getFileSystemFolderChanges();
// get the currentFolder Id
int currentFolderId = (cms.readFolder(currentFolder)).getResourceId();
// start creating content
StringBuffer content = new StringBuffer();
content.append("<html> \n<head> \n<script language=JavaScript>\n");
content.append("function initialize() {\n");
if(listonly) {
content.append("top.openfolderMethod='openthisfolderflat';\n");
} else {
content.append("top.openfolderMethod='openthisfolder';\n");
}
if(projectView) {
content.append("top.projectView=true;\n");
} else {
content.append("top.projectView=false;\n");
}
// the flaturl
if(flaturl != null) {
content.append("top.flaturl='" + flaturl + "';\n");
} else if (!listonly){
content.append("top.flaturl='';\n");
}
// the help_url
content.append("top.help_url='ExplorerAnsicht/index.html';\n");
// the project
content.append("top.setProject(" + cms.getRequestContext().currentProject().getId() + ");\n");
// the onlineProject
content.append("top.setOnlineProject(" + cms.onlineProject().getId() + ");\n");
// set the checksum for the tree
content.append("top.setChecksum(" + check + ");\n");
// set the writeAccess for the current Folder
CmsFolder test = cms.readFolder(currentFolder);
boolean writeAccess = test.getProjectId() == cms.getRequestContext().currentProject().getId();
content.append("top.enableNewButton(" + writeAccess + ");\n");
// the folder
content.append("top.setDirectory(" + currentFolderId + ",\"" + currentFolder + "\");\n");
content.append("top.rD();\n\n");
// now look which filelist colums we want to show
int filelist = getDefaultPreferences(cms);
boolean showTitle = (filelist & C_FILELIST_TITLE) > 0;
boolean showDateChanged = (filelist & C_FILELIST_CHANGED) > 0;
boolean showOwner = (filelist & C_FILELIST_OWNER) > 0;
boolean showGroup = (filelist & C_FILELIST_GROUP) > 0;
boolean showSize = (filelist & C_FILELIST_SIZE) > 0;
// now get the entries for the filelist
Vector resources = getRessources(cms, currentFolder, projectView);
// if a folder contains to much entrys we split them to pages of C_ENTRYS_PER_PAGE
// but only in the explorer view
int startat = 0;
int stopat = resources.size();
int selectedPage = 1;
int numberOfPages = 0;
int maxEntrys = C_ENTRYS_PER_PAGE; // later this comes from the usersettings
if(!(listonly || projectView)){
String selPage = (String)parameters.get("selPage");
if(selPage != null && !"".equals(selPage)){
try{
selectedPage = Integer.parseInt(selPage);
}catch(Exception e){
}
}
if(stopat > maxEntrys){
// we have to splitt
numberOfPages = (stopat / maxEntrys) +1;
if(selectedPage > numberOfPages){
// the user has changed the folder and then selected a page for the old folder
selectedPage =1;
}
startat = (selectedPage -1) * maxEntrys;
if((startat + maxEntrys) < stopat){
stopat = startat + maxEntrys;
}
}
}
for(int i = startat;i < stopat;i++) {
CmsResource res = (CmsResource)resources.elementAt(i);
content.append("top.aF(");
// the name
content.append("\"" + res.getName() + "\",");
// the path
if(projectView){
content.append("\"" + res.getPath() + "\",");
}else{
//is taken from top.setDirectory
content.append("\"\",");
}
// the title
if(showTitle){
String title = "";
try {
title = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_TITLE);
}catch(CmsException e) {
}
if(title == null) {
title = "";
}
content.append("\"" + getChars(title) + "\",");
}else{
content.append("\"\",");
}
// the type
content.append(res.getType() + ",");
// date of last change
if(showDateChanged){
content.append("\"" + Utils.getNiceDate(res.getDateLastModified()) + "\",");
}else{
content.append("\"\",");
}
// TODO:user who changed it: content.append("\"" + "TODO" + "\",");
content.append("\"\",");
// date
// not yet used: content.append("\"" + Utils.getNiceDate(res.getDateCreated()) + "\",");
content.append("\"\",");
// size
if(res.isFolder() || (!showSize)) {
content.append("\"\",");
}else {
content.append( res.getLength() + ",");
}
// state
content.append(res.getState() + ",");
// project
content.append(res.getProjectId() + ",");
// owner
if(showOwner){
content.append("\"" + cms.readUser(res.getOwnerId()).getName() + "\",");
}else{
content.append("\"\",");
}
// group
if(showGroup){
content.append("\"" + cms.readGroup(res).getName() + "\",");
}else{
content.append("\"\",");
}
// accessFlags
content.append(res.getAccessFlags() + ",");
// locked by
if(res.isLockedBy() == C_UNKNOWN_ID) {
content.append("\"\",");
}else {
content.append("\"" + cms.lockedBy(res).getName() + "\",");
}
// locked in project
int lockedInProject = res.getLockedInProject();
String lockedInProjectName = "";
try {
lockedInProjectName = cms.readProject(lockedInProject).getName();
} catch(CmsException exc) {
// ignore the exception - this is an old project so ignore it
}
content.append("\"" + lockedInProjectName + "\"," + lockedInProject + ");\n");
}
// now the tree, only if changed
if(newTreePlease && (!listonly)) {
content.append("\n top.rT();\n");
Vector tree = cms.getFolderTree();
int startAt = 1;
int parentId;
boolean grey = false;
int onlineProjectId = cms.onlineProject().getId();
if(onlineProjectId == cms.getRequestContext().currentProject().getId()) {
// all easy: we are in the onlineProject
CmsFolder rootFolder = (CmsFolder)tree.elementAt(0);
content.append("top.aC(");
content.append(rootFolder.getResourceId() + ", ");
content.append("\"" + lang.getDataValue("title.rootfolder") + "\", ");
content.append(rootFolder.getParentId() + ", false);\n");
for(int i = startAt;i < tree.size();i++) {
CmsFolder folder = (CmsFolder)tree.elementAt(i);
content.append("top.aC(");
// id
content.append(folder.getResourceId() + ", ");
// name
content.append("\"" + folder.getName() + "\", ");
// parentId
content.append(folder.getParentId() + ", false);\n");
}
}else {
// offline Project
Hashtable idMixer = new Hashtable();
CmsFolder rootFolder = (CmsFolder)tree.elementAt(0);
String folderToIgnore = null;
if(rootFolder.getProjectId() != onlineProjectId) {
startAt = 2;
grey = false;
idMixer.put(new Integer(((CmsFolder)tree.elementAt(1)).getResourceId()),
new Integer(rootFolder.getResourceId()));
}else {
grey = true;
}
content.append("top.aC(");
content.append(rootFolder.getResourceId() + ", ");
content.append("\"" + lang.getDataValue("title.rootfolder") + "\", ");
content.append(rootFolder.getParentId() + ", " + grey + ");\n");
for(int i = startAt;i < tree.size();i++) {
CmsFolder folder = (CmsFolder)tree.elementAt(i);
if((folder.getState() == C_STATE_DELETED) || (folder.getAbsolutePath().equals(folderToIgnore))) {
// if the folder is deleted - ignore it and the following online res
folderToIgnore = folder.getAbsolutePath();
}else {
if(folder.getProjectId() != onlineProjectId) {
grey = false;
parentId = folder.getParentId();
try {
// the next res is the same res in the online-project: ignore it!
if(folder.getAbsolutePath().equals(((CmsFolder)tree.elementAt(i + 1)).getAbsolutePath())) {
i++;
idMixer.put(new Integer(((CmsFolder)tree.elementAt(i)).getResourceId()),
new Integer(folder.getResourceId()));
}
}catch(IndexOutOfBoundsException exc) {
// ignore the exception, this was the last resource
}
}else {
grey = true;
parentId = folder.getParentId();
if(idMixer.containsKey(new Integer(parentId))) {
parentId = ((Integer)idMixer.get(new Integer(parentId))).intValue();
}
}
content.append("top.aC(");
// id
content.append(folder.getResourceId() + ", ");
// name
content.append("\"" + folder.getName() + "\", ");
// parentId
content.append(parentId + ", " + grey + ");\n");
}
}
}
}
if(listonly || projectView) {
// only show the filelist
content.append(" top.dUL(document); \n");
} else {
// update all frames
content.append(" top.dU(document,"+numberOfPages+","+selectedPage+"); \n");
}
content.append("}\n");
content.append("</script>\n</head> \n<BODY onLoad=\"initialize()\"></BODY> \n</html>\n");
return (content.toString()).getBytes();
}
/**
* Gets the content of a given template file.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName <em>not used here</em>.
* @param parameters <em>not used here</em>.
* @param templateSelector <em>not used here</em>.
* @return Unprocessed content of the given template file.
* @exception CmsException
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
// ignore the templateSelector since we only dump the template
return getContent(cms, templateFile, elementName, parameters);
}
/**
* Sets the default preferences for the current user if those values are not available.
* @return Hashtable with default preferences.
*/
private int getDefaultPreferences(CmsObject cms) {
int filelist;
String explorerSettings = (String)cms.getRequestContext().currentUser().getAdditionalInfo(C_ADDITIONAL_INFO_EXPLORERSETTINGS);
if(explorerSettings != null) {
filelist = new Integer(explorerSettings).intValue();
}else {
filelist = C_FILELIST_NAME + C_FILELIST_TITLE + C_FILELIST_TYPE + C_FILELIST_CHANGED;
}
return filelist;
}
/**
* Gets the key that should be used to cache the results of
* this template class.
* <P>
* Since this class is quite simple it's okay to return
* just the name of the template file here.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return key that can be used for caching
*/
public Object getKey(CmsObject cms, String templateFile, Hashtable parameter,
String templateSelector) {
//return templateFile.getAbsolutePath();
//Vector v = new Vector();
CmsRequestContext reqContext = cms.getRequestContext();
//v.addElement(reqContext.currentProject().getName());
//v.addElement(templateFile);
//return v;
return "" + reqContext.currentProject().getId() + ":" + templateFile;
}
/**
* Template cache is not used here since we don't include
* any subtemplates. So we can always return <code>true</code> here.
* @return <code>true</code>
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
public boolean isProxyPrivateCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isProxyPublicCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isExportable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public boolean isStreamable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
public CmsCacheDirectives collectCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
CmsCacheDirectives myCd = new CmsCacheDirectives(false);
return myCd;
}
/**
* Any results of this class are cacheable since we don't include
* any subtemplates. So we can always return <code>true</code> here.
* @return <code>true</code>
*/
public boolean isTemplateCacheSet() {
return true;
}
/**
* Template cache is not used here since we don't include
* any subtemplates <em>(not implemented)</em>.
*/
public void setTemplateCache(I_CmsTemplateCache c) {
// do nothing.
}
/**
* Template cache is not used here since we don't include
* any subtemplates. So we can always return <code>false</code> here.
* @return <code>false</code>
*/
public boolean shouldReload(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
public A_CmsElement createElement(CmsObject cms, String templateFile, Hashtable parameters) {
return new CmsElementDump(getClass().getName(), templateFile, null, getCacheDirectives(cms, templateFile, null, parameters, null),
cms.getRequestContext().getElementCache().getVariantCachesize());
}
/**
* Get the resources in the folder stored in parameter param
* or in the project shown in the projectview
*
* @param cms The CmsObject
* @param param The name of the folder
* @param projectView True if the projectview is shown
* @return The vector with all ressources
*/
private Vector getRessources(CmsObject cms, String param, boolean projectView) throws CmsException {
if(projectView) {
I_CmsSession session = cms.getRequestContext().getSession(true);
String filter = new String();
filter = (String) session.getValue("filter");
String projectId = (String) session.getValue("projectid");
int currentProjectId;
if(projectId == null || "".equals(projectId)){
currentProjectId = cms.getRequestContext().currentProject().getId();
} else {
currentProjectId = Integer.parseInt(projectId);
}
session.removeValue("filter");
return cms.readProjectView(currentProjectId, filter);
} else {
return cms.getResourcesInFolder(param);
}
}
}
|
bugfix: the current page is stored in the session now so if you look a file you will see the same page again.
|
src/com/opencms/workplace/CmsNewExplorerFileList.java
|
bugfix: the current page is stored in the session now so if you look a file you will see the same page again.
|
|
Java
|
apache-2.0
|
461360cd01a69c8ed48e5e24b771dbfaae2944f0
| 0
|
arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.web.page.admin.users.component;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommonException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem;
import com.evolveum.midpoint.web.component.util.SelectableBean;
import com.evolveum.midpoint.web.page.admin.users.PageOrgTree;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableTreeProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import java.util.*;
/**
* @author lazyman
*/
public class OrgTreeProvider extends SortableTreeProvider<SelectableBean<OrgType>, String> {
private static final long serialVersionUID = 1L;
private static final Trace LOGGER = TraceManager.getTrace(OrgTreeProvider.class);
private static final String DOT_CLASS = OrgTreeProvider.class.getName() + ".";
private static final String LOAD_ORG_UNIT = DOT_CLASS + "loadOrgUnit";
private static final String LOAD_ORG_UNITS = DOT_CLASS + "loadOrgUnits";
private Component component;
private IModel<String> rootOid;
private SelectableBean<OrgType> root;
private List<SelectableBean<OrgType>> availableData;
public OrgTreeProvider(Component component, IModel<String> rootOid) {
this.component = component;
this.rootOid = rootOid;
}
public List<SelectableBean<OrgType>> getAvailableData() {
if (availableData == null){
availableData = new ArrayList<>();
}
return availableData;
}
private PageBase getPageBase() {
return WebComponentUtil.getPageBase(component);
}
private ModelService getModelService() {
return getPageBase().getModelService();
}
/*
* Wicket calls getChildren twice: in order to get actual children data, but also to know their number.
* We'll cache the children to avoid duplicate processing.
*/
private static final long EXPIRATION_AFTER_LAST_FETCH_OPERATION = 500L;
private long lastFetchOperation = 0;
private Map<String, List<SelectableBean<OrgType>>> childrenCache = new HashMap<>(); // key is the node OID
@Override
public Iterator<? extends SelectableBean<OrgType>> getChildren(SelectableBean<OrgType> node) {
LOGGER.debug("Getting children for {}", node.getValue());
String nodeOid = node.getValue().getOid();
List<SelectableBean<OrgType>> children;
long currentTime = System.currentTimeMillis();
if (currentTime > lastFetchOperation + EXPIRATION_AFTER_LAST_FETCH_OPERATION) {
childrenCache.clear();
}
if (childrenCache.containsKey(nodeOid)) {
LOGGER.debug("Using cached children for {}", node.getValue());
children = childrenCache.get(nodeOid);
} else {
LOGGER.debug("Loading fresh children for {}", node.getValue());
OperationResult result = new OperationResult(LOAD_ORG_UNITS);
try {
ObjectQuery query = QueryBuilder.queryFor(OrgType.class, getPageBase().getPrismContext())
.isDirectChildOf(nodeOid)
.build();
Task task = getPageBase().createSimpleTask(LOAD_ORG_UNITS);
List<PrismObject<OrgType>> orgs = getModelService().searchObjects(OrgType.class, query, null, task, result);
Collections.sort(orgs, new Comparator<PrismObject<OrgType>>() {
@Override
public int compare(PrismObject<OrgType> o1, PrismObject<OrgType> o2) {
String s1 = WebComponentUtil.getDisplayNameOrName(o1);
String s2 = WebComponentUtil.getDisplayNameOrName(o2);
return String.CASE_INSENSITIVE_ORDER.compare(s1, s2);
}
});
LOGGER.debug("Found {} sub-orgs.", orgs.size());
children = new ArrayList<>();
for (PrismObject<OrgType> org : orgs) {
children.add(createObjectWrapper(node, org));
}
childrenCache.put(nodeOid, children);
} catch (CommonException|RuntimeException ex) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load children", ex);
result.recordFatalError("Unable to load children for unit", ex);
children = new ArrayList<>();
} finally {
result.computeStatus();
}
if (WebComponentUtil.showResultInPage(result)) {
getPageBase().showResult(result);
throw new RestartResponseException(PageOrgTree.class);
}
getAvailableData().addAll(children);
}
LOGGER.debug("Finished getting children.");
lastFetchOperation = System.currentTimeMillis();
return children.iterator();
}
private SelectableBean<OrgType> createObjectWrapper(SelectableBean<OrgType> parent, PrismObject<OrgType> unit) {
if (unit == null) {
return null;
}
//todo relation [lazyman]
OrgType org = unit.asObjectable();
if (parent != null) {
org.getParentOrg().clear();
org.getParentOrg().add(parent.getValue());
}
SelectableBean<OrgType> orgDto = new SelectableBean<>(org);
orgDto.getMenuItems().addAll(createInlineMenuItems(orgDto.getValue()));
return orgDto;
}
protected List<InlineMenuItem> createInlineMenuItems(OrgType org){
return null;
}
@Override
public Iterator<SelectableBean<OrgType>> getRoots() {
OperationResult result = null;
if (root == null) {
Task task = getPageBase().createSimpleTask(LOAD_ORG_UNIT);
result = task.getResult();
LOGGER.debug("Getting roots for: " + rootOid.getObject());
PrismObject<OrgType> object = WebModelServiceUtils.loadObject(OrgType.class, rootOid.getObject(),
WebModelServiceUtils.createOptionsForParentOrgRefs(), getPageBase(), task, result);
result.computeStatus();
root = createObjectWrapper(null, object);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("\n{}", result.debugDump());
LOGGER.debug("Finished roots loading.");
}
}
if (WebComponentUtil.showResultInPage(result)) {
getPageBase().showResult(result);
}
List<SelectableBean<OrgType>> list = new ArrayList<>();
if (root != null) {
list.add(root);
if (!getAvailableData().contains(root)){
getAvailableData().add(root);
}
}
return list.iterator();
}
@Override
public boolean hasChildren(SelectableBean<OrgType> node) {
return true;
}
@Override
public IModel<SelectableBean<OrgType>> model(SelectableBean<OrgType> object) {
return new Model<>(object);
}
public List<OrgType> getSelectedObjects(){
List<OrgType> selectedOrgs = new ArrayList<>();
for (SelectableBean<OrgType> selected : getAvailableData()){
if (selected.isSelected() && selected.getValue() != null) {
selectedOrgs.add(selected.getValue());
}
}
return selectedOrgs;
}
}
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.web.page.admin.users.component;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommonException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem;
import com.evolveum.midpoint.web.component.util.SelectableBean;
import com.evolveum.midpoint.web.page.admin.users.PageOrgTree;
import com.evolveum.midpoint.web.page.admin.users.PageUsers;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableTreeProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import java.util.*;
/**
* @author lazyman
*/
public class OrgTreeProvider extends SortableTreeProvider<SelectableBean<OrgType>, String> {
private static final long serialVersionUID = 1L;
private static final Trace LOGGER = TraceManager.getTrace(OrgTreeProvider.class);
private static final String DOT_CLASS = OrgTreeProvider.class.getName() + ".";
private static final String LOAD_ORG_UNIT = DOT_CLASS + "loadOrgUnit";
private static final String LOAD_ORG_UNITS = DOT_CLASS + "loadOrgUnits";
private Component component;
private IModel<String> rootOid;
private SelectableBean<OrgType> root;
private List<SelectableBean<OrgType>> availableData;
public OrgTreeProvider(Component component, IModel<String> rootOid) {
this.component = component;
this.rootOid = rootOid;
}
public List<SelectableBean<OrgType>> getAvailableData() {
if (availableData == null){
availableData = new ArrayList<>();
}
return availableData;
}
private PageBase getPageBase() {
return WebComponentUtil.getPageBase(component);
}
private ModelService getModelService() {
return getPageBase().getModelService();
}
/*
* Wicket calls getChildren twice: in order to get actual children data, but also to know their number.
* We'll cache the children to avoid duplicate processing.
*/
private static final long EXPIRATION_AFTER_LAST_FETCH_OPERATION = 500L;
private long lastFetchOperation = 0;
private Map<String, List<SelectableBean<OrgType>>> childrenCache = new HashMap<>(); // key is the node OID
@Override
public Iterator<? extends SelectableBean<OrgType>> getChildren(SelectableBean<OrgType> node) {
LOGGER.debug("Getting children for {}", node.getValue());
String nodeOid = node.getValue().getOid();
List<SelectableBean<OrgType>> children;
long currentTime = System.currentTimeMillis();
if (currentTime > lastFetchOperation + EXPIRATION_AFTER_LAST_FETCH_OPERATION) {
childrenCache.clear();
}
if (childrenCache.containsKey(nodeOid)) {
LOGGER.debug("Using cached children for {}", node.getValue());
children = childrenCache.get(nodeOid);
} else {
LOGGER.debug("Loading fresh children for {}", node.getValue());
OperationResult result = new OperationResult(LOAD_ORG_UNITS);
try {
ObjectQuery query = QueryBuilder.queryFor(ObjectType.class, getPageBase().getPrismContext())
.isDirectChildOf(nodeOid)
.asc(ObjectType.F_NAME)
.build();
Task task = getPageBase().createSimpleTask(LOAD_ORG_UNITS);
List<PrismObject<OrgType>> orgs = getModelService().searchObjects(OrgType.class, query, null, task, result);
LOGGER.debug("Found {} sub-orgs.", orgs.size());
children = new ArrayList<>();
for (PrismObject<OrgType> org : orgs) {
children.add(createObjectWrapper(node, org));
}
childrenCache.put(nodeOid, children);
} catch (CommonException|RuntimeException ex) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load children", ex);
result.recordFatalError("Unable to load children for unit", ex);
children = new ArrayList<>();
} finally {
result.computeStatus();
}
if (WebComponentUtil.showResultInPage(result)) {
getPageBase().showResult(result);
throw new RestartResponseException(PageOrgTree.class);
}
getAvailableData().addAll(children);
}
LOGGER.debug("Finished getting children.");
lastFetchOperation = System.currentTimeMillis();
return children.iterator();
}
private SelectableBean<OrgType> createObjectWrapper(SelectableBean<OrgType> parent, PrismObject<OrgType> unit) {
if (unit == null) {
return null;
}
//todo relation [lazyman]
OrgType org = unit.asObjectable();
if (parent != null) {
org.getParentOrg().clear();
org.getParentOrg().add(parent.getValue());
}
SelectableBean<OrgType> orgDto = new SelectableBean<>(org);
orgDto.getMenuItems().addAll(createInlineMenuItems(orgDto.getValue()));
return orgDto;
}
protected List<InlineMenuItem> createInlineMenuItems(OrgType org){
return null;
}
@Override
public Iterator<SelectableBean<OrgType>> getRoots() {
OperationResult result = null;
if (root == null) {
Task task = getPageBase().createSimpleTask(LOAD_ORG_UNIT);
result = task.getResult();
LOGGER.debug("Getting roots for: " + rootOid.getObject());
PrismObject<OrgType> object = WebModelServiceUtils.loadObject(OrgType.class, rootOid.getObject(),
WebModelServiceUtils.createOptionsForParentOrgRefs(), getPageBase(), task, result);
result.computeStatus();
root = createObjectWrapper(null, object);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("\n{}", result.debugDump());
LOGGER.debug("Finished roots loading.");
}
}
if (WebComponentUtil.showResultInPage(result)) {
getPageBase().showResult(result);
}
List<SelectableBean<OrgType>> list = new ArrayList<>();
if (root != null) {
list.add(root);
if (!getAvailableData().contains(root)){
getAvailableData().add(root);
}
}
return list.iterator();
}
@Override
public boolean hasChildren(SelectableBean<OrgType> node) {
return true;
}
@Override
public IModel<SelectableBean<OrgType>> model(SelectableBean<OrgType> object) {
return new Model<>(object);
}
public List<OrgType> getSelectedObjects(){
List<OrgType> selectedOrgs = new ArrayList<>();
for (SelectableBean<OrgType> selected : getAvailableData()){
if (selected.isSelected() && selected.getValue() != null) {
selectedOrgs.add(selected.getValue());
}
}
return selectedOrgs;
}
}
|
MID-4672 Org. tree sorting/ordering
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java
|
MID-4672 Org. tree sorting/ordering
|
|
Java
|
apache-2.0
|
e5e2c3340c05bd708ed2814917df38d01b65f34b
| 0
|
VisuFlow/visuflow-plugin
|
package de.unipaderborn.visuflow.ui.view;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import de.unipaderborn.visuflow.model.DataModel;
import de.unipaderborn.visuflow.model.VFClass;
import de.unipaderborn.visuflow.model.VFMethod;
import de.unipaderborn.visuflow.model.VFNode;
import de.unipaderborn.visuflow.model.VFUnit;
import de.unipaderborn.visuflow.util.ServiceUtil;
import soot.SootMethod;
import soot.jimple.internal.JAddExpr;
import soot.jimple.internal.JAssignStmt;
import soot.jimple.internal.JIdentityStmt;
import soot.jimple.internal.JInvokeStmt;
import soot.jimple.internal.JReturnStmt;
public class UnitView extends ViewPart implements EventHandler {
DataModel dataModel;
static Tree tree;
Combo classCombo, methodCombo;
Button checkBox;
String classSelection, methodSelection;
private List<VFUnit> listUnits;
private List<VFNode> nodeList;
GridData gridUnitTable;
class ViewLabelProvider extends LabelProvider implements ILabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
@Override
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(3, true);
parent.setLayout(layout);
GridData gridVFClass = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridVFClass.widthHint = SWT.DEFAULT;
gridVFClass.heightHint = SWT.DEFAULT;
classCombo = new Combo(parent, SWT.DROP_DOWN);
classCombo.setLayout(layout);
classCombo.setLayoutData(gridVFClass);
GridData gridVFMethod = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridVFMethod.widthHint = SWT.DEFAULT;
gridVFMethod.heightHint = SWT.DEFAULT;
methodCombo = new Combo(parent, SWT.DROP_DOWN);
methodCombo.setLayout(layout);
methodCombo.setLayoutData(gridVFMethod);
GridData gridCheck = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridCheck.widthHint = SWT.DEFAULT;
gridCheck.heightHint = SWT.DEFAULT;
checkBox = new Button(parent, SWT.CHECK);
checkBox.setText("Sync with Graph View");
checkBox.setLayoutData(gridCheck);
gridUnitTable = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
gridUnitTable.widthHint = SWT.DEFAULT;
gridUnitTable.heightHint = SWT.DEFAULT;
tree = new Tree(parent, SWT.FILL | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BACKGROUND | SWT.MULTI | SWT.BACKGROUND);
tree.setHeaderVisible(true);
tree.setLayout(layout);
tree.setLayoutData(gridUnitTable);
// methodCombo.select(0);
classCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
String selectedClass = classCombo.getText();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(selectedClass)) {
methodCombo.removeAll();
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
}
}
methodCombo.select(0);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
methodCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
String selectMethod = methodCombo.getText();
String selectedClass = classCombo.getText();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(selectedClass)) {
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
if (vfmethod.getSootMethod().getDeclaration().toString().equals(selectMethod)) {
tree.removeAll();
listUnits = vfmethod.getUnits();
populateUnits(listUnits);
break;
}
break;
}
}
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
checkBox.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!listUnits.isEmpty()) {
tree.removeAll();
populateUnits(listUnits);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_MODEL_CHANGED);
ServiceUtil.registerService(EventHandler.class, this, properties);
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_SELECTION);
ServiceUtil.registerService(EventHandler.class, this, properties);
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_FILTER_GRAPH);
ServiceUtil.registerService(EventHandler.class, this, properties);
}
@Override
public void setFocus() {
}
public static void populateUnits(List<VFUnit> listUnits) {
for (VFUnit unit : listUnits) {
TreeItem treeItem = new TreeItem(tree, SWT.NONE | SWT.BORDER);
treeItem.setText(unit.getUnit().toString());
int stType = 0;
if (unit.getUnit() instanceof JAssignStmt)
stType = 1;
else if (unit.getUnit() instanceof JAddExpr)
stType = 2;
else if (unit.getUnit() instanceof JInvokeStmt)
stType = 3;
else if (unit.getUnit() instanceof JReturnStmt)
stType = 4;
else if (unit.getUnit() instanceof JIdentityStmt)
stType = 5;
switch (stType) {
case 1:
JAssignStmt jassStmt = (JAssignStmt) unit.getUnit();
TreeItem treeUnitAssType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitAssType.setText(new String[] { "Unit Type : " + jassStmt.getClass().toString() });
TreeItem treeLeft = new TreeItem(treeUnitAssType, SWT.LEFT | SWT.BORDER);
treeLeft.setText(new String[] { "Left" });
TreeItem treeLeftValue = new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
treeLeftValue.setText(new String[] { "Value : " + jassStmt.leftBox.getValue().toString() });
TreeItem treeLeftClass = new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
treeLeftClass.setText(new String[] { "Class : " + jassStmt.leftBox.getValue().getClass().toString() });
TreeItem treeRight = new TreeItem(treeUnitAssType, SWT.LEFT | SWT.BORDER);
treeRight.setText(new String[] { "Right" });
TreeItem treeRightValue = new TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
treeRightValue.setText(new String[] { "Value : " + jassStmt.rightBox.getValue().toString() });
TreeItem treeRightClass = new TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
treeRightClass.setText(new String[] { "Class : " + jassStmt.rightBox.getValue().getClass().toString() });
break;
case 2:
JAddExpr jaddStmt = (JAddExpr) unit.getUnit();
TreeItem treeUnitAddType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitAddType.setText(new String[] { "Unit Type : " + jaddStmt.getClass().toString() });
TreeItem treeOp1 = new TreeItem(treeUnitAddType, SWT.LEFT | SWT.BORDER);
treeOp1.setText(new String[] { "Operator 1" });
TreeItem treeOp1Value = new TreeItem(treeOp1, SWT.LEFT | SWT.BORDER);
treeOp1Value.setText(new String[] { "Value : " + jaddStmt.getOp1().toString() });
TreeItem treeOp1Class = new TreeItem(treeOp1, SWT.LEFT | SWT.BORDER);
treeOp1Class.setText(new String[] { "Class : " + jaddStmt.getOp1().getClass().toString() });
TreeItem treeOp2 = new TreeItem(treeUnitAddType, SWT.LEFT | SWT.BORDER);
treeOp2.setText(new String[] { "Operator 2" });
TreeItem treeOp2Value = new TreeItem(treeOp2, SWT.LEFT | SWT.BORDER);
treeOp2Value.setText(new String[] { "Value : " + jaddStmt.getOp1().toString() });
TreeItem treeOp2Class = new TreeItem(treeOp2, SWT.LEFT | SWT.BORDER);
treeOp2Class.setText(new String[] { "Class : " + jaddStmt.getOp1().getClass().toString() });
break;
case 3:
JInvokeStmt jinvokestmt = (JInvokeStmt) unit.getUnit();
TreeItem treeUnitInvType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitInvType.setText(new String[] { "Unit Type : " + jinvokestmt.getClass().toString() });
TreeItem treeInvokeExp = new TreeItem(treeUnitInvType, SWT.LEFT | SWT.BORDER);
treeInvokeExp.setText(new String[] { "Invoke Expression : " + jinvokestmt.getInvokeExpr() });
TreeItem treeMethodClass = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodClass.setText(new String[] { "Method Declaring Class : " + jinvokestmt.getInvokeExpr().getMethod().getDeclaringClass() });
TreeItem treeMethodSig = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodSig.setText(new String[] { "Method Signature : " + jinvokestmt.getInvokeExpr().getMethod().getDeclaration() });
int argCount = jinvokestmt.getInvokeExpr().getMethod().getParameterCount();
TreeItem treeArgcount = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeArgcount.setText(new String[] { "Parameter Count : " + argCount });
if (argCount > 0) {
for (int i = 0; i < argCount; i++) {
TreeItem treeArg = new TreeItem(treeArgcount, SWT.LEFT | SWT.BORDER);
treeArg.setText(new String[] { "Parameter " + (i + 1) + " type : " + jinvokestmt.getInvokeExpr().getMethod().getParameterType(i) });
}
}
TreeItem treeFieldref = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
if (jinvokestmt.containsFieldRef())
treeFieldref.setText(new String[] { "Field Reference : " + jinvokestmt.getFieldRef() });
else
treeFieldref.setText(new String[] { "Field Reference : Null" });
TreeItem treeMethodReturnType = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodReturnType.setText(new String[] { "Method return Type : " + jinvokestmt.getInvokeExpr().getMethod().getReturnType() });
break;
case 4:
JReturnStmt jretStmt = (JReturnStmt) unit.getUnit();
TreeItem treeUnitRetType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitRetType.setText(new String[] { "Unit Type : " + jretStmt.getClass().toString() });
if (jretStmt.containsInvokeExpr()) {
TreeItem treeReturnInv = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnInv.setText(new String[] { "Return Expression : " + jretStmt.getInvokeExpr() });
}
TreeItem treeReturnValue = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnValue.setText(new String[] { "Return Value : " + jretStmt.getOp() });
TreeItem treeReturnType = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnType.setText(new String[] { "Return Value : " + jretStmt.getOp().getType() });
break;
case 5:
JIdentityStmt jidenStmt = (JIdentityStmt) unit.getUnit();
TreeItem treeUnitIdenType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitIdenType.setText(new String[] { "Unit Type : " + jidenStmt.getClass().toString() });
TreeItem treeIdenLeft = new TreeItem(treeUnitIdenType, SWT.LEFT | SWT.BORDER);
treeIdenLeft.setText(new String[] { "Left" });
TreeItem treeIdenLeftValue = new TreeItem(treeIdenLeft, SWT.LEFT | SWT.BORDER);
treeIdenLeftValue.setText(new String[] { "Value : " + jidenStmt.leftBox.getValue().toString() });
TreeItem treeIdenLeftClass = new TreeItem(treeIdenLeft, SWT.LEFT | SWT.BORDER);
treeIdenLeftClass.setText(new String[] { "Class : " + jidenStmt.leftBox.getValue().getClass().toString() });
TreeItem treeIdenRight = new TreeItem(treeUnitIdenType, SWT.LEFT | SWT.BORDER);
treeIdenRight.setText(new String[] { "Right" });
TreeItem treeIdenRightValue = new TreeItem(treeIdenRight, SWT.LEFT | SWT.BORDER);
treeIdenRightValue.setText(new String[] { "Value : " + jidenStmt.rightBox.getValue().toString() });
TreeItem treeIdenRightClass = new TreeItem(treeIdenRight, SWT.LEFT | SWT.BORDER);
treeIdenRightClass.setText(new String[] { "Class : " + jidenStmt.rightBox.getValue().getClass().toString() });
break;
case 0:
break;
}
}
}
@Override
public void handleEvent(Event event) {
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_SELECTION)) {
getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
listUnits = (List<VFUnit>) event.getProperty("selectedMethodUnits");
if (checkBox.getSelection()) {
tree.removeAll();
populateUnits(listUnits);
}
}
});
}
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_MODEL_CHANGED)) {
getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
dataModel = ServiceUtil.getService(DataModel.class);
for (VFClass vfclass : dataModel.listClasses()) {
classCombo.add(vfclass.getSootClass().getName());
}
classCombo.select(0);
classSelection = classCombo.getText().trim();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(classSelection)) {
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
}
}
methodCombo.select(0);
String selectMethod = methodCombo.getText();
String selectedClass = classCombo.getText();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(selectedClass)) {
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
if (vfmethod.getSootMethod().getDeclaration().toString().equals(selectMethod)) {
tree.removeAll();
listUnits = vfmethod.getUnits();
populateUnits(listUnits);
break;
}
break;
}
}
}
}
});
}
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_FILTER_GRAPH)) {
getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
nodeList = (List<VFNode>) event.getProperty("nodesToFilter");
VFClass selectedClass = nodeList.get(0).getVFUnit().getVfMethod().getVfClass();
VFMethod selectedMethod = nodeList.get(0).getVFUnit().getVfMethod();
int i = -1;
for (String classString : classCombo.getItems()) {
i++;
if (classString.equals(selectedClass.getSootClass().getName().toString())) {
classCombo.select(i);
methodCombo.removeAll();
for (VFMethod vfmethod : dataModel.listMethods(selectedClass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
break;
}
}
int j = -1;
for (String methodString : methodCombo.getItems()) {
j++;
if (methodString.equals(selectedMethod.getSootMethod().getDeclaration().toString())) {
methodCombo.select(j);
tree.removeAll();
populateUnits(selectedMethod.getUnits());
break;
}
}
for (TreeItem treeItem : tree.getItems()) {
if (treeItem.getText().equals(nodeList.get(0).getUnit().toString())) {
tree.setSelection(treeItem);
break;
}
}
}
});
}
}
public static Display getDisplay() {
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
return display;
}
}
|
src/de/unipaderborn/visuflow/ui/view/UnitView.java
|
package de.unipaderborn.visuflow.ui.view;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import de.unipaderborn.visuflow.model.DataModel;
import de.unipaderborn.visuflow.model.VFClass;
import de.unipaderborn.visuflow.model.VFMethod;
import de.unipaderborn.visuflow.model.VFNode;
import de.unipaderborn.visuflow.model.VFUnit;
import de.unipaderborn.visuflow.util.ServiceUtil;
import soot.SootMethod;
import soot.jimple.internal.JAddExpr;
import soot.jimple.internal.JAssignStmt;
import soot.jimple.internal.JIdentityStmt;
import soot.jimple.internal.JInvokeStmt;
import soot.jimple.internal.JReturnStmt;
public class UnitView extends ViewPart implements EventHandler {
DataModel dataModel;
static Tree tree;
Combo classCombo, methodCombo;
Button checkBox;
String classSelection, methodSelection;
private List<VFUnit> listUnits;
private List<VFNode> nodeList;
GridData gridUnitTable;
class ViewLabelProvider extends LabelProvider implements ILabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
@Override
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(3, true);
parent.setLayout(layout);
GridData gridVFClass = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridVFClass.widthHint = SWT.DEFAULT;
gridVFClass.heightHint = SWT.DEFAULT;
classCombo = new Combo(parent, SWT.DROP_DOWN);
classCombo.setLayout(layout);
classCombo.setLayoutData(gridVFClass);
GridData gridVFMethod = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridVFMethod.widthHint = SWT.DEFAULT;
gridVFMethod.heightHint = SWT.DEFAULT;
methodCombo = new Combo(parent, SWT.DROP_DOWN);
methodCombo.setLayout(layout);
methodCombo.setLayoutData(gridVFMethod);
GridData gridCheck = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gridCheck.widthHint = SWT.DEFAULT;
gridCheck.heightHint = SWT.DEFAULT;
checkBox = new Button(parent, SWT.CHECK);
checkBox.setText("Sync with Graph View");
checkBox.setLayoutData(gridCheck);
gridUnitTable = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
gridUnitTable.widthHint = SWT.DEFAULT;
gridUnitTable.heightHint = SWT.DEFAULT;
tree = new Tree(parent, SWT.FILL | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BACKGROUND
| SWT.MULTI | SWT.BACKGROUND);
tree.setHeaderVisible(true);
tree.setLayout(layout);
tree.setLayoutData(gridUnitTable);
// methodCombo.select(0);
classCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
String selectedClass = classCombo.getText();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(selectedClass)) {
methodCombo.removeAll();
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
}
}
methodCombo.select(0);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
methodCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
String selectMethod = methodCombo.getText();
String selectedClass = classCombo.getText();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(selectedClass)) {
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
if (vfmethod.getSootMethod().getDeclaration().toString().equals(selectMethod)) {
tree.removeAll();
listUnits = vfmethod.getUnits();
populateUnits(listUnits);
/*
* for (VFUnit unit : listUnits) { TreeItem
* treeItem= new TreeItem(tree, SWT.NONE |
* SWT.BORDER);
* treeItem.setText(unit.getUnit().toString());
* if (unit.getUnit() instanceof JAssignStmt) {
* JAssignStmt stmt =
* (JAssignStmt)unit.getUnit(); TreeItem
* treeLeft = new TreeItem(treeItem, SWT.LEFT |
* SWT.BORDER); treeLeft.setText(new String[]
* {"Left"}); TreeItem treeLeftValue= new
* TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
* treeLeftValue.setText(new String[]
* {"Value : "+stmt.leftBox.getValue().toString(
* )}); TreeItem treeLeftClass= new
* TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
* treeLeftClass.setText(new String[]
* {"Class : "+stmt.leftBox.getValue().getClass(
* ).toString()});
*
* TreeItem treeRight = new TreeItem(treeItem,
* SWT.LEFT | SWT.BORDER); treeRight.setText(new
* String[] {"Right"}); TreeItem treeRightValue=
* new TreeItem(treeRight, SWT.LEFT |
* SWT.BORDER); treeRightValue.setText(new
* String[]
* {"Value : "+stmt.leftBox.getValue().toString(
* )}); TreeItem treeRightClass= new
* TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
* treeRightClass.setText(new String[]
* {"Class : "+stmt.leftBox.getValue().getClass(
* ).toString()}); } }
*/
}
}
}
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
checkBox.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!listUnits.isEmpty()) {
tree.removeAll();
populateUnits(listUnits);
/*
* for (VFUnit unit : listUnits) { TreeItem treeItem= new
* TreeItem(tree, SWT.NONE | SWT.BORDER);
* treeItem.setText(unit.getUnit().toString()); if
* (unit.getUnit() instanceof JAssignStmt) { JAssignStmt
* stmt = (JAssignStmt)unit.getUnit(); TreeItem treeLeft =
* new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
* treeLeft.setText(new String[] {"Left"}); TreeItem
* treeLeftValue= new TreeItem(treeLeft, SWT.LEFT |
* SWT.BORDER); treeLeftValue.setText(new String[]
* {"Value : "+stmt.leftBox.getValue().toString()});
* TreeItem treeLeftClass= new TreeItem(treeLeft, SWT.LEFT |
* SWT.BORDER); treeLeftClass.setText(new String[]
* {"Class : "+stmt.leftBox.getValue().getClass().toString()
* });
*
* TreeItem treeRight = new TreeItem(treeItem, SWT.LEFT |
* SWT.BORDER); treeRight.setText(new String[] {"Right"});
* TreeItem treeRightValue= new TreeItem(treeRight, SWT.LEFT
* | SWT.BORDER); treeRightValue.setText(new String[]
* {"Value : "+stmt.leftBox.getValue().toString()});
* TreeItem treeRightClass= new TreeItem(treeRight, SWT.LEFT
* | SWT.BORDER); treeRightClass.setText(new String[]
* {"Class : "+stmt.leftBox.getValue().getClass().toString()
* }); } }
*/
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_MODEL_CHANGED);
ServiceUtil.registerService(EventHandler.class, this, properties);
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_SELECTION);
ServiceUtil.registerService(EventHandler.class, this, properties);
properties.put(EventConstants.EVENT_TOPIC, DataModel.EA_TOPIC_DATA_FILTER_GRAPH);
ServiceUtil.registerService(EventHandler.class, this, properties);
}
@Override
public void setFocus() {
}
public static void populateUnits(List<VFUnit> listUnits) {
for (VFUnit unit : listUnits) {
TreeItem treeItem = new TreeItem(tree, SWT.NONE | SWT.BORDER);
treeItem.setText(unit.getUnit().toString());
int stType = 0;
if (unit.getUnit() instanceof JAssignStmt)
stType = 1;
else if (unit.getUnit() instanceof JAddExpr)
stType = 2;
else if (unit.getUnit() instanceof JInvokeStmt)
stType = 3;
else if (unit.getUnit() instanceof JReturnStmt)
stType = 4;
else if (unit.getUnit() instanceof JIdentityStmt)
stType = 5;
switch (stType) {
case 1:
JAssignStmt jassStmt = (JAssignStmt) unit.getUnit();
TreeItem treeUnitAssType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitAssType.setText(new String[] { "Unit Type : " + jassStmt.getClass().toString() });
TreeItem treeLeft = new TreeItem(treeUnitAssType, SWT.LEFT | SWT.BORDER);
treeLeft.setText(new String[] { "Left" });
TreeItem treeLeftValue = new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
treeLeftValue.setText(new String[] { "Value : " + jassStmt.leftBox.getValue().toString() });
TreeItem treeLeftClass = new TreeItem(treeLeft, SWT.LEFT | SWT.BORDER);
treeLeftClass.setText(new String[] { "Class : " + jassStmt.leftBox.getValue().getClass().toString() });
TreeItem treeRight = new TreeItem(treeUnitAssType, SWT.LEFT | SWT.BORDER);
treeRight.setText(new String[] { "Right" });
TreeItem treeRightValue = new TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
treeRightValue.setText(new String[] { "Value : " + jassStmt.rightBox.getValue().toString() });
TreeItem treeRightClass = new TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
treeRightClass
.setText(new String[] { "Class : " + jassStmt.rightBox.getValue().getClass().toString() });
break;
case 2:
JAddExpr jaddStmt = (JAddExpr) unit.getUnit();
TreeItem treeUnitAddType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitAddType.setText(new String[] { "Unit Type : " + jaddStmt.getClass().toString() });
TreeItem treeOp1 = new TreeItem(treeUnitAddType, SWT.LEFT | SWT.BORDER);
treeOp1.setText(new String[] { "Operator 1" });
TreeItem treeOp1Value = new TreeItem(treeOp1, SWT.LEFT | SWT.BORDER);
treeOp1Value.setText(new String[] { "Value : " + jaddStmt.getOp1().toString() });
TreeItem treeOp1Class = new TreeItem(treeOp1, SWT.LEFT | SWT.BORDER);
treeOp1Class.setText(new String[] { "Class : " + jaddStmt.getOp1().getClass().toString() });
TreeItem treeOp2 = new TreeItem(treeUnitAddType, SWT.LEFT | SWT.BORDER);
treeOp2.setText(new String[] { "Operator 2" });
TreeItem treeOp2Value = new TreeItem(treeOp2, SWT.LEFT | SWT.BORDER);
treeOp2Value.setText(new String[] { "Value : " + jaddStmt.getOp1().toString() });
TreeItem treeOp2Class = new TreeItem(treeOp2, SWT.LEFT | SWT.BORDER);
treeOp2Class.setText(new String[] { "Class : " + jaddStmt.getOp1().getClass().toString() });
break;
case 3:
JInvokeStmt jinvokestmt = (JInvokeStmt) unit.getUnit();
TreeItem treeUnitInvType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitInvType.setText(new String[] { "Unit Type : " + jinvokestmt.getClass().toString() });
TreeItem treeInvokeExp = new TreeItem(treeUnitInvType, SWT.LEFT | SWT.BORDER);
treeInvokeExp.setText(new String[] { "Invoke Expression : " + jinvokestmt.getInvokeExpr() });
TreeItem treeMethodClass = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodClass.setText(new String[] {
"Method Declaring Class : " + jinvokestmt.getInvokeExpr().getMethod().getDeclaringClass() });
TreeItem treeMethodSig = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodSig.setText(new String[] {
"Method Signature : " + jinvokestmt.getInvokeExpr().getMethod().getDeclaration() });
int argCount = jinvokestmt.getInvokeExpr().getMethod().getParameterCount();
TreeItem treeArgcount = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeArgcount.setText(new String[] { "Parameter Count : " + argCount });
if (argCount > 0) {
for (int i = 0; i < argCount; i++) {
TreeItem treeArg = new TreeItem(treeArgcount, SWT.LEFT | SWT.BORDER);
treeArg.setText(new String[] { "Parameter " + (i + 1) + " type : "
+ jinvokestmt.getInvokeExpr().getMethod().getParameterType(i) });
}
}
TreeItem treeFieldref = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
if (jinvokestmt.containsFieldRef())
treeFieldref.setText(new String[] { "Field Reference : " + jinvokestmt.getFieldRef() });
else
treeFieldref.setText(new String[] { "Field Reference : Null" });
TreeItem treeMethodReturnType = new TreeItem(treeInvokeExp, SWT.LEFT | SWT.BORDER);
treeMethodReturnType.setText(new String[] {
"Method return Type : " + jinvokestmt.getInvokeExpr().getMethod().getReturnType() });
break;
case 4:
JReturnStmt jretStmt = (JReturnStmt) unit.getUnit();
TreeItem treeUnitRetType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitRetType.setText(new String[] { "Unit Type : " + jretStmt.getClass().toString() });
if (jretStmt.containsInvokeExpr()) {
TreeItem treeReturnInv = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnInv.setText(new String[] { "Return Expression : " + jretStmt.getInvokeExpr() });
}
TreeItem treeReturnValue = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnValue.setText(new String[] { "Return Value : " + jretStmt.getOp() });
TreeItem treeReturnType = new TreeItem(treeUnitRetType, SWT.LEFT | SWT.BORDER);
treeReturnType.setText(new String[] { "Return Value : " + jretStmt.getOp().getType() });
break;
case 5:
JIdentityStmt jidenStmt = (JIdentityStmt) unit.getUnit();
TreeItem treeUnitIdenType = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
treeUnitIdenType.setText(new String[] { "Unit Type : " + jidenStmt.getClass().toString() });
TreeItem treeIdenLeft = new TreeItem(treeUnitIdenType, SWT.LEFT | SWT.BORDER);
treeIdenLeft.setText(new String[] { "Left" });
TreeItem treeIdenLeftValue = new TreeItem(treeIdenLeft, SWT.LEFT | SWT.BORDER);
treeIdenLeftValue.setText(new String[] { "Value : " + jidenStmt.leftBox.getValue().toString() });
TreeItem treeIdenLeftClass = new TreeItem(treeIdenLeft, SWT.LEFT | SWT.BORDER);
treeIdenLeftClass.setText(new String[] { "Class : " + jidenStmt.leftBox.getValue().getClass().toString() });
TreeItem treeIdenRight = new TreeItem(treeUnitIdenType, SWT.LEFT | SWT.BORDER);
treeIdenRight.setText(new String[] { "Right" });
TreeItem treeIdenRightValue = new TreeItem(treeIdenRight, SWT.LEFT | SWT.BORDER);
treeIdenRightValue.setText(new String[] { "Value : " + jidenStmt.rightBox.getValue().toString() });
TreeItem treeIdenRightClass = new TreeItem(treeIdenRight, SWT.LEFT | SWT.BORDER);
treeIdenRightClass
.setText(new String[] { "Class : " + jidenStmt.rightBox.getValue().getClass().toString() });
break;
case 0:
break;
}
}
}
@Override
public void handleEvent(Event event) {
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_SELECTION)) {
getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
listUnits = (List<VFUnit>) event.getProperty("selectedMethodUnits");
if (checkBox.getSelection()) {
tree.removeAll();
populateUnits(listUnits);
/*
* for (VFUnit unit : listUnits) { TreeItem treeItem=
* new TreeItem(tree, SWT.NONE | SWT.BORDER);
* treeItem.setText(unit.getUnit().toString()); if
* (unit.getUnit() instanceof JAssignStmt) { JAssignStmt
* stmt = (JAssignStmt)unit.getUnit(); TreeItem treeLeft
* = new TreeItem(treeItem, SWT.LEFT | SWT.BORDER);
* treeLeft.setText(new String[] {"Left"}); TreeItem
* treeLeftValue= new TreeItem(treeLeft, SWT.LEFT |
* SWT.BORDER); treeLeftValue.setText(new String[]
* {"Value : "+stmt.leftBox.getValue().toString()});
* TreeItem treeLeftClass= new TreeItem(treeLeft,
* SWT.LEFT | SWT.BORDER); treeLeftClass.setText(new
* String[]
* {"Class : "+stmt.leftBox.getValue().getClass().
* toString()});
*
* TreeItem treeRight = new TreeItem(treeItem, SWT.LEFT
* | SWT.BORDER); treeRight.setText(new String[]
* {"Right"}); TreeItem treeRightValue= new
* TreeItem(treeRight, SWT.LEFT | SWT.BORDER);
* treeRightValue.setText(new String[]
* {"Value : "+stmt.leftBox.getValue().toString()});
* TreeItem treeRightClass= new TreeItem(treeRight,
* SWT.LEFT | SWT.BORDER); treeRightClass.setText(new
* String[]
* {"Class : "+stmt.leftBox.getValue().getClass().
* toString()}); } }
*/
}
}
});
}
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_MODEL_CHANGED)) {
getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
dataModel = ServiceUtil.getService(DataModel.class);
for (VFClass vfclass : dataModel.listClasses()) {
classCombo.add(vfclass.getSootClass().getName());
}
classCombo.select(0);
classSelection = classCombo.getText().trim();
for (VFClass vfclass : dataModel.listClasses()) {
if (vfclass.getSootClass().getName().toString().equals(classSelection)) {
for (VFMethod vfmethod : dataModel.listMethods(vfclass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
}
}
methodCombo.select(0);
}
});
}
if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_FILTER_GRAPH)) {
getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
nodeList = (List<VFNode>) event.getProperty("nodesToFilter");
VFClass selectedClass = nodeList.get(0).getVFUnit().getVfMethod().getVfClass();
VFMethod selectedMethod = nodeList.get(0).getVFUnit().getVfMethod();
int i = -1;
for (String classString : classCombo.getItems()) {
i++;
if(classString.equals(selectedClass.getSootClass().getName().toString()))
{
classCombo.select(i);
methodCombo.removeAll();
for (VFMethod vfmethod : dataModel.listMethods(selectedClass)) {
methodCombo.add(vfmethod.getSootMethod().getDeclaration());
}
break;
}
}
int j = -1;
for (String methodString : methodCombo.getItems()) {
j++;
if(methodString.equals(selectedMethod.getSootMethod().getDeclaration().toString())) {
methodCombo.select(j);
tree.removeAll();
populateUnits(selectedMethod.getUnits());
break;
}
}
for (TreeItem treeItem : tree.getItems()) {
if(treeItem.getText().equals(nodeList.get(0).getUnit().toString())) {
treeItem.setChecked(true);
//treeItem.setBackground(new Color(getDisplay(), new RGB(50, 100, 300)));
break;
}
}
}
});
}
}
// TODO move this to a utility class ?!?
public static Display getDisplay() {
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
return display;
}
}
|
Updated the Unit View to respond to all events
|
src/de/unipaderborn/visuflow/ui/view/UnitView.java
|
Updated the Unit View to respond to all events
|
|
Java
|
apache-2.0
|
922924690c756428b326dcd664d1bacdcd36b046
| 0
|
rikles/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,anzhdanov/seeding-realistic-concurrency-bugs,anzhdanov/seeding-realistic-concurrency-bugs,mureinik/commons-lang,rikles/commons-lang,rikles/commons-lang,mureinik/commons-lang,mureinik/commons-lang
|
/*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang;
/**
* <p>Operations on <code>CharSet</code>s.</p>
*
* <p>This class handles <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.</p>
*
* @see CharSet
* @author <a href="bayard@generationjava.com">Henri Yandell</a>
* @author Stephen Colebourne
* @author Phil Steitz
* @author Gary Gregory
* @since 1.0
* @version $Id$
*/
public class CharSetUtils {
/**
* <p>CharSetUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>CharSetUtils.evaluateSet(null);</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public CharSetUtils() {
}
// Factory
//-----------------------------------------------------------------------
/**
* <p>Creates a <code>CharSet</code> instance which allows a certain amount of
* set logic to be performed.</p>
* <p>The syntax is:</p>
* <ul>
* <li>"aeio" which implies 'a','e',..</li>
* <li>"^e" implies not e.</li>
* <li>"ej-m" implies e,j->m. e,j,k,l,m.</li>
* </ul>
*
* <pre>
* CharSetUtils.evaluateSet(null) = null
* CharSetUtils.evaluateSet([]) = CharSet matching nothing
* CharSetUtils.evaluateSet(["a-e"]) = CharSet matching a,b,c,d,e
* </pre>
*
* @param set the set, may be null
* @return a CharSet instance, <code>null</code> if null input
* @deprecated Use {@link CharSet#getInstance(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static CharSet evaluateSet(String[] set) {
if (set == null) {
return null;
}
return new CharSet(set);
}
// Squeeze
//-----------------------------------------------------------------------
/**
* <p>Squeezes any repetitions of a character that is mentioned in the
* supplied set.</p>
*
* <pre>
* CharSetUtils.squeeze(null, *) = null
* CharSetUtils.squeeze("", *) = ""
* CharSetUtils.squeeze(*, null) = *
* CharSetUtils.squeeze(*, "") = *
* CharSetUtils.squeeze("hello", "k-p") = "helo"
* CharSetUtils.squeeze("hello", "a-e") = "hello"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String squeeze(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
strs[0] = set;
return squeeze(str, strs);
}
/**
* <p>Squeezes any repetitions of a character that is mentioned in the
* supplied set.</p>
*
* <p>An example is:</p>
* <ul>
* <li>squeeze("hello", {"el"}) => "helo"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String squeeze(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
CharSet chars = evaluateSet(set);
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
char lastChar = ' ';
char ch = ' ';
for (int i = 0; i < sz; i++) {
ch = chrs[i];
if (chars.contains(ch)) {
if ((ch == lastChar) && (i != 0)) {
continue;
}
}
buffer.append(ch);
lastChar = ch;
}
return buffer.toString();
}
// Count
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and returns the number of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.count(null, *) = 0
* CharSetUtils.count("", *) = 0
* CharSetUtils.count(*, null) = 0
* CharSetUtils.count(*, "") = 0
* CharSetUtils.count("hello", "k-p") = 3
* CharSetUtils.count("hello", "a-e") = 1
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to count characters in, may be null
* @param set String set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return 0;
}
String[] strs = new String[1];
strs[0] = set;
return count(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and returns the number of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>count("hello", {"c-f", "o"}) returns 2.</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to count characters in, may be null
* @param set String[] set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return 0;
}
CharSet chars = evaluateSet(set);
int count = 0;
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; i<sz; i++) {
if(chars.contains(chrs[i])) {
count++;
}
}
return count;
}
// Keep
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and keeps any of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.keep(null, *) = null
* CharSetUtils.keep("", *) = ""
* CharSetUtils.keep(*, null) = ""
* CharSetUtils.keep(*, "") = ""
* CharSetUtils.keep("hello", "hl") = "hll"
* CharSetUtils.keep("hello", "le") = "ell"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String set of characters to keep, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String keep(String str, String set) {
if (str == null) {
return null;
}
if (str.length() == 0 || StringUtils.isEmpty(set)) {
return "";
}
String[] strs = new String[1];
strs[0] = set;
return keep(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and keeps any of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>keep("hello", {"c-f", "o"})
* returns "eo"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String[] set of characters to keep, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String keep(String str, String[] set) {
if (str == null) {
return null;
}
if (str.length() == 0 || ArrayUtils.isEmpty(set)) {
return "";
}
return modify(str, set, true);
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and deletes any of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.delete(null, *) = null
* CharSetUtils.delete("", *) = ""
* CharSetUtils.delete(*, null) = *
* CharSetUtils.delete(*, "") = *
* CharSetUtils.delete("hello", "hl") = "eo"
* CharSetUtils.delete("hello", "le") = "ho"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String set of characters to delete, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String delete(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
strs[0] = set;
return delete(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and deletes any of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>delete("hello", {"c-f", "o"}) returns
* "hll"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String[] set of characters to delete, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String delete(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
return modify(str, set, false);
}
//-----------------------------------------------------------------------
/**
* Implementation of delete and keep
*
* @param str String to modify characters within
* @param set String[] set of characters to modify
* @param expect whether to evaluate on match, or non-match
* @return modified String
*/
private static String modify(String str, String[] set, boolean expect) {
CharSet chars = evaluateSet(set);
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; i<sz; i++) {
if(chars.contains(chrs[i]) == expect) {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
// Translate
//-----------------------------------------------------------------------
/**
* <p>Translate characters in a String.
* This is a multi character search and replace routine.</p>
*
* <p>An example is:</p>
* <ul>
* <li>translate("hello", "ho", "jy")
* => jelly</li>
* </ul>
*
* <p>If the length of characters to search for is greater than the
* length of characters to replace, then the last character is
* used.</p>
*
* <pre>
* CharSetUtils.translate(null, *, *) = null
* CharSetUtils.translate("", *, *) = ""
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, must not be null
* @param replaceChars a set of characters to replace, must not be null or empty ("")
* @return translated String, <code>null</code> if null string input
* @throws NullPointerException if <code>searchChars</code> or <code>replaceChars</code>
* is <code>null</code>
* @throws ArrayIndexOutOfBoundsException if <code>replaceChars</code> is empty ("")
* @deprecated Use {@link StringUtils#replaceChars(String, String, String)}.
* Method will be removed in Commons Lang 3.0.
* NOTE: StringUtils#replaceChars behaves differently when 'searchChars' is longer
* than 'replaceChars'. CharSetUtils#translate will use the last char of the replacement
* string whereas StringUtils#replaceChars will delete
*/
public static String translate(String str, String searchChars, String replaceChars) {
if (StringUtils.isEmpty(str)) {
return str;
}
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
char[] withChrs = replaceChars.toCharArray();
int sz = chrs.length;
int withMax = replaceChars.length() - 1;
for(int i=0; i<sz; i++) {
int idx = searchChars.indexOf(chrs[i]);
if(idx != -1) {
if(idx > withMax) {
idx = withMax;
}
buffer.append(withChrs[idx]);
} else {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
}
|
src/java/org/apache/commons/lang/CharSetUtils.java
|
/*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang;
/**
* <p>Operations on <code>CharSet</code>s.</p>
*
* <p>This class handles <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.</p>
*
* @see CharSet
* @author <a href="bayard@generationjava.com">Henri Yandell</a>
* @author Stephen Colebourne
* @author Phil Steitz
* @author Gary Gregory
* @since 1.0
* @version $Id: CharSetUtils.java,v 1.33 2004/03/10 23:31:53 scolebourne Exp $
*/
public class CharSetUtils {
/**
* <p>CharSetUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>CharSetUtils.evaluateSet(null);</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public CharSetUtils() {
}
// Factory
//-----------------------------------------------------------------------
/**
* <p>Creates a <code>CharSet</code> instance which allows a certain amount of
* set logic to be performed.</p>
* <p>The syntax is:</p>
* <ul>
* <li>"aeio" which implies 'a','e',..</li>
* <li>"^e" implies not e.</li>
* <li>"ej-m" implies e,j->m. e,j,k,l,m.</li>
* </ul>
*
* <pre>
* CharSetUtils.evaluateSet(null) = null
* CharSetUtils.evaluateSet([]) = CharSet matching nothing
* CharSetUtils.evaluateSet(["a-e"]) = CharSet matching a,b,c,d,e
* </pre>
*
* @param set the set, may be null
* @return a CharSet instance, <code>null</code> if null input
* @deprecated Use {@link CharSet#getInstance(String)}.
* Method will be removed in Commons Lang 3.0.
*/
public static CharSet evaluateSet(String[] set) {
if (set == null) {
return null;
}
return new CharSet(set);
}
// Squeeze
//-----------------------------------------------------------------------
/**
* <p>Squeezes any repetitions of a character that is mentioned in the
* supplied set.</p>
*
* <pre>
* CharSetUtils.squeeze(null, *) = null
* CharSetUtils.squeeze("", *) = ""
* CharSetUtils.squeeze(*, null) = *
* CharSetUtils.squeeze(*, "") = *
* CharSetUtils.squeeze("hello", "k-p") = "helo"
* CharSetUtils.squeeze("hello", "a-e") = "hello"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String squeeze(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
strs[0] = set;
return squeeze(str, strs);
}
/**
* <p>Squeezes any repetitions of a character that is mentioned in the
* supplied set.</p>
*
* <p>An example is:</p>
* <ul>
* <li>squeeze("hello", {"el"}) => "helo"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str the string to squeeze, may be null
* @param set the character set to use for manipulation, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String squeeze(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
CharSet chars = evaluateSet(set);
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
char lastChar = ' ';
char ch = ' ';
for (int i = 0; i < sz; i++) {
ch = chrs[i];
if (chars.contains(ch)) {
if ((ch == lastChar) && (i != 0)) {
continue;
}
}
buffer.append(ch);
lastChar = ch;
}
return buffer.toString();
}
// Count
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and returns the number of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.count(null, *) = 0
* CharSetUtils.count("", *) = 0
* CharSetUtils.count(*, null) = 0
* CharSetUtils.count(*, "") = 0
* CharSetUtils.count("hello", "k-p") = 3
* CharSetUtils.count("hello", "a-e") = 1
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to count characters in, may be null
* @param set String set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return 0;
}
String[] strs = new String[1];
strs[0] = set;
return count(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and returns the number of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>count("hello", {"c-f", "o"}) returns 2.</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to count characters in, may be null
* @param set String[] set of characters to count, may be null
* @return character count, zero if null string input
*/
public static int count(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return 0;
}
CharSet chars = evaluateSet(set);
int count = 0;
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; i<sz; i++) {
if(chars.contains(chrs[i])) {
count++;
}
}
return count;
}
// Keep
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and keeps any of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.keep(null, *) = null
* CharSetUtils.keep("", *) = ""
* CharSetUtils.keep(*, null) = ""
* CharSetUtils.keep(*, "") = ""
* CharSetUtils.keep("hello", "hl") = "hll"
* CharSetUtils.keep("hello", "le") = "ell"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String set of characters to keep, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String keep(String str, String set) {
if (str == null) {
return null;
}
if (str.length() == 0 || StringUtils.isEmpty(set)) {
return "";
}
String[] strs = new String[1];
strs[0] = set;
return keep(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and keeps any of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>keep("hello", {"c-f", "o"})
* returns "eo"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to keep characters from, may be null
* @param set String[] set of characters to keep, may be null
* @return modified String, <code>null</code> if null string input
* @since 2.0
*/
public static String keep(String str, String[] set) {
if (str == null) {
return null;
}
if (str.length() == 0 || ArrayUtils.isEmpty(set)) {
return "";
}
return modify(str, set, true);
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and deletes any of characters present in the specified string.</p>
*
* <pre>
* CharSetUtils.delete(null, *) = null
* CharSetUtils.delete("", *) = ""
* CharSetUtils.delete(*, null) = *
* CharSetUtils.delete(*, "") = *
* CharSetUtils.delete("hello", "hl") = "eo"
* CharSetUtils.delete("hello", "le") = "ho"
* </pre>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String set of characters to delete, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String delete(String str, String set) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) {
return str;
}
String[] strs = new String[1];
strs[0] = set;
return delete(str, strs);
}
/**
* <p>Takes an argument in set-syntax, see evaluateSet,
* and deletes any of characters present in the specified string.</p>
*
* <p>An example would be:</p>
* <ul>
* <li>delete("hello", {"c-f", "o"}) returns
* "hll"</li>
* </ul>
*
* @see #evaluateSet(java.lang.String[]) for set-syntax.
* @param str String to delete characters from, may be null
* @param set String[] set of characters to delete, may be null
* @return modified String, <code>null</code> if null string input
*/
public static String delete(String str, String[] set) {
if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) {
return str;
}
return modify(str, set, false);
}
//-----------------------------------------------------------------------
// Implementation of delete and keep
private static String modify(String str, String[] set, boolean expect) {
CharSet chars = evaluateSet(set);
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
int sz = chrs.length;
for(int i=0; i<sz; i++) {
if(chars.contains(chrs[i]) == expect) {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
// Translate
//-----------------------------------------------------------------------
/**
* <p>Translate characters in a String.
* This is a multi character search and replace routine.</p>
*
* <p>An example is:</p>
* <ul>
* <li>translate("hello", "ho", "jy")
* => jelly</li>
* </ul>
*
* <p>If the length of characters to search for is greater than the
* length of characters to replace, then the last character is
* used.</p>
*
* <pre>
* CharSetUtils.translate(null, *, *) = null
* CharSetUtils.translate("", *, *) = ""
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, must not be null
* @param replaceChars a set of characters to replace, must not be null or empty ("")
* @return translated String, <code>null</code> if null string input
* @throws NullPointerException if <code>searchChars</code> or <code>replaceChars</code>
* is <code>null</code>
* @throws ArrayIndexOutOfBoundsException if <code>replaceChars</code> is empty ("")
* @deprecated Use {@link StringUtils#replaceChars(String, String, String)}.
* Method will be removed in Commons Lang 3.0.
* NOTE: StringUtils#replaceChars behaves differently when 'searchChars' is longer
* than 'replaceChars'. CharSetUtils#translate will use the last char of the replacement
* string whereas StringUtils#replaceChars will delete
*/
public static String translate(String str, String searchChars, String replaceChars) {
if (StringUtils.isEmpty(str)) {
return str;
}
StringBuffer buffer = new StringBuffer(str.length());
char[] chrs = str.toCharArray();
char[] withChrs = replaceChars.toCharArray();
int sz = chrs.length;
int withMax = replaceChars.length() - 1;
for(int i=0; i<sz; i++) {
int idx = searchChars.indexOf(chrs[i]);
if(idx != -1) {
if(idx > withMax) {
idx = withMax;
}
buffer.append(withChrs[idx]);
} else {
buffer.append(chrs[i]);
}
}
return buffer.toString();
}
}
|
added missing javadoc for private method, as per checkstyle
git-svn-id: d201ecbade8cc7da50e7bffa1d709f7a0d92be7d@151295 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/commons/lang/CharSetUtils.java
|
added missing javadoc for private method, as per checkstyle
|
|
Java
|
apache-2.0
|
7c3bb4aa1b4056aefbb9e571f473ac30b60d3528
| 0
|
gbecares/bdt
|
/*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.qa.specs;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.mongodb.DBObject;
import com.stratio.qa.assertions.DBObjectsAssert;
import com.stratio.qa.utils.PreviousWebElements;
import com.stratio.qa.utils.ThreadProperty;
import cucumber.api.DataTable;
import cucumber.api.java.en.Then;
import gherkin.formatter.model.DataTableRow;
import org.apache.zookeeper.KeeperException;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Fail;
import org.assertj.core.api.WritableAssertionInfo;
import org.json.JSONArray;
import org.openqa.selenium.WebElement;
import java.util.*;
import java.util.regex.Pattern;
import static com.stratio.qa.assertions.Assertions.assertThat;
public class ThenGSpec extends BaseGSpec {
public static final int VALUE_SUBSTRING = 3;
/**
* Class constructor.
*
* @param spec
*/
public ThenGSpec(CommonG spec) {
this.commonspec = spec;
}
/**
* Checks if an exception has been thrown.
*
* @param exception : "IS NOT" | "IS"
* @param foo
* @param clazz
* @param bar
* @param exceptionMsg
*/
@Then("^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?")
public void assertExceptionNotThrown(String exception, String foo, String clazz, String bar, String exceptionMsg)
throws ClassNotFoundException {
List<Exception> exceptions = commonspec.getExceptions();
if ("IS NOT".equals(exception)) {
assertThat(exceptions).as("Captured exception list is not empty").isEmpty();
} else {
assertThat(exceptions).as("Captured exception list is empty").isNotEmpty();
Exception ex = exceptions.get(exceptions.size() - 1);
if ((clazz != null) && (exceptionMsg != null)) {
assertThat(ex.toString()).as("Unexpected last exception class").contains(clazz);
assertThat(ex.toString()).as("Unexpected last exception message").contains(exceptionMsg);
} else if (clazz != null) {
assertThat(exceptions.get(exceptions.size() - 1).getClass().getSimpleName()).as("Unexpected last exception class").isEqualTo(clazz);
}
commonspec.getExceptions().clear();
}
}
/**
* Checks if a keyspaces exists in Cassandra.
*
* @param keyspace
*/
@Then("^a Cassandra keyspace '(.+?)' exists$")
public void assertKeyspaceOnCassandraExists(String keyspace) {
assertThat(commonspec.getCassandraClient().getKeyspaces()).as("The keyspace " + keyspace + "exists on cassandra").contains(keyspace);
}
/**
* Checks if a cassandra keyspace contains a table.
*
* @param keyspace
* @param tableName
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)'$")
public void assertTableExistsOnCassandraKeyspace(String keyspace, String tableName) {
assertThat(commonspec.getCassandraClient().getTables(keyspace)).as("The table " + tableName + "exists on cassandra").contains(tableName);
}
/**
* Checks the number of rows in a cassandra table.
*
* @param keyspace
* @param tableName
* @param numberRows
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with '(.+?)' rows$")
public void assertRowNumberOfTableOnCassandraKeyspace(String keyspace, String tableName, String numberRows) {
Long numberRowsLong = Long.parseLong(numberRows);
commonspec.getCassandraClient().useKeyspace(keyspace);
assertThat(commonspec.getCassandraClient().executeQuery("SELECT COUNT(*) FROM " + tableName + ";").all().get(0).getLong(0)).as("The table " + tableName + "exists on cassandra").
isEqualTo(numberRowsLong);
}
/**
* Checks if a cassandra table contains the values of a DataTable.
*
* @param keyspace
* @param tableName
* @param data
* @throws InterruptedException
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$")
public void assertValuesOfTable(String keyspace, String tableName, DataTable data) throws InterruptedException {
// USE of Keyspace
commonspec.getCassandraClient().useKeyspace(keyspace);
// Obtain the types and column names of the datatable
// to return in a hashmap,
Map<String, String> dataTableColumns = extractColumnNamesAndTypes(data.raw().get(0));
// check if the table has columns
String query = "SELECT * FROM " + tableName + " LIMIT 1;";
ResultSet res = commonspec.getCassandraClient().executeQuery(query);
equalsColumns(res.getColumnDefinitions(), dataTableColumns);
//receiving the string from the select with the columns
// that belong to the dataTable
List<String> selectQueries = giveQueriesList(data, tableName, columnNames(data.raw().get(0)));
//Check the data of cassandra with different queries
int index = 1;
for (String execQuery : selectQueries) {
res = commonspec.getCassandraClient().executeQuery(execQuery);
List<Row> resAsList = res.all();
assertThat(resAsList.size()).as("The query " + execQuery + " not return any result on Cassandra").isGreaterThan(0);
assertThat(resAsList.get(0).toString()
.substring(VALUE_SUBSTRING)).as("The resultSet is not as expected").isEqualTo(data.raw().get(index).toString());
index++;
}
}
@SuppressWarnings("rawtypes")
private void equalsColumns(ColumnDefinitions resCols, Map<String, String> dataTableColumns) {
Iterator it = dataTableColumns.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertThat(resCols.toString()).as("The table not contains the column.").contains(e.getKey().toString());
DataType type = resCols.getType(e.getKey().toString());
assertThat(type.getName().toString()).as("The column type is not equals.").isEqualTo(e.getValue().toString());
}
}
private List<String> giveQueriesList(DataTable data, String tableName, String colNames) {
List<String> queryList = new ArrayList<String>();
for (int i = 1; i < data.raw().size(); i++) {
String query = "SELECT " + colNames + " FROM " + tableName;
List<String> row = data.raw().get(i);
query += conditionWhere(row, colNames.split(",")) + ";";
queryList.add(query);
}
return queryList;
}
private String conditionWhere(List<String> values, String[] columnNames) {
StringBuilder condition = new StringBuilder();
condition.append(" WHERE ");
Pattern numberPat = Pattern.compile("^\\d+(\\.*\\d*)?");
Pattern booleanPat = Pattern.compile("true|false");
for (int i = 0; i < values.size() - 1; i++) {
condition.append(columnNames[i]).append(" =");
if (numberPat.matcher(values.get(i)).matches() || booleanPat.matcher(values.get(i)).matches()) {
condition.append(" ").append(values.get(i)).append(" AND ");
} else {
condition.append(" '").append(values.get(i)).append("' AND ");
}
}
condition.append(columnNames[columnNames.length - 1]).append(" =");
if (numberPat.matcher(values.get(values.size() - 1)).matches()
|| booleanPat.matcher(values.get(values.size() - 1)).matches()) {
condition.append(" ").append(values.get(values.size() - 1));
} else {
condition.append(" '").append(values.get(values.size() - 1)).append("'");
}
return condition.toString();
}
private String columnNames(List<String> firstRow) {
StringBuilder columnNamesForQuery = new StringBuilder();
for (String s : firstRow) {
String[] aux = s.split("-");
columnNamesForQuery.append(aux[0]).append(",");
}
return columnNamesForQuery.toString().substring(0, columnNamesForQuery.length() - 1);
}
private Map<String, String> extractColumnNamesAndTypes(List<String> firstRow) {
HashMap<String, String> columns = new HashMap<String, String>();
for (String s : firstRow) {
String[] aux = s.split("-");
columns.put(aux[0], aux[1]);
}
return columns;
}
/**
* Checks the values of a MongoDB table.
*
* @param dataBase
* @param tableName
* @param data
*/
@Then("^a Mongo dataBase '(.+?)' contains a table '(.+?)' with values:")
public void assertValuesOfTableMongo(String dataBase, String tableName, DataTable data) {
commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase);
ArrayList<DBObject> result = (ArrayList<DBObject>) commonspec.getMongoDBClient().readFromMongoDBCollection(
tableName, data);
DBObjectsAssert.assertThat(result).containedInMongoDBResult(data);
}
/**
* Checks if a MongoDB database contains a table.
*
* @param database
* @param tableName
*/
@Then("^a Mongo dataBase '(.+?)' doesnt contains a table '(.+?)'$")
public void aMongoDataBaseContainsaTable(String database, String tableName) {
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
Set<String> collectionsNames = commonspec.getMongoDBClient().getMongoDBCollections();
assertThat(collectionsNames).as("The Mongo dataBase contains the table").doesNotContain(tableName);
}
/**
* Checks if a text exists in the source of an already loaded URL.
*
* @param text
*/
@Then("^this text exists:$")
public void assertSeleniumTextInSource(String text) {
assertThat(this.commonspec, commonspec.getDriver()).as("Expected text not found at page").contains(text);
}
/**
* Verifies that a webelement previously found has {@code text} as text
*
* @param index
* @param text
*/
@Then("^the element on index '(\\d+?)' has this text:$")
public void assertSeleniumTextOnElementPresent(Integer index, String text) {
assertThat(commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(commonspec.getPreviousWebElements().getPreviousWebElements().get(index)).contains(text);
}
/**
* Checks if {@code expectedCount} webelements are found, with a location {@code method}.
*
* @param expectedCount
* @param method
* @param element
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
*/
@Then("^'(\\d+?)' elements? exists? with '([^:]*?):([^:]*?)'$")
public void assertSeleniumNElementExists(Integer expectedCount, String method, String element) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = commonspec.locateElement(method, element, expectedCount);
PreviousWebElements pwel = new PreviousWebElements(wel);
commonspec.setPreviousWebElements(pwel);
}
/**
* Checks if {@code expectedCount} webelements are found, whithin a {@code timeout} and with a location
* {@code method}. Each negative lookup is followed by a wait of {@code wait} seconds. Selenium times are not
* accounted for the mentioned timeout.
*
* @param timeout
* @param wait
* @param expectedCount
* @param method
* @param element
* @throws InterruptedException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
*/
@Then("^in less than '(\\d+?)' seconds, checking each '(\\d+?)' seconds, '(\\d+?)' elements exists with '([^:]*?):([^:]*?)'$")
public void assertSeleniumNElementExistsOnTimeOut(Integer timeout, Integer wait, Integer expectedCount,
String method, String element) throws InterruptedException, ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = null;
for (int i = 0; i < timeout; i += wait) {
wel = commonspec.locateElement(method, element, -1);
if (wel.size() == expectedCount) {
break;
} else {
Thread.sleep(wait * 1000);
}
}
PreviousWebElements pwel = new PreviousWebElements(wel);
assertThat(this.commonspec, pwel).as("Element count doesnt match").hasSize(expectedCount);
commonspec.setPreviousWebElements(pwel);
}
/**
* Checks if {@code expectedCount} element is found, whithin a {@code timeout} and with a location
* {@code method}. Each negative lookup is followed by a wait of {@code wait} seconds. Selenium times are not
* accounted for the mentioned timeout.
*
* @param timeout
* @param wait
* @param command
* @param search
* @throws InterruptedException
*/
@Then("^in less than '(\\d+?)' seconds, checking each '(\\d+?)' seconds, the command output '(.+?)' contains '(.+?)'$")
public void assertCommandExistsOnTimeOut(Integer timeout, Integer wait, String command, String search) throws Exception {
Boolean found = false;
AssertionError ex = null;
for (int i = 0; (i <= timeout); i += wait) {
if (found) {
break;
}
commonspec.getLogger().debug("Checking output value");
commonspec.getRemoteSSHConnection().runCommand(command);
commonspec.setCommandResult(commonspec.getRemoteSSHConnection().getResult());
try {
assertThat(commonspec.getCommandResult()).as("Contains " + search + ".").contains(search);
found = true;
timeout = i;
} catch (AssertionError e) {
commonspec.getLogger().info("Command output don't found yet after " + i + " seconds");
Thread.sleep(wait * 1000);
ex = e;
}
}
if (!found) {
throw (ex);
}
commonspec.getLogger().info("Command output found after " + timeout + " seconds");
}
/**
* Verifies that a webelement previously found {@code isDisplayed}
*
* @param index
* @param isDisplayed
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) displayed$")
public void assertSeleniumIsDisplayed(Integer index, Boolean isDisplayed) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isDisplayed()).as(
"Unexpected element display property").isEqualTo(isDisplayed);
}
/**
* Verifies that a webelement previously found {@code isEnabled}
*
* @param index
* @param isEnabled
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) enabled$")
public void assertSeleniumIsEnabled(Integer index, Boolean isEnabled) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isEnabled())
.as("Unexpected element enabled property").isEqualTo(isEnabled);
}
/**
* Verifies that a webelement previously found {@code isSelected}
*
* @param index
* @param isSelected
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) selected$")
public void assertSeleniumIsSelected(Integer index, Boolean isSelected) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isSelected()).as(
"Unexpected element selected property").isEqualTo(isSelected);
}
/**
* Verifies that a webelement previously found has {@code attribute} with {@code value} (as a regexp)
*
* @param index
* @param attribute
* @param value
*/
@Then("^the element on index '(\\d+?)' has '(.+?)' as '(.+?)'$")
public void assertSeleniumHasAttributeValue(Integer index, String attribute, String value) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
String val = commonspec.getPreviousWebElements().getPreviousWebElements().get(index).getAttribute(attribute);
assertThat(this.commonspec, val).as("Attribute not found").isNotNull();
assertThat(this.commonspec, val).as("Unexpected value for specified attribute").matches(value);
}
/**
* Takes an snapshot of the current page
*
* @throws Exception
*/
@Then("^I take a snapshot$")
public void seleniumSnapshot() throws Exception {
commonspec.captureEvidence(commonspec.getDriver(), "screenCapture");
}
/**
* Checks that we are in the URL passed
*
* @param url
* @throws Exception
*/
@Then("^we are in page '(.+?)'$")
public void checkURL(String url) throws Exception {
if (commonspec.getWebHost() == null) {
throw new Exception("Web host has not been set");
}
if (commonspec.getWebPort() == null) {
throw new Exception("Web port has not been set");
}
String webURL = commonspec.getWebHost() + commonspec.getWebPort();
assertThat(commonspec.getDriver().getCurrentUrl()).as("We are not in the expected url: " + webURL.toLowerCase() + url)
.endsWith(webURL.toLowerCase() + url);
}
@Then("^the service response status must be '(.*?)'.$")
public void assertResponseStatus(Integer expectedStatus) {
assertThat(commonspec.getResponse().getStatusCode()).isEqualTo(expectedStatus);
}
@Then("^the service response must contain the text '(.*?)'$")
public void assertResponseMessage(String expectedText) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Pattern pattern = CommonG.matchesOrContains(expectedText);
assertThat(commonspec.getResponse().getResponse()).containsPattern(pattern);
}
@Then("^the service response status must be '(.*?)' and its response must contain the text '(.*?)'$")
public void assertResponseStatusMessage(Integer expectedStatus, String expectedText) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
WritableAssertionInfo assertionInfo = new WritableAssertionInfo();
Pattern pattern = CommonG.matchesOrContains(expectedText);
assertThat(Optional.of(commonspec.getResponse())).hasValueSatisfying(r -> {
assertThat(r.getStatusCode()).isEqualTo(expectedStatus);
assertThat(r.getResponse()).containsPattern(pattern);
});
}
@Then("^the service response status must be '(.*?)' and its response length must be '(.*?)'$")
public void assertResponseStatusLength(Integer expectedStatus, Integer expectedLength) {
assertThat(Optional.of(commonspec.getResponse())).hasValueSatisfying(r -> {
assertThat(r.getStatusCode()).isEqualTo(expectedStatus);
assertThat((new JSONArray(r.getResponse())).length()).isEqualTo(expectedLength);
});
}
/**
* Checks the different results of a previous query
*
* @param expectedResults A DataTable Object with all data needed for check the results. The DataTable must contains at least 2 columns:
* a) A field column from the result
* b) Occurrences column (Integer type)
* <p>
* Example:
* |latitude| longitude|place |occurrences|
* |12.5 |12.7 |Valencia |1 |
* |2.5 | 2.6 |Stratio |0 |
* |12.5 |13.7 |Sevilla |1 |
* IMPORTANT: There no should be no existing columns
* @throws Exception
*/
@Then("^There are results found with:$")
public void resultsMustBe(DataTable expectedResults) throws Exception {
String type = commonspec.getResultsType();
assertThat(type).isNotEqualTo("").overridingErrorMessage("It's necessary to define the result type");
switch (type) {
case "cassandra":
commonspec.resultsMustBeCassandra(expectedResults);
break;
case "mongo":
commonspec.resultsMustBeMongo(expectedResults);
break;
case "elasticsearch":
commonspec.resultsMustBeElasticsearch(expectedResults);
break;
case "csv":
commonspec.resultsMustBeCSV(expectedResults);
break;
default:
commonspec.getLogger().warn("default switch branch on results check");
}
}
/**
* Check the existence of a text at a command output
*
* @param search
**/
@Then("^the command output contains '(.+?)'$")
public void findShellOutput(String search) throws Exception {
assertThat(commonspec.getCommandResult()).as("Contains " + search + ".").contains(search);
}
/**
* Check the non existence of a text at a command output
*
* @param search
**/
@Then("^the command output does not contain '(.+?)'$")
public void notFindShellOutput(String search) throws Exception {
assertThat(commonspec.getCommandResult()).as("NotContains " + search + ".").doesNotContain(search);
}
/**
* Check the exitStatus of previous command execution matches the expected one
*
* @param expectedExitStatus
* @deprecated Success exit status is directly checked in the "execute remote command" method, so this is not
* needed anymore.
**/
@Deprecated
@Then("^the command exit status is '(.+?)'$")
public void checkShellExitStatus(int expectedExitStatus) throws Exception {
assertThat(commonspec.getCommandExitStatus()).as("Is equal to " + expectedExitStatus + ".").isEqualTo(expectedExitStatus);
}
/**
* Save cookie in context for future references
**/
@Then("^I save selenium cookies in context$")
public void saveSeleniumCookies() throws Exception {
commonspec.setSeleniumCookies(commonspec.getDriver().manage().getCookies());
}
/**
* Check if expression defined by JSOPath (http://goessner.net/articles/JsonPath/index.html)
* match in JSON stored in a environment variable.
*
* @param envVar environment variable where JSON is stored
* @param table data table in which each row stores one expression
*/
@Then("^'(.+?)' matches the following cases:$")
public void matchWithExpresion(String envVar, DataTable table) throws Exception {
String jsonString = ThreadProperty.get(envVar);
for (DataTableRow row : table.getGherkinRows()) {
String expression = row.getCells().get(0);
String condition = row.getCells().get(1);
String result = row.getCells().get(2);
String value = commonspec.getJSONPathString(jsonString, expression, null);
commonspec.evaluateJSONElementOperation(value, condition, result);
}
}
/**
* A PUT request over the body value.
*
* @param key
* @param value
* @param service
* @throws Exception
*/
@Then("^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$")
public void sendAppendRequest(String key, String value, String service) throws Exception {
commonspec.runCommandAndGetResult("touch " + service + ".json && dcos marathon app show " + service + " > /dcos/" + service + ".json");
commonspec.runCommandAndGetResult("cat /dcos/" + service + ".json");
String configFile = commonspec.getRemoteSSHConnection().getResult();
String myValue = commonspec.getJSONPathString(configFile, ".labels", "0");
String myJson = commonspec.updateMarathonJson(commonspec.removeJSONPathElement(configFile, ".labels"));
String newValue = myValue.replaceFirst("}", ", \"" + key + "\": \"" + value + "\"}");
newValue = "\"labels\":" + newValue;
String myFinalJson = myJson.replaceFirst("\\{", "{" + newValue + ",");
String test = myFinalJson.replaceAll("\"uris\"", "\"none\"");
commonspec.runCommandAndGetResult("echo '" + test + "' > /dcos/final" + service + ".json");
commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + ".json");
commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus());
}
/**
* Read zPath
*
* @param zNode path at zookeeper
* @param document expected content of znode
*/
@Then("^the zNode '(.+?)' exists( and contains '(.+?)')?$")
public void checkZnodeExists(String zNode, String foo, String document) throws Exception {
if (document == null) {
String breakpoint = commonspec.getZookeeperSecClient().zRead(zNode);
Assertions.assertThat(commonspec.getZookeeperSecClient().zRead(zNode))
.withFailMessage("The zNode does not exist")
.as("zNode exists").isEqualTo("");
} else {
Assertions.assertThat(commonspec.getZookeeperSecClient().zRead(zNode))
.withFailMessage("The zNode does not exist or the content does not match")
.as("ZNode contains {} ", document).contains(document);
}
}
@Then("^the zNode '(.+?)' does not exist")
public void checkZnodeNotExist(String zNode) throws Exception {
Assertions.assertThat(!commonspec.getZookeeperSecClient().exists(zNode)).withFailMessage("The zNode exists");
}
/**
* Check that a kafka topic exist
*
* @param topic_name name of topic
*/
@Then("^A kafka topic named '(.+?)' exists")
public void kafkaTopicExist(String topic_name) throws KeeperException, InterruptedException {
Assertions.assertThat(commonspec.getKafkaUtils().listTopics().contains(topic_name)).withFailMessage("There is no topic with that name");
}
/**
* Check that a kafka topic not exist
*
* @param topic_name name of topic
*/
@Then("^A kafka topic named '(.+?)' not exists")
public void kafkaTopicNotExist(String topic_name) throws KeeperException, InterruptedException {
Assertions.assertThat(!commonspec.getKafkaUtils().listTopics().contains(topic_name)).withFailMessage("There is no topic with that name");
}
/**
* Set a environment variable in marathon and deploy again.
*
* @param key
* @param value
* @param service
* @throws Exception
*/
@Then("^I modify the enviroment variable '(.+?)' with value '(.+?)' for service '(.+?)'?$")
public void setMarathonProperty(String key, String value, String service) throws Exception {
commonspec.runCommandAndGetResult("touch " + service + "-env.json && dcos marathon app show " + service + " > /dcos/" + service + "-env.json");
commonspec.runCommandAndGetResult("cat /dcos/" + service + "-env.json");
String configFile = commonspec.getRemoteSSHConnection().getResult();
String myJson1 = commonspec.replaceJSONPathElement(configFile, key, value);
String myJson4 = commonspec.updateMarathonJson(myJson1);
String myJson = myJson4.replaceAll("\"uris\"", "\"none\"");
commonspec.runCommandAndGetResult("echo '" + myJson + "' > /dcos/final" + service + "-env.json");
commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + "-env.json");
commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus());
}
/**
* Check that the number of partitions is like expected.
*
* @param topic_name Name of kafka topic
* @param numOfPartitions Number of partitions
* @throws Exception
*/
@Then("^The number of partitions in topic '(.+?)' should be '(.+?)''?$")
public void checkNumberOfPartitions(String topic_name, int numOfPartitions) throws Exception {
Assertions.assertThat(commonspec.getKafkaUtils().getPartitions(topic_name)).isEqualTo(numOfPartitions);
}
/**
* Check that the ElasticSearch index exists.
*
* @param indexName
*/
@Then("^An elasticsearch index named '(.+?)' exists")
public void elasticSearchIndexExist(String indexName) {
Assertions.assertThat(commonspec.getElasticSearchClient().indexExists(indexName)).isTrue()
.withFailMessage("There is no index with that name");
}
/**
* Check that the ElasticSearch index does not exist.
*
* @param indexName
*/
@Then("^An elasticsearch index named '(.+?)' does not exist")
public void elasticSearchIndexDoesNotExist(String indexName) {
Assertions.assertThat(commonspec.getElasticSearchClient().indexExists(indexName)).isFalse()
.withFailMessage("There is an index with that name");
}
/**
* Check that an elasticsearch index contains a specific document
*
* @param indexName
* @param columnName
* @param columnValue
*/
@Then("^The Elasticsearch index named '(.+?)' and mapping '(.+?)' contains a column named '(.+?)' with the value '(.+?)'$")
public void elasticSearchIndexContainsDocument(String indexName, String mappingName, String columnName, String columnValue) throws Exception {
Assertions.assertThat((commonspec.getElasticSearchClient().searchSimpleFilterElasticsearchQuery(
indexName,
mappingName,
columnName,
columnValue,
"equals"
).size()) > 0).isTrue().withFailMessage("The index does not contain that document");
}
/*
* Check value stored in environment variable "is|matches|is higher than|is lower than|contains|is different from" to value provided
*
* @param envVar
* @param value
*
*/
@Then("^'(?s)(.+?)' ((?!.*with).+?) '(.+?)'$")
public void checkValue(String envVar, String operation, String value) throws Exception {
switch (operation.toLowerCase()) {
case "is":
Assertions.assertThat(envVar).isEqualTo(value);
break;
case "matches":
Assertions.assertThat(envVar).matches(value);
break;
case "is higher than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).isGreaterThan(Integer.parseInt(value));
} else {
Fail.fail("A number should be provided in order to perform a valid comparison.");
}
break;
case "is lower than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).isLessThan(Integer.parseInt(value));
} else {
Fail.fail("A number should be provided in order to perform a valid comparison.");
}
break;
case "contains":
Assertions.assertThat(envVar).contains(value);
break;
case "is different from":
Assertions.assertThat(envVar).isNotEqualTo(value);
break;
default:
Fail.fail("Not a valid comparison. Valid ones are: is | matches | is higher than | is lower than | contains | is different from");
}
}
@Then("^The kafka topic '(.*?)' has a message containing '(.*?)'$")
public void checkMessages(String topic, String content) {
Assertions.assertThat(commonspec.getKafkaUtils().readTopicFromBeginning(topic).contains(content)).as("Topic {} contains {}", topic, content).withFailMessage("{} not found", content);
}
}
|
src/main/java/com/stratio/qa/specs/ThenGSpec.java
|
/*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.qa.specs;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.mongodb.DBObject;
import com.stratio.qa.assertions.DBObjectsAssert;
import com.stratio.qa.utils.PreviousWebElements;
import com.stratio.qa.utils.ThreadProperty;
import cucumber.api.DataTable;
import cucumber.api.java.en.Then;
import gherkin.formatter.model.DataTableRow;
import org.apache.zookeeper.KeeperException;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Fail;
import org.assertj.core.api.WritableAssertionInfo;
import org.json.JSONArray;
import org.openqa.selenium.WebElement;
import java.util.*;
import java.util.regex.Pattern;
import static com.stratio.qa.assertions.Assertions.assertThat;
public class ThenGSpec extends BaseGSpec {
public static final int VALUE_SUBSTRING = 3;
/**
* Class constructor.
*
* @param spec
*/
public ThenGSpec(CommonG spec) {
this.commonspec = spec;
}
/**
* Checks if an exception has been thrown.
*
* @param exception : "IS NOT" | "IS"
* @param foo
* @param clazz
* @param bar
* @param exceptionMsg
*/
@Then("^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?")
public void assertExceptionNotThrown(String exception, String foo, String clazz, String bar, String exceptionMsg)
throws ClassNotFoundException {
List<Exception> exceptions = commonspec.getExceptions();
if ("IS NOT".equals(exception)) {
assertThat(exceptions).as("Captured exception list is not empty").isEmpty();
} else {
assertThat(exceptions).as("Captured exception list is empty").isNotEmpty();
Exception ex = exceptions.get(exceptions.size() - 1);
if ((clazz != null) && (exceptionMsg != null)) {
assertThat(ex.toString()).as("Unexpected last exception class").contains(clazz);
assertThat(ex.toString()).as("Unexpected last exception message").contains(exceptionMsg);
} else if (clazz != null) {
assertThat(exceptions.get(exceptions.size() - 1).getClass().getSimpleName()).as("Unexpected last exception class").isEqualTo(clazz);
}
commonspec.getExceptions().clear();
}
}
/**
* Checks if a keyspaces exists in Cassandra.
*
* @param keyspace
*/
@Then("^a Cassandra keyspace '(.+?)' exists$")
public void assertKeyspaceOnCassandraExists(String keyspace) {
assertThat(commonspec.getCassandraClient().getKeyspaces()).as("The keyspace " + keyspace + "exists on cassandra").contains(keyspace);
}
/**
* Checks if a cassandra keyspace contains a table.
*
* @param keyspace
* @param tableName
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)'$")
public void assertTableExistsOnCassandraKeyspace(String keyspace, String tableName) {
assertThat(commonspec.getCassandraClient().getTables(keyspace)).as("The table " + tableName + "exists on cassandra").contains(tableName);
}
/**
* Checks the number of rows in a cassandra table.
*
* @param keyspace
* @param tableName
* @param numberRows
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with '(.+?)' rows$")
public void assertRowNumberOfTableOnCassandraKeyspace(String keyspace, String tableName, String numberRows) {
Long numberRowsLong = Long.parseLong(numberRows);
commonspec.getCassandraClient().useKeyspace(keyspace);
assertThat(commonspec.getCassandraClient().executeQuery("SELECT COUNT(*) FROM " + tableName + ";").all().get(0).getLong(0)).as("The table " + tableName + "exists on cassandra").
isEqualTo(numberRowsLong);
}
/**
* Checks if a cassandra table contains the values of a DataTable.
*
* @param keyspace
* @param tableName
* @param data
* @throws InterruptedException
*/
@Then("^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$")
public void assertValuesOfTable(String keyspace, String tableName, DataTable data) throws InterruptedException {
// USE of Keyspace
commonspec.getCassandraClient().useKeyspace(keyspace);
// Obtain the types and column names of the datatable
// to return in a hashmap,
Map<String, String> dataTableColumns = extractColumnNamesAndTypes(data.raw().get(0));
// check if the table has columns
String query = "SELECT * FROM " + tableName + " LIMIT 1;";
ResultSet res = commonspec.getCassandraClient().executeQuery(query);
equalsColumns(res.getColumnDefinitions(), dataTableColumns);
//receiving the string from the select with the columns
// that belong to the dataTable
List<String> selectQueries = giveQueriesList(data, tableName, columnNames(data.raw().get(0)));
//Check the data of cassandra with different queries
int index = 1;
for (String execQuery : selectQueries) {
res = commonspec.getCassandraClient().executeQuery(execQuery);
List<Row> resAsList = res.all();
assertThat(resAsList.size()).as("The query " + execQuery + " not return any result on Cassandra").isGreaterThan(0);
assertThat(resAsList.get(0).toString()
.substring(VALUE_SUBSTRING)).as("The resultSet is not as expected").isEqualTo(data.raw().get(index).toString());
index++;
}
}
@SuppressWarnings("rawtypes")
private void equalsColumns(ColumnDefinitions resCols, Map<String, String> dataTableColumns) {
Iterator it = dataTableColumns.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
assertThat(resCols.toString()).as("The table not contains the column.").contains(e.getKey().toString());
DataType type = resCols.getType(e.getKey().toString());
assertThat(type.getName().toString()).as("The column type is not equals.").isEqualTo(e.getValue().toString());
}
}
private List<String> giveQueriesList(DataTable data, String tableName, String colNames) {
List<String> queryList = new ArrayList<String>();
for (int i = 1; i < data.raw().size(); i++) {
String query = "SELECT " + colNames + " FROM " + tableName;
List<String> row = data.raw().get(i);
query += conditionWhere(row, colNames.split(",")) + ";";
queryList.add(query);
}
return queryList;
}
private String conditionWhere(List<String> values, String[] columnNames) {
StringBuilder condition = new StringBuilder();
condition.append(" WHERE ");
Pattern numberPat = Pattern.compile("^\\d+(\\.*\\d*)?");
Pattern booleanPat = Pattern.compile("true|false");
for (int i = 0; i < values.size() - 1; i++) {
condition.append(columnNames[i]).append(" =");
if (numberPat.matcher(values.get(i)).matches() || booleanPat.matcher(values.get(i)).matches()) {
condition.append(" ").append(values.get(i)).append(" AND ");
} else {
condition.append(" '").append(values.get(i)).append("' AND ");
}
}
condition.append(columnNames[columnNames.length - 1]).append(" =");
if (numberPat.matcher(values.get(values.size() - 1)).matches()
|| booleanPat.matcher(values.get(values.size() - 1)).matches()) {
condition.append(" ").append(values.get(values.size() - 1));
} else {
condition.append(" '").append(values.get(values.size() - 1)).append("'");
}
return condition.toString();
}
private String columnNames(List<String> firstRow) {
StringBuilder columnNamesForQuery = new StringBuilder();
for (String s : firstRow) {
String[] aux = s.split("-");
columnNamesForQuery.append(aux[0]).append(",");
}
return columnNamesForQuery.toString().substring(0, columnNamesForQuery.length() - 1);
}
private Map<String, String> extractColumnNamesAndTypes(List<String> firstRow) {
HashMap<String, String> columns = new HashMap<String, String>();
for (String s : firstRow) {
String[] aux = s.split("-");
columns.put(aux[0], aux[1]);
}
return columns;
}
/**
* Checks the values of a MongoDB table.
*
* @param dataBase
* @param tableName
* @param data
*/
@Then("^a Mongo dataBase '(.+?)' contains a table '(.+?)' with values:")
public void assertValuesOfTableMongo(String dataBase, String tableName, DataTable data) {
commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase);
ArrayList<DBObject> result = (ArrayList<DBObject>) commonspec.getMongoDBClient().readFromMongoDBCollection(
tableName, data);
DBObjectsAssert.assertThat(result).containedInMongoDBResult(data);
}
/**
* Checks if a MongoDB database contains a table.
*
* @param database
* @param tableName
*/
@Then("^a Mongo dataBase '(.+?)' doesnt contains a table '(.+?)'$")
public void aMongoDataBaseContainsaTable(String database, String tableName) {
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
Set<String> collectionsNames = commonspec.getMongoDBClient().getMongoDBCollections();
assertThat(collectionsNames).as("The Mongo dataBase contains the table").doesNotContain(tableName);
}
/**
* Checks if a text exists in the source of an already loaded URL.
*
* @param text
*/
@Then("^a text '(.+?)' exists$")
public void assertSeleniumTextInSource(String text) {
assertThat(this.commonspec, commonspec.getDriver()).as("Expected text not found at page").contains(text);
}
/**
* Verifies that a webelement previously found has {@code text} as text
*
* @param index
* @param text
*/
@Then("^the element on index '(\\d+?)' has '(.*?)' as text$")
public void assertSeleniumTextOnElementPresent(Integer index, String text) {
assertThat(commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(commonspec.getPreviousWebElements().getPreviousWebElements().get(index)).contains(text);
}
/**
* Checks if {@code expectedCount} webelements are found, with a location {@code method}.
*
* @param expectedCount
* @param method
* @param element
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
*/
@Then("^'(\\d+?)' elements? exists? with '([^:]*?):([^:]*?)'$")
public void assertSeleniumNElementExists(Integer expectedCount, String method, String element) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = commonspec.locateElement(method, element, expectedCount);
PreviousWebElements pwel = new PreviousWebElements(wel);
commonspec.setPreviousWebElements(pwel);
}
/**
* Checks if {@code expectedCount} webelements are found, whithin a {@code timeout} and with a location
* {@code method}. Each negative lookup is followed by a wait of {@code wait} seconds. Selenium times are not
* accounted for the mentioned timeout.
*
* @param timeout
* @param wait
* @param expectedCount
* @param method
* @param element
* @throws InterruptedException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws ClassNotFoundException
*/
@Then("^in less than '(\\d+?)' seconds, checking each '(\\d+?)' seconds, '(\\d+?)' elements exists with '([^:]*?):([^:]*?)'$")
public void assertSeleniumNElementExistsOnTimeOut(Integer timeout, Integer wait, Integer expectedCount,
String method, String element) throws InterruptedException, ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<WebElement> wel = null;
for (int i = 0; i < timeout; i += wait) {
wel = commonspec.locateElement(method, element, -1);
if (wel.size() == expectedCount) {
break;
} else {
Thread.sleep(wait * 1000);
}
}
PreviousWebElements pwel = new PreviousWebElements(wel);
assertThat(this.commonspec, pwel).as("Element count doesnt match").hasSize(expectedCount);
commonspec.setPreviousWebElements(pwel);
}
/**
* Checks if {@code expectedCount} element is found, whithin a {@code timeout} and with a location
* {@code method}. Each negative lookup is followed by a wait of {@code wait} seconds. Selenium times are not
* accounted for the mentioned timeout.
*
* @param timeout
* @param wait
* @param command
* @param search
* @throws InterruptedException
*/
@Then("^in less than '(\\d+?)' seconds, checking each '(\\d+?)' seconds, the command output '(.+?)' contains '(.+?)'$")
public void assertCommandExistsOnTimeOut(Integer timeout, Integer wait, String command, String search) throws Exception {
Boolean found = false;
AssertionError ex = null;
for (int i = 0; (i <= timeout); i += wait) {
if (found) {
break;
}
commonspec.getLogger().debug("Checking output value");
commonspec.getRemoteSSHConnection().runCommand(command);
commonspec.setCommandResult(commonspec.getRemoteSSHConnection().getResult());
try {
assertThat(commonspec.getCommandResult()).as("Contains " + search + ".").contains(search);
found = true;
timeout = i;
} catch (AssertionError e) {
commonspec.getLogger().info("Command output don't found yet after " + i + " seconds");
Thread.sleep(wait * 1000);
ex = e;
}
}
if (!found) {
throw (ex);
}
commonspec.getLogger().info("Command output found after " + timeout + " seconds");
}
/**
* Verifies that a webelement previously found {@code isDisplayed}
*
* @param index
* @param isDisplayed
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) displayed$")
public void assertSeleniumIsDisplayed(Integer index, Boolean isDisplayed) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isDisplayed()).as(
"Unexpected element display property").isEqualTo(isDisplayed);
}
/**
* Verifies that a webelement previously found {@code isEnabled}
*
* @param index
* @param isEnabled
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) enabled$")
public void assertSeleniumIsEnabled(Integer index, Boolean isEnabled) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isEnabled())
.as("Unexpected element enabled property").isEqualTo(isEnabled);
}
/**
* Verifies that a webelement previously found {@code isSelected}
*
* @param index
* @param isSelected
*/
@Then("^the element on index '(\\d+?)' (IS|IS NOT) selected$")
public void assertSeleniumIsSelected(Integer index, Boolean isSelected) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isSelected()).as(
"Unexpected element selected property").isEqualTo(isSelected);
}
/**
* Verifies that a webelement previously found has {@code attribute} with {@code value} (as a regexp)
*
* @param index
* @param attribute
* @param value
*/
@Then("^the element on index '(\\d+?)' has '(.+?)' as '(.+?)'$")
public void assertSeleniumHasAttributeValue(Integer index, String attribute, String value) {
assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
.hasAtLeast(index);
String val = commonspec.getPreviousWebElements().getPreviousWebElements().get(index).getAttribute(attribute);
assertThat(this.commonspec, val).as("Attribute not found").isNotNull();
assertThat(this.commonspec, val).as("Unexpected value for specified attribute").matches(value);
}
/**
* Takes an snapshot of the current page
*
* @throws Exception
*/
@Then("^I take a snapshot$")
public void seleniumSnapshot() throws Exception {
commonspec.captureEvidence(commonspec.getDriver(), "screenCapture");
}
/**
* Checks that we are in the URL passed
*
* @param url
* @throws Exception
*/
@Then("^we are in page '(.+?)'$")
public void checkURL(String url) throws Exception {
if (commonspec.getWebHost() == null) {
throw new Exception("Web host has not been set");
}
if (commonspec.getWebPort() == null) {
throw new Exception("Web port has not been set");
}
String webURL = commonspec.getWebHost() + commonspec.getWebPort();
assertThat(commonspec.getDriver().getCurrentUrl()).as("We are not in the expected url: " + webURL.toLowerCase() + url)
.endsWith(webURL.toLowerCase() + url);
}
@Then("^the service response status must be '(.*?)'.$")
public void assertResponseStatus(Integer expectedStatus) {
assertThat(commonspec.getResponse().getStatusCode()).isEqualTo(expectedStatus);
}
@Then("^the service response must contain the text '(.*?)'$")
public void assertResponseMessage(String expectedText) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Pattern pattern = CommonG.matchesOrContains(expectedText);
assertThat(commonspec.getResponse().getResponse()).containsPattern(pattern);
}
@Then("^the service response status must be '(.*?)' and its response must contain the text '(.*?)'$")
public void assertResponseStatusMessage(Integer expectedStatus, String expectedText) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
WritableAssertionInfo assertionInfo = new WritableAssertionInfo();
Pattern pattern = CommonG.matchesOrContains(expectedText);
assertThat(Optional.of(commonspec.getResponse())).hasValueSatisfying(r -> {
assertThat(r.getStatusCode()).isEqualTo(expectedStatus);
assertThat(r.getResponse()).containsPattern(pattern);
});
}
@Then("^the service response status must be '(.*?)' and its response length must be '(.*?)'$")
public void assertResponseStatusLength(Integer expectedStatus, Integer expectedLength) {
assertThat(Optional.of(commonspec.getResponse())).hasValueSatisfying(r -> {
assertThat(r.getStatusCode()).isEqualTo(expectedStatus);
assertThat((new JSONArray(r.getResponse())).length()).isEqualTo(expectedLength);
});
}
/**
* Checks the different results of a previous query
*
* @param expectedResults A DataTable Object with all data needed for check the results. The DataTable must contains at least 2 columns:
* a) A field column from the result
* b) Occurrences column (Integer type)
* <p>
* Example:
* |latitude| longitude|place |occurrences|
* |12.5 |12.7 |Valencia |1 |
* |2.5 | 2.6 |Stratio |0 |
* |12.5 |13.7 |Sevilla |1 |
* IMPORTANT: There no should be no existing columns
* @throws Exception
*/
@Then("^There are results found with:$")
public void resultsMustBe(DataTable expectedResults) throws Exception {
String type = commonspec.getResultsType();
assertThat(type).isNotEqualTo("").overridingErrorMessage("It's necessary to define the result type");
switch (type) {
case "cassandra":
commonspec.resultsMustBeCassandra(expectedResults);
break;
case "mongo":
commonspec.resultsMustBeMongo(expectedResults);
break;
case "elasticsearch":
commonspec.resultsMustBeElasticsearch(expectedResults);
break;
case "csv":
commonspec.resultsMustBeCSV(expectedResults);
break;
default:
commonspec.getLogger().warn("default switch branch on results check");
}
}
/**
* Check the existence of a text at a command output
*
* @param search
**/
@Then("^the command output contains '(.+?)'$")
public void findShellOutput(String search) throws Exception {
assertThat(commonspec.getCommandResult()).as("Contains " + search + ".").contains(search);
}
/**
* Check the non existence of a text at a command output
*
* @param search
**/
@Then("^the command output does not contain '(.+?)'$")
public void notFindShellOutput(String search) throws Exception {
assertThat(commonspec.getCommandResult()).as("NotContains " + search + ".").doesNotContain(search);
}
/**
* Check the exitStatus of previous command execution matches the expected one
*
* @param expectedExitStatus
* @deprecated Success exit status is directly checked in the "execute remote command" method, so this is not
* needed anymore.
**/
@Deprecated
@Then("^the command exit status is '(.+?)'$")
public void checkShellExitStatus(int expectedExitStatus) throws Exception {
assertThat(commonspec.getCommandExitStatus()).as("Is equal to " + expectedExitStatus + ".").isEqualTo(expectedExitStatus);
}
/**
* Save cookie in context for future references
**/
@Then("^I save selenium cookies in context$")
public void saveSeleniumCookies() throws Exception {
commonspec.setSeleniumCookies(commonspec.getDriver().manage().getCookies());
}
/**
* Check if expression defined by JSOPath (http://goessner.net/articles/JsonPath/index.html)
* match in JSON stored in a environment variable.
*
* @param envVar environment variable where JSON is stored
* @param table data table in which each row stores one expression
*/
@Then("^'(.+?)' matches the following cases:$")
public void matchWithExpresion(String envVar, DataTable table) throws Exception {
String jsonString = ThreadProperty.get(envVar);
for (DataTableRow row : table.getGherkinRows()) {
String expression = row.getCells().get(0);
String condition = row.getCells().get(1);
String result = row.getCells().get(2);
String value = commonspec.getJSONPathString(jsonString, expression, null);
commonspec.evaluateJSONElementOperation(value, condition, result);
}
}
/**
* A PUT request over the body value.
*
* @param key
* @param value
* @param service
* @throws Exception
*/
@Then("^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$")
public void sendAppendRequest(String key, String value, String service) throws Exception {
commonspec.runCommandAndGetResult("touch " + service + ".json && dcos marathon app show " + service + " > /dcos/" + service + ".json");
commonspec.runCommandAndGetResult("cat /dcos/" + service + ".json");
String configFile = commonspec.getRemoteSSHConnection().getResult();
String myValue = commonspec.getJSONPathString(configFile, ".labels", "0");
String myJson = commonspec.updateMarathonJson(commonspec.removeJSONPathElement(configFile, ".labels"));
String newValue = myValue.replaceFirst("}", ", \"" + key + "\": \"" + value + "\"}");
newValue = "\"labels\":" + newValue;
String myFinalJson = myJson.replaceFirst("\\{", "{" + newValue + ",");
String test = myFinalJson.replaceAll("\"uris\"", "\"none\"");
commonspec.runCommandAndGetResult("echo '" + test + "' > /dcos/final" + service + ".json");
commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + ".json");
commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus());
}
/**
* Read zPath
*
* @param zNode path at zookeeper
* @param document expected content of znode
*/
@Then("^the zNode '(.+?)' exists( and contains '(.+?)')?$")
public void checkZnodeExists(String zNode, String foo, String document) throws Exception {
if (document == null) {
String breakpoint = commonspec.getZookeeperSecClient().zRead(zNode);
Assertions.assertThat(commonspec.getZookeeperSecClient().zRead(zNode))
.withFailMessage("The zNode does not exist")
.as("zNode exists").isEqualTo("");
} else {
Assertions.assertThat(commonspec.getZookeeperSecClient().zRead(zNode))
.withFailMessage("The zNode does not exist or the content does not match")
.as("ZNode contains {} ", document).contains(document);
}
}
@Then("^the zNode '(.+?)' does not exist")
public void checkZnodeNotExist(String zNode) throws Exception {
Assertions.assertThat(!commonspec.getZookeeperSecClient().exists(zNode)).withFailMessage("The zNode exists");
}
/**
* Check that a kafka topic exist
*
* @param topic_name name of topic
*/
@Then("^A kafka topic named '(.+?)' exists")
public void kafkaTopicExist(String topic_name) throws KeeperException, InterruptedException {
Assertions.assertThat(commonspec.getKafkaUtils().listTopics().contains(topic_name)).withFailMessage("There is no topic with that name");
}
/**
* Check that a kafka topic not exist
*
* @param topic_name name of topic
*/
@Then("^A kafka topic named '(.+?)' not exists")
public void kafkaTopicNotExist(String topic_name) throws KeeperException, InterruptedException {
Assertions.assertThat(!commonspec.getKafkaUtils().listTopics().contains(topic_name)).withFailMessage("There is no topic with that name");
}
/**
* Set a environment variable in marathon and deploy again.
*
* @param key
* @param value
* @param service
* @throws Exception
*/
@Then("^I modify the enviroment variable '(.+?)' with value '(.+?)' for service '(.+?)'?$")
public void setMarathonProperty(String key, String value, String service) throws Exception {
commonspec.runCommandAndGetResult("touch " + service + "-env.json && dcos marathon app show " + service + " > /dcos/" + service + "-env.json");
commonspec.runCommandAndGetResult("cat /dcos/" + service + "-env.json");
String configFile = commonspec.getRemoteSSHConnection().getResult();
String myJson1 = commonspec.replaceJSONPathElement(configFile, key, value);
String myJson4 = commonspec.updateMarathonJson(myJson1);
String myJson = myJson4.replaceAll("\"uris\"", "\"none\"");
commonspec.runCommandAndGetResult("echo '" + myJson + "' > /dcos/final" + service + "-env.json");
commonspec.runCommandAndGetResult("dcos marathon app update " + service + " < /dcos/final" + service + "-env.json");
commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus());
}
/**
* Check that the number of partitions is like expected.
*
* @param topic_name Name of kafka topic
* @param numOfPartitions Number of partitions
* @throws Exception
*/
@Then("^The number of partitions in topic '(.+?)' should be '(.+?)''?$")
public void checkNumberOfPartitions(String topic_name, int numOfPartitions) throws Exception {
Assertions.assertThat(commonspec.getKafkaUtils().getPartitions(topic_name)).isEqualTo(numOfPartitions);
}
/**
* Check that the ElasticSearch index exists.
*
* @param indexName
*/
@Then("^An elasticsearch index named '(.+?)' exists")
public void elasticSearchIndexExist(String indexName) {
Assertions.assertThat(commonspec.getElasticSearchClient().indexExists(indexName)).isTrue()
.withFailMessage("There is no index with that name");
}
/**
* Check that the ElasticSearch index does not exist.
*
* @param indexName
*/
@Then("^An elasticsearch index named '(.+?)' does not exist")
public void elasticSearchIndexDoesNotExist(String indexName) {
Assertions.assertThat(commonspec.getElasticSearchClient().indexExists(indexName)).isFalse()
.withFailMessage("There is an index with that name");
}
/**
* Check that an elasticsearch index contains a specific document
*
* @param indexName
* @param columnName
* @param columnValue
*/
@Then("^The Elasticsearch index named '(.+?)' and mapping '(.+?)' contains a column named '(.+?)' with the value '(.+?)'$")
public void elasticSearchIndexContainsDocument(String indexName, String mappingName, String columnName, String columnValue) throws Exception {
Assertions.assertThat((commonspec.getElasticSearchClient().searchSimpleFilterElasticsearchQuery(
indexName,
mappingName,
columnName,
columnValue,
"equals"
).size()) > 0).isTrue().withFailMessage("The index does not contain that document");
}
/*
* Check value stored in environment variable "is|matches|is higher than|is lower than|contains|is different from" to value provided
*
* @param envVar
* @param value
*
*/
@Then("^'(?s)(.+?)' ((?!.*with).+?) '(.+?)'$")
public void checkValue(String envVar, String operation, String value) throws Exception {
switch (operation.toLowerCase()) {
case "is":
Assertions.assertThat(envVar).isEqualTo(value);
break;
case "matches":
Assertions.assertThat(envVar).matches(value);
break;
case "is higher than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).isGreaterThan(Integer.parseInt(value));
} else {
Fail.fail("A number should be provided in order to perform a valid comparison.");
}
break;
case "is lower than":
if (envVar.matches("^-?\\d+$") && value.matches("^-?\\d+$")) {
Assertions.assertThat(Integer.parseInt(envVar)).isLessThan(Integer.parseInt(value));
} else {
Fail.fail("A number should be provided in order to perform a valid comparison.");
}
break;
case "contains":
Assertions.assertThat(envVar).contains(value);
break;
case "is different from":
Assertions.assertThat(envVar).isNotEqualTo(value);
break;
default:
Fail.fail("Not a valid comparison. Valid ones are: is | matches | is higher than | is lower than | contains | is different from");
}
}
@Then("^The kafka topic '(.*?)' has a message containing '(.*?)'$")
public void checkMessages(String topic, String content) {
Assertions.assertThat(commonspec.getKafkaUtils().readTopicFromBeginning(topic).contains(content)).as("Topic {} contains {}", topic, content).withFailMessage("{} not found", content);
}
}
|
text exists with block, has this block (#194)
|
src/main/java/com/stratio/qa/specs/ThenGSpec.java
|
text exists with block, has this block (#194)
|
|
Java
|
apache-2.0
|
d52fa9c480b50c282862abb8b3fd2b3219806730
| 0
|
BD2K-DDI/ddi-annotation
|
package uk.ac.ebi.ddi.retriever.providers;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.client.utils.URIBuilder;
import org.json.XML;
import org.springframework.http.ResponseEntity;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import uk.ac.ebi.ddi.ddidomaindb.database.DB;
import uk.ac.ebi.ddi.retriever.DatasetFileUrlRetriever;
import uk.ac.ebi.ddi.retriever.IDatasetFileUrlRetriever;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ENAFileUrlRetriever extends DatasetFileUrlRetriever {
private static final String ENA_ENDPOINT = "www.ebi.ac.uk/ena/portal/api";
public ENAFileUrlRetriever(IDatasetFileUrlRetriever datasetDownloadingRetriever) {
super(datasetDownloadingRetriever);
}
@Override
public Set<String> getAllDatasetFiles(String accession, String database) throws IOException {
Set<String> result = new HashSet<>();
result.addAll(getReadRunFiles(accession));
result.addAll(getAnalysisFiles(accession));
result.addAll(getAssemblyFiles(accession));
result.addAll(getWgsFiles(accession));
return result;
}
/*public <T> void getFiles(URI uri, Class<T[]> data) throws IOException{
Set<String> result = new HashSet<>();
CloseableHttpClient httpclient = HttpClients.createDefault();
ObjectMapper objectMapper = new ObjectMapper();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try{
if(response1.getStatusLine().getStatusCode() == 200) {
HttpEntity entity1 = response1.getEntity();
T[] myObject = objectMapper.readValue(entity1.getContent(), data);
System.out.println(myObject.length);
}
} finally {
response1.close();
}
}*/
public Set<String> getReadRunFiles(String accession) throws IOException {
Set<String> result = new HashSet<>();
try {
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.setParameter("result", "read_run")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
/*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*/
}
//getFiles(uri, ENAReadRunDataset[].class);
} catch (URISyntaxException ex) {
}
return result;
}
public Set<String> getAnalysisFiles(String accession) throws IOException {
Set<String> result = new HashSet<>();
try {
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,submitted_ftp,submitted_aspera,submitted_galaxy")
.setParameter("result", "analysis")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
if(files.getBody() != null) {
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("submitted_ftp").asText().split(";")));
}
}
//getFiles(uri);
} catch (URISyntaxException ex) {
}
return result;
}
public Set<String> getAssemblyFiles(String accession) throws IOException {
Set<String> result = new HashSet<>();
try {
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "accession")
.setParameter("result", "assembly")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
String acc = node.get("accession").textValue();
URI viewUri = new URIBuilder()
.setScheme("https")
.setHost("www.ebi.ac.uk/ena/data/view")
.setPath("/" + acc + ".1&display=xml")
.build();
ResponseEntity<String> assemblyFiles = execute(x -> restTemplate.getForEntity(viewUri, String.class));
XPath xPath = XPathFactory.newInstance().newXPath();
result.add(xPath.evaluate("ROOT/ASSEMBLY/ASSEMBLY_LINKS/ASSEMBLY_LINK/URL_LINK/URL", new InputSource(new StringReader(assemblyFiles.getBody()))));
assemblyFiles.getStatusCode();
}
// getFiles(uri);
} catch (URISyntaxException ex) {
} catch (XPathException ex) {
}
return result;
}
public Set<String> getWgsFiles(String accession) throws IOException {
Set<String> result = new HashSet<>();
try {
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,embl_file,fasta_file,master_file")
.setParameter("result", "wgs_set")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.add(node.get("embl_file").textValue());
result.add(node.get("fasta_file").textValue());
result.add(node.get("master_file").textValue());
}
} catch (URISyntaxException ex) {
}
return result;
}
@Override
protected boolean isSupported(String database) {
return DB.ENA.getDBName().equals(database);
}
/*public void getTemplateFiles()
{
Set<String> result = new HashSet<>();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.ebi.ac.uk/ena/portal/api")
.path("/search")
.queryParam("query", "(study_accession=PRJNA215355)")
.queryParam("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.queryParam("result", "read_run")
.queryParam("limit", "0")
.queryParam("format", "json");
URI uriForFiles = builder.build().toUri();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uriForFiles, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
*//*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*//*
}
}*/
}
|
src/main/java/uk/ac/ebi/ddi/retriever/providers/ENAFileUrlRetriever.java
|
package uk.ac.ebi.ddi.retriever.providers;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
import uk.ac.ebi.ddi.annotation.model.ENAReadRunDataset;
import uk.ac.ebi.ddi.ddidomaindb.database.DB;
import uk.ac.ebi.ddi.retriever.DatasetFileUrlRetriever;
import uk.ac.ebi.ddi.retriever.IDatasetFileUrlRetriever;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ENAFileUrlRetriever extends DatasetFileUrlRetriever {
private static final String ENA_ENDPOINT = "www.ebi.ac.uk/ena/portal/api";
public ENAFileUrlRetriever(IDatasetFileUrlRetriever datasetDownloadingRetriever) {
super(datasetDownloadingRetriever);
}
@Override
public Set<String> getAllDatasetFiles(String accession, String database) throws IOException {
Set<String> result = new HashSet<>();
//getTemplateFiles();
//getReadRunFiles();
return result;
}
/*public <T> void getFiles(URI uri, Class<T[]> data) throws IOException{
Set<String> result = new HashSet<>();
CloseableHttpClient httpclient = HttpClients.createDefault();
ObjectMapper objectMapper = new ObjectMapper();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try{
if(response1.getStatusLine().getStatusCode() == 200) {
HttpEntity entity1 = response1.getEntity();
T[] myObject = objectMapper.readValue(entity1.getContent(), data);
System.out.println(myObject.length);
}
} finally {
response1.close();
}
}*/
public Set<String> getReadRunFiles(String accession) throws IOException{
Set<String> result = new HashSet<>();
try{
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.setParameter("result", "read_run")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
/*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*/
}
//getFiles(uri, ENAReadRunDataset[].class);
}
catch(URISyntaxException ex){
}
return result;
}
public Set<String> getAnalysisFiles(String accession) throws IOException{
Set<String> result = new HashSet<>();
try{
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.setParameter("result", "analysis")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
/*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*/
}
//getFiles(uri);
}
catch(URISyntaxException ex){
}
return result;
}
public Set<String> getAssemblyFiles(String accession) throws IOException{
Set<String> result = new HashSet<>();
try{
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.setParameter("result", "assembly")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
/*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*/
}
// getFiles(uri);
}
catch(URISyntaxException ex){
}
return result;
}
public Set<String> getWgsFiles(String accession) throws IOException{
Set<String> result = new HashSet<>();
try{
URI uri = new URIBuilder()
.setScheme("https")
.setHost(ENA_ENDPOINT)
.setPath("/search")
.setParameter("query", "(study_accession=" + accession + ")")
.setParameter("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.setParameter("result", "wgs_set")
.setParameter("limit", "0")
.setParameter("format", "json")
.build();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uri, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
/*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*/
}
//getFiles(uri);
}
catch(URISyntaxException ex){
}
return result;
}
@Override
protected boolean isSupported(String database) {
return DB.ENA.getDBName().equals(database);
}
/*public void getTemplateFiles()
{
Set<String> result = new HashSet<>();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.ebi.ac.uk/ena/portal/api")
.path("/search")
.queryParam("query", "(study_accession=PRJNA215355)")
.queryParam("fields", "study_accession,fastq_ftp,fastq_aspera,fastq_galaxy")
.queryParam("result", "read_run")
.queryParam("limit", "0")
.queryParam("format", "json");
URI uriForFiles = builder.build().toUri();
ResponseEntity<JsonNode> files = execute(x -> restTemplate.getForEntity(uriForFiles, JsonNode.class));
for (JsonNode node : files.getBody()) {
result.addAll(Arrays.asList(node.get("fastq_ftp").asText().split(";")));
*//*String fastqAspera = node.get("fastq_aspera").asText();
String fastqGalaxy = node.get("fastq_galaxy").asText();*//*
}
}*/
}
|
updated ena file retriever code
|
src/main/java/uk/ac/ebi/ddi/retriever/providers/ENAFileUrlRetriever.java
|
updated ena file retriever code
|
|
Java
|
apache-2.0
|
395c88d236358971e7049c5d262b52dc42163816
| 0
|
borrom/AndEngine,zcwk/AndEngine,yaye729125/gles,zhidew/AndEngine,pongo710/AndEngine,zcwk/AndEngine,shiguang1120/AndEngine,luoxiaoshenghustedu/AndEngine,nicolasgramlich/AndEngine,zcwk/AndEngine,shiguang1120/AndEngine,godghdai/AndEngine,ericlaro/AndEngineLibrary,chautn/AndEngine,jduberville/AndEngine,zhidew/AndEngine,zhidew/AndEngine,viacheslavokolitiy/AndEngine,Munazza/AndEngine,borrom/AndEngine,Munazza/AndEngine,parthipanramesh/AndEngine,ericlaro/AndEngineLibrary,yaye729125/gles,borrom/AndEngine,godghdai/AndEngine,jduberville/AndEngine,msdgwzhy6/AndEngine,zhidew/AndEngine,Munazza/AndEngine,nicolasgramlich/AndEngine,viacheslavokolitiy/AndEngine,zcwk/AndEngine,msdgwzhy6/AndEngine,chautn/AndEngine,Munazza/AndEngine,parthipanramesh/AndEngine,shiguang1120/AndEngine,borrom/AndEngine,yudhir/AndEngine,pongo710/AndEngine,luoxiaoshenghustedu/AndEngine,msdgwzhy6/AndEngine,pongo710/AndEngine,yudhir/AndEngine,parthipanramesh/AndEngine,jduberville/AndEngine,yudhir/AndEngine,yaye729125/gles,nicolasgramlich/AndEngine,jduberville/AndEngine,chautn/AndEngine,yudhir/AndEngine,luoxiaoshenghustedu/AndEngine,shiguang1120/AndEngine,yaye729125/gles,parthipanramesh/AndEngine,nicolasgramlich/AndEngine,msdgwzhy6/AndEngine,godghdai/AndEngine,pongo710/AndEngine,luoxiaoshenghustedu/AndEngine,chautn/AndEngine,ericlaro/AndEngineLibrary,godghdai/AndEngine,viacheslavokolitiy/AndEngine,ericlaro/AndEngineLibrary,viacheslavokolitiy/AndEngine
|
package org.andengine.entity.sprite;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.Scene.ITouchArea;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.util.debug.Debug;
/**
* Note: {@link ButtonSprite} needs to be registered as a {@link ITouchArea} to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}, otherwise it won't be clickable.
* To make {@link ButtonSprite} function properly, you should consider setting {@link Scene#setTouchAreaBindingOnActionDownEnabled(boolean)} to <code>true</code>.
*
* (c) Zynga 2012
*
* @author Scott Kennedy <skennedy@zynga.com>
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 15:51:57 - 05.01.2012
*/
public class ButtonSprite extends TiledSprite {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mStateCount;
private OnClickListener mOnClickListener;
private boolean mEnabled = true;
private State mState;
// ===========================================================
// Constructors
// ===========================================================
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion) {
this(pX, pY, pNormalTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion) {
this(pX, pY, pNormalTextureRegion, pPressedTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion, pPressedTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final ITextureRegion pDisabledTextureRegion) {
this(pX, pY, pNormalTextureRegion, pPressedTextureRegion, pDisabledTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final ITextureRegion pDisabledTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion, pPressedTextureRegion, pDisabledTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pTiledTextureRegion) {
this(pX, pY, pTiledTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pTiledTextureRegion, final OnClickListener pOnClickListener) {
super(pX, pY, pTiledTextureRegion);
this.mOnClickListener = pOnClickListener;
this.mStateCount = pTiledTextureRegion.getTileCount();
switch(this.mStateCount) {
case 1:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.PRESSED + ".");
case 2:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.DISABLED + ".");
break;
case 3:
break;
default:
throw new IllegalArgumentException("The supplied " + ITiledTextureRegion.class.getSimpleName() + " has an unexpected amount of states: '" + this.mStateCount + "'.");
}
this.changeState(State.NORMAL);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isEnabled() {
return this.mEnabled;
}
public void setEnabled(final boolean pEnabled) {
this.mEnabled = pEnabled;
if(this.mEnabled && this.mState == State.DISABLED) {
this.changeState(State.NORMAL);
} else if(!this.mEnabled) {
this.changeState(State.DISABLED);
}
}
public boolean isPressed() {
return this.mState == State.PRESSED;
}
public void setOnClickListener(final OnClickListener pOnClickListener) {
this.mOnClickListener = pOnClickListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if(!this.mEnabled) {
this.changeState(State.DISABLED);
} else if(pSceneTouchEvent.isActionDown()) {
this.changeState(State.PRESSED);
} else if(pSceneTouchEvent.isActionCancel() || !this.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
this.changeState(State.NORMAL);
} else if(pSceneTouchEvent.isActionUp() && this.mState == State.PRESSED) {
this.changeState(State.NORMAL);
if(this.mOnClickListener != null) {
this.mOnClickListener.onClick(this, pTouchAreaLocalX, pTouchAreaLocalY);
}
}
return true;
}
@Override
public boolean contains(final float pX, final float pY) {
if(!this.isVisible()) {
return false;
} else {
return super.contains(pX, pY);
}
}
// ===========================================================
// Methods
// ===========================================================
private void changeState(final State pState) {
if(pState == this.mState) {
return;
}
this.mState = pState;
final int stateTiledTextureRegionIndex = this.mState.getTiledTextureRegionIndex();
if(stateTiledTextureRegionIndex >= this.mStateCount) {
this.setCurrentTileIndex(0);
Debug.w(this.getClass().getSimpleName() + " changed its " + State.class.getSimpleName() + " to " + pState.toString() + ", which doesn't have a " + ITextureRegion.class.getSimpleName() + " supplied. Applying default " + ITextureRegion.class.getSimpleName() + ".");
} else {
this.setCurrentTileIndex(stateTiledTextureRegionIndex);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface OnClickListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onClick(final ButtonSprite pButtonSprite, final float pTouchAreaLocalX, final float pTouchAreaLocalY);
}
private static enum State {
// ===========================================================
// Elements
// ===========================================================
NORMAL(0),
PRESSED(1),
DISABLED(2);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mTiledTextureRegionIndex;
// ===========================================================
// Constructors
// ===========================================================
private State(final int pTiledTextureRegionIndex) {
this.mTiledTextureRegionIndex = pTiledTextureRegionIndex;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getTiledTextureRegionIndex() {
return this.mTiledTextureRegionIndex;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
|
src/org/andengine/entity/sprite/ButtonSprite.java
|
package org.andengine.entity.sprite;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.Scene.ITouchArea;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.util.debug.Debug;
/**
* Note: {@link ButtonSprite} needs to be registered as a {@link ITouchArea} to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}, otherwise it won't be clickable.
* To make {@link ButtonSprite} function properly, you should consider setting {@link Scene#setTouchAreaBindingOnActionDownEnabled(boolean)} to <code>true</code>.
*
* (c) Zynga 2012
*
* @author Scott Kennedy <skennedy@zynga.com>
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 15:51:57 - 05.01.2012
*/
public class ButtonSprite extends TiledSprite {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mStateCount;
private OnClickListener mOnClickListener;
private boolean mEnabled = true;
private State mState;
// ===========================================================
// Constructors
// ===========================================================
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion) {
this(pX, pY, pNormalTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion) {
this(pX, pY, pNormalTextureRegion, pPressedTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion, pPressedTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final ITextureRegion pDisabledTextureRegion) {
this(pX, pY, pNormalTextureRegion, pPressedTextureRegion, pDisabledTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITextureRegion pNormalTextureRegion, final ITextureRegion pPressedTextureRegion, final ITextureRegion pDisabledTextureRegion, final OnClickListener pOnClickListener) {
this(pX, pY, new TiledTextureRegion(pNormalTextureRegion.getTexture(), pNormalTextureRegion, pPressedTextureRegion, pDisabledTextureRegion), pOnClickListener);
}
public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pTiledTextureRegion) {
this(pX, pY, pTiledTextureRegion, (OnClickListener) null);
}
public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pTiledTextureRegion, final OnClickListener pOnClickListener) {
super(pX, pY, pTiledTextureRegion);
this.mOnClickListener = pOnClickListener;
this.mStateCount = pTiledTextureRegion.getTileCount();
switch(this.mStateCount) {
case 1:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.PRESSED + ".");
case 2:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.DISABLED + ".");
break;
case 3:
break;
default:
throw new IllegalArgumentException("The supplied " + ITiledTextureRegion.class.getSimpleName() + " has an unexpected amount of states: '" + this.mStateCount + "'.");
}
this.changeState(State.NORMAL);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isEnabled() {
return this.mEnabled;
}
public void setEnabled(final boolean pEnabled) {
this.mEnabled = pEnabled;
if(this.mEnabled && this.mState == State.DISABLED) {
this.changeState(State.NORMAL);
} else if(!this.mEnabled) {
this.changeState(State.DISABLED);
}
}
public boolean isPressed() {
return this.mState == State.PRESSED;
}
public void setOnClickListener(final OnClickListener pOnClickListener) {
this.mOnClickListener = pOnClickListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if(!this.mEnabled) {
this.changeState(State.DISABLED);
} else if(pSceneTouchEvent.isActionDown()) {
this.changeState(State.PRESSED);
} else if(pSceneTouchEvent.isActionCancel() || !this.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) {
this.changeState(State.NORMAL);
} else if(pSceneTouchEvent.isActionUp() && this.mState == State.PRESSED) {
this.changeState(State.NORMAL);
if(this.mOnClickListener != null) {
this.mOnClickListener.onClick(this, pTouchAreaLocalX, pTouchAreaLocalY);
}
}
return true;
}
@Override
public boolean contains(final float pX, final float pY) {
if(!this.isVisible()) {
return false;
} else {
return super.contains(pX, pY);
}
}
// ===========================================================
// Methods
// ===========================================================
private void changeState(final State pState) {
if(pState == this.mState) {
return;
}
this.mState = pState;
final int stateTiledTextureRegionIndex = this.mState.getTiledTextureRegionIndex();
if(stateTiledTextureRegionIndex >= this.mStateCount) {
this.setCurrentTileIndex(0);
Debug.w(this.getClass().getSimpleName() + " changed its " + State.class.getSimpleName() + " to " + pState.toString() + ", which doesn't have a " + ITextureRegion.class.getSimpleName()
+ " supplied. Applying default " + ITextureRegion.class.getSimpleName() + ".");
} else {
this.setCurrentTileIndex(stateTiledTextureRegionIndex);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface OnClickListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onClick(final ButtonSprite pButtonSprite, final float pTouchAreaLocalX, final float pTouchAreaLocalY);
}
private static enum State {
// ===========================================================
// Elements
// ===========================================================
NORMAL(0), PRESSED(1), DISABLED(2);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mTiledTextureRegionIndex;
// ===========================================================
// Constructors
// ===========================================================
private State(final int pTiledTextureRegionIndex) {
this.mTiledTextureRegionIndex = pTiledTextureRegionIndex;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getTiledTextureRegionIndex() {
return this.mTiledTextureRegionIndex;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
|
Fixed formatting.
|
src/org/andengine/entity/sprite/ButtonSprite.java
|
Fixed formatting.
|
|
Java
|
apache-2.0
|
e52d7df695a81c71f9cc064b61436616fe8df60f
| 0
|
luismcl/crossdata,hdominguez1989/Crossdata,pmadrigal/Crossdata,pfcoperez/crossdata,gserranojc/Crossdata,jjlopezm/crossdata,darroyocazorla/crossdata,pmadrigal/Crossdata,gserranojc/Crossdata,compae/Crossdata,Stratio/crossdata,darroyocazorla/crossdata,ccaballe/crossdata,compae/Crossdata,Stratio/crossdata,luismcl/crossdata,pfcoperez/crossdata,jjlopezm/crossdata,ccaballe/crossdata,hdominguez1989/Crossdata,miguel0afd/crossdata,miguel0afd/crossdata
|
/*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.inmemory;
import com.stratio.connector.inmemory.datastore.datatypes.SimpleValue;
import com.stratio.connector.inmemory.datastore.selector.InMemoryColumnSelector;
import com.stratio.connector.inmemory.datastore.selector.InMemorySelector;
import com.stratio.crossdata.common.data.ResultSet;
import com.stratio.crossdata.common.data.Row;
import com.stratio.crossdata.common.exceptions.ConnectorException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.exceptions.UnsupportedException;
import com.stratio.crossdata.common.logicalplan.*;
import com.stratio.crossdata.common.metadata.ColumnType;
import com.stratio.crossdata.common.metadata.DataType;
import com.stratio.crossdata.common.metadata.Operations;
import com.stratio.crossdata.common.metadata.TableMetadata;
import com.stratio.crossdata.common.result.QueryResult;
import com.stratio.crossdata.common.statements.structures.*;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.testng.Assert.*;
/**
* Query engine test.
*/
public class InMemoryQueryEngineTest extends InMemoryQueryEngineTestParent {
@Test
public void simpleSelect() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"name"};
ColumnType[] usersTypes = {new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectAllColumns() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name", "boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT),
new ColumnType(DataType.TEXT),
new ColumnType(DataType.BOOLEAN)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterTextEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(1));
StringSelector right = new StringSelector(projectUsers.getTableName(), "User-9");
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterBoolEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.BOOLEAN)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
BooleanSelector right = new BooleanSelector(projectUsers.getTableName(), true);
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS / 2, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterTextEQNoResult() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(1));
StringSelector right = new StringSelector(projectUsers.getTableName(), "User-50");
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 0, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterIntEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
IntegerSelector right = new IntegerSelector(projectUsers.getTableName(), 5);
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterNonIndexedIntGT() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
IntegerSelector right = new IntegerSelector(projectUsers.getTableName(), NUM_ROWS/2);
Filter filter = new Filter(singleton(Operations.FILTER_NON_INDEXED_GT),
new Relation(left, Operator.GT, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), (NUM_ROWS/2)-1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectBoolOrder() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.BOOLEAN)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "boss", OrderDirection.DESC);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
int i = 0;
for (Row row: results.getRows()){
if (i<5){
assertTrue((Boolean) row.getCell("boss").getValue(),"Invalid Result OrderBy");
}else{
assertFalse((Boolean) row.getCell("boss").getValue(), "Invalid Result OrderBy");
}
i++;
}
}
@Test
public void sortNumberASC() throws UnsupportedException, ExecutionException {
sortNumber(OrderDirection.ASC);
}
@Test
public void sortNumberDES() throws UnsupportedException, ExecutionException {
sortNumber(OrderDirection.DESC);
}
public void sortNumber(OrderDirection direction) throws UnsupportedException, ExecutionException {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "id", direction);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
InMemorySelector column = new InMemoryColumnSelector("id");
List<SimpleValue[]> results = new ArrayList<>();
results.add(new SimpleValue[]{new SimpleValue(column, 2)});
results.add(new SimpleValue[]{new SimpleValue(column, 1)});
results.add(new SimpleValue[]{new SimpleValue(column, 3)});
results.add(new SimpleValue[]{new SimpleValue(column, 4)});
//Experimentation
List<SimpleValue[]> result = ((InMemoryQueryEngine)connector.getQueryEngine()).orderResult(results, workflow);
//Espectations
int i =direction.equals(OrderDirection.DESC) ? result.size():1;
for (SimpleValue[] value: result){
assertEquals(value[0].getValue(), direction.equals(OrderDirection.DESC) ? i-- : i++, "Invalid Order");
}
}
@Test
public void sortBoolDES() throws UnsupportedException, ExecutionException {
sortBool(OrderDirection.DESC);
}
@Test
public void sortBoolASC() throws UnsupportedException, ExecutionException {
sortBool(OrderDirection.ASC);
}
public void sortBool(OrderDirection direction) throws UnsupportedException, ExecutionException {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id","boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.BOOLEAN)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "boss", direction);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
InMemorySelector columnBoss = new InMemoryColumnSelector("boss");
InMemorySelector columnId = new InMemoryColumnSelector("id");
List<SimpleValue[]> results = new ArrayList<>();
results.add(new SimpleValue[]{new SimpleValue(columnId, 1),new SimpleValue(columnBoss, false)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 2),new SimpleValue(columnBoss, true)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 3),new SimpleValue(columnBoss, false)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 4),new SimpleValue(columnBoss, true)});
//Experimentation
List<SimpleValue[]> result = ((InMemoryQueryEngine)connector.getQueryEngine()).orderResult(results, workflow);
//Espectations
int i = 0;
for (SimpleValue[] value: result){
if (direction.equals(OrderDirection.ASC)){
assertTrue((Boolean) value[1].getValue().equals(i >= result.size()/2) , "Bad Order");
}else{
assertTrue((Boolean) value[1].getValue().equals(i < result.size()/2) , "Bad Order");
}
i++;
}
}
@Test
public void testCompareCellsASC() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.ASC, true, false), -1);
}
@Test
public void testCompareCellsASCCase2() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.ASC, false, true), 1);
}
@Test
public void testCompareCellsDESC() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.DESC, true, false), 1);
}
@Test
public void testCompareCellsDESCCase2() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.DESC, false, true), -1);
}
@Test
public void testCompareCellsDESCNumber() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.DESC, 1, 2), -1);
}
@Test
public void testCompareCellsASCNumber() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.ASC, 1, 2), 1);
}
@Test
public void testCompareCellsASCNumberEQ() throws UnsupportedException {
assertEquals(compareCell(OrderDirection.DESC, 1, 1), 0);
}
public int compareCell(OrderDirection direction, Object value1, Object value2) throws UnsupportedException {
buildUsersTable();
SimpleValue toBeOrdered = new SimpleValue(null, value1);
SimpleValue alreadyOrdered = new SimpleValue(null, value2);
return ((InMemoryQueryEngine)connector.getQueryEngine()).compareCells(toBeOrdered, alreadyOrdered, direction);
}
@Test
public void testBugCROSSDATA_516(){
TableMetadata incomeTable = buildIncomeTable();
Map<String, Object> values = new HashMap<>();
values.put("id", 5);
values.put("money",4.4);
values.put("reten", new Double(-40.4));
insertTestData(clusterName, incomeTable, values);
String [] columnNames = {"money", "reten"};
ColumnType[] usersTypes = {new ColumnType(DataType.DOUBLE), new ColumnType(DataType.DOUBLE)};
Project project = generateProjectAndSelect(columnNames, usersTypes, incomeTable.getName());
ColumnSelector left = new ColumnSelector(project.getColumnList().get(1));
FloatingPointSelector right = new FloatingPointSelector(project.getTableName(), new Double(-40.40));
Filter filter = new Filter(singleton(Operations.FILTER_NON_INDEXED_LT), new Relation(left, Operator.LT, right));
Select s = Select.class.cast(project.getNextStep());
filter.setNextStep(s);
project.setNextStep(filter);
filter.setPrevious(project);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) project));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 0, "Invalid number of results returned");
}
}
|
crossdata-connector-inmemory/src/test/java/com/stratio/connector/inmemory/InMemoryQueryEngineTest.java
|
/*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.inmemory;
import com.stratio.connector.inmemory.datastore.datatypes.SimpleValue;
import com.stratio.connector.inmemory.datastore.selector.InMemoryColumnSelector;
import com.stratio.connector.inmemory.datastore.selector.InMemorySelector;
import com.stratio.crossdata.common.data.ResultSet;
import com.stratio.crossdata.common.data.Row;
import com.stratio.crossdata.common.exceptions.ConnectorException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.exceptions.UnsupportedException;
import com.stratio.crossdata.common.logicalplan.*;
import com.stratio.crossdata.common.metadata.ColumnType;
import com.stratio.crossdata.common.metadata.DataType;
import com.stratio.crossdata.common.metadata.Operations;
import com.stratio.crossdata.common.metadata.TableMetadata;
import com.stratio.crossdata.common.result.QueryResult;
import com.stratio.crossdata.common.statements.structures.*;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.testng.Assert.*;
/**
* Query engine test.
*/
public class InMemoryQueryEngineTest extends InMemoryQueryEngineTestParent {
@Test
public void simpleSelect() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"name"};
ColumnType[] usersTypes = {new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectAllColumns() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name", "boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT),
new ColumnType(DataType.TEXT),
new ColumnType(DataType.BOOLEAN)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterTextEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(1));
StringSelector right = new StringSelector(projectUsers.getTableName(), "User-9");
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterBoolEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.BOOLEAN)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
BooleanSelector right = new BooleanSelector(projectUsers.getTableName(), true);
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS / 2, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterTextEQNoResult() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id", "name"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.TEXT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(1));
StringSelector right = new StringSelector(projectUsers.getTableName(), "User-50");
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 0, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterIntEQ() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
IntegerSelector right = new IntegerSelector(projectUsers.getTableName(), 5);
Filter filter = new Filter(
singleton(Operations.FILTER_NON_INDEXED_EQ),
new Relation(left, Operator.EQ, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectFilterNonIndexedIntGT() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName());
ColumnSelector left = new ColumnSelector(projectUsers.getColumnList().get(0));
IntegerSelector right = new IntegerSelector(projectUsers.getTableName(), NUM_ROWS/2);
Filter filter = new Filter(singleton(Operations.FILTER_NON_INDEXED_GT),
new Relation(left, Operator.GT, right));
Select s = Select.class.cast(projectUsers.getNextStep());
filter.setNextStep(s);
projectUsers.setNextStep(filter);
filter.setPrevious(projectUsers);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), (NUM_ROWS/2)-1, "Invalid number of results returned");
checkResultMetadata(results, usersColumnNames, usersTypes);
}
@Test
public void simpleSelectBoolOrder() {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.BOOLEAN)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "boss", OrderDirection.DESC);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), NUM_ROWS, "Invalid number of results returned");
int i = 0;
for (Row row: results.getRows()){
if (i<5){
assertTrue((Boolean) row.getCell("boss").getValue(),"Invalid Result OrderBy");
}else{
assertFalse((Boolean) row.getCell("boss").getValue(), "Invalid Result OrderBy");
}
i++;
}
}
@Test
public void sortNumberASC() throws UnsupportedException, ExecutionException {
sortNumber(OrderDirection.ASC);
}
@Test
public void sortNumberDES() throws UnsupportedException, ExecutionException {
sortNumber(OrderDirection.DESC);
}
public void sortNumber(OrderDirection direction) throws UnsupportedException, ExecutionException {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "id", direction);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
InMemorySelector column = new InMemoryColumnSelector("id");
List<SimpleValue[]> results = new ArrayList<>();
results.add(new SimpleValue[]{new SimpleValue(column, 2)});
results.add(new SimpleValue[]{new SimpleValue(column, 1)});
results.add(new SimpleValue[]{new SimpleValue(column, 3)});
results.add(new SimpleValue[]{new SimpleValue(column, 4)});
//Experimentation
List<SimpleValue[]> result = ((InMemoryQueryEngine)connector.getQueryEngine()).orderResult(results, workflow);
//Espectations
int i =direction.equals(OrderDirection.DESC) ? result.size():1;
for (SimpleValue[] value: result){
assertEquals(value[0].getValue(), direction.equals(OrderDirection.DESC) ? i-- : i++, "Invalid Order");
}
}
@Test
public void sortBoolDES() throws UnsupportedException, ExecutionException {
sortBool(OrderDirection.DESC);
}
@Test
public void sortBoolASC() throws UnsupportedException, ExecutionException {
sortBool(OrderDirection.ASC);
}
public void sortBool(OrderDirection direction) throws UnsupportedException, ExecutionException {
TableMetadata usersTable = buildUsersTable();
String [] usersColumnNames = {"id","boss"};
ColumnType[] usersTypes = {new ColumnType(DataType.INT), new ColumnType(DataType.BOOLEAN)};
OrderBy orderBy = generateOrderByClausule(usersTable.getName(), "boss", direction);
Project projectUsers = generateProjectAndSelect(usersColumnNames, usersTypes, usersTable.getName(), orderBy);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) projectUsers));
InMemorySelector columnBoss = new InMemoryColumnSelector("boss");
InMemorySelector columnId = new InMemoryColumnSelector("id");
List<SimpleValue[]> results = new ArrayList<>();
results.add(new SimpleValue[]{new SimpleValue(columnId, 1),new SimpleValue(columnBoss, false)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 2),new SimpleValue(columnBoss, true)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 3),new SimpleValue(columnBoss, false)});
results.add(new SimpleValue[]{new SimpleValue(columnId, 4),new SimpleValue(columnBoss, true)});
//Experimentation
List<SimpleValue[]> result = ((InMemoryQueryEngine)connector.getQueryEngine()).orderResult(results, workflow);
//Espectations
int i = 0;
for (SimpleValue[] value: result){
if (direction.equals(OrderDirection.ASC)){
assertTrue((Boolean) value[1].getValue().equals(i >= result.size()/2) , "Bad Order");
}else{
assertTrue((Boolean) value[1].getValue().equals(i < result.size()/2) , "Bad Order");
}
i++;
}
}
@Test
public void testCompareCellsASC() throws UnsupportedException {
testCompareCell(OrderDirection.ASC, true, false, -1);
}
@Test
public void testCompareCellsASCCase2() throws UnsupportedException {
testCompareCell(OrderDirection.ASC, false, true, 1);
}
@Test
public void testCompareCellsDESC() throws UnsupportedException {
testCompareCell(OrderDirection.DESC, true, false, 1);
}
@Test
public void testCompareCellsDESCCase2() throws UnsupportedException {
testCompareCell(OrderDirection.DESC, false, true, -1);
}
@Test
public void testCompareCellsDESCNumber() throws UnsupportedException {
testCompareCell(OrderDirection.DESC, 1, 2, -1);
}
@Test
public void testCompareCellsASCNumber() throws UnsupportedException {
testCompareCell(OrderDirection.ASC, 1, 2, 1);
}
@Test
public void testCompareCellsASCNumberEQ() throws UnsupportedException {
testCompareCell(OrderDirection.DESC, 1, 1, 0);
}
public void testCompareCell(OrderDirection direction, Object value1, Object value2, int expected) throws UnsupportedException {
buildUsersTable();
SimpleValue toBeOrdered = new SimpleValue(null, value1);
SimpleValue alreadyOrdered = new SimpleValue(null, value2);
int result = ((InMemoryQueryEngine)connector.getQueryEngine()).compareCells(toBeOrdered, alreadyOrdered, direction);
assertEquals(result, expected);
}
@Test
public void testBugCROSSDATA_516(){
TableMetadata incomeTable = buildIncomeTable();
Map<String, Object> values = new HashMap<>();
values.put("id", 5);
values.put("money",4.4);
values.put("reten", new Double(-40.4));
insertTestData(clusterName, incomeTable, values);
String [] columnNames = {"money", "reten"};
ColumnType[] usersTypes = {new ColumnType(DataType.DOUBLE), new ColumnType(DataType.DOUBLE)};
Project project = generateProjectAndSelect(columnNames, usersTypes, incomeTable.getName());
ColumnSelector left = new ColumnSelector(project.getColumnList().get(1));
FloatingPointSelector right = new FloatingPointSelector(project.getTableName(), new Double(-40.40));
Filter filter = new Filter(singleton(Operations.FILTER_NON_INDEXED_LT), new Relation(left, Operator.LT, right));
Select s = Select.class.cast(project.getNextStep());
filter.setNextStep(s);
project.setNextStep(filter);
filter.setPrevious(project);
s.setPrevious(filter);
LogicalWorkflow workflow = new LogicalWorkflow(singletonList((LogicalStep) project));
ResultSet results = null;
try {
QueryResult result = connector.getQueryEngine().execute(workflow);
results = result.getResultSet();
} catch (ConnectorException e) {
fail("Cannot retrieve data", e);
}
assertEquals(results.size(), 0, "Invalid number of results returned");
}
}
|
minor changes
|
crossdata-connector-inmemory/src/test/java/com/stratio/connector/inmemory/InMemoryQueryEngineTest.java
|
minor changes
|
|
Java
|
apache-2.0
|
41673ce6f6db8e0e913ec09bca0c5b2f1aa067b3
| 0
|
korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,korpling/ANNIS,zangsir/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS
|
/*
* Copyright 2013 Corpuslinguistic working group Humboldt University Berlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package annis.gui;
import annis.libgui.Helper;
import annis.gui.beans.HistoryEntry;
import annis.gui.components.ExceptionDialog;
import annis.libgui.media.MediaController;
import annis.gui.model.PagedResultQuery;
import annis.gui.model.Query;
import annis.gui.paging.PagingCallback;
import annis.gui.resultview.ResultViewPanel;
import annis.gui.resultview.SingleResultPanel;
import annis.gui.resultview.VisualizerContextChanger;
import annis.gui.resultview.VisualizerPanel;
import annis.libgui.PollControl;
import annis.libgui.visualizers.IFrameResourceMap;
import annis.service.objects.MatchAndDocumentCount;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.sun.jersey.api.client.AsyncWebResource;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.Tab;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.collections15.set.ListOrderedSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manages all the query related actions.
*
* <strong>This class is not reentrant.</strong>
* It is expected that you call the functions from the Vaadin session lock
* context, either implicitly (e.g. from a component constructor or a handler
* callback) or explicitly with {@link VaadinSession#lock() }.
*
* @author Thomas Krause <krauseto@hu-berlin.de>
*/
public class QueryController implements TabSheet.SelectedTabChangeListener,
Serializable
{
private static final Logger log = LoggerFactory.getLogger(
ResultViewPanel.class);
private final SearchUI ui;
private transient Future<?> lastMatchFuture;
private final ListOrderedSet<HistoryEntry> history;
private Future<MatchAndDocumentCount> futureCount;
private UUID lastQueryUUID;
private PagedResultQuery preparedQuery;
private transient Map<UUID, PagedResultQuery> queries;
private transient BiMap<UUID, ResultViewPanel> queryPanels;
private transient Map<UUID, MatchAndDocumentCount> counts;
private Map<UUID, Map<Integer, PagedResultQuery>> updatedQueries;
private int maxShortID;
private transient List<CorpusSelectionChangeListener> corpusSelChangeListeners
= new LinkedList<CorpusSelectionChangeListener>();
public QueryController(SearchUI ui)
{
this.ui = ui;
this.history = new ListOrderedSet<HistoryEntry>();
}
public void updateCorpusSetList()
{
ui.getControlPanel().getCorpusList().updateCorpusSetList();
}
public void setQueryFromUI()
{
setQuery(ui.getControlPanel().getQueryPanel().getQuery());
}
public void setQuery(String query)
{
setQuery(new Query(query, ui.getControlPanel().getCorpusList().
getSelectedCorpora()));
}
public void setQuery(Query query)
{
// Check if a corpus is selected.
if (ui.getControlPanel().getCorpusList().getSelectedCorpora().isEmpty()
&& query.getCorpora() != null)
{
ui.getControlPanel().getCorpusList().selectCorpora(query.getCorpora());
}
PagedResultQuery paged = new PagedResultQuery(
ui.getControlPanel().getSearchOptions().getLeftContext(),
ui.getControlPanel().getSearchOptions().getRightContext(),
0,
ui.getControlPanel().getSearchOptions().getResultsPerPage(),
ui.getControlPanel().getSearchOptions().getSegmentationLayer(),
query.getQuery(), query.getCorpora());
setQuery(paged);
}
public void setQuery(PagedResultQuery query)
{
// only allow offset at multiples of the limit size
query.setOffset(query.getOffset() - (query.getOffset() % query.getLimit()));
preparedQuery = query;
ui.getControlPanel().getQueryPanel().setQuery(query.getQuery());
ui.getControlPanel().getSearchOptions().setLeftContext(query.
getContextLeft());
ui.getControlPanel().getSearchOptions().setRightContext(query.
getContextRight());
ui.getControlPanel().getSearchOptions().setSegmentationLayer(query.
getSegmentation());
if (query.getCorpora() != null)
{
ui.getControlPanel().getCorpusList().selectCorpora(query.getCorpora());
}
}
/**
* Cancel queries from the client side.
*
* Important: This does not magically cancel the query on the server side, so
* don't use this to implement a "real" query cancelation.
*/
private void cancelQueries()
{
// don't spin forever when canceled
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(false);
// abort last tasks if running
if (futureCount != null && !futureCount.isDone())
{
futureCount.cancel(true);
}
if (lastMatchFuture != null && !lastMatchFuture.isDone())
{
lastMatchFuture.cancel(true);
}
futureCount = null;
}
/**
* Adds a history entry to the history panel.
*
* @param e the entry, which is added.
*
* @see HistoryPanel
*/
public void addHistoryEntry(HistoryEntry e)
{
// remove it first in order to let it appear on the beginning of the list
history.remove(e);
history.add(0, e);
ui.getControlPanel().getQueryPanel().updateShortHistory(history.asList());
}
public void addCorpusSelectionChangeListener(
CorpusSelectionChangeListener listener)
{
if (corpusSelChangeListeners == null)
{
corpusSelChangeListeners = new LinkedList<CorpusSelectionChangeListener>();
}
corpusSelChangeListeners.add(listener);
}
public void removeCorpusSelectionChangeListener(
CorpusSelectionChangeListener listener)
{
if (corpusSelChangeListeners == null)
{
corpusSelChangeListeners = new LinkedList<CorpusSelectionChangeListener>();
}
else
{
corpusSelChangeListeners.remove(listener);
}
}
public UUID executeQuery()
{
return executeQuery(true);
}
/**
* Common actions for preparing the executions of a query.
*/
private void prepareExecuteQuery()
{
cancelQueries();
// cleanup resources
VaadinSession session = VaadinSession.getCurrent();
session.setAttribute(IFrameResourceMap.class, new IFrameResourceMap());
if (session.getAttribute(MediaController.class) != null)
{
session.getAttribute(MediaController.class).clearMediaPlayers();
}
ui.updateFragment(preparedQuery);
HistoryEntry e = new HistoryEntry();
e.setCorpora(preparedQuery.getCorpora());
e.setQuery(preparedQuery.getQuery());
addHistoryEntry(e);
}
public UUID executeQuery(boolean replaceOldTab)
{
Validate.notNull(preparedQuery,
"You have to set a query before you can execute it.");
prepareExecuteQuery();
if (preparedQuery.getCorpora() == null || preparedQuery.getCorpora().
isEmpty())
{
Notification.show("Please select a corpus",
Notification.Type.WARNING_MESSAGE);
return null;
}
if ("".equals(preparedQuery.getQuery()))
{
Notification.show("Empty query", Notification.Type.WARNING_MESSAGE);
return null;
}
UUID oldQueryUUID = lastQueryUUID;
lastQueryUUID = UUID.randomUUID();
AsyncWebResource res = Helper.getAnnisAsyncWebResource();
//
// begin execute match fetching
//
// remove old result from view
ResultViewPanel oldPanel = getQueryPanels().get(oldQueryUUID);
if (replaceOldTab && oldQueryUUID != null && oldPanel != null)
{
removeQuery(oldQueryUUID);
}
// create a short ID for display
maxShortID++;
ResultViewPanel newResultView = new ResultViewPanel(this, ui, lastQueryUUID,
ui.getInstanceConfig());
Tab newTab;
String caption = getQueryPanels().isEmpty()
? "Query Result" : "Query Result #" + maxShortID;
if (replaceOldTab && oldPanel != null)
{
ui.getMainTab().replaceComponent(oldPanel, newResultView);
newTab = ui.getMainTab().getTab(newResultView);
newTab.setCaption(caption);
}
else
{
newTab = ui.getMainTab().addTab(newResultView, caption);
newTab.setClosable(true);
newTab.setIcon(new ThemeResource("tango-icons/16x16/system-search.png"));
}
ui.getMainTab().setSelectedTab(newResultView);
newResultView.getPaging().addCallback(new SpecificPagingCallback(
lastQueryUUID));
getQueryPanels().put(lastQueryUUID, newResultView);
PollControl.runInBackground(500, ui, new ResultFetchJob(preparedQuery,
newResultView, ui));
//
// end execute match fetching
//
//
// begin execute count
//
// start count query
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(true);
futureCount = res.path("query").path("search").path("count").
queryParam(
"q", preparedQuery.getQuery()).queryParam("corpora",
StringUtils.join(preparedQuery.getCorpora(), ",")).get(
MatchAndDocumentCount.class);
PollControl.runInBackground(500, ui, new CountCallback(lastQueryUUID));
//
// end execute count
//
// remember the query object for later re-usage
getQueries().put(lastQueryUUID, preparedQuery);
return lastQueryUUID;
}
private void updateMatches(UUID uuid, PagedResultQuery newQuery)
{
ResultViewPanel panel = getQueryPanels().get(uuid);
if (panel != null && preparedQuery != null)
{
prepareExecuteQuery();
getQueries().put(uuid, newQuery);
lastMatchFuture = PollControl.runInBackground(500, ui,
new ResultFetchJob(newQuery,
panel, ui));
}
}
public void corpusSelectionChangedInBackground()
{
ui.getControlPanel().getSearchOptions()
.updateSearchPanelConfigurationInBackground(ui.getControlPanel().
getCorpusList().
getSelectedCorpora());
ui.updateFragementWithSelectedCorpus(getSelectedCorpora());
if (corpusSelChangeListeners != null)
{
Set<String> selected = getSelectedCorpora();
for (CorpusSelectionChangeListener listener : corpusSelChangeListeners)
{
listener.onCorpusSelectionChanged(selected);
}
}
}
@Override
public void selectedTabChange(TabSheet.SelectedTabChangeEvent event)
{
if (event.getTabSheet().getSelectedTab() instanceof ResultViewPanel)
{
ResultViewPanel panel = (ResultViewPanel) event.getTabSheet().
getSelectedTab();
UUID uuid = getQueryPanels().inverse().get(panel);
if (uuid != null)
{
lastQueryUUID = uuid;
PagedResultQuery query = getQueries().get(uuid);
if (query != null)
{
ui.updateFragment(query);
}
}
}
}
public Set<String> getSelectedCorpora()
{
return ui.getControlPanel().getCorpusList().getSelectedCorpora();
}
/**
* Get the query that is currently prepared for execution, but not executed
* yet.
*
* @return
*/
public PagedResultQuery getPreparedQuery()
{
return preparedQuery;
}
/**
* Clear the collected informations about a certain query. Also remove any
* attached {@link ResultViewPanel} for that query.
*
* @param uuid The UUID of the query to remove.
*/
private void removeQuery(UUID uuid)
{
if (uuid != null)
{
getQueries().remove(uuid);
getQueryPanels().remove(uuid);
getCounts().remove(uuid);
}
}
public void notifyTabClose(ResultViewPanel panel)
{
if (panel != null)
{
removeQuery(getQueryPanels().inverse().get(panel));
}
}
public String getQueryDraft()
{
return ui.getControlPanel().getQueryPanel().getQuery();
}
private Map<UUID, PagedResultQuery> getQueries()
{
if (queries == null)
{
queries = new HashMap<UUID, PagedResultQuery>();
}
return queries;
}
private BiMap<UUID, ResultViewPanel> getQueryPanels()
{
if (queryPanels == null)
{
queryPanels = HashBiMap.create();
}
return queryPanels;
}
private Map<UUID, MatchAndDocumentCount> getCounts()
{
if (counts == null)
{
counts = new HashMap<UUID, MatchAndDocumentCount>();
}
return counts;
}
private class SpecificPagingCallback implements PagingCallback
{
private UUID uuid;
public SpecificPagingCallback(UUID uuid)
{
this.uuid = uuid;
}
@Override
public void switchPage(int offset, int limit)
{
PagedResultQuery query = getQueries().get(uuid);
if (query != null)
{
query.setOffset(offset);
query.setLimit(limit);
// execute the result query again
updateMatches(uuid, query);
}
}
}
private class CountCallback implements Runnable
{
private UUID uuid;
public CountCallback(UUID uuid)
{
this.uuid = uuid;
}
@Override
public void run()
{
final MatchAndDocumentCount countResult;
MatchAndDocumentCount tmpCountResult = null;
if (futureCount != null)
{
UniformInterfaceException cause = null;
try
{
tmpCountResult = futureCount.get();
getCounts().put(uuid, tmpCountResult);
}
catch (InterruptedException ex)
{
log.warn(null, ex);
}
catch (ExecutionException root)
{
if (root.getCause() instanceof UniformInterfaceException)
{
cause = (UniformInterfaceException) root.getCause();
}
else
{
log.error("Unexcepted ExecutionException cause", root);
}
}
finally
{
countResult = tmpCountResult;
}
futureCount = null;
final UniformInterfaceException causeFinal = cause;
ui.accessSynchronously(new Runnable()
{
@Override
public void run()
{
if (causeFinal == null)
{
if (countResult != null)
{
String documentString = countResult.getDocumentCount() > 1 ? "documents" : "document";
String matchesString = countResult.getMatchCount() > 1 ? "matches" : "match";
ui.getControlPanel().getQueryPanel().setStatus("" + countResult.
getMatchCount() + " " + matchesString
+ "\nin " + countResult.getDocumentCount() + " " + documentString);
if (lastQueryUUID != null && countResult.getMatchCount() > 0
&& getQueryPanels().get(lastQueryUUID) != null)
{
getQueryPanels().get(lastQueryUUID).getPaging().setPageSize(
getQueries().get(uuid).getLimit(), false);
getQueryPanels().get(lastQueryUUID).setCount(countResult.
getMatchCount());
}
}
}
else
{
if (causeFinal.getResponse().getStatus() == 400)
{
Notification.show(
"parsing error",
causeFinal.getResponse().getEntity(String.class),
Notification.Type.WARNING_MESSAGE);
}
else if (causeFinal.getResponse().getStatus() == 504) // gateway timeout
{
Notification.show(
"Timeout: query execution took too long.",
"Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
Notification.Type.WARNING_MESSAGE);
}
else
{
log.error("Unexpected exception: " + causeFinal.
getLocalizedMessage(), causeFinal);
ExceptionDialog.show(causeFinal);
}
} // end if cause != null
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(false);
}
});
}
}
}
public void changeCtx(UUID queryID, int offset, int context,
VisualizerContextChanger visCtxChange, boolean left)
{
PagedResultQuery query;
if (queries.containsKey(queryID) && queryPanels.containsKey(queryID))
{
if (updatedQueries == null)
{
updatedQueries = new HashMap<UUID, Map<Integer, PagedResultQuery>>();
}
if (!updatedQueries.containsKey(queryID))
{
updatedQueries.put(queryID, new HashMap<Integer, PagedResultQuery>());
}
if (!updatedQueries.get(queryID).containsKey(offset))
{
query = (PagedResultQuery) queries.get(queryID).clone();
updatedQueries.get(queryID).put(offset, query);
}
else
{
query = updatedQueries.get(queryID).get(offset);
}
if (left)
{
query.setContextLeft(context);
}
else
{
query.setContextRight(context);
}
query.setOffset(offset);
query.setLimit(1);
// TODO do not delete queries
PollControl.runInBackground(500, ui, new SingleResultFetchJob(query,
queryPanels.get(queryID), ui, visCtxChange));
}
else
{
log.warn("no query with {} found");
return;
}
}
}
|
annis-gui/src/main/java/annis/gui/QueryController.java
|
/*
* Copyright 2013 Corpuslinguistic working group Humboldt University Berlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package annis.gui;
import annis.libgui.Helper;
import annis.gui.beans.HistoryEntry;
import annis.gui.components.ExceptionDialog;
import annis.libgui.media.MediaController;
import annis.gui.model.PagedResultQuery;
import annis.gui.model.Query;
import annis.gui.paging.PagingCallback;
import annis.gui.resultview.ResultViewPanel;
import annis.gui.resultview.SingleResultPanel;
import annis.gui.resultview.VisualizerContextChanger;
import annis.gui.resultview.VisualizerPanel;
import annis.libgui.PollControl;
import annis.libgui.visualizers.IFrameResourceMap;
import annis.service.objects.MatchAndDocumentCount;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.sun.jersey.api.client.AsyncWebResource;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.Tab;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.collections15.set.ListOrderedSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manages all the query related actions.
*
* <strong>This class is not reentrant.</strong>
* It is expected that you call the functions from the Vaadin session lock
* context, either implicitly (e.g. from a component constructor or a handler
* callback) or explicitly with {@link VaadinSession#lock() }.
*
* @author Thomas Krause <krauseto@hu-berlin.de>
*/
public class QueryController implements TabSheet.SelectedTabChangeListener,
Serializable
{
private static final Logger log = LoggerFactory.getLogger(
ResultViewPanel.class);
private final SearchUI ui;
private transient Future<?> lastMatchFuture;
private final ListOrderedSet<HistoryEntry> history;
private Future<MatchAndDocumentCount> futureCount;
private UUID lastQueryUUID;
private PagedResultQuery preparedQuery;
private transient Map<UUID, PagedResultQuery> queries;
private transient BiMap<UUID, ResultViewPanel> queryPanels;
private transient Map<UUID, MatchAndDocumentCount> counts;
private Map<UUID, Map<Integer, PagedResultQuery>> updatedQueries;
private int maxShortID;
private transient List<CorpusSelectionChangeListener> corpusSelChangeListeners
= new LinkedList<CorpusSelectionChangeListener>();
public QueryController(SearchUI ui)
{
this.ui = ui;
this.history = new ListOrderedSet<HistoryEntry>();
}
public void updateCorpusSetList()
{
ui.getControlPanel().getCorpusList().updateCorpusSetList();
}
public void setQueryFromUI()
{
setQuery(ui.getControlPanel().getQueryPanel().getQuery());
}
public void setQuery(String query)
{
setQuery(new Query(query, ui.getControlPanel().getCorpusList().
getSelectedCorpora()));
}
public void setQuery(Query query)
{
// Check if a corpus is selected.
if (ui.getControlPanel().getCorpusList().getSelectedCorpora().isEmpty()
&& query.getCorpora() != null)
{
ui.getControlPanel().getCorpusList().selectCorpora(query.getCorpora());
}
PagedResultQuery paged = new PagedResultQuery(
ui.getControlPanel().getSearchOptions().getLeftContext(),
ui.getControlPanel().getSearchOptions().getRightContext(),
0,
ui.getControlPanel().getSearchOptions().getResultsPerPage(),
ui.getControlPanel().getSearchOptions().getSegmentationLayer(),
query.getQuery(), query.getCorpora());
setQuery(paged);
}
public void setQuery(PagedResultQuery query)
{
// only allow offset at multiples of the limit size
query.setOffset(query.getOffset() - (query.getOffset() % query.getLimit()));
preparedQuery = query;
ui.getControlPanel().getQueryPanel().setQuery(query.getQuery());
ui.getControlPanel().getSearchOptions().setLeftContext(query.
getContextLeft());
ui.getControlPanel().getSearchOptions().setRightContext(query.
getContextRight());
ui.getControlPanel().getSearchOptions().setSegmentationLayer(query.
getSegmentation());
if (query.getCorpora() != null)
{
ui.getControlPanel().getCorpusList().selectCorpora(query.getCorpora());
}
}
/**
* Cancel queries from the client side.
*
* Important: This does not magically cancel the query on the server side, so
* don't use this to implement a "real" query cancelation.
*/
private void cancelQueries()
{
// don't spin forever when canceled
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(false);
// abort last tasks if running
if (futureCount != null && !futureCount.isDone())
{
futureCount.cancel(true);
}
if (lastMatchFuture != null && !lastMatchFuture.isDone())
{
lastMatchFuture.cancel(true);
}
futureCount = null;
}
/**
* Adds a history entry to the history panel.
*
* @param e the entry, which is added.
*
* @see HistoryPanel
*/
public void addHistoryEntry(HistoryEntry e)
{
// remove it first in order to let it appear on the beginning of the list
history.remove(e);
history.add(0, e);
ui.getControlPanel().getQueryPanel().updateShortHistory(history.asList());
}
public void addCorpusSelectionChangeListener(
CorpusSelectionChangeListener listener)
{
if (corpusSelChangeListeners == null)
{
corpusSelChangeListeners = new LinkedList<CorpusSelectionChangeListener>();
}
corpusSelChangeListeners.add(listener);
}
public void removeCorpusSelectionChangeListener(
CorpusSelectionChangeListener listener)
{
if (corpusSelChangeListeners == null)
{
corpusSelChangeListeners = new LinkedList<CorpusSelectionChangeListener>();
}
else
{
corpusSelChangeListeners.remove(listener);
}
}
public UUID executeQuery()
{
return executeQuery(true);
}
/**
* Common actions for preparing the executions of a query.
*/
private void prepareExecuteQuery()
{
cancelQueries();
// cleanup resources
VaadinSession session = VaadinSession.getCurrent();
session.setAttribute(IFrameResourceMap.class, new IFrameResourceMap());
if (session.getAttribute(MediaController.class) != null)
{
session.getAttribute(MediaController.class).clearMediaPlayers();
}
ui.updateFragment(preparedQuery);
HistoryEntry e = new HistoryEntry();
e.setCorpora(preparedQuery.getCorpora());
e.setQuery(preparedQuery.getQuery());
addHistoryEntry(e);
}
public UUID executeQuery(boolean replaceOldTab)
{
Validate.notNull(preparedQuery,
"You have to set a query before you can execute it.");
prepareExecuteQuery();
if (preparedQuery.getCorpora() == null || preparedQuery.getCorpora().
isEmpty())
{
Notification.show("Please select a corpus",
Notification.Type.WARNING_MESSAGE);
return null;
}
if ("".equals(preparedQuery.getQuery()))
{
Notification.show("Empty query", Notification.Type.WARNING_MESSAGE);
return null;
}
UUID oldQueryUUID = lastQueryUUID;
lastQueryUUID = UUID.randomUUID();
AsyncWebResource res = Helper.getAnnisAsyncWebResource();
//
// begin execute match fetching
//
// remove old result from view
ResultViewPanel oldPanel = getQueryPanels().get(oldQueryUUID);
if (replaceOldTab && oldQueryUUID != null && oldPanel != null)
{
//removeQuery(oldQueryUUID);
}
// create a short ID for display
maxShortID++;
ResultViewPanel newResultView = new ResultViewPanel(this, ui, lastQueryUUID,
ui.getInstanceConfig());
Tab newTab;
String caption = getQueryPanels().isEmpty()
? "Query Result" : "Query Result #" + maxShortID;
if (replaceOldTab && oldPanel != null)
{
ui.getMainTab().replaceComponent(oldPanel, newResultView);
newTab = ui.getMainTab().getTab(newResultView);
newTab.setCaption(caption);
}
else
{
newTab = ui.getMainTab().addTab(newResultView, caption);
newTab.setClosable(true);
newTab.setIcon(new ThemeResource("tango-icons/16x16/system-search.png"));
}
ui.getMainTab().setSelectedTab(newResultView);
newResultView.getPaging().addCallback(new SpecificPagingCallback(
lastQueryUUID));
getQueryPanels().put(lastQueryUUID, newResultView);
PollControl.runInBackground(500, ui, new ResultFetchJob(preparedQuery,
newResultView, ui));
//
// end execute match fetching
//
//
// begin execute count
//
// start count query
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(true);
futureCount = res.path("query").path("search").path("count").
queryParam(
"q", preparedQuery.getQuery()).queryParam("corpora",
StringUtils.join(preparedQuery.getCorpora(), ",")).get(
MatchAndDocumentCount.class);
PollControl.runInBackground(500, ui, new CountCallback(lastQueryUUID));
//
// end execute count
//
// remember the query object for later re-usage
getQueries().put(lastQueryUUID, preparedQuery);
return lastQueryUUID;
}
private void updateMatches(UUID uuid, PagedResultQuery newQuery)
{
ResultViewPanel panel = getQueryPanels().get(uuid);
if (panel != null && preparedQuery != null)
{
prepareExecuteQuery();
getQueries().put(uuid, newQuery);
lastMatchFuture = PollControl.runInBackground(500, ui,
new ResultFetchJob(newQuery,
panel, ui));
}
}
public void corpusSelectionChangedInBackground()
{
ui.getControlPanel().getSearchOptions()
.updateSearchPanelConfigurationInBackground(ui.getControlPanel().
getCorpusList().
getSelectedCorpora());
ui.updateFragementWithSelectedCorpus(getSelectedCorpora());
if (corpusSelChangeListeners != null)
{
Set<String> selected = getSelectedCorpora();
for (CorpusSelectionChangeListener listener : corpusSelChangeListeners)
{
listener.onCorpusSelectionChanged(selected);
}
}
}
@Override
public void selectedTabChange(TabSheet.SelectedTabChangeEvent event)
{
if (event.getTabSheet().getSelectedTab() instanceof ResultViewPanel)
{
ResultViewPanel panel = (ResultViewPanel) event.getTabSheet().
getSelectedTab();
UUID uuid = getQueryPanels().inverse().get(panel);
if (uuid != null)
{
lastQueryUUID = uuid;
PagedResultQuery query = getQueries().get(uuid);
if (query != null)
{
ui.updateFragment(query);
}
}
}
}
public Set<String> getSelectedCorpora()
{
return ui.getControlPanel().getCorpusList().getSelectedCorpora();
}
/**
* Get the query that is currently prepared for execution, but not executed
* yet.
*
* @return
*/
public PagedResultQuery getPreparedQuery()
{
return preparedQuery;
}
/**
* Clear the collected informations about a certain query. Also remove any
* attached {@link ResultViewPanel} for that query.
*
* @param uuid The UUID of the query to remove.
*/
private void removeQuery(UUID uuid)
{
if (uuid != null)
{
getQueries().remove(uuid);
getQueryPanels().remove(uuid);
getCounts().remove(uuid);
}
}
public void notifyTabClose(ResultViewPanel panel)
{
if (panel != null)
{
removeQuery(getQueryPanels().inverse().get(panel));
}
}
public String getQueryDraft()
{
return ui.getControlPanel().getQueryPanel().getQuery();
}
private Map<UUID, PagedResultQuery> getQueries()
{
if (queries == null)
{
queries = new HashMap<UUID, PagedResultQuery>();
}
return queries;
}
private BiMap<UUID, ResultViewPanel> getQueryPanels()
{
if (queryPanels == null)
{
queryPanels = HashBiMap.create();
}
return queryPanels;
}
private Map<UUID, MatchAndDocumentCount> getCounts()
{
if (counts == null)
{
counts = new HashMap<UUID, MatchAndDocumentCount>();
}
return counts;
}
private class SpecificPagingCallback implements PagingCallback
{
private UUID uuid;
public SpecificPagingCallback(UUID uuid)
{
this.uuid = uuid;
}
@Override
public void switchPage(int offset, int limit)
{
PagedResultQuery query = getQueries().get(uuid);
if (query != null)
{
query.setOffset(offset);
query.setLimit(limit);
// execute the result query again
updateMatches(uuid, query);
}
}
}
private class CountCallback implements Runnable
{
private UUID uuid;
public CountCallback(UUID uuid)
{
this.uuid = uuid;
}
@Override
public void run()
{
final MatchAndDocumentCount countResult;
MatchAndDocumentCount tmpCountResult = null;
if (futureCount != null)
{
UniformInterfaceException cause = null;
try
{
tmpCountResult = futureCount.get();
getCounts().put(uuid, tmpCountResult);
}
catch (InterruptedException ex)
{
log.warn(null, ex);
}
catch (ExecutionException root)
{
if (root.getCause() instanceof UniformInterfaceException)
{
cause = (UniformInterfaceException) root.getCause();
}
else
{
log.error("Unexcepted ExecutionException cause", root);
}
}
finally
{
countResult = tmpCountResult;
}
futureCount = null;
final UniformInterfaceException causeFinal = cause;
ui.accessSynchronously(new Runnable()
{
@Override
public void run()
{
if (causeFinal == null)
{
if (countResult != null)
{
String documentString = countResult.getDocumentCount() > 1 ? "documents" : "document";
String matchesString = countResult.getMatchCount() > 1 ? "matches" : "match";
ui.getControlPanel().getQueryPanel().setStatus("" + countResult.
getMatchCount() + " " + matchesString
+ "\nin " + countResult.getDocumentCount() + " " + documentString);
if (lastQueryUUID != null && countResult.getMatchCount() > 0
&& getQueryPanels().get(lastQueryUUID) != null)
{
getQueryPanels().get(lastQueryUUID).getPaging().setPageSize(
getQueries().get(uuid).getLimit(), false);
getQueryPanels().get(lastQueryUUID).setCount(countResult.
getMatchCount());
}
}
}
else
{
if (causeFinal.getResponse().getStatus() == 400)
{
Notification.show(
"parsing error",
causeFinal.getResponse().getEntity(String.class),
Notification.Type.WARNING_MESSAGE);
}
else if (causeFinal.getResponse().getStatus() == 504) // gateway timeout
{
Notification.show(
"Timeout: query execution took too long.",
"Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
Notification.Type.WARNING_MESSAGE);
}
else
{
log.error("Unexpected exception: " + causeFinal.
getLocalizedMessage(), causeFinal);
ExceptionDialog.show(causeFinal);
}
} // end if cause != null
ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(false);
}
});
}
}
}
public void changeCtx(UUID queryID, int offset, int context,
VisualizerContextChanger visCtxChange, boolean left)
{
PagedResultQuery query;
if (queries.containsKey(queryID) && queryPanels.containsKey(queryID))
{
if (updatedQueries == null)
{
updatedQueries = new HashMap<UUID, Map<Integer, PagedResultQuery>>();
}
if (!updatedQueries.containsKey(queryID))
{
updatedQueries.put(queryID, new HashMap<Integer, PagedResultQuery>());
}
if (!updatedQueries.get(queryID).containsKey(offset))
{
query = (PagedResultQuery) queries.get(queryID).clone();
updatedQueries.get(queryID).put(offset, query);
}
else
{
query = updatedQueries.get(queryID).get(offset);
}
if (left)
{
query.setContextLeft(context);
}
else
{
query.setContextRight(context);
}
query.setOffset(offset);
query.setLimit(1);
// TODO do not delete queries
PollControl.runInBackground(500, ui, new SingleResultFetchJob(query,
queryPanels.get(queryID), ui, visCtxChange));
}
else
{
log.warn("no query with {} found");
return;
}
}
}
|
Remove old queries.
|
annis-gui/src/main/java/annis/gui/QueryController.java
|
Remove old queries.
|
|
Java
|
apache-2.0
|
5fd2ad2e14896bcf264c856a82d0f55d8e8d4a4c
| 0
|
idunnololz/LoLCraft
|
package com.ggstudios.lolcraft;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Color;
import android.util.Log;
import android.util.SparseIntArray;
import com.ggstudios.lolcraft.ChampionInfo.Skill;
import com.ggstudios.utils.DebugLog;
import com.google.gson.Gson;
/**
* Class that holds information about a build, such as build order, stats and cost.
*/
public class Build {
private static final String TAG = "Build";
public static final int RUNE_TYPE_RED = 0;
public static final int RUNE_TYPE_BLUE = 1;
public static final int RUNE_TYPE_YELLOW = 2;
public static final int RUNE_TYPE_BLACK = 3;
public static final double MAX_ATTACK_SPEED = 2.5;
public static final double MAX_CDR = 0.4;
private static final int[] RUNE_COUNT_MAX = new int[] {
9, 9, 9, 3
};
private static final int[] GROUP_COLOR = new int[] {
0xff2ecc71, // emerald
//0xffe74c3c, // alizarin
0xff3498db, // peter river
0xff9b59b6, // amethyst
0xffe67e22, // carrot
0xff34495e, // wet asphalt
0xff1abc9c, // turquoise
0xfff1c40f, // sun flower
};
private static final int FLAG_SCALING = 0x80000000;
public static final String SN_NULL = "null";
public static final int STAT_NULL = 0;
public static final int STAT_HP = 1;
public static final int STAT_HPR = 2;
public static final int STAT_MP = 3;
public static final int STAT_MPR = 4;
public static final int STAT_AD = 5;
//public static final int STAT_BASE_AS = asdf;
public static final int STAT_ASP = 6;
public static final int STAT_AR = 7;
public static final int STAT_MR = 8;
public static final int STAT_MS = 9;
public static final int STAT_RANGE = 10;
public static final int STAT_CRIT = 11;
public static final int STAT_AP = 12;
public static final int STAT_LS = 13;
public static final int STAT_MSP = 14;
public static final int STAT_CDR = 15;
public static final int STAT_ARPEN = 16;
public static final int STAT_NRG = 17;
public static final int STAT_NRGR = 18;
public static final int STAT_GP10 = 19;
public static final int STAT_MRP = 20;
public static final int STAT_CD = 21;
public static final int STAT_DT = 22;
public static final int STAT_APP = 23;
public static final int STAT_SV = 24;
public static final int STAT_MPENP = 25;
public static final int STAT_APENP = 26;
public static final int STAT_DMG_REDUCTION = 27;
public static final int STAT_CC_RED = 28;
public static final int STAT_AA_TRUE_DAMAGE = 29;
public static final int STAT_AA_MAGIC_DAMAGE = 30;
public static final int STAT_MAGIC_DMG_REDUCTION = 31;
public static final int STAT_MAGIC_HP = 32;
public static final int STAT_INVULNERABILITY = 33;
public static final int STAT_SPELL_BLOCK = 34;
public static final int STAT_CC_IMMUNE = 35;
public static final int STAT_INVULNERABILITY_ALL_BUT_ONE = 36;
public static final int STAT_AOE_DPS_MAGIC = 37;
public static final int STAT_PERCENT_HP_MISSING = 38;
public static final int STAT_TOTAL_AR = 40;
public static final int STAT_TOTAL_AD = 41;
public static final int STAT_TOTAL_HP = 42;
public static final int STAT_CD_MOD = 43;
public static final int STAT_TOTAL_AP = 44;
public static final int STAT_TOTAL_MS = 45;
public static final int STAT_TOTAL_MR = 46;
public static final int STAT_AS = 47;
public static final int STAT_LEVEL = 48;
public static final int STAT_TOTAL_RANGE = 49;
public static final int STAT_TOTAL_MP = 50;
public static final int STAT_BONUS_AD = 60;
public static final int STAT_BONUS_HP = 61;
public static final int STAT_BONUS_MS = 62;
public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
public static final int STAT_BONUS_AR = 63;
public static final int STAT_BONUS_MR = 64;
public static final int STAT_LEVEL_MINUS_ONE = 65;
public static final int STAT_CRIT_DMG = 66;
public static final int STAT_AA_DPS = 70;
public static final int STAT_NAUTILUS_Q_CD = 80;
public static final int STAT_RENGAR_Q_BASE_DAMAGE = 81;
public static final int STAT_VI_W = 82;
public static final int STAT_STACKS = 83; // generic stat... could be used for Ashe/Nasus, etc
public static final int STAT_SOULS = 84;
public static final int STAT_ENEMY_MISSING_HP = 100;
public static final int STAT_ENEMY_CURRENT_HP = 101;
public static final int STAT_ENEMY_MAX_HP = 102;
public static final int STAT_ONE = 120;
public static final int STAT_TYPE_DEFAULT = 0;
public static final int STAT_TYPE_PERCENT = 1;
private static final int MAX_STATS = 121;
private static final int MAX_ACTIVE_ITEMS = 6;
public static final String JSON_KEY_RUNES = "runes";
public static final String JSON_KEY_ITEMS = "items";
public static final String JSON_KEY_BUILD_NAME = "build_name";
public static final String JSON_KEY_COLOR = "color";
private static final Map<String, Integer> statKeyToIndex = new HashMap<String, Integer>();
private static final SparseIntArray statIdToStringId = new SparseIntArray();
private static final SparseIntArray statIdToSkillStatDescStringId = new SparseIntArray();
private static final int COLOR_AP = 0xFF59BD1A;
private static final int COLOR_AD = 0xFFFAA316;
private static final int COLOR_TANK = 0xFF1092E8;
private static final float STAT_VALUE_HP = 2.66f;
private static final float STAT_VALUE_AR = 20f;
private static final float STAT_VALUE_MR = 20f;
private static final float STAT_VALUE_AD = 36f;
private static final float STAT_VALUE_AP = 21.75f;
private static final float STAT_VALUE_CRIT = 50f;
private static final float STAT_VALUE_ASP = 30f;
private static ItemLibrary itemLibrary;
private static RuneLibrary runeLibrary;
private static final double[] RENGAR_Q_BASE = new double[] {
30,
45,
60,
75,
90,
105,
120,
135,
150,
160,
170,
180,
190,
200,
210,
220,
230,
240
};
static {
statKeyToIndex.put("FlatArmorMod", STAT_AR);
statKeyToIndex.put("FlatAttackSpeedMod", STAT_NULL);
statKeyToIndex.put("FlatBlockMod", STAT_NULL);
statKeyToIndex.put("FlatCritChanceMod", STAT_CRIT);
statKeyToIndex.put("FlatCritDamageMod", STAT_NULL);
statKeyToIndex.put("FlatEXPBonus", STAT_NULL);
statKeyToIndex.put("FlatEnergyPoolMod", STAT_NULL);
statKeyToIndex.put("FlatEnergyRegenMod", STAT_NULL);
statKeyToIndex.put("FlatHPPoolMod", STAT_HP);
statKeyToIndex.put("FlatHPRegenMod", STAT_HPR);
statKeyToIndex.put("FlatMPPoolMod", STAT_MP);
statKeyToIndex.put("FlatMPRegenMod", STAT_MPR);
statKeyToIndex.put("FlatMagicDamageMod", STAT_AP);
statKeyToIndex.put("FlatMovementSpeedMod", STAT_MS);
statKeyToIndex.put("FlatPhysicalDamageMod", STAT_AD);
statKeyToIndex.put("FlatSpellBlockMod", STAT_MR);
statKeyToIndex.put("FlatCoolDownRedMod", STAT_CDR);
statKeyToIndex.put("PercentArmorMod", STAT_NULL);
statKeyToIndex.put("PercentAttackSpeedMod", STAT_ASP);
statKeyToIndex.put("PercentBlockMod", STAT_NULL);
statKeyToIndex.put("PercentCritChanceMod", STAT_NULL);
statKeyToIndex.put("PercentCritDamageMod", STAT_NULL);
statKeyToIndex.put("PercentDodgeMod", STAT_NULL);
statKeyToIndex.put("PercentEXPBonus", STAT_NULL);
statKeyToIndex.put("PercentHPPoolMod", STAT_NULL);
statKeyToIndex.put("PercentHPRegenMod", STAT_NULL);
statKeyToIndex.put("PercentLifeStealMod", STAT_LS);
statKeyToIndex.put("PercentMPPoolMod", STAT_NULL);
statKeyToIndex.put("PercentMPRegenMod", STAT_NULL);
statKeyToIndex.put("PercentMagicDamageMod", STAT_APP);
statKeyToIndex.put("PercentMovementSpeedMod", STAT_MSP);
statKeyToIndex.put("PercentPhysicalDamageMod", STAT_NULL);
statKeyToIndex.put("PercentSpellBlockMod", STAT_NULL);
statKeyToIndex.put("PercentSpellVampMod", STAT_SV);
statKeyToIndex.put("CCRed", STAT_CC_RED);
statKeyToIndex.put("FlatAaTrueDamageMod", STAT_AA_TRUE_DAMAGE);
statKeyToIndex.put("FlatAaMagicDamageMod", STAT_AA_MAGIC_DAMAGE);
statKeyToIndex.put("magic_aoe_dps", STAT_AOE_DPS_MAGIC);
statKeyToIndex.put("perpercenthpmissing", STAT_PERCENT_HP_MISSING);
statKeyToIndex.put("rFlatArmorModPerLevel", STAT_AR | FLAG_SCALING);
statKeyToIndex.put("rFlatArmorPenetrationMod", STAT_ARPEN);
statKeyToIndex.put("rFlatArmorPenetrationModPerLevel", STAT_ARPEN | FLAG_SCALING);
statKeyToIndex.put("rFlatEnergyModPerLevel", STAT_NRG | FLAG_SCALING);
statKeyToIndex.put("rFlatEnergyRegenModPerLevel", STAT_NRGR | FLAG_SCALING);
statKeyToIndex.put("rFlatGoldPer10Mod", STAT_GP10);
statKeyToIndex.put("rFlatHPModPerLevel", STAT_HP | FLAG_SCALING);
statKeyToIndex.put("rFlatHPRegenModPerLevel", STAT_HPR | FLAG_SCALING);
statKeyToIndex.put("rFlatMPModPerLevel", STAT_MP | FLAG_SCALING);
statKeyToIndex.put("rFlatMPRegenModPerLevel", STAT_MPR | FLAG_SCALING);
statKeyToIndex.put("rFlatMagicDamageModPerLevel", STAT_AP | FLAG_SCALING);
statKeyToIndex.put("rFlatMagicPenetrationMod", STAT_MRP);
statKeyToIndex.put("rFlatMagicPenetrationModPerLevel", STAT_MRP | FLAG_SCALING);
statKeyToIndex.put("rFlatPhysicalDamageModPerLevel", STAT_AD | FLAG_SCALING);
statKeyToIndex.put("rFlatSpellBlockModPerLevel", STAT_MR | FLAG_SCALING);
statKeyToIndex.put("rPercentCooldownMod", STAT_CD); // negative val...
statKeyToIndex.put("rPercentCooldownModPerLevel", STAT_CD | FLAG_SCALING);
statKeyToIndex.put("rPercentTimeDeadMod", STAT_DT);
statKeyToIndex.put("rPercentTimeDeadModPerLevel", STAT_DT | FLAG_SCALING);
statKeyToIndex.put("rPercentMagicPenetrationMod", STAT_MPENP);
statKeyToIndex.put("rPercentArmorPenetrationMod", STAT_APENP);
statKeyToIndex.put("damagereduction", STAT_DMG_REDUCTION);
statKeyToIndex.put("magicaldamagereduction", STAT_MAGIC_DMG_REDUCTION);
statKeyToIndex.put("FlatMagicHp", STAT_MAGIC_HP);
statKeyToIndex.put("Invulnerability", STAT_INVULNERABILITY);
statKeyToIndex.put("SpellBlock", STAT_SPELL_BLOCK);
statKeyToIndex.put("CcImmune", STAT_CC_IMMUNE);
statKeyToIndex.put("InvulnerabilityButOne", STAT_INVULNERABILITY_ALL_BUT_ONE);
// keys used for skills...
statKeyToIndex.put("spelldamage", STAT_TOTAL_AP);
statKeyToIndex.put("attackdamage", STAT_TOTAL_AD);
statKeyToIndex.put("bonushealth", STAT_BONUS_HP);
statKeyToIndex.put("armor", STAT_TOTAL_AR);
statKeyToIndex.put("bonusattackdamage", STAT_BONUS_AD);
statKeyToIndex.put("health", STAT_TOTAL_HP);
statKeyToIndex.put("bonusarmor", STAT_BONUS_AR);
statKeyToIndex.put("bonusspellblock", STAT_BONUS_MR);
statKeyToIndex.put("levelMinusOne", STAT_LEVEL_MINUS_ONE);
statKeyToIndex.put("level", STAT_LEVEL);
statKeyToIndex.put("RangeMod", STAT_RANGE);
statKeyToIndex.put("mana", STAT_TOTAL_MP);
statKeyToIndex.put("critdamage", STAT_CRIT_DMG);
statKeyToIndex.put("enemymissinghealth", STAT_ENEMY_MISSING_HP);
statKeyToIndex.put("enemycurrenthealth", STAT_ENEMY_CURRENT_HP);
statKeyToIndex.put("enemymaxhealth", STAT_ENEMY_MAX_HP);
statKeyToIndex.put("movementspeed", STAT_TOTAL_MS);
// special keys...
statKeyToIndex.put("@special.BraumWArmor", STAT_NULL);
statKeyToIndex.put("@special.BraumWMR", STAT_NULL);
statKeyToIndex.put("@cooldownchampion", STAT_CD_MOD);
statKeyToIndex.put("@stacks", STAT_STACKS);
statKeyToIndex.put("@souls", STAT_SOULS);
// heim
statKeyToIndex.put("@dynamic.abilitypower", STAT_AP);
// rengar
statKeyToIndex.put("@dynamic.attackdamage", STAT_RENGAR_Q_BASE_DAMAGE);
statKeyToIndex.put("@special.nautilusq", STAT_NAUTILUS_Q_CD);
// vi
statKeyToIndex.put("@special.viw", STAT_VI_W);
// darius
statKeyToIndex.put("@special.dariusr3", STAT_ONE);
statKeyToIndex.put("null", STAT_NULL);
SparseIntArray a = statIdToStringId;
a.put(STAT_NULL, R.string.stat_desc_null);
a.put(STAT_HP, R.string.stat_desc_hp);
a.put(STAT_HPR, R.string.stat_desc_hpr);
a.put(STAT_MP, R.string.stat_desc_mp);
a.put(STAT_MPR, R.string.stat_desc_mpr);
a.put(STAT_AD, R.string.stat_desc_ad);
a.put(STAT_ASP, R.string.stat_desc_asp);
a.put(STAT_AR, R.string.stat_desc_ar);
a.put(STAT_MR, R.string.stat_desc_mr);
// public static final int STAT_MS = 9;
a.put(STAT_RANGE, R.string.stat_desc_range);
// public static final int STAT_CRIT = 11;
// public static final int STAT_AP = 12;
// public static final int STAT_LS = 13;
// public static final int STAT_MSP = 14;
// public static final int STAT_CDR = 15;
// public static final int STAT_ARPEN = 16;
// public static final int STAT_NRG = 17;
// public static final int STAT_NRGR = 18;
// public static final int STAT_GP10 = 19;
// public static final int STAT_MRP = 20;
// public static final int STAT_CD = 21;
// public static final int STAT_DT = 22;
// public static final int STAT_APP = 23;
// public static final int STAT_SV = 24;
// public static final int STAT_MPENP = 25;
// public static final int STAT_APENP = 26;
a.put(STAT_DMG_REDUCTION, R.string.stat_desc_damage_reduction);
//
// public static final int STAT_TOTAL_AR = 40;
// public static final int STAT_TOTAL_AD = 41;
// public static final int STAT_TOTAL_HP = 42;
// public static final int STAT_CD_MOD = 43;
// public static final int STAT_TOTAL_AP = 44;
// public static final int STAT_TOTAL_MS = 45;
// public static final int STAT_TOTAL_MR = 46;
// public static final int STAT_AS = 47;
// public static final int STAT_LEVEL = 48;
//
// public static final int STAT_BONUS_AD = 50;
// public static final int STAT_BONUS_HP = 51;
// public static final int STAT_BONUS_MS = 52;
// public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
// public static final int STAT_BONUS_AR = 53;
// public static final int STAT_BONUS_MR = 54;
//
//
// public static final int STAT_AA_DPS = 60;
SparseIntArray b = statIdToSkillStatDescStringId;
b.put(STAT_NULL, R.string.skill_stat_null);
b.put(STAT_TOTAL_AP, R.string.skill_stat_ap);
b.put(STAT_LEVEL_MINUS_ONE, R.string.skill_stat_level_minus_one);
b.put(STAT_TOTAL_AD, R.string.skill_stat_ad);
b.put(STAT_BONUS_AD, R.string.skill_stat_bonus_ad);
b.put(STAT_CD_MOD, R.string.skill_stat_cd_mod);
b.put(STAT_STACKS, R.string.skill_stat_stacks);
b.put(STAT_ONE, R.string.skill_stat_one);
// public static final int STAT_TOTAL_AR = 40;
// public static final int STAT_TOTAL_AD = 41;
// public static final int STAT_TOTAL_HP = 42;
// public static final int STAT_CD_MOD = 43;
// public static final int STAT_TOTAL_MS = 45;
// public static final int STAT_TOTAL_MR = 46;
// public static final int STAT_AS = 47;
// public static final int STAT_LEVEL = 48;
// public static final int STAT_TOTAL_RANGE = 49;
// public static final int STAT_TOTAL_MP = 50;
//
// public static final int STAT_BONUS_HP = 61;
// public static final int STAT_BONUS_MS = 62;
// public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
// public static final int STAT_BONUS_AR = 63;
// public static final int STAT_BONUS_MR = 64;
// public static final int STAT_LEVEL_MINUS_ONE = 65;
// public static final int STAT_CRIT_DMG = 66;
}
private String buildName;
private List<BuildSkill> activeSkills;
private List<BuildRune> runeBuild;
private List<BuildItem> itemBuild;
private ChampionInfo champ;
private int champLevel;
private List<BuildObserver> observers = new ArrayList<BuildObserver>();
private int enabledBuildStart = 0;
private int enabledBuildEnd = 0;
private int currentGroupCounter = 0;
private int[] runeCount = new int[4];
private double[] stats = new double[MAX_STATS];
private double[] statsWithActives = new double[MAX_STATS];
private boolean itemBuildDirty = false;
private Gson gson;
private OnRuneCountChangedListener onRuneCountChangedListener = new OnRuneCountChangedListener() {
@Override
public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) {
Build.this.onRuneCountChanged(rune, oldCount, newCount);
}
};
public Build() {
itemBuild = new ArrayList<BuildItem>();
runeBuild = new ArrayList<BuildRune>();
activeSkills = new ArrayList<BuildSkill>();
gson = StateManager.getInstance().getGson();
if (itemLibrary == null) {
itemLibrary = LibraryManager.getInstance().getItemLibrary();
}
if (runeLibrary == null) {
runeLibrary = LibraryManager.getInstance().getRuneLibrary();
}
champLevel = 1;
}
public void setBuildName(String name) {
buildName = name;
}
public String getBuildName() {
return buildName;
}
private void clearGroups() {
for (BuildItem item : itemBuild) {
item.group = -1;
item.to = null;
item.depth = 0;
item.from.clear();
}
currentGroupCounter = 0;
}
private void recalculateAllGroups() {
clearGroups();
for (int i = 0; i < itemBuild.size(); i++) {
labelAllIngredients(itemBuild.get(i), i);
}
}
private BuildItem getFreeItemWithId(int id, int index) {
for (int i = index - 1; i >= 0; i--) {
if (itemBuild.get(i).getId() == id && itemBuild.get(i).to == null) {
return itemBuild.get(i);
}
}
return null;
}
private void labelAllIngredients(BuildItem item, int index) {
int curGroup = currentGroupCounter;
boolean grouped = false;
Stack<Integer> from = new Stack<Integer>();
from.addAll(item.info.from);
while (!from.empty()) {
int i = from.pop();
BuildItem ingredient = getFreeItemWithId(i, index);
if (ingredient != null && ingredient.to == null) {
if (ingredient.group != -1) {
curGroup = ingredient.group;
}
ingredient.to = item;
item.from.add(ingredient);
grouped = true;
calculateItemCost(item);
} else {
from.addAll(itemLibrary.getItemInfo(i).from);
}
}
if (grouped) {
increaseIngredientDepth(item);
for (BuildItem i : item.from) {
i.group = curGroup;
}
item.group = curGroup;
if (curGroup == currentGroupCounter) {
currentGroupCounter++;
}
}
}
private void calculateItemCost(BuildItem item) {
int p = item.info.totalGold;
for (BuildItem i : item.from) {
p -= i.info.totalGold;
}
item.costPer = p;
}
private void recalculateItemCosts() {
for (BuildItem item : itemBuild) {
calculateItemCost(item);
}
}
private void increaseIngredientDepth(BuildItem item) {
for (BuildItem i : item.from) {
i.depth++;
increaseIngredientDepth(i);
}
}
public void addItem(ItemInfo item) {
addItem(item, 1, true);
}
public void addItem(ItemInfo item, int count, boolean isAll) {
BuildItem buildItem = null;
BuildItem last = getLastItem();
if (last != null && item == last.info) {
if (item.stacks > last.count) {
last.count += count;
buildItem = last;
}
}
if (isAll == false) {
itemBuildDirty = true;
}
boolean itemNull = buildItem == null;
if (itemNull) {
buildItem = new BuildItem(item);
buildItem.count = Math.min(item.stacks, count);
// check if ingredients of this item is already part of the build...
labelAllIngredients(buildItem, itemBuild.size());
if (itemBuild.size() == enabledBuildEnd) {
enabledBuildEnd++;
}
itemBuild.add(buildItem);
calculateItemCost(buildItem);
}
if (isAll) {
recalculateStats();
if (itemBuildDirty) {
itemBuildDirty = false;
buildItem = null;
}
notifyItemAdded(buildItem, itemNull);
}
}
public void clearItems() {
itemBuild.clear();
normalizeValues();
recalculateItemCosts();
recalculateAllGroups();
recalculateStats();
notifyBuildChanged();
}
public void removeItemAt(int position) {
BuildItem item = itemBuild.get(position);
itemBuild.remove(position);
normalizeValues();
recalculateItemCosts();
recalculateAllGroups();
recalculateStats();
notifyBuildChanged();
}
public int getItemCount() {
return itemBuild.size();
}
private void clearStats(double[] stats) {
for (int i = 0; i < stats.length; i++) {
stats[i] = 0;
}
}
private void recalculateStats() {
calculateStats(stats, enabledBuildStart, enabledBuildEnd, false, champLevel);
}
private void calculateStats(double[] stats, int startItemBuild, int endItemBuild, boolean onlyDoRawCalculation, int champLevel) {
clearStats(stats);
int active = 0;
for (BuildRune r : runeBuild) {
appendStat(stats, r);
}
if (!onlyDoRawCalculation) {
for (BuildItem item : itemBuild) {
item.active = false;
}
}
HashSet<Integer> alreadyAdded = new HashSet<Integer>();
for (int i = endItemBuild - 1; i >= startItemBuild; i--) {
BuildItem item = itemBuild.get(i);
if (item.to == null || itemBuild.indexOf(item.to) >= enabledBuildEnd) {
if (!onlyDoRawCalculation) {
item.active = true;
}
ItemInfo info = item.info;
appendStat(stats, info.stats);
int id = info.id;
if (info.uniquePassiveStat != null && !alreadyAdded.contains(id)) {
alreadyAdded.add(info.id);
appendStat(stats, info.uniquePassiveStat);
}
active++;
if (active == MAX_ACTIVE_ITEMS)
break;
}
}
calculateTotalStats(stats, champLevel);
if (!onlyDoRawCalculation) {
notifyBuildStatsChanged();
}
}
private void appendStat(double[] stats, JSONObject jsonStats) {
Iterator<?> iter = jsonStats.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
try {
stats[getStatIndex(key)] += jsonStats.getDouble(key);
} catch (JSONException e) {
DebugLog.e(TAG, e);
}
}
}
private void appendStat(double[] stats, BuildRune rune) {
RuneInfo info = rune.info;
Iterator<?> iter = info.stats.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
try {
int f = getStatIndex(key);
if ((f & FLAG_SCALING) != 0) {
stats[f & ~FLAG_SCALING] += info.stats.getDouble(key) * champLevel * rune.count;
} else {
stats[f] += info.stats.getDouble(key) * rune.count;
}
} catch (JSONException e) {
DebugLog.e(TAG, e);
}
}
}
private void calculateTotalStats() {
calculateTotalStats(stats, champLevel);
}
private void calculateTotalStats(double[] stats, int champLevel) {
// do some stat normalization...
stats[STAT_CDR] = Math.min(MAX_CDR, stats[STAT_CDR] - stats[STAT_CD]);
int levMinusOne = champLevel - 1;
stats[STAT_TOTAL_AR] = stats[STAT_AR] + champ.ar + champ.arG * levMinusOne;
stats[STAT_TOTAL_AD] = stats[STAT_AD] + champ.ad + champ.adG * levMinusOne;
stats[STAT_TOTAL_HP] = stats[STAT_HP] + champ.hp + champ.hpG * levMinusOne;
stats[STAT_CD_MOD] = 1.0 - stats[STAT_CDR];
stats[STAT_TOTAL_MS] = (stats[STAT_MS] + champ.ms) * stats[STAT_MSP] + stats[STAT_MS] + champ.ms;
stats[STAT_TOTAL_AP] = stats[STAT_AP] * (stats[STAT_APP] + 1);
stats[STAT_TOTAL_MR] = stats[STAT_MR] + champ.mr + champ.mrG * levMinusOne;
stats[STAT_AS] = Math.min(champ.as * (1 + levMinusOne * champ.asG + stats[STAT_ASP]), MAX_ATTACK_SPEED);
stats[STAT_LEVEL] = champLevel;
stats[STAT_TOTAL_RANGE] = stats[STAT_RANGE] + champ.range;
stats[STAT_TOTAL_MP] = stats[STAT_MP] + champ.mp + champ.mpG * levMinusOne;
stats[STAT_BONUS_AD] = stats[STAT_TOTAL_AD] - champ.ad;
stats[STAT_BONUS_HP] = stats[STAT_TOTAL_HP] - champ.hp;
stats[STAT_BONUS_MS] = stats[STAT_TOTAL_MS] - champ.ms;
stats[STAT_BONUS_AR] = stats[STAT_TOTAL_AR] - champ.ar;
stats[STAT_BONUS_MR] = stats[STAT_TOTAL_MR] - champ.mr;
stats[STAT_LEVEL_MINUS_ONE] = stats[STAT_LEVEL] - 1;
stats[STAT_CRIT_DMG] = stats[STAT_TOTAL_AD] * 2.0;
// pure stats...
stats[STAT_AA_DPS] = stats[STAT_TOTAL_AD] * stats[STAT_AS];
// static values...
stats[STAT_NAUTILUS_Q_CD] = 0.5;
stats[STAT_ONE] = 1;
}
private static int addColor(int base, int value) {
double result = 1 - (1 - base / 256.0) * (1 - value / 256.0);
return (int) (result * 256);
}
public int generateColorBasedOnBuild() {
int r = 0, g = 0, b = 0;
int hp = 0;
int mr = 0;
int ar = 0;
int ad = 0;
int ap = 0;
int crit = 0;
int as = 0;
calculateTotalStats(stats, 1);
hp = (int) (stats[STAT_BONUS_HP] * STAT_VALUE_HP);
mr = (int) (stats[STAT_BONUS_MR] * STAT_VALUE_MR);
ar = (int) (stats[STAT_BONUS_AR] * STAT_VALUE_AR);
ad = (int) (stats[STAT_BONUS_AD] * STAT_VALUE_AD);
ap = (int) (stats[STAT_BONUS_AP] * STAT_VALUE_AP);
crit = (int) (stats[STAT_CRIT] * 100 * STAT_VALUE_CRIT);
as = (int) (stats[STAT_ASP] * 100 * STAT_VALUE_ASP);
int tank = hp + mr + ar;
int dps = ad + as + crit;
int burst = ap;
double total = tank + dps + burst;
double tankness = tank / total;
double adness = dps / total;
double apness = burst / total;
r = addColor((int) (Color.red(COLOR_AD) * adness), r);
r = addColor((int) (Color.red(COLOR_AP) * apness), r);
r = addColor((int) (Color.red(COLOR_TANK) * tankness), r);
g = addColor((int) (Color.green(COLOR_AD) * adness), g);
g = addColor((int) (Color.green(COLOR_AP) * apness), g);
g = addColor((int) (Color.green(COLOR_TANK) * tankness), g);
b = addColor((int) (Color.blue(COLOR_AD) * adness), b);
b = addColor((int) (Color.blue(COLOR_AP) * apness), b);
b = addColor((int) (Color.blue(COLOR_TANK) * tankness), b);
Log.d(TAG, String.format("Tankiness: %f Apness: %f Adness: %f", tankness, apness, adness));
return Color.rgb(r, g, b);
}
public BuildRune addRune(RuneInfo rune) {
return addRune(rune, 1, true);
}
public BuildRune addRune(RuneInfo rune, int count, boolean isAll) {
// Check if this rune is already in the build...
BuildRune r = null;
for (BuildRune br : runeBuild) {
if (br.id == rune.id) {
r = br;
break;
}
}
if (r == null) {
r = new BuildRune(rune, rune.id);
runeBuild.add(r);
r.listener = onRuneCountChangedListener;
notifyRuneAdded(r);
}
r.addRune(count);
recalculateStats();
return r;
}
public void clearRunes() {
for (BuildRune r : runeBuild) {
r.listener = null;
notifyRuneRemoved(r);
}
runeBuild.clear();
recalculateStats();
}
public boolean canAdd(RuneInfo rune) {
return runeCount[rune.runeType] + 1 <= RUNE_COUNT_MAX[rune.runeType];
}
public void removeRune(BuildRune rune) {
rune.listener = null;
runeBuild.remove(rune);
recalculateStats();
notifyRuneRemoved(rune);
}
private void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) {
int runeType = rune.info.runeType;
if (runeCount[runeType] + (newCount - oldCount) > RUNE_COUNT_MAX[runeType]) {
rune.count = oldCount;
return;
}
runeCount[runeType] += (newCount - oldCount);
if (rune.getCount() == 0) {
removeRune(rune);
} else {
recalculateStats();
}
}
public BuildSkill addActiveSkill(Skill skill, double base, double scaling, String scaleType, String bonusType) {
BuildSkill sk = new BuildSkill();
sk.skill = skill;
sk.base = base;
sk.scaleTypeId = getStatIndex(scaleType);
sk.bonusTypeId = getStatIndex(bonusType);
sk.scaling = scaling;
activeSkills.add(sk);
DebugLog.d(TAG, "Skill " + skill.name + " bonus: " + base + "; ");
return sk;
}
public double[] calculateStatWithActives(int gold, int champLevel) {
double[] s = new double[stats.length];
int itemEndIndex = itemBuild.size();
int buildCost = 0;
for (int i = 0; i < itemBuild.size(); i++) {
BuildItem item = itemBuild.get(i);
int itemCost = item.costPer * item.count;
if (buildCost + itemCost > gold) {
itemEndIndex = i;
break;
} else {
buildCost += itemCost;
}
}
calculateStats(s, 0, itemEndIndex, true, champLevel);
for (BuildSkill sk : activeSkills) {
sk.totalBonus = s[sk.scaleTypeId] * sk.scaling + sk.base;
s[sk.bonusTypeId] += sk.totalBonus;
}
calculateTotalStats(s, champLevel);
return s;
}
public List<BuildSkill> getActives() {
return activeSkills;
}
public void clearActiveSkills() {
activeSkills.clear();
}
public void setChampion(ChampionInfo champ) {
this.champ = champ;
recalculateStats();
}
public void setChampionLevel(int level) {
champLevel = level;
recalculateStats();
}
public void registerObserver(BuildObserver observer) {
observers.add(observer);
}
public void unregisterObserver(BuildObserver observer) {
observers.remove(observer);
}
private void notifyBuildChanged() {
for (BuildObserver o : observers) {
o.onBuildChanged(this);
}
}
private void notifyItemAdded(BuildItem item, boolean isNewItem) {
for (BuildObserver o : observers) {
o.onItemAdded(this, item, isNewItem);
}
}
private void notifyRuneAdded(BuildRune rune) {
for (BuildObserver o : observers) {
o.onRuneAdded(this, rune);
}
}
private void notifyRuneRemoved(BuildRune rune) {
for (BuildObserver o : observers) {
o.onRuneRemoved(this, rune);
}
}
private void notifyBuildStatsChanged() {
for (BuildObserver o : observers) {
o.onBuildStatsChanged();
}
}
private void normalizeValues() {
if (enabledBuildStart < 0) {
enabledBuildStart = 0;
}
if (enabledBuildEnd > itemBuild.size()) {
enabledBuildEnd = itemBuild.size();
}
}
public BuildItem getItem(int index) {
return itemBuild.get(index);
}
public int getBuildSize() {
return itemBuild.size();
}
public BuildRune getRune(int index) {
return runeBuild.get(index);
}
public int getRuneCount() {
return runeBuild.size();
}
public BuildItem getLastItem() {
if (itemBuild.size() == 0) return null;
return itemBuild.get(itemBuild.size() - 1);
}
public double getBonusHp() {
return stats[STAT_HP];
}
public double getBonusHpRegen() {
return stats[STAT_HPR];
}
public double getBonusMp() {
if (champ.partype == ChampionInfo.TYPE_MANA) {
return stats[STAT_MP];
} else {
return 0;
}
}
public double getBonusMpRegen() {
if (champ.partype == ChampionInfo.TYPE_MANA) {
return stats[STAT_MPR];
} else {
return 0;
}
}
public double getBonusAd() {
return stats[STAT_AD];
}
public double getBonusAs() {
return stats[STAT_ASP];
}
public double getBonusAr() {
return stats[STAT_AR];
}
public double getBonusMr() {
return stats[STAT_MR];
}
public double getBonusMs() {
return stats[STAT_BONUS_MS];
}
public double getBonusRange() {
return stats[STAT_RANGE];
}
public double getBonusAp() {
return stats[STAT_BONUS_AP];
}
public double getBonusEnergy() {
return stats[STAT_NRG];
}
public double getBonusEnergyRegen() {
return stats[STAT_NRGR];
}
public double[] getRawStats() {
return stats;
}
public double getStat(String key) {
int statId = getStatIndex(key);
if (statId == STAT_NULL) return 0.0;
if (statId == STAT_RENGAR_Q_BASE_DAMAGE) {
// refresh rengar q base damage since it looks like we are going to be using it...
stats[STAT_RENGAR_Q_BASE_DAMAGE] = RENGAR_Q_BASE[champLevel - 1];
}
if (statId == STAT_VI_W) {
stats[STAT_VI_W] = 0.00081632653 * stats[STAT_BONUS_AD];
}
return stats[statId];
}
public double getStat(int statId) {
if (statId == STAT_NULL) return 0.0;
return stats[statId];
}
public void reorder(int itemOldPosition, int itemNewPosition) {
BuildItem item = itemBuild.get(itemOldPosition);
itemBuild.remove(itemOldPosition);
itemBuild.add(itemNewPosition, item);
recalculateAllGroups();
recalculateStats();
notifyBuildStatsChanged();
}
public int getEnabledBuildStart() {
return enabledBuildStart;
}
public int getEnabledBuildEnd() {
return enabledBuildEnd;
}
public void setEnabledBuildStart(int start) {
enabledBuildStart = start;
recalculateStats();
notifyBuildStatsChanged();
}
public void setEnabledBuildEnd(int end) {
enabledBuildEnd = end;
recalculateStats();
notifyBuildStatsChanged();
}
public BuildSaveObject toSaveObject() {
BuildSaveObject o = new BuildSaveObject();
for (BuildRune r : runeBuild) {
o.runes.add(r.info.id);
o.runes.add(r.count);
}
for (BuildItem i : itemBuild) {
o.items.add(i.info.id);
o.items.add(i.count);
}
o.buildName = buildName;
o.buildColor = generateColorBasedOnBuild();
return o;
}
public void fromSaveObject(BuildSaveObject o) {
clearItems();
clearRunes();
int count = o.runes.size();
for (int i = 0; i < count; i += 2) {
addRune(runeLibrary.getRuneInfo(o.runes.get(i)), o.runes.get(i++), i + 2 >= count);
}
count = o.items.size();
for (int i = 0; i < count; i += 2) {
int itemId = o.items.get(i);
int c = o.items.get(i + 1);
addItem(itemLibrary.getItemInfo(itemId), c, i == count - 2);
}
buildName = o.buildName;
}
public static int getSuggestedColorForGroup(int groupId) {
return GROUP_COLOR[groupId % GROUP_COLOR.length];
}
public static interface BuildObserver {
public void onBuildChanged(Build build);
public void onItemAdded(Build build, BuildItem item, boolean isNewItem);
public void onRuneAdded(Build build, BuildRune rune);
public void onRuneRemoved(Build build, BuildRune rune);
public void onBuildStatsChanged();
}
public static class BuildItem {
ItemInfo info;
int group = -1;
boolean active = true;
int count = 1;
int costPer = 0;
int depth = 0;
List<BuildItem> from;
BuildItem to;
private BuildItem(ItemInfo info) {
this.info = info;
from = new ArrayList<BuildItem>();
}
public int getId() {
return info.id;
}
}
public static class BuildRune {
RuneInfo info;
Object tag;
int id;
private int count;
private OnRuneCountChangedListener listener;
private OnRuneCountChangedListener onRuneCountChangedListener;
private BuildRune(RuneInfo info, int id) {
this.info = info;
count = 0;
this.id = id;
}
public void addRune() {
addRune(1);
}
public void addRune(int n) {
count += n;
int c = count;
listener.onRuneCountChanged(this, count - n, count);
if (c == count && onRuneCountChangedListener != null) {
onRuneCountChangedListener.onRuneCountChanged(this, count - n, count);
}
}
public void removeRune() {
if (count == 0) return;
count--;
int c = count;
listener.onRuneCountChanged(this, count + 1, count);
if (c == count && onRuneCountChangedListener != null) {
onRuneCountChangedListener.onRuneCountChanged(this, count + 1, count);
}
}
public int getCount() {
return count;
}
public void setOnRuneCountChangedListener(OnRuneCountChangedListener listener) {
onRuneCountChangedListener = listener;
}
}
public static class BuildSkill {
public double totalBonus;
Skill skill;
double base;
double scaling;
int scaleTypeId;
int bonusTypeId;
}
public static interface OnRuneCountChangedListener {
public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount);
}
public static int getStatIndex(String statName) {
Integer i;
i = statKeyToIndex.get(statName);
if (i == null) {
throw new RuntimeException("Stat name not found: " + statName);
}
return i;
}
public static int getStatName(int statId) {
int i;
i = statIdToStringId.get(statId);
if (i == 0) {
throw new RuntimeException("Stat id does not have string resource: " + statId);
}
return i;
}
public static int getSkillStatDesc(int statId) {
int i;
i = statIdToSkillStatDescStringId.get(statId);
if (i == 0) {
throw new RuntimeException("Stat id does not have a skill stat description: " + statId);
}
return i;
}
public static int getStatType(int statId) {
switch (statId) {
case STAT_DMG_REDUCTION:
return STAT_TYPE_PERCENT;
default:
return STAT_TYPE_DEFAULT;
}
}
public static int getScalingType(int statId) {
switch (statId) {
case STAT_CD_MOD:
case STAT_STACKS:
case STAT_ONE:
return STAT_TYPE_DEFAULT;
default:
return STAT_TYPE_PERCENT;
}
}
}
|
app/src/main/java/com/ggstudios/lolcraft/Build.java
|
package com.ggstudios.lolcraft;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Color;
import android.util.Log;
import android.util.SparseIntArray;
import com.ggstudios.lolcraft.ChampionInfo.Skill;
import com.ggstudios.utils.DebugLog;
import com.google.gson.Gson;
/**
* Class that holds information about a build, such as build order, stats and cost.
*/
public class Build {
private static final String TAG = "Build";
public static final int RUNE_TYPE_RED = 0;
public static final int RUNE_TYPE_BLUE = 1;
public static final int RUNE_TYPE_YELLOW = 2;
public static final int RUNE_TYPE_BLACK = 3;
public static final double MAX_ATTACK_SPEED = 2.5;
public static final double MAX_CDR = 0.4;
private static final int[] RUNE_COUNT_MAX = new int[] {
9, 9, 9, 3
};
private static final int[] GROUP_COLOR = new int[] {
0xff2ecc71, // emerald
//0xffe74c3c, // alizarin
0xff3498db, // peter river
0xff9b59b6, // amethyst
0xffe67e22, // carrot
0xff34495e, // wet asphalt
0xff1abc9c, // turquoise
0xfff1c40f, // sun flower
};
private static final int FLAG_SCALING = 0x80000000;
public static final String SN_NULL = "null";
public static final int STAT_NULL = 0;
public static final int STAT_HP = 1;
public static final int STAT_HPR = 2;
public static final int STAT_MP = 3;
public static final int STAT_MPR = 4;
public static final int STAT_AD = 5;
//public static final int STAT_BASE_AS = asdf;
public static final int STAT_ASP = 6;
public static final int STAT_AR = 7;
public static final int STAT_MR = 8;
public static final int STAT_MS = 9;
public static final int STAT_RANGE = 10;
public static final int STAT_CRIT = 11;
public static final int STAT_AP = 12;
public static final int STAT_LS = 13;
public static final int STAT_MSP = 14;
public static final int STAT_CDR = 15;
public static final int STAT_ARPEN = 16;
public static final int STAT_NRG = 17;
public static final int STAT_NRGR = 18;
public static final int STAT_GP10 = 19;
public static final int STAT_MRP = 20;
public static final int STAT_CD = 21;
public static final int STAT_DT = 22;
public static final int STAT_APP = 23;
public static final int STAT_SV = 24;
public static final int STAT_MPENP = 25;
public static final int STAT_APENP = 26;
public static final int STAT_DMG_REDUCTION = 27;
public static final int STAT_CC_RED = 28;
public static final int STAT_AA_TRUE_DAMAGE = 29;
public static final int STAT_AA_MAGIC_DAMAGE = 30;
public static final int STAT_MAGIC_DMG_REDUCTION = 31;
public static final int STAT_MAGIC_HP = 32;
public static final int STAT_INVULNERABILITY = 33;
public static final int STAT_SPELL_BLOCK = 34;
public static final int STAT_CC_IMMUNE = 35;
public static final int STAT_INVULNERABILITY_ALL_BUT_ONE = 36;
public static final int STAT_AOE_DPS_MAGIC = 37;
public static final int STAT_PERCENT_HP_MISSING = 38;
public static final int STAT_TOTAL_AR = 40;
public static final int STAT_TOTAL_AD = 41;
public static final int STAT_TOTAL_HP = 42;
public static final int STAT_CD_MOD = 43;
public static final int STAT_TOTAL_AP = 44;
public static final int STAT_TOTAL_MS = 45;
public static final int STAT_TOTAL_MR = 46;
public static final int STAT_AS = 47;
public static final int STAT_LEVEL = 48;
public static final int STAT_TOTAL_RANGE = 49;
public static final int STAT_TOTAL_MP = 50;
public static final int STAT_BONUS_AD = 60;
public static final int STAT_BONUS_HP = 61;
public static final int STAT_BONUS_MS = 62;
public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
public static final int STAT_BONUS_AR = 63;
public static final int STAT_BONUS_MR = 64;
public static final int STAT_LEVEL_MINUS_ONE = 65;
public static final int STAT_CRIT_DMG = 66;
public static final int STAT_AA_DPS = 70;
public static final int STAT_NAUTILUS_Q_CD = 80;
public static final int STAT_RENGAR_Q_BASE_DAMAGE = 81;
public static final int STAT_VI_W = 82;
public static final int STAT_STACKS = 83; // generic stat... could be used for Ashe/Nasus, etc
public static final int STAT_ENEMY_MISSING_HP = 100;
public static final int STAT_ENEMY_CURRENT_HP = 101;
public static final int STAT_ENEMY_MAX_HP = 102;
public static final int STAT_ONE = 120;
public static final int STAT_TYPE_DEFAULT = 0;
public static final int STAT_TYPE_PERCENT = 1;
private static final int MAX_STATS = 121;
private static final int MAX_ACTIVE_ITEMS = 6;
public static final String JSON_KEY_RUNES = "runes";
public static final String JSON_KEY_ITEMS = "items";
public static final String JSON_KEY_BUILD_NAME = "build_name";
public static final String JSON_KEY_COLOR = "color";
private static final Map<String, Integer> statKeyToIndex = new HashMap<String, Integer>();
private static final SparseIntArray statIdToStringId = new SparseIntArray();
private static final SparseIntArray statIdToSkillStatDescStringId = new SparseIntArray();
private static final int COLOR_AP = 0xFF59BD1A;
private static final int COLOR_AD = 0xFFFAA316;
private static final int COLOR_TANK = 0xFF1092E8;
private static final float STAT_VALUE_HP = 2.66f;
private static final float STAT_VALUE_AR = 20f;
private static final float STAT_VALUE_MR = 20f;
private static final float STAT_VALUE_AD = 36f;
private static final float STAT_VALUE_AP = 21.75f;
private static final float STAT_VALUE_CRIT = 50f;
private static final float STAT_VALUE_ASP = 30f;
private static ItemLibrary itemLibrary;
private static RuneLibrary runeLibrary;
private static final double[] RENGAR_Q_BASE = new double[] {
30,
45,
60,
75,
90,
105,
120,
135,
150,
160,
170,
180,
190,
200,
210,
220,
230,
240
};
static {
statKeyToIndex.put("FlatArmorMod", STAT_AR);
statKeyToIndex.put("FlatAttackSpeedMod", STAT_NULL);
statKeyToIndex.put("FlatBlockMod", STAT_NULL);
statKeyToIndex.put("FlatCritChanceMod", STAT_CRIT);
statKeyToIndex.put("FlatCritDamageMod", STAT_NULL);
statKeyToIndex.put("FlatEXPBonus", STAT_NULL);
statKeyToIndex.put("FlatEnergyPoolMod", STAT_NULL);
statKeyToIndex.put("FlatEnergyRegenMod", STAT_NULL);
statKeyToIndex.put("FlatHPPoolMod", STAT_HP);
statKeyToIndex.put("FlatHPRegenMod", STAT_HPR);
statKeyToIndex.put("FlatMPPoolMod", STAT_MP);
statKeyToIndex.put("FlatMPRegenMod", STAT_MPR);
statKeyToIndex.put("FlatMagicDamageMod", STAT_AP);
statKeyToIndex.put("FlatMovementSpeedMod", STAT_MS);
statKeyToIndex.put("FlatPhysicalDamageMod", STAT_AD);
statKeyToIndex.put("FlatSpellBlockMod", STAT_MR);
statKeyToIndex.put("FlatCoolDownRedMod", STAT_CDR);
statKeyToIndex.put("PercentArmorMod", STAT_NULL);
statKeyToIndex.put("PercentAttackSpeedMod", STAT_ASP);
statKeyToIndex.put("PercentBlockMod", STAT_NULL);
statKeyToIndex.put("PercentCritChanceMod", STAT_NULL);
statKeyToIndex.put("PercentCritDamageMod", STAT_NULL);
statKeyToIndex.put("PercentDodgeMod", STAT_NULL);
statKeyToIndex.put("PercentEXPBonus", STAT_NULL);
statKeyToIndex.put("PercentHPPoolMod", STAT_NULL);
statKeyToIndex.put("PercentHPRegenMod", STAT_NULL);
statKeyToIndex.put("PercentLifeStealMod", STAT_LS);
statKeyToIndex.put("PercentMPPoolMod", STAT_NULL);
statKeyToIndex.put("PercentMPRegenMod", STAT_NULL);
statKeyToIndex.put("PercentMagicDamageMod", STAT_APP);
statKeyToIndex.put("PercentMovementSpeedMod", STAT_MSP);
statKeyToIndex.put("PercentPhysicalDamageMod", STAT_NULL);
statKeyToIndex.put("PercentSpellBlockMod", STAT_NULL);
statKeyToIndex.put("PercentSpellVampMod", STAT_SV);
statKeyToIndex.put("CCRed", STAT_CC_RED);
statKeyToIndex.put("FlatAaTrueDamageMod", STAT_AA_TRUE_DAMAGE);
statKeyToIndex.put("FlatAaMagicDamageMod", STAT_AA_MAGIC_DAMAGE);
statKeyToIndex.put("magic_aoe_dps", STAT_AOE_DPS_MAGIC);
statKeyToIndex.put("perpercenthpmissing", STAT_PERCENT_HP_MISSING);
statKeyToIndex.put("rFlatArmorModPerLevel", STAT_AR | FLAG_SCALING);
statKeyToIndex.put("rFlatArmorPenetrationMod", STAT_ARPEN);
statKeyToIndex.put("rFlatArmorPenetrationModPerLevel", STAT_ARPEN | FLAG_SCALING);
statKeyToIndex.put("rFlatEnergyModPerLevel", STAT_NRG | FLAG_SCALING);
statKeyToIndex.put("rFlatEnergyRegenModPerLevel", STAT_NRGR | FLAG_SCALING);
statKeyToIndex.put("rFlatGoldPer10Mod", STAT_GP10);
statKeyToIndex.put("rFlatHPModPerLevel", STAT_HP | FLAG_SCALING);
statKeyToIndex.put("rFlatHPRegenModPerLevel", STAT_HPR | FLAG_SCALING);
statKeyToIndex.put("rFlatMPModPerLevel", STAT_MP | FLAG_SCALING);
statKeyToIndex.put("rFlatMPRegenModPerLevel", STAT_MPR | FLAG_SCALING);
statKeyToIndex.put("rFlatMagicDamageModPerLevel", STAT_AP | FLAG_SCALING);
statKeyToIndex.put("rFlatMagicPenetrationMod", STAT_MRP);
statKeyToIndex.put("rFlatMagicPenetrationModPerLevel", STAT_MRP | FLAG_SCALING);
statKeyToIndex.put("rFlatPhysicalDamageModPerLevel", STAT_AD | FLAG_SCALING);
statKeyToIndex.put("rFlatSpellBlockModPerLevel", STAT_MR | FLAG_SCALING);
statKeyToIndex.put("rPercentCooldownMod", STAT_CD); // negative val...
statKeyToIndex.put("rPercentCooldownModPerLevel", STAT_CD | FLAG_SCALING);
statKeyToIndex.put("rPercentTimeDeadMod", STAT_DT);
statKeyToIndex.put("rPercentTimeDeadModPerLevel", STAT_DT | FLAG_SCALING);
statKeyToIndex.put("rPercentMagicPenetrationMod", STAT_MPENP);
statKeyToIndex.put("rPercentArmorPenetrationMod", STAT_APENP);
statKeyToIndex.put("damagereduction", STAT_DMG_REDUCTION);
statKeyToIndex.put("magicaldamagereduction", STAT_MAGIC_DMG_REDUCTION);
statKeyToIndex.put("FlatMagicHp", STAT_MAGIC_HP);
statKeyToIndex.put("Invulnerability", STAT_INVULNERABILITY);
statKeyToIndex.put("SpellBlock", STAT_SPELL_BLOCK);
statKeyToIndex.put("CcImmune", STAT_CC_IMMUNE);
statKeyToIndex.put("InvulnerabilityButOne", STAT_INVULNERABILITY_ALL_BUT_ONE);
// keys used for skills...
statKeyToIndex.put("spelldamage", STAT_TOTAL_AP);
statKeyToIndex.put("attackdamage", STAT_TOTAL_AD);
statKeyToIndex.put("bonushealth", STAT_BONUS_HP);
statKeyToIndex.put("armor", STAT_TOTAL_AR);
statKeyToIndex.put("bonusattackdamage", STAT_BONUS_AD);
statKeyToIndex.put("health", STAT_TOTAL_HP);
statKeyToIndex.put("bonusarmor", STAT_BONUS_AR);
statKeyToIndex.put("bonusspellblock", STAT_BONUS_MR);
statKeyToIndex.put("levelMinusOne", STAT_LEVEL_MINUS_ONE);
statKeyToIndex.put("level", STAT_LEVEL);
statKeyToIndex.put("RangeMod", STAT_RANGE);
statKeyToIndex.put("mana", STAT_TOTAL_MP);
statKeyToIndex.put("critdamage", STAT_CRIT_DMG);
statKeyToIndex.put("enemymissinghealth", STAT_ENEMY_MISSING_HP);
statKeyToIndex.put("enemycurrenthealth", STAT_ENEMY_CURRENT_HP);
statKeyToIndex.put("enemymaxhealth", STAT_ENEMY_MAX_HP);
statKeyToIndex.put("movementspeed", STAT_TOTAL_MS);
// special keys...
statKeyToIndex.put("@special.BraumWArmor", STAT_NULL);
statKeyToIndex.put("@special.BraumWMR", STAT_NULL);
statKeyToIndex.put("@cooldownchampion", STAT_CD_MOD);
statKeyToIndex.put("@stacks", STAT_STACKS);
// heim
statKeyToIndex.put("@dynamic.abilitypower", STAT_AP);
// rengar
statKeyToIndex.put("@dynamic.attackdamage", STAT_RENGAR_Q_BASE_DAMAGE);
statKeyToIndex.put("@special.nautilusq", STAT_NAUTILUS_Q_CD);
// vi
statKeyToIndex.put("@special.viw", STAT_VI_W);
// darius
statKeyToIndex.put("@special.dariusr3", STAT_ONE);
statKeyToIndex.put("null", STAT_NULL);
SparseIntArray a = statIdToStringId;
a.put(STAT_NULL, R.string.stat_desc_null);
a.put(STAT_HP, R.string.stat_desc_hp);
a.put(STAT_HPR, R.string.stat_desc_hpr);
a.put(STAT_MP, R.string.stat_desc_mp);
a.put(STAT_MPR, R.string.stat_desc_mpr);
a.put(STAT_AD, R.string.stat_desc_ad);
a.put(STAT_ASP, R.string.stat_desc_asp);
a.put(STAT_AR, R.string.stat_desc_ar);
a.put(STAT_MR, R.string.stat_desc_mr);
// public static final int STAT_MS = 9;
a.put(STAT_RANGE, R.string.stat_desc_range);
// public static final int STAT_CRIT = 11;
// public static final int STAT_AP = 12;
// public static final int STAT_LS = 13;
// public static final int STAT_MSP = 14;
// public static final int STAT_CDR = 15;
// public static final int STAT_ARPEN = 16;
// public static final int STAT_NRG = 17;
// public static final int STAT_NRGR = 18;
// public static final int STAT_GP10 = 19;
// public static final int STAT_MRP = 20;
// public static final int STAT_CD = 21;
// public static final int STAT_DT = 22;
// public static final int STAT_APP = 23;
// public static final int STAT_SV = 24;
// public static final int STAT_MPENP = 25;
// public static final int STAT_APENP = 26;
a.put(STAT_DMG_REDUCTION, R.string.stat_desc_damage_reduction);
//
// public static final int STAT_TOTAL_AR = 40;
// public static final int STAT_TOTAL_AD = 41;
// public static final int STAT_TOTAL_HP = 42;
// public static final int STAT_CD_MOD = 43;
// public static final int STAT_TOTAL_AP = 44;
// public static final int STAT_TOTAL_MS = 45;
// public static final int STAT_TOTAL_MR = 46;
// public static final int STAT_AS = 47;
// public static final int STAT_LEVEL = 48;
//
// public static final int STAT_BONUS_AD = 50;
// public static final int STAT_BONUS_HP = 51;
// public static final int STAT_BONUS_MS = 52;
// public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
// public static final int STAT_BONUS_AR = 53;
// public static final int STAT_BONUS_MR = 54;
//
//
// public static final int STAT_AA_DPS = 60;
SparseIntArray b = statIdToSkillStatDescStringId;
b.put(STAT_NULL, R.string.skill_stat_null);
b.put(STAT_TOTAL_AP, R.string.skill_stat_ap);
b.put(STAT_LEVEL_MINUS_ONE, R.string.skill_stat_level_minus_one);
b.put(STAT_TOTAL_AD, R.string.skill_stat_ad);
b.put(STAT_BONUS_AD, R.string.skill_stat_bonus_ad);
b.put(STAT_CD_MOD, R.string.skill_stat_cd_mod);
b.put(STAT_STACKS, R.string.skill_stat_stacks);
b.put(STAT_ONE, R.string.skill_stat_one);
// public static final int STAT_TOTAL_AR = 40;
// public static final int STAT_TOTAL_AD = 41;
// public static final int STAT_TOTAL_HP = 42;
// public static final int STAT_CD_MOD = 43;
// public static final int STAT_TOTAL_MS = 45;
// public static final int STAT_TOTAL_MR = 46;
// public static final int STAT_AS = 47;
// public static final int STAT_LEVEL = 48;
// public static final int STAT_TOTAL_RANGE = 49;
// public static final int STAT_TOTAL_MP = 50;
//
// public static final int STAT_BONUS_HP = 61;
// public static final int STAT_BONUS_MS = 62;
// public static final int STAT_BONUS_AP = 44; // note that cause base AP is always 0, bonusAp always = totalAp
// public static final int STAT_BONUS_AR = 63;
// public static final int STAT_BONUS_MR = 64;
// public static final int STAT_LEVEL_MINUS_ONE = 65;
// public static final int STAT_CRIT_DMG = 66;
}
private String buildName;
private List<BuildSkill> activeSkills;
private List<BuildRune> runeBuild;
private List<BuildItem> itemBuild;
private ChampionInfo champ;
private int champLevel;
private List<BuildObserver> observers = new ArrayList<BuildObserver>();
private int enabledBuildStart = 0;
private int enabledBuildEnd = 0;
private int currentGroupCounter = 0;
private int[] runeCount = new int[4];
private double[] stats = new double[MAX_STATS];
private double[] statsWithActives = new double[MAX_STATS];
private boolean itemBuildDirty = false;
private Gson gson;
private OnRuneCountChangedListener onRuneCountChangedListener = new OnRuneCountChangedListener() {
@Override
public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) {
Build.this.onRuneCountChanged(rune, oldCount, newCount);
}
};
public Build() {
itemBuild = new ArrayList<BuildItem>();
runeBuild = new ArrayList<BuildRune>();
activeSkills = new ArrayList<BuildSkill>();
gson = StateManager.getInstance().getGson();
if (itemLibrary == null) {
itemLibrary = LibraryManager.getInstance().getItemLibrary();
}
if (runeLibrary == null) {
runeLibrary = LibraryManager.getInstance().getRuneLibrary();
}
champLevel = 1;
}
public void setBuildName(String name) {
buildName = name;
}
public String getBuildName() {
return buildName;
}
private void clearGroups() {
for (BuildItem item : itemBuild) {
item.group = -1;
item.to = null;
item.depth = 0;
item.from.clear();
}
currentGroupCounter = 0;
}
private void recalculateAllGroups() {
clearGroups();
for (int i = 0; i < itemBuild.size(); i++) {
labelAllIngredients(itemBuild.get(i), i);
}
}
private BuildItem getFreeItemWithId(int id, int index) {
for (int i = index - 1; i >= 0; i--) {
if (itemBuild.get(i).getId() == id && itemBuild.get(i).to == null) {
return itemBuild.get(i);
}
}
return null;
}
private void labelAllIngredients(BuildItem item, int index) {
int curGroup = currentGroupCounter;
boolean grouped = false;
Stack<Integer> from = new Stack<Integer>();
from.addAll(item.info.from);
while (!from.empty()) {
int i = from.pop();
BuildItem ingredient = getFreeItemWithId(i, index);
if (ingredient != null && ingredient.to == null) {
if (ingredient.group != -1) {
curGroup = ingredient.group;
}
ingredient.to = item;
item.from.add(ingredient);
grouped = true;
calculateItemCost(item);
} else {
from.addAll(itemLibrary.getItemInfo(i).from);
}
}
if (grouped) {
increaseIngredientDepth(item);
for (BuildItem i : item.from) {
i.group = curGroup;
}
item.group = curGroup;
if (curGroup == currentGroupCounter) {
currentGroupCounter++;
}
}
}
private void calculateItemCost(BuildItem item) {
int p = item.info.totalGold;
for (BuildItem i : item.from) {
p -= i.info.totalGold;
}
item.costPer = p;
}
private void recalculateItemCosts() {
for (BuildItem item : itemBuild) {
calculateItemCost(item);
}
}
private void increaseIngredientDepth(BuildItem item) {
for (BuildItem i : item.from) {
i.depth++;
increaseIngredientDepth(i);
}
}
public void addItem(ItemInfo item) {
addItem(item, 1, true);
}
public void addItem(ItemInfo item, int count, boolean isAll) {
BuildItem buildItem = null;
BuildItem last = getLastItem();
if (last != null && item == last.info) {
if (item.stacks > last.count) {
last.count += count;
buildItem = last;
}
}
if (isAll == false) {
itemBuildDirty = true;
}
boolean itemNull = buildItem == null;
if (itemNull) {
buildItem = new BuildItem(item);
buildItem.count = Math.min(item.stacks, count);
// check if ingredients of this item is already part of the build...
labelAllIngredients(buildItem, itemBuild.size());
if (itemBuild.size() == enabledBuildEnd) {
enabledBuildEnd++;
}
itemBuild.add(buildItem);
calculateItemCost(buildItem);
}
if (isAll) {
recalculateStats();
if (itemBuildDirty) {
itemBuildDirty = false;
buildItem = null;
}
notifyItemAdded(buildItem, itemNull);
}
}
public void clearItems() {
itemBuild.clear();
normalizeValues();
recalculateItemCosts();
recalculateAllGroups();
recalculateStats();
notifyBuildChanged();
}
public void removeItemAt(int position) {
BuildItem item = itemBuild.get(position);
itemBuild.remove(position);
normalizeValues();
recalculateItemCosts();
recalculateAllGroups();
recalculateStats();
notifyBuildChanged();
}
public int getItemCount() {
return itemBuild.size();
}
private void clearStats(double[] stats) {
for (int i = 0; i < stats.length; i++) {
stats[i] = 0;
}
}
private void recalculateStats() {
calculateStats(stats, enabledBuildStart, enabledBuildEnd, false, champLevel);
}
private void calculateStats(double[] stats, int startItemBuild, int endItemBuild, boolean onlyDoRawCalculation, int champLevel) {
clearStats(stats);
int active = 0;
for (BuildRune r : runeBuild) {
appendStat(stats, r);
}
if (!onlyDoRawCalculation) {
for (BuildItem item : itemBuild) {
item.active = false;
}
}
HashSet<Integer> alreadyAdded = new HashSet<Integer>();
for (int i = endItemBuild - 1; i >= startItemBuild; i--) {
BuildItem item = itemBuild.get(i);
if (item.to == null || itemBuild.indexOf(item.to) >= enabledBuildEnd) {
if (!onlyDoRawCalculation) {
item.active = true;
}
ItemInfo info = item.info;
appendStat(stats, info.stats);
int id = info.id;
if (info.uniquePassiveStat != null && !alreadyAdded.contains(id)) {
alreadyAdded.add(info.id);
appendStat(stats, info.uniquePassiveStat);
}
active++;
if (active == MAX_ACTIVE_ITEMS)
break;
}
}
calculateTotalStats(stats, champLevel);
if (!onlyDoRawCalculation) {
notifyBuildStatsChanged();
}
}
private void appendStat(double[] stats, JSONObject jsonStats) {
Iterator<?> iter = jsonStats.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
try {
stats[getStatIndex(key)] += jsonStats.getDouble(key);
} catch (JSONException e) {
DebugLog.e(TAG, e);
}
}
}
private void appendStat(double[] stats, BuildRune rune) {
RuneInfo info = rune.info;
Iterator<?> iter = info.stats.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
try {
int f = getStatIndex(key);
if ((f & FLAG_SCALING) != 0) {
stats[f & ~FLAG_SCALING] += info.stats.getDouble(key) * champLevel * rune.count;
} else {
stats[f] += info.stats.getDouble(key) * rune.count;
}
} catch (JSONException e) {
DebugLog.e(TAG, e);
}
}
}
private void calculateTotalStats() {
calculateTotalStats(stats, champLevel);
}
private void calculateTotalStats(double[] stats, int champLevel) {
// do some stat normalization...
stats[STAT_CDR] = Math.min(MAX_CDR, stats[STAT_CDR] - stats[STAT_CD]);
int levMinusOne = champLevel - 1;
stats[STAT_TOTAL_AR] = stats[STAT_AR] + champ.ar + champ.arG * levMinusOne;
stats[STAT_TOTAL_AD] = stats[STAT_AD] + champ.ad + champ.adG * levMinusOne;
stats[STAT_TOTAL_HP] = stats[STAT_HP] + champ.hp + champ.hpG * levMinusOne;
stats[STAT_CD_MOD] = 1.0 - stats[STAT_CDR];
stats[STAT_TOTAL_MS] = (stats[STAT_MS] + champ.ms) * stats[STAT_MSP] + stats[STAT_MS] + champ.ms;
stats[STAT_TOTAL_AP] = stats[STAT_AP] * (stats[STAT_APP] + 1);
stats[STAT_TOTAL_MR] = stats[STAT_MR] + champ.mr + champ.mrG * levMinusOne;
stats[STAT_AS] = Math.min(champ.as * (1 + levMinusOne * champ.asG + stats[STAT_ASP]), MAX_ATTACK_SPEED);
stats[STAT_LEVEL] = champLevel;
stats[STAT_TOTAL_RANGE] = stats[STAT_RANGE] + champ.range;
stats[STAT_TOTAL_MP] = stats[STAT_MP] + champ.mp + champ.mpG * levMinusOne;
stats[STAT_BONUS_AD] = stats[STAT_TOTAL_AD] - champ.ad;
stats[STAT_BONUS_HP] = stats[STAT_TOTAL_HP] - champ.hp;
stats[STAT_BONUS_MS] = stats[STAT_TOTAL_MS] - champ.ms;
stats[STAT_BONUS_AR] = stats[STAT_TOTAL_AR] - champ.ar;
stats[STAT_BONUS_MR] = stats[STAT_TOTAL_MR] - champ.mr;
stats[STAT_LEVEL_MINUS_ONE] = stats[STAT_LEVEL] - 1;
stats[STAT_CRIT_DMG] = stats[STAT_TOTAL_AD] * 2.0;
// pure stats...
stats[STAT_AA_DPS] = stats[STAT_TOTAL_AD] * stats[STAT_AS];
// static values...
stats[STAT_NAUTILUS_Q_CD] = 0.5;
stats[STAT_ONE] = 1;
}
private static int addColor(int base, int value) {
double result = 1 - (1 - base / 256.0) * (1 - value / 256.0);
return (int) (result * 256);
}
public int generateColorBasedOnBuild() {
int r = 0, g = 0, b = 0;
int hp = 0;
int mr = 0;
int ar = 0;
int ad = 0;
int ap = 0;
int crit = 0;
int as = 0;
calculateTotalStats(stats, 1);
hp = (int) (stats[STAT_BONUS_HP] * STAT_VALUE_HP);
mr = (int) (stats[STAT_BONUS_MR] * STAT_VALUE_MR);
ar = (int) (stats[STAT_BONUS_AR] * STAT_VALUE_AR);
ad = (int) (stats[STAT_BONUS_AD] * STAT_VALUE_AD);
ap = (int) (stats[STAT_BONUS_AP] * STAT_VALUE_AP);
crit = (int) (stats[STAT_CRIT] * 100 * STAT_VALUE_CRIT);
as = (int) (stats[STAT_ASP] * 100 * STAT_VALUE_ASP);
int tank = hp + mr + ar;
int dps = ad + as + crit;
int burst = ap;
double total = tank + dps + burst;
double tankness = tank / total;
double adness = dps / total;
double apness = burst / total;
r = addColor((int) (Color.red(COLOR_AD) * adness), r);
r = addColor((int) (Color.red(COLOR_AP) * apness), r);
r = addColor((int) (Color.red(COLOR_TANK) * tankness), r);
g = addColor((int) (Color.green(COLOR_AD) * adness), g);
g = addColor((int) (Color.green(COLOR_AP) * apness), g);
g = addColor((int) (Color.green(COLOR_TANK) * tankness), g);
b = addColor((int) (Color.blue(COLOR_AD) * adness), b);
b = addColor((int) (Color.blue(COLOR_AP) * apness), b);
b = addColor((int) (Color.blue(COLOR_TANK) * tankness), b);
Log.d(TAG, String.format("Tankiness: %f Apness: %f Adness: %f", tankness, apness, adness));
return Color.rgb(r, g, b);
}
public BuildRune addRune(RuneInfo rune) {
return addRune(rune, 1, true);
}
public BuildRune addRune(RuneInfo rune, int count, boolean isAll) {
// Check if this rune is already in the build...
BuildRune r = null;
for (BuildRune br : runeBuild) {
if (br.id == rune.id) {
r = br;
break;
}
}
if (r == null) {
r = new BuildRune(rune, rune.id);
runeBuild.add(r);
r.listener = onRuneCountChangedListener;
notifyRuneAdded(r);
}
r.addRune(count);
recalculateStats();
return r;
}
public void clearRunes() {
for (BuildRune r : runeBuild) {
r.listener = null;
notifyRuneRemoved(r);
}
runeBuild.clear();
recalculateStats();
}
public boolean canAdd(RuneInfo rune) {
return runeCount[rune.runeType] + 1 <= RUNE_COUNT_MAX[rune.runeType];
}
public void removeRune(BuildRune rune) {
rune.listener = null;
runeBuild.remove(rune);
recalculateStats();
notifyRuneRemoved(rune);
}
private void onRuneCountChanged(BuildRune rune, int oldCount, int newCount) {
int runeType = rune.info.runeType;
if (runeCount[runeType] + (newCount - oldCount) > RUNE_COUNT_MAX[runeType]) {
rune.count = oldCount;
return;
}
runeCount[runeType] += (newCount - oldCount);
if (rune.getCount() == 0) {
removeRune(rune);
} else {
recalculateStats();
}
}
public BuildSkill addActiveSkill(Skill skill, double base, double scaling, String scaleType, String bonusType) {
BuildSkill sk = new BuildSkill();
sk.skill = skill;
sk.base = base;
sk.scaleTypeId = getStatIndex(scaleType);
sk.bonusTypeId = getStatIndex(bonusType);
sk.scaling = scaling;
activeSkills.add(sk);
DebugLog.d(TAG, "Skill " + skill.name + " bonus: " + base + "; ");
return sk;
}
public double[] calculateStatWithActives(int gold, int champLevel) {
double[] s = new double[stats.length];
int itemEndIndex = itemBuild.size();
int buildCost = 0;
for (int i = 0; i < itemBuild.size(); i++) {
BuildItem item = itemBuild.get(i);
int itemCost = item.costPer * item.count;
if (buildCost + itemCost > gold) {
itemEndIndex = i;
break;
} else {
buildCost += itemCost;
}
}
calculateStats(s, 0, itemEndIndex, true, champLevel);
for (BuildSkill sk : activeSkills) {
sk.totalBonus = s[sk.scaleTypeId] * sk.scaling + sk.base;
s[sk.bonusTypeId] += sk.totalBonus;
}
calculateTotalStats(s, champLevel);
return s;
}
public List<BuildSkill> getActives() {
return activeSkills;
}
public void clearActiveSkills() {
activeSkills.clear();
}
public void setChampion(ChampionInfo champ) {
this.champ = champ;
recalculateStats();
}
public void setChampionLevel(int level) {
champLevel = level;
recalculateStats();
}
public void registerObserver(BuildObserver observer) {
observers.add(observer);
}
public void unregisterObserver(BuildObserver observer) {
observers.remove(observer);
}
private void notifyBuildChanged() {
for (BuildObserver o : observers) {
o.onBuildChanged(this);
}
}
private void notifyItemAdded(BuildItem item, boolean isNewItem) {
for (BuildObserver o : observers) {
o.onItemAdded(this, item, isNewItem);
}
}
private void notifyRuneAdded(BuildRune rune) {
for (BuildObserver o : observers) {
o.onRuneAdded(this, rune);
}
}
private void notifyRuneRemoved(BuildRune rune) {
for (BuildObserver o : observers) {
o.onRuneRemoved(this, rune);
}
}
private void notifyBuildStatsChanged() {
for (BuildObserver o : observers) {
o.onBuildStatsChanged();
}
}
private void normalizeValues() {
if (enabledBuildStart < 0) {
enabledBuildStart = 0;
}
if (enabledBuildEnd > itemBuild.size()) {
enabledBuildEnd = itemBuild.size();
}
}
public BuildItem getItem(int index) {
return itemBuild.get(index);
}
public int getBuildSize() {
return itemBuild.size();
}
public BuildRune getRune(int index) {
return runeBuild.get(index);
}
public int getRuneCount() {
return runeBuild.size();
}
public BuildItem getLastItem() {
if (itemBuild.size() == 0) return null;
return itemBuild.get(itemBuild.size() - 1);
}
public double getBonusHp() {
return stats[STAT_HP];
}
public double getBonusHpRegen() {
return stats[STAT_HPR];
}
public double getBonusMp() {
if (champ.partype == ChampionInfo.TYPE_MANA) {
return stats[STAT_MP];
} else {
return 0;
}
}
public double getBonusMpRegen() {
if (champ.partype == ChampionInfo.TYPE_MANA) {
return stats[STAT_MPR];
} else {
return 0;
}
}
public double getBonusAd() {
return stats[STAT_AD];
}
public double getBonusAs() {
return stats[STAT_ASP];
}
public double getBonusAr() {
return stats[STAT_AR];
}
public double getBonusMr() {
return stats[STAT_MR];
}
public double getBonusMs() {
return stats[STAT_BONUS_MS];
}
public double getBonusRange() {
return stats[STAT_RANGE];
}
public double getBonusAp() {
return stats[STAT_BONUS_AP];
}
public double getBonusEnergy() {
return stats[STAT_NRG];
}
public double getBonusEnergyRegen() {
return stats[STAT_NRGR];
}
public double[] getRawStats() {
return stats;
}
public double getStat(String key) {
int statId = getStatIndex(key);
if (statId == STAT_NULL) return 0.0;
if (statId == STAT_RENGAR_Q_BASE_DAMAGE) {
// refresh rengar q base damage since it looks like we are going to be using it...
stats[STAT_RENGAR_Q_BASE_DAMAGE] = RENGAR_Q_BASE[champLevel - 1];
}
if (statId == STAT_VI_W) {
stats[STAT_VI_W] = 0.00081632653 * stats[STAT_BONUS_AD];
}
return stats[statId];
}
public double getStat(int statId) {
if (statId == STAT_NULL) return 0.0;
return stats[statId];
}
public void reorder(int itemOldPosition, int itemNewPosition) {
BuildItem item = itemBuild.get(itemOldPosition);
itemBuild.remove(itemOldPosition);
itemBuild.add(itemNewPosition, item);
recalculateAllGroups();
recalculateStats();
notifyBuildStatsChanged();
}
public int getEnabledBuildStart() {
return enabledBuildStart;
}
public int getEnabledBuildEnd() {
return enabledBuildEnd;
}
public void setEnabledBuildStart(int start) {
enabledBuildStart = start;
recalculateStats();
notifyBuildStatsChanged();
}
public void setEnabledBuildEnd(int end) {
enabledBuildEnd = end;
recalculateStats();
notifyBuildStatsChanged();
}
public BuildSaveObject toSaveObject() {
BuildSaveObject o = new BuildSaveObject();
for (BuildRune r : runeBuild) {
o.runes.add(r.info.id);
o.runes.add(r.count);
}
for (BuildItem i : itemBuild) {
o.items.add(i.info.id);
o.items.add(i.count);
}
o.buildName = buildName;
o.buildColor = generateColorBasedOnBuild();
return o;
}
public void fromSaveObject(BuildSaveObject o) {
clearItems();
clearRunes();
int count = o.runes.size();
for (int i = 0; i < count; i += 2) {
addRune(runeLibrary.getRuneInfo(o.runes.get(i)), o.runes.get(i++), i + 2 >= count);
}
count = o.items.size();
for (int i = 0; i < count; i += 2) {
int itemId = o.items.get(i);
int c = o.items.get(i + 1);
addItem(itemLibrary.getItemInfo(itemId), c, i == count - 2);
}
buildName = o.buildName;
}
public static int getSuggestedColorForGroup(int groupId) {
return GROUP_COLOR[groupId % GROUP_COLOR.length];
}
public static interface BuildObserver {
public void onBuildChanged(Build build);
public void onItemAdded(Build build, BuildItem item, boolean isNewItem);
public void onRuneAdded(Build build, BuildRune rune);
public void onRuneRemoved(Build build, BuildRune rune);
public void onBuildStatsChanged();
}
public static class BuildItem {
ItemInfo info;
int group = -1;
boolean active = true;
int count = 1;
int costPer = 0;
int depth = 0;
List<BuildItem> from;
BuildItem to;
private BuildItem(ItemInfo info) {
this.info = info;
from = new ArrayList<BuildItem>();
}
public int getId() {
return info.id;
}
}
public static class BuildRune {
RuneInfo info;
Object tag;
int id;
private int count;
private OnRuneCountChangedListener listener;
private OnRuneCountChangedListener onRuneCountChangedListener;
private BuildRune(RuneInfo info, int id) {
this.info = info;
count = 0;
this.id = id;
}
public void addRune() {
addRune(1);
}
public void addRune(int n) {
count += n;
int c = count;
listener.onRuneCountChanged(this, count - n, count);
if (c == count && onRuneCountChangedListener != null) {
onRuneCountChangedListener.onRuneCountChanged(this, count - n, count);
}
}
public void removeRune() {
if (count == 0) return;
count--;
int c = count;
listener.onRuneCountChanged(this, count + 1, count);
if (c == count && onRuneCountChangedListener != null) {
onRuneCountChangedListener.onRuneCountChanged(this, count + 1, count);
}
}
public int getCount() {
return count;
}
public void setOnRuneCountChangedListener(OnRuneCountChangedListener listener) {
onRuneCountChangedListener = listener;
}
}
public static class BuildSkill {
public double totalBonus;
Skill skill;
double base;
double scaling;
int scaleTypeId;
int bonusTypeId;
}
public static interface OnRuneCountChangedListener {
public void onRuneCountChanged(BuildRune rune, int oldCount, int newCount);
}
public static int getStatIndex(String statName) {
Integer i;
i = statKeyToIndex.get(statName);
if (i == null) {
throw new RuntimeException("Stat name not found: " + statName);
}
return i;
}
public static int getStatName(int statId) {
int i;
i = statIdToStringId.get(statId);
if (i == 0) {
throw new RuntimeException("Stat id does not have string resource: " + statId);
}
return i;
}
public static int getSkillStatDesc(int statId) {
int i;
i = statIdToSkillStatDescStringId.get(statId);
if (i == 0) {
throw new RuntimeException("Stat id does not have a skill stat description: " + statId);
}
return i;
}
public static int getStatType(int statId) {
switch (statId) {
case STAT_DMG_REDUCTION:
return STAT_TYPE_PERCENT;
default:
return STAT_TYPE_DEFAULT;
}
}
public static int getScalingType(int statId) {
switch (statId) {
case STAT_CD_MOD:
case STAT_STACKS:
case STAT_ONE:
return STAT_TYPE_DEFAULT;
default:
return STAT_TYPE_PERCENT;
}
}
}
|
Fix indentation
|
app/src/main/java/com/ggstudios/lolcraft/Build.java
|
Fix indentation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.