diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/deegree-datastores/deegree-tilestores/deegree-tilestore-remotewms/src/main/java/org/deegree/tile/persistence/remotewms/RemoteWMSTile.java b/deegree-datastores/deegree-tilestores/deegree-tilestore-remotewms/src/main/java/org/deegree/tile/persistence/remotewms/RemoteWMSTile.java
index 7ebf94bb28..cd26a13a7d 100644
--- a/deegree-datastores/deegree-tilestores/deegree-tilestore-remotewms/src/main/java/org/deegree/tile/persistence/remotewms/RemoteWMSTile.java
+++ b/deegree-datastores/deegree-tilestores/deegree-tilestore-remotewms/src/main/java/org/deegree/tile/persistence/remotewms/RemoteWMSTile.java
@@ -1,154 +1,153 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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.
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
http://www.occamlabs.de/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.tile.persistence.remotewms;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.feature.FeatureCollection;
import org.deegree.geometry.Envelope;
import org.deegree.layer.LayerRef;
import org.deegree.protocol.wms.client.WMSClient;
import org.deegree.protocol.wms.ops.GetFeatureInfo;
import org.deegree.protocol.wms.ops.GetMap;
import org.deegree.tile.Tile;
import org.deegree.tile.TileIOException;
/**
* {@link Tile} implementation used by the {@link RemoteWMSTileDataLevel}.
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $
*/
class RemoteWMSTile implements Tile {
private final WMSClient client;
private final GetMap gm;
private final String outputFormat;
/**
* Creates a new {@link RemoteWMSTile} instance.
*
* @param client
* client to use for performing the {@link GetMap} request, never <code>null</code>
* @param gm
* request for retrieving the tile image, never <code>null</code>
* @param outputFormat
* if not null, images will be recoded into specified output format (use ImageIO like formats, eg. 'png')
*/
RemoteWMSTile( WMSClient client, GetMap gm, String outputFormat ) {
this.client = client;
this.gm = gm;
this.outputFormat = outputFormat;
}
@Override
public BufferedImage getAsImage()
throws TileIOException {
InputStream in = null;
try {
return ImageIO.read( in = getAsStream() );
} catch ( IOException e ) {
throw new TileIOException( "Error decoding image : " + e.getMessage(), e );
} finally {
IOUtils.closeQuietly( in );
}
}
@Override
public InputStream getAsStream()
throws TileIOException {
try {
if ( outputFormat != null ) {
BufferedImage img = ImageIO.read( client.getMap( gm ) );
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write( img, outputFormat, out );
out.close();
return new ByteArrayInputStream( out.toByteArray() );
}
return client.getMap( gm );
} catch ( IOException e ) {
throw new TileIOException( "Error performing GetMap request: " + e.getMessage(), e );
}
}
@Override
public Envelope getEnvelope() {
return gm.getBoundingBox();
}
@Override
- public FeatureCollection getFeatures( int i, int j, int limit )
- throws UnsupportedOperationException {
+ public FeatureCollection getFeatures( int i, int j, int limit ) {
FeatureCollection fc = null;
try {
List<String> layers = new ArrayList<String>();
for ( LayerRef layerRef : gm.getLayers() ) {
layers.add( layerRef.getName() );
}
int width = gm.getWidth();
int height = gm.getHeight();
Envelope bbox = gm.getBoundingBox();
ICRS crs = gm.getCoordinateSystem();
GetFeatureInfo request = new GetFeatureInfo( layers, width, height, i, j, bbox, crs, limit );
fc = client.doGetFeatureInfo( request, null );
} catch ( Exception e ) {
String msg = "Error executing GetFeatureInfo request on remote server: " + e.getMessage();
throw new RuntimeException( msg, e );
}
return fc;
}
}
| true | true | public FeatureCollection getFeatures( int i, int j, int limit )
throws UnsupportedOperationException {
FeatureCollection fc = null;
try {
List<String> layers = new ArrayList<String>();
for ( LayerRef layerRef : gm.getLayers() ) {
layers.add( layerRef.getName() );
}
int width = gm.getWidth();
int height = gm.getHeight();
Envelope bbox = gm.getBoundingBox();
ICRS crs = gm.getCoordinateSystem();
GetFeatureInfo request = new GetFeatureInfo( layers, width, height, i, j, bbox, crs, limit );
fc = client.doGetFeatureInfo( request, null );
} catch ( Exception e ) {
String msg = "Error executing GetFeatureInfo request on remote server: " + e.getMessage();
throw new RuntimeException( msg, e );
}
return fc;
}
| public FeatureCollection getFeatures( int i, int j, int limit ) {
FeatureCollection fc = null;
try {
List<String> layers = new ArrayList<String>();
for ( LayerRef layerRef : gm.getLayers() ) {
layers.add( layerRef.getName() );
}
int width = gm.getWidth();
int height = gm.getHeight();
Envelope bbox = gm.getBoundingBox();
ICRS crs = gm.getCoordinateSystem();
GetFeatureInfo request = new GetFeatureInfo( layers, width, height, i, j, bbox, crs, limit );
fc = client.doGetFeatureInfo( request, null );
} catch ( Exception e ) {
String msg = "Error executing GetFeatureInfo request on remote server: " + e.getMessage();
throw new RuntimeException( msg, e );
}
return fc;
}
|
diff --git a/alfresco-mobile-android/src/org/alfresco/mobile/android/application/fragments/activities/ActivityEventAdapter.java b/alfresco-mobile-android/src/org/alfresco/mobile/android/application/fragments/activities/ActivityEventAdapter.java
index d2194601..9ad4cda2 100644
--- a/alfresco-mobile-android/src/org/alfresco/mobile/android/application/fragments/activities/ActivityEventAdapter.java
+++ b/alfresco-mobile-android/src/org/alfresco/mobile/android/application/fragments/activities/ActivityEventAdapter.java
@@ -1,448 +1,448 @@
/*******************************************************************************
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of the Alfresco Mobile SDK.
*
* 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.alfresco.mobile.android.application.fragments.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.alfresco.mobile.android.api.constants.CloudConstant;
import org.alfresco.mobile.android.api.constants.OnPremiseConstant;
import org.alfresco.mobile.android.api.model.ActivityEntry;
import org.alfresco.mobile.android.api.session.AlfrescoSession;
import org.alfresco.mobile.android.application.R;
import org.alfresco.mobile.android.application.activity.MainActivity;
import org.alfresco.mobile.android.application.fragments.menu.MenuActionItem;
import org.alfresco.mobile.android.application.fragments.person.PersonProfileFragment;
import org.alfresco.mobile.android.application.manager.RenditionManager;
import org.alfresco.mobile.android.application.utils.UIUtils;
import org.alfresco.mobile.android.ui.fragments.BaseListAdapter;
import org.alfresco.mobile.android.ui.manager.MimeTypeManager;
import org.alfresco.mobile.android.ui.utils.ViewHolder;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
/**
* Provides access to activity entries and displays them as a view based on
* GenericViewHolder.
*
* @author Jean Marie Pascal
*/
public class ActivityEventAdapter extends BaseListAdapter<ActivityEntry, GenericViewHolder> implements
OnMenuItemClickListener
{
private List<ActivityEntry> selectedItems;
private RenditionManager renditionManager;
private List<ActivityEntry> selectedOptionItems = new ArrayList<ActivityEntry>();
private Fragment fr;
public ActivityEventAdapter(Fragment fr, AlfrescoSession session, int textViewResourceId,
List<ActivityEntry> listItems, List<ActivityEntry> selectedItems)
{
super(fr.getActivity(), textViewResourceId, listItems);
this.vhClassName = GenericViewHolder.class.getCanonicalName();
this.renditionManager = new RenditionManager(fr.getActivity(), session);
this.selectedItems = selectedItems;
this.fr = fr;
}
@Override
protected void updateTopText(GenericViewHolder vh, ActivityEntry item)
{
vh.topText.setText(getUser(item));
vh.content.setText(Html.fromHtml(getActivityTypeMessage(item)));
}
@Override
protected void updateBottomText(GenericViewHolder vh, ActivityEntry item)
{
String s = "";
if (item.getCreatedAt() != null)
{
s = formatDate(getContext(), item.getCreatedAt().getTime());
}
vh.bottomText.setText(s);
if (selectedItems != null && selectedItems.contains(item))
{
UIUtils.setBackground(((LinearLayout) vh.icon.getParent().getParent().getParent()), getContext().getResources()
.getDrawable(R.drawable.list_longpressed_holo));
}
else
{
UIUtils.setBackground(((LinearLayout) vh.icon.getParent().getParent().getParent()), null);
}
/* Uncomment to activate people & site shortcut */
// Add support for people & sites
// UIUtils.setBackground(((View) vh.choose),
// getContext().getResources().getDrawable(R.drawable.quickcontact_badge_overlay_light));
((View) vh.icon.getParent()).setTag(R.id.entry_action, item);
((View) vh.icon.getParent()).setOnClickListener(new OnClickListener()
{
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onClick(View v)
{
ActivityEntry item = (ActivityEntry) v.getTag(R.id.entry_action);
PersonProfileFragment.newInstance(item.getCreatedBy()).show(fr.getActivity().getFragmentManager(),
PersonProfileFragment.TAG);
}
});
}
@Override
protected void updateIcon(GenericViewHolder vh, ActivityEntry item)
{
getCreatorAvatar(vh, item);
}
private void getCreatorAvatar(GenericViewHolder vh, ActivityEntry item)
{
String type = item.getType();
String tmp = null;
if (type.startsWith(PREFIX_FILE))
{
renditionManager.display(vh.icon, item.getCreatedBy(), R.drawable.ic_person);
}
else if (type.startsWith(PREFIX_GROUP))
{
vh.icon.setImageDrawable(getContext().getResources().getDrawable(getFileDrawableId(item)));
}
else if (type.startsWith(PREFIX_USER))
{
tmp = getData(item, CloudConstant.MEMEBERUSERNAME_VALUE);
if (tmp.isEmpty())
{
tmp = null;
}
renditionManager.display(vh.icon, tmp, R.drawable.ic_person);
}
else if (type.startsWith(PREFIX_SUBSCRIPTION))
{
tmp = getData(item, CloudConstant.FOLLOWERUSERNAME_VALUE);
if (tmp.isEmpty())
{
tmp = null;
}
renditionManager.display(vh.icon, tmp, R.drawable.ic_person);
}
else
{
renditionManager.display(vh.icon, item.getCreatedBy(), R.drawable.ic_person);
}
}
private int getFileDrawableId(ActivityEntry item)
{
int drawable = R.drawable.ic_menu_notif;
String s = item.getType();
if (s.startsWith(PREFIX_FILE))
{
drawable = MimeTypeManager.getIcon(getData(item, OnPremiseConstant.TITLE_VALUE));
}
else
{
for (Entry<String, Integer> icon : EVENT_ICON.entrySet())
{
if (s.startsWith(icon.getKey()))
{
drawable = icon.getValue();
break;
}
}
}
return drawable;
}
// ///////////////////////////////////////////////////////////////////////////
// MENU
// ///////////////////////////////////////////////////////////////////////////
public void getMenu(Menu menu, ActivityEntry entry)
{
/*
* if (entry.getSiteShortName() != null) { menu.add(Menu.NONE,
* MenuActionItem.MENU_ACTIVITY_SITE, Menu.FIRST +
* MenuActionItem.MENU_ACTIVITY_SITE, R.string.activity_site); }
*/
if (entry.getCreatedBy() != null)
{
menu.add(Menu.NONE, MenuActionItem.MENU_ACTIVITY_PROFILE,
Menu.FIRST + MenuActionItem.MENU_ACTIVITY_PROFILE,
String.format(getContext().getString(R.string.activity_profile), entry.getCreatedBy()));
}
}
@Override
public boolean onMenuItemClick(MenuItem item)
{
boolean onMenuItemClick = true;
switch (item.getItemId())
{
case MenuActionItem.MENU_ACTIVITY_SITE:
((MainActivity) fr.getActivity()).addNavigationFragment(selectedOptionItems.get(0).getSiteShortName());
onMenuItemClick = true;
break;
case MenuActionItem.MENU_ACTIVITY_PROFILE:
((MainActivity) fr.getActivity()).addPersonProfileFragment(selectedOptionItems.get(0).getCreatedBy());
onMenuItemClick = true;
break;
default:
onMenuItemClick = false;
break;
}
selectedOptionItems.clear();
return onMenuItemClick;
}
// ///////////////////////////////////////////////////////////////////////////
// TYPE
// ///////////////////////////////////////////////////////////////////////////
public static final String PREFIX_LINK = "org.alfresco.links.link";
public static final String PREFIX_EVENT = "org.alfresco.calendar.event";
public static final String PREFIX_WIKI = "org.alfresco.wiki.page";
public static final String PREFIX_FILE = "org.alfresco.documentlibrary.file";
public static final String PREFIX_USER = "org.alfresco.site.user";
public static final String PREFIX_DATALIST = "org.alfresco.datalists.list";
public static final String PREFIX_DISCUSSIONS = "org.alfresco.discussions";
public static final String PREFIX_FOLDER = "org.alfresco.documentlibrary.folder";
public static final String PREFIX_COMMENT = "org.alfresco.comments.comment";
public static final String PREFIX_BLOG = "org.alfresco.blog";
public static final String PREFIX_SUBSCRIPTION = "org.alfresco.subscriptions";
public static final String PREFIX_GROUP = "org.alfresco.site.group";
@SuppressWarnings("serial")
private static final Map<String, Integer> EVENT_ICON = new HashMap<String, Integer>()
{
{
put(PREFIX_LINK, R.drawable.ic_menu_share);
put(PREFIX_EVENT, R.drawable.ic_menu_today);
put(PREFIX_WIKI, R.drawable.ic_menu_notif);
put(PREFIX_USER, R.drawable.ic_avatar);
put(PREFIX_DATALIST, R.drawable.ic_menu_notif);
put(PREFIX_DISCUSSIONS, R.drawable.ic_action_dialog);
put(PREFIX_FOLDER, R.drawable.ic_menu_archive);
put(PREFIX_COMMENT, R.drawable.ic_action_dialog);
put(PREFIX_BLOG, R.drawable.ic_menu_notif);
put(PREFIX_SUBSCRIPTION, R.drawable.ic_menu_notif);
put(PREFIX_GROUP, R.drawable.ic_menu_notif);
}
};
//
private static final String PARAM_TITLE = "{0}";
private static final String PARAM_USER_PROFILE = "{1}";
private static final String PARAM_CUSTOM = "{2}";
private static final String PARAM_SITE_LINK = "{4}";
private static final String PARAM_SUBSCRIBER = "{5}";
private static final String PARAM_STATUS = "{6}";
private String getUser(ActivityEntry item)
{
String s = item.getType();
String username = item.getCreatedBy();
if (MAP_ACTIVITY_TYPE.get(s) != null)
{
s = getContext().getResources().getString(MAP_ACTIVITY_TYPE.get(item.getType()));
if (s.contains(PARAM_CUSTOM))
{
s = s.replace(PARAM_CUSTOM, getData(item, OnPremiseConstant.ROLE_VALUE));
username = getData(item, OnPremiseConstant.MEMEBERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.MEMBERLASTNAME_VALUE);
}
else
{
username = getData(item, OnPremiseConstant.FIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.LASTNAME_VALUE);
}
}
return username;
}
private String getActivityTypeMessage(ActivityEntry item)
{
String s = item.getType();
if (MAP_ACTIVITY_TYPE.get(s) != null)
{
s = getContext().getResources().getString(MAP_ACTIVITY_TYPE.get(item.getType()));
if (s.contains(PARAM_CUSTOM))
{
s = s.replace(PARAM_CUSTOM, getData(item, OnPremiseConstant.ROLE_VALUE));
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.MEMEBERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.MEMBERLASTNAME_VALUE) + "</b>");
}
else
{
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.FIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.LASTNAME_VALUE) + "</b>");
}
if (s.contains(PARAM_TITLE))
{
s = s.replace(PARAM_TITLE, "<b>" + getData(item, OnPremiseConstant.TITLE_VALUE) + "</b>");
}
if (s.contains(PARAM_SITE_LINK))
{
- s = s.replace(PARAM_SITE_LINK, item.getSiteShortName());
+ s = s.replace(PARAM_SITE_LINK, item.getSiteShortName() != null ? item.getSiteShortName() : "");
}
if (s.contains(PARAM_STATUS))
{
s = s.replace(PARAM_STATUS, getData(item, OnPremiseConstant.STATUS_VALUE));
}
if (s.contains(PARAM_SUBSCRIBER))
{
s = s.replace(PARAM_SUBSCRIBER, "<b>" + getData(item, OnPremiseConstant.USERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.USERLASTNAME_VALUE) + "</b>");
}
}
return s;
}
private String getData(ActivityEntry entry, String key)
{
String value = "";
if (entry == null) { return value; }
value = entry.getData(key);
if (value == null)
{
value = "";
}
return value;
}
@SuppressWarnings("serial")
private static final Map<String, Integer> MAP_ACTIVITY_TYPE = new HashMap<String, Integer>()
{
{
put("org.alfresco.blog.post-created", R.string.org_alfresco_blog_post_created);
put("org.alfresco.blog.post-updated", R.string.org_alfresco_blog_post_updated);
put("org.alfresco.blog.post-deleted", R.string.org_alfresco_blog_post_deleted);
put("org.alfresco.comments.comment-created", R.string.org_alfresco_comments_comment_created);
put("org.alfresco.comments.comment-updated", R.string.org_alfresco_comments_comment_updated);
put("org.alfresco.comments.comment-deleted", R.string.org_alfresco_comments_comment_deleted);
put("org.alfresco.discussions.post-created", R.string.org_alfresco_discussions_post_created);
put("org.alfresco.discussions.post-updated", R.string.org_alfresco_discussions_post_updated);
put("org.alfresco.discussions.post-deleted", R.string.org_alfresco_discussions_post_deleted);
put("org.alfresco.discussions.reply-created", R.string.org_alfresco_discussions_reply_created);
put("org.alfresco.discussions.reply-updated", R.string.org_alfresco_discussions_reply_updated);
put("org.alfresco.calendar.event-created", R.string.org_alfresco_calendar_event_created);
put("org.alfresco.calendar.event-updated", R.string.org_alfresco_calendar_event_updated);
put("org.alfresco.calendar.event-deleted", R.string.org_alfresco_calendar_event_deleted);
put("org.alfresco.documentlibrary.file-added", R.string.org_alfresco_documentlibrary_file_added);
put("org.alfresco.documentlibrary.files-added", R.string.org_alfresco_documentlibrary_files_added);
put("org.alfresco.documentlibrary.file-created", R.string.org_alfresco_documentlibrary_file_created);
put("org.alfresco.documentlibrary.file-deleted", R.string.org_alfresco_documentlibrary_file_deleted);
put("org.alfresco.documentlibrary.files-deleted", R.string.org_alfresco_documentlibrary_files_deleted);
put("org.alfresco.documentlibrary.file-updated", R.string.org_alfresco_documentlibrary_file_updated);
put("org.alfresco.documentlibrary.files-updated", R.string.org_alfresco_documentlibrary_files_updated);
put("org.alfresco.documentlibrary.folder-added", R.string.org_alfresco_documentlibrary_folder_added);
put("org.alfresco.documentlibrary.folder-deleted", R.string.org_alfresco_documentlibrary_folders_deleted);
put("org.alfresco.documentlibrary.folders-added", R.string.org_alfresco_documentlibrary_folder_added);
put("org.alfresco.documentlibrary.folders-deleted", R.string.org_alfresco_documentlibrary_folders_deleted);
put("org.alfresco.documentlibrary.google-docs-checkout",
R.string.org_alfresco_documentlibrary_google_docs_checkout);
put("org.alfresco.documentlibrary.google-docs-checkin",
R.string.org_alfresco_documentlibrary_google_docs_checkin);
put("org.alfresco.documentlibrary.inline-edit", R.string.org_alfresco_documentlibrary_inline_edit);
put("org.alfresco.documentlibrary.file-liked", R.string.org_alfresco_documentlibrary_file_liked);
put("org.alfresco.documentlibrary.folder-liked", R.string.org_alfresco_documentlibrary_folder_liked);
put("org.alfresco.wiki.page-created", R.string.org_alfresco_wiki_page_created);
put("org.alfresco.wiki.page-edited", R.string.org_alfresco_wiki_page_edited);
put("org.alfresco.wiki.page-renamed", R.string.org_alfresco_wiki_page_renamed);
put("org.alfresco.wiki.page-deleted", R.string.org_alfresco_wiki_page_deleted);
put("org.alfresco.site.group-added", R.string.org_alfresco_site_group_added);
put("org.alfresco.site.group-removed", R.string.org_alfresco_site_group_removed);
put("org.alfresco.site.group-role_changed", R.string.org_alfresco_site_group_role_changed);
put("org.alfresco.site.user-joined", R.string.org_alfresco_site_user_joined);
put("org.alfresco.site.user-left", R.string.org_alfresco_site_user_left);
put("org.alfresco.site.user-role-changed", R.string.org_alfresco_site_user_role_changed);
put("org.alfresco.links.link-created", R.string.org_alfresco_links_link_created);
put("org.alfresco.links.link-updated", R.string.org_alfresco_links_link_updated);
put("org.alfresco.links.link-deleted", R.string.org_alfresco_links_link_deleted);
put("org.alfresco.datalists.list-created", R.string.org_alfresco_datalists_list_created);
put("org.alfresco.datalists.list-updated", R.string.org_alfresco_datalists_list_updated);
put("org.alfresco.datalists.list-deleted", R.string.org_alfresco_datalists_list_deleted);
put("org.alfresco.subscriptions.followed", R.string.org_alfresco_subscriptions_followed);
put("org.alfresco.subscriptions.subscribed", R.string.org_alfresco_subscriptions_subscribed);
put("org.alfresco.profile.status-changed", R.string.org_alfresco_profile_status_changed);
}
};
}
final class GenericViewHolder extends ViewHolder
{
public TextView topText;
public TextView bottomText;
public ImageView icon;
public TextView content;
public GenericViewHolder(View v)
{
super(v);
icon = (ImageView) v.findViewById(R.id.icon);
topText = (TextView) v.findViewById(R.id.toptext);
bottomText = (TextView) v.findViewById(R.id.bottomtext);
content = (TextView) v.findViewById(R.id.content);
}
}
| true | true | private String getActivityTypeMessage(ActivityEntry item)
{
String s = item.getType();
if (MAP_ACTIVITY_TYPE.get(s) != null)
{
s = getContext().getResources().getString(MAP_ACTIVITY_TYPE.get(item.getType()));
if (s.contains(PARAM_CUSTOM))
{
s = s.replace(PARAM_CUSTOM, getData(item, OnPremiseConstant.ROLE_VALUE));
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.MEMEBERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.MEMBERLASTNAME_VALUE) + "</b>");
}
else
{
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.FIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.LASTNAME_VALUE) + "</b>");
}
if (s.contains(PARAM_TITLE))
{
s = s.replace(PARAM_TITLE, "<b>" + getData(item, OnPremiseConstant.TITLE_VALUE) + "</b>");
}
if (s.contains(PARAM_SITE_LINK))
{
s = s.replace(PARAM_SITE_LINK, item.getSiteShortName());
}
if (s.contains(PARAM_STATUS))
{
s = s.replace(PARAM_STATUS, getData(item, OnPremiseConstant.STATUS_VALUE));
}
if (s.contains(PARAM_SUBSCRIBER))
{
s = s.replace(PARAM_SUBSCRIBER, "<b>" + getData(item, OnPremiseConstant.USERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.USERLASTNAME_VALUE) + "</b>");
}
}
return s;
}
| private String getActivityTypeMessage(ActivityEntry item)
{
String s = item.getType();
if (MAP_ACTIVITY_TYPE.get(s) != null)
{
s = getContext().getResources().getString(MAP_ACTIVITY_TYPE.get(item.getType()));
if (s.contains(PARAM_CUSTOM))
{
s = s.replace(PARAM_CUSTOM, getData(item, OnPremiseConstant.ROLE_VALUE));
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.MEMEBERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.MEMBERLASTNAME_VALUE) + "</b>");
}
else
{
s = s.replace(PARAM_USER_PROFILE, "<b>" + getData(item, OnPremiseConstant.FIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.LASTNAME_VALUE) + "</b>");
}
if (s.contains(PARAM_TITLE))
{
s = s.replace(PARAM_TITLE, "<b>" + getData(item, OnPremiseConstant.TITLE_VALUE) + "</b>");
}
if (s.contains(PARAM_SITE_LINK))
{
s = s.replace(PARAM_SITE_LINK, item.getSiteShortName() != null ? item.getSiteShortName() : "");
}
if (s.contains(PARAM_STATUS))
{
s = s.replace(PARAM_STATUS, getData(item, OnPremiseConstant.STATUS_VALUE));
}
if (s.contains(PARAM_SUBSCRIBER))
{
s = s.replace(PARAM_SUBSCRIBER, "<b>" + getData(item, OnPremiseConstant.USERFIRSTNAME_VALUE) + " "
+ getData(item, OnPremiseConstant.USERLASTNAME_VALUE) + "</b>");
}
}
return s;
}
|
diff --git a/src/java/is/idega/block/agresso/dao/impl/AgressoDAOImpl.java b/src/java/is/idega/block/agresso/dao/impl/AgressoDAOImpl.java
index e7f1a06..65b745a 100644
--- a/src/java/is/idega/block/agresso/dao/impl/AgressoDAOImpl.java
+++ b/src/java/is/idega/block/agresso/dao/impl/AgressoDAOImpl.java
@@ -1,70 +1,73 @@
package is.idega.block.agresso.dao.impl;
import is.idega.block.agresso.dao.AgressoDAO;
import is.idega.block.agresso.data.AgressoFinanceEntry;
import java.sql.Timestamp;
import java.util.Date;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.idega.core.persistence.impl.GenericDaoImpl;
import com.idega.util.IWTimestamp;
@Scope("singleton")
@Repository("agressoDAO")
@Transactional(readOnly = true)
public class AgressoDAOImpl extends GenericDaoImpl implements AgressoDAO {
@Transactional(readOnly = false)
public void addFinanceEntry(String entryType, String userSSN,
Integer amount, Timestamp paymentDate, String info) {
AgressoFinanceEntry entry = new AgressoFinanceEntry();
entry.setAmount(amount);
entry.setCreationDate(IWTimestamp.getTimestampRightNow());
entry.setEntryUser(userSSN);
entry.setEntryType(entryType);
entry.setPaymentDate(paymentDate);
entry.setInfo(info);
getEntityManager().persist(entry);
}
@Transactional(readOnly = false)
public void addFinanceEntryParking(String entryType, String userSSN,
Integer amount, Timestamp paymentDate, Date creationDate, String info,
String registrationNumber, String permanentNumber, String carType,
String owner, String ticketNumber, String ticketOfficer,
String streetName, String streetNumber, String streetDescription,
String meterNumber, String invoiceNumber) {
AgressoFinanceEntry entry = new AgressoFinanceEntry();
entry.setAmount(amount);
if(creationDate==null){
entry.setCreationDate(IWTimestamp.getTimestampRightNow());
}
+ else{
+ entry.setCreationDate(creationDate);
+ }
entry.setEntryUser(userSSN);
entry.setEntryType(entryType);
entry.setPaymentDate(paymentDate);
entry.setInfo(info);
entry.setRegistrationNumber(registrationNumber);
entry.setPermanentNumber(permanentNumber);
entry.setCarType(carType);
entry.setOwner(owner);
entry.setTicketNumber(ticketNumber);
entry.setTicketOfficer(ticketOfficer);
entry.setStreetName(streetName);
entry.setStreetNumber(streetNumber);
entry.setStreetDescription(streetDescription);
entry.setMeterNumber(meterNumber);
entry.setInvoiceNumber(invoiceNumber);
getEntityManager().persist(entry);
}
}
| true | true | public void addFinanceEntryParking(String entryType, String userSSN,
Integer amount, Timestamp paymentDate, Date creationDate, String info,
String registrationNumber, String permanentNumber, String carType,
String owner, String ticketNumber, String ticketOfficer,
String streetName, String streetNumber, String streetDescription,
String meterNumber, String invoiceNumber) {
AgressoFinanceEntry entry = new AgressoFinanceEntry();
entry.setAmount(amount);
if(creationDate==null){
entry.setCreationDate(IWTimestamp.getTimestampRightNow());
}
entry.setEntryUser(userSSN);
entry.setEntryType(entryType);
entry.setPaymentDate(paymentDate);
entry.setInfo(info);
entry.setRegistrationNumber(registrationNumber);
entry.setPermanentNumber(permanentNumber);
entry.setCarType(carType);
entry.setOwner(owner);
entry.setTicketNumber(ticketNumber);
entry.setTicketOfficer(ticketOfficer);
entry.setStreetName(streetName);
entry.setStreetNumber(streetNumber);
entry.setStreetDescription(streetDescription);
entry.setMeterNumber(meterNumber);
entry.setInvoiceNumber(invoiceNumber);
getEntityManager().persist(entry);
}
| public void addFinanceEntryParking(String entryType, String userSSN,
Integer amount, Timestamp paymentDate, Date creationDate, String info,
String registrationNumber, String permanentNumber, String carType,
String owner, String ticketNumber, String ticketOfficer,
String streetName, String streetNumber, String streetDescription,
String meterNumber, String invoiceNumber) {
AgressoFinanceEntry entry = new AgressoFinanceEntry();
entry.setAmount(amount);
if(creationDate==null){
entry.setCreationDate(IWTimestamp.getTimestampRightNow());
}
else{
entry.setCreationDate(creationDate);
}
entry.setEntryUser(userSSN);
entry.setEntryType(entryType);
entry.setPaymentDate(paymentDate);
entry.setInfo(info);
entry.setRegistrationNumber(registrationNumber);
entry.setPermanentNumber(permanentNumber);
entry.setCarType(carType);
entry.setOwner(owner);
entry.setTicketNumber(ticketNumber);
entry.setTicketOfficer(ticketOfficer);
entry.setStreetName(streetName);
entry.setStreetNumber(streetNumber);
entry.setStreetDescription(streetDescription);
entry.setMeterNumber(meterNumber);
entry.setInvoiceNumber(invoiceNumber);
getEntityManager().persist(entry);
}
|
diff --git a/h2/src/main/org/h2/server/web/WebSession.java b/h2/src/main/org/h2/server/web/WebSession.java
index 324614f18..bbd0f2167 100644
--- a/h2/src/main/org/h2/server/web/WebSession.java
+++ b/h2/src/main/org/h2/server/web/WebSession.java
@@ -1,258 +1,258 @@
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.server.web;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.h2.bnf.Bnf;
import org.h2.bnf.context.DbContents;
import org.h2.bnf.context.DbContextRule;
import org.h2.message.TraceSystem;
import org.h2.util.New;
/**
* The web session keeps all data of a user session.
* This class is used by the H2 Console.
*/
class WebSession {
private static final int MAX_HISTORY = 1000;
/**
* The last time this client sent a request.
*/
long lastAccess;
/**
* The session attribute map.
*/
final HashMap<String, Object> map = New.hashMap();
/**
* The current locale.
*/
Locale locale;
/**
* The currently executing statement.
*/
Statement executingStatement;
/**
* The current updatable result set.
*/
ResultSet result;
private final WebServer server;
private final ArrayList<String> commandHistory = New.arrayList();
private Connection conn;
private DatabaseMetaData meta;
private DbContents contents = new DbContents();
private Bnf bnf;
private boolean shutdownServerOnDisconnect;
WebSession(WebServer server) {
this.server = server;
}
/**
* Put an attribute value in the map.
*
* @param key the key
* @param value the new value
*/
void put(String key, Object value) {
map.put(key, value);
}
/**
* Get the value for the given key.
*
* @param key the key
* @return the value
*/
Object get(String key) {
if ("sessions".equals(key)) {
return server.getSessions();
}
return map.get(key);
}
/**
* Remove a session attribute from the map.
*
* @param key the key
*/
void remove(String key) {
map.remove(key);
}
/**
* Get the BNF object.
*
* @return the BNF object
*/
Bnf getBnf() {
return bnf;
}
/**
* Load the SQL grammar BNF.
*/
void loadBnf() {
try {
Bnf newBnf = Bnf.getInstance(null);
DbContextRule columnRule = new DbContextRule(contents, DbContextRule.COLUMN);
DbContextRule newAliasRule = new DbContextRule(contents, DbContextRule.NEW_TABLE_ALIAS);
DbContextRule aliasRule = new DbContextRule(contents, DbContextRule.TABLE_ALIAS);
DbContextRule tableRule = new DbContextRule(contents, DbContextRule.TABLE);
DbContextRule schemaRule = new DbContextRule(contents, DbContextRule.SCHEMA);
DbContextRule columnAliasRule = new DbContextRule(contents, DbContextRule.COLUMN_ALIAS);
DbContextRule procedureRule = new DbContextRule(contents, DbContextRule.PROCEDURE);
newBnf.updateTopic("column_name", columnRule);
newBnf.updateTopic("new_table_alias", newAliasRule);
newBnf.updateTopic("table_alias", aliasRule);
newBnf.updateTopic("column_alias", columnAliasRule);
newBnf.updateTopic("table_name", tableRule);
newBnf.updateTopic("schema_name", schemaRule);
- newBnf.updateTopic("expression", procedureRule);
+ // newBnf.updateTopic("expression", procedureRule);
newBnf.linkStatements();
bnf = newBnf;
} catch (Exception e) {
// ok we don't have the bnf
server.traceError(e);
}
}
/**
* Get the SQL statement from history.
*
* @param id the history id
* @return the SQL statement
*/
String getCommand(int id) {
return commandHistory.get(id);
}
/**
* Add a SQL statement to the history.
*
* @param sql the SQL statement
*/
void addCommand(String sql) {
if (sql == null) {
return;
}
sql = sql.trim();
if (sql.length() == 0) {
return;
}
if (commandHistory.size() > MAX_HISTORY) {
commandHistory.remove(0);
}
int idx = commandHistory.indexOf(sql);
if (idx >= 0) {
commandHistory.remove(idx);
}
commandHistory.add(sql);
}
/**
* Get the list of SQL statements in the history.
*
* @return the commands
*/
ArrayList<String> getCommands() {
return commandHistory;
}
/**
* Update session meta data information and get the information in a map.
*
* @return a map containing the session meta data
*/
HashMap<String, Object> getInfo() {
HashMap<String, Object> m = New.hashMap();
m.putAll(map);
m.put("lastAccess", new Timestamp(lastAccess).toString());
try {
m.put("url", conn == null ? "${text.admin.notConnected}" : conn.getMetaData().getURL());
m.put("user", conn == null ? "-" : conn.getMetaData().getUserName());
m.put("lastQuery", commandHistory.size() == 0 ? "" : commandHistory.get(0));
m.put("executing", executingStatement == null ? "${text.admin.no}" : "${text.admin.yes}");
} catch (SQLException e) {
TraceSystem.traceThrowable(e);
}
return m;
}
void setConnection(Connection conn) throws SQLException {
this.conn = conn;
if (conn == null) {
meta = null;
} else {
meta = conn.getMetaData();
}
contents = new DbContents();
}
DatabaseMetaData getMetaData() {
return meta;
}
Connection getConnection() {
return conn;
}
DbContents getContents() {
return contents;
}
/**
* Shutdown the server when disconnecting.
*/
void setShutdownServerOnDisconnect() {
this.shutdownServerOnDisconnect = true;
}
boolean getShutdownServerOnDisconnect() {
return shutdownServerOnDisconnect;
}
/**
* Close the connection and stop the statement if one is currently
* executing.
*/
void close() {
if (executingStatement != null) {
try {
executingStatement.cancel();
} catch (Exception e) {
// ignore
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
// ignore
}
}
}
}
| true | true | void loadBnf() {
try {
Bnf newBnf = Bnf.getInstance(null);
DbContextRule columnRule = new DbContextRule(contents, DbContextRule.COLUMN);
DbContextRule newAliasRule = new DbContextRule(contents, DbContextRule.NEW_TABLE_ALIAS);
DbContextRule aliasRule = new DbContextRule(contents, DbContextRule.TABLE_ALIAS);
DbContextRule tableRule = new DbContextRule(contents, DbContextRule.TABLE);
DbContextRule schemaRule = new DbContextRule(contents, DbContextRule.SCHEMA);
DbContextRule columnAliasRule = new DbContextRule(contents, DbContextRule.COLUMN_ALIAS);
DbContextRule procedureRule = new DbContextRule(contents, DbContextRule.PROCEDURE);
newBnf.updateTopic("column_name", columnRule);
newBnf.updateTopic("new_table_alias", newAliasRule);
newBnf.updateTopic("table_alias", aliasRule);
newBnf.updateTopic("column_alias", columnAliasRule);
newBnf.updateTopic("table_name", tableRule);
newBnf.updateTopic("schema_name", schemaRule);
newBnf.updateTopic("expression", procedureRule);
newBnf.linkStatements();
bnf = newBnf;
} catch (Exception e) {
// ok we don't have the bnf
server.traceError(e);
}
}
| void loadBnf() {
try {
Bnf newBnf = Bnf.getInstance(null);
DbContextRule columnRule = new DbContextRule(contents, DbContextRule.COLUMN);
DbContextRule newAliasRule = new DbContextRule(contents, DbContextRule.NEW_TABLE_ALIAS);
DbContextRule aliasRule = new DbContextRule(contents, DbContextRule.TABLE_ALIAS);
DbContextRule tableRule = new DbContextRule(contents, DbContextRule.TABLE);
DbContextRule schemaRule = new DbContextRule(contents, DbContextRule.SCHEMA);
DbContextRule columnAliasRule = new DbContextRule(contents, DbContextRule.COLUMN_ALIAS);
DbContextRule procedureRule = new DbContextRule(contents, DbContextRule.PROCEDURE);
newBnf.updateTopic("column_name", columnRule);
newBnf.updateTopic("new_table_alias", newAliasRule);
newBnf.updateTopic("table_alias", aliasRule);
newBnf.updateTopic("column_alias", columnAliasRule);
newBnf.updateTopic("table_name", tableRule);
newBnf.updateTopic("schema_name", schemaRule);
// newBnf.updateTopic("expression", procedureRule);
newBnf.linkStatements();
bnf = newBnf;
} catch (Exception e) {
// ok we don't have the bnf
server.traceError(e);
}
}
|
diff --git a/core/src/main/java/woko/facets/builtin/developer/ListTabularImpl.java b/core/src/main/java/woko/facets/builtin/developer/ListTabularImpl.java
index 2adaaf52..2d3803f9 100644
--- a/core/src/main/java/woko/facets/builtin/developer/ListTabularImpl.java
+++ b/core/src/main/java/woko/facets/builtin/developer/ListTabularImpl.java
@@ -1,18 +1,18 @@
package woko.facets.builtin.developer;
import woko.facets.builtin.TabularResultFacet;
import java.util.List;
public class ListTabularImpl extends ListImpl implements TabularResultFacet {
@Override
public String getPath() {
- return "/WEB-INF/jsp/developer/list-tabular.jsp";
+ return "/WEB-INF/woko/jsp/developer/listTabular.jsp";
}
@Override
public List<String> getPropertyNames() {
return null;
}
}
| true | true | public String getPath() {
return "/WEB-INF/jsp/developer/list-tabular.jsp";
}
| public String getPath() {
return "/WEB-INF/woko/jsp/developer/listTabular.jsp";
}
|
diff --git a/loci/formats/in/LIFReader.java b/loci/formats/in/LIFReader.java
index a3044b758..4ac0484a9 100644
--- a/loci/formats/in/LIFReader.java
+++ b/loci/formats/in/LIFReader.java
@@ -1,675 +1,675 @@
//
// LIFReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import loci.formats.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* LIFReader is the file format reader for Leica LIF files.
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class LIFReader extends FormatReader {
// -- Constants --
/** Factory for generating SAX parsers. */
public static final SAXParserFactory SAX_FACTORY =
SAXParserFactory.newInstance();
// -- Fields --
/** Offsets to memory blocks, paired with their corresponding description. */
protected Vector offsets;
/** Bits per pixel. */
private int[] bitsPerPixel;
/** Extra dimensions. */
private int[] extraDimensions;
/** Number of valid bits per pixel */
private int[][] validBits;
private int bpp;
private Vector xcal;
private Vector ycal;
private Vector zcal;
private Vector seriesNames;
private Vector channelMins;
private Vector channelMaxs;
// -- Constructor --
/** Constructs a new Leica LIF reader. */
public LIFReader() { super("Leica Image File Format", "lif"); }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return block[0] == 0x70;
}
/* @see loci.formats.IFormatReader#openBytes(int) */
public byte[] openBytes(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
bpp = bitsPerPixel[series];
while (bpp % 8 != 0) bpp++;
byte[] buf = new byte[core.sizeX[series] * core.sizeY[series] *
(bpp / 8) * getRGBChannelCount()];
return openBytes(no, buf);
}
/* @see loci.formats.IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
if (no < 0 || no >= getImageCount()) {
throw new FormatException("Invalid image number: " + no);
}
bpp = bitsPerPixel[series];
while (bpp % 8 != 0) bpp++;
int bytes = bpp / 8;
if (buf.length < core.sizeX[series] * core.sizeY[series] * bytes *
getRGBChannelCount())
{
throw new FormatException("Buffer too small.");
}
long offset = ((Long) offsets.get(series)).longValue();
in.seek(offset + core.sizeX[series] * core.sizeY[series] *
bytes * no * getRGBChannelCount());
in.read(buf);
return buf;
}
/* @see loci.formats.IFormatReader#openImage(int) */
public BufferedImage openImage(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
return ImageTools.makeImage(openBytes(no), core.sizeX[series],
core.sizeY[series], isRGB() ? core.sizeC[series] : 1, false, bpp / 8,
core.littleEndian[series], validBits[series]);
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("LIFReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
offsets = new Vector();
core.littleEndian[0] = true;
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
channelMins = new Vector();
channelMaxs = new Vector();
// read the header
status("Reading header");
byte checkOne = (byte) in.read();
in.skipBytes(2);
byte checkTwo = (byte) in.read();
if (checkOne != 0x70 && checkTwo != 0x70) {
throw new FormatException(id + " is not a valid Leica LIF file");
}
in.skipBytes(4);
// read and parse the XML description
if (in.read() != 0x2a) {
throw new FormatException("Invalid XML description");
}
// number of Unicode characters in the XML block
int nc = DataTools.read4SignedBytes(in, core.littleEndian[0]);
byte[] s = new byte[nc * 2];
in.read(s);
String xml = DataTools.stripString(new String(s));
status("Finding image offsets");
while (in.getFilePointer() < in.length()) {
if (DataTools.read4SignedBytes(in, core.littleEndian[0]) != 0x70) {
throw new FormatException("Invalid Memory Block");
}
in.skipBytes(4);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int blockLength = DataTools.read4SignedBytes(in, core.littleEndian[0]);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int descrLength = DataTools.read4SignedBytes(in, core.littleEndian[0]);
byte[] memDescr = new byte[2*descrLength];
in.read(memDescr);
if (blockLength > 0) {
offsets.add(new Long(in.getFilePointer()));
}
in.skipBytes(blockLength);
}
initMetadata(xml);
}
// -- Helper methods --
/** Parses a string of XML and puts the values in a Hashtable. */
private void initMetadata(String xml) throws FormatException, IOException {
// parse raw key/value pairs - adapted from FlexReader
LIFHandler handler = new LIFHandler();
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml +
"</LEICA>";
// strip out invalid characters
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
Vector elements = new Vector();
seriesNames = new Vector();
status("Populating native metadata");
// first parse each element in the XML string
StringTokenizer st = new StringTokenizer(xml, ">");
while (st.hasMoreTokens()) {
String token = st.nextToken();
elements.add(token.substring(1));
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
addMeta(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
String prefix = "";
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
if (token.startsWith("ScannerSettingRecord")) {
if (token.indexOf("csScanMode") != -1) {
int index = token.indexOf("Variant") + 7;
String ordering = token.substring(index + 2,
token.indexOf("\"", index + 3));
ordering = ordering.toLowerCase();
if (ordering.indexOf("x") == -1 || ordering.indexOf("y") == -1 ||
ordering.indexOf("xy") == -1)
{
int xPos = ordering.indexOf("x");
int yPos = ordering.indexOf("y");
int zPos = ordering.indexOf("z");
int tPos = ordering.indexOf("t");
if (xPos < 0) xPos = 0;
if (yPos < 0) yPos = 1;
if (zPos < 0) zPos = 2;
if (tPos < 0) tPos = 3;
int x = ((Integer) widths.get(widths.size() - 1)).intValue();
int y = ((Integer) heights.get(widths.size() - 1)).intValue();
int z = ((Integer) zs.get(widths.size() - 1)).intValue();
int t = ((Integer) ts.get(widths.size() - 1)).intValue();
int[] dimensions = {x, y, z, t};
x = dimensions[xPos];
y = dimensions[yPos];
z = dimensions[zPos];
t = dimensions[tPos];
widths.setElementAt(new Integer(x), widths.size() - 1);
heights.setElementAt(new Integer(y), heights.size() - 1);
zs.setElementAt(new Integer(z), zs.size() - 1);
ts.setElementAt(new Integer(t), ts.size() - 1);
}
}
else if (token.indexOf("dblVoxel") != -1) {
int index = token.indexOf("Variant") + 7;
String size = token.substring(index + 2,
token.indexOf("\"", index + 3));
float cal = Float.parseFloat(size) * 1000000;
if (token.indexOf("X") != -1) xcal.add(new Float(cal));
else if (token.indexOf("Y") != -1) ycal.add(new Float(cal));
else if (token.indexOf("Z") != -1) zcal.add(new Float(cal));
}
}
else if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
if (token.startsWith("Element Name")) {
// hack to override first series name
seriesNames.setElementAt(token.substring(token.indexOf("=") + 2,
token.length() - 1), seriesNames.size() - 1);
prefix = (String) seriesNames.get(seriesNames.size() - 1);
}
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
String sMin = (String) tmp.get("Min");
String sMax = (String) tmp.get("Max");
if (sMin != null && sMax != null) {
double min = Double.parseDouble(sMin);
double max = Double.parseDouble(sMax);
channelMins.add(new Integer((int) min));
channelMaxs.add(new Integer((int) max));
}
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1:
widths.add(new Integer(w));
break;
case 2:
heights.add(new Integer(w));
break;
case 3:
zs.add(new Integer(w));
break;
case 4:
ts.add(new Integer(w));
break;
default:
extras *= w;
}
}
}
ndx++;
if (elements != null && ndx < elements.size()) {
token = (String) elements.get(ndx);
}
else break;
}
extraDims.add(new Integer(extras));
if (numChannels == 0) numChannels++;
channels.add(new Integer(numChannels));
if (widths.size() < numDatasets && heights.size() < numDatasets) {
numDatasets--;
}
else {
if (widths.size() < numDatasets) widths.add(new Integer(1));
if (heights.size() < numDatasets) heights.add(new Integer(1));
if (zs.size() < numDatasets) zs.add(new Integer(1));
if (ts.size() < numDatasets) ts.add(new Integer(1));
if (bps.size() < numDatasets) bps.add(new Integer(8));
}
}
ndx++;
}
numDatasets = widths.size();
bitsPerPixel = new int[numDatasets];
extraDimensions = new int[numDatasets];
// Populate metadata store
status("Populating metadata");
// The metadata store we're working with.
MetadataStore store = getMetadataStore();
core = new CoreMetadata(numDatasets);
Arrays.fill(core.orderCertain, true);
validBits = new int[numDatasets][];
for (int i=0; i<numDatasets; i++) {
core.sizeX[i] = ((Integer) widths.get(i)).intValue();
core.sizeY[i] = ((Integer) heights.get(i)).intValue();
core.sizeZ[i] = ((Integer) zs.get(i)).intValue();
core.sizeC[i] = ((Integer) channels.get(i)).intValue();
core.sizeT[i] = ((Integer) ts.get(i)).intValue();
core.currentOrder[i] =
(core.sizeZ[i] > core.sizeT[i]) ? "XYCZT" : "XYCTZ";
bitsPerPixel[i] = ((Integer) bps.get(i)).intValue();
extraDimensions[i] = ((Integer) extraDims.get(i)).intValue();
if (extraDimensions[i] > 1) {
if (core.sizeZ[i] == 1) core.sizeZ[i] = extraDimensions[i];
else core.sizeT[i] *= extraDimensions[i];
extraDimensions[i] = 1;
}
core.littleEndian[i] = true;
core.rgb[i] = core.sizeC[i] > 1 && core.sizeC[i] < 4;
core.interleaved[i] = true;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i];
if (!core.rgb[i]) core.imageCount[i] *= core.sizeC[i];
validBits[i] = new int[core.sizeC[i] != 2 ? core.sizeC[i] : 3];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = bitsPerPixel[i];
}
while (bitsPerPixel[i] % 8 != 0) bitsPerPixel[i]++;
switch (bitsPerPixel[i]) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
Integer ii = new Integer(i);
String seriesName = (String) seriesNames.get(i);
if (seriesName == null || seriesName.trim().length() == 0) {
seriesName = "Series " + (i + 1);
}
store.setImage(seriesName, null, null, ii);
store.setPixels(
new Integer(core.sizeX[i]), // SizeX
new Integer(core.sizeY[i]), // SizeY
new Integer(core.sizeZ[i]), // SizeZ
new Integer(core.sizeC[i]), // SizeC
new Integer(core.sizeT[i]), // SizeT
new Integer(core.pixelType[i]), // PixelType
new Boolean(!core.littleEndian[i]), // BigEndian
core.currentOrder[i], // DimensionOrder
ii, // Image index
null); // Pixels index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
for (int j=0; j<core.sizeC[i]; j++) {
store.setLogicalChannel(j, null, null, null, null, null, null, ii);
}
String zoom = (String) getMeta(seriesName + " - dblZoom");
store.setDisplayOptions(zoom == null ? null : new Float(zoom),
new Boolean(core.sizeC[i] > 1), new Boolean(core.sizeC[i] > 1),
new Boolean(core.sizeC[i] > 2), new Boolean(isRGB()), null,
null, null, null, null, ii, null, null, null, null, null);
Enumeration keys = metadata.keys();
while (keys.hasMoreElements()) {
String k = (String) keys.nextElement();
boolean use = true;
for (int j=0; j<seriesNames.size(); j++) {
- if (j != i && k.startsWith((String) seriesNames.get(i))) {
+ if (j != i && k.startsWith((String) seriesNames.get(j))) {
use = false;
break;
}
}
if (use) core.seriesMetadata[i].put(k, metadata.get(k));
}
}
}
// -- Helper class --
/** SAX handler for parsing XML. */
class LIFHandler extends DefaultHandler {
private String series;
private int count = 0;
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Element")) {
if (!attributes.getValue("Name").equals("DCROISet")) {
series = attributes.getValue("Name");
}
}
else if (qName.equals("Experiment")) {
for (int i=0; i<attributes.getLength(); i++) {
addMeta(attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("ChannelDescription")) {
String prefix = series + " - Channel " + count + " - ";
addMeta(prefix + "Min", attributes.getValue("Min"));
addMeta(prefix + "Max", attributes.getValue("Max"));
addMeta(prefix + "Resolution", attributes.getValue("Resolution"));
addMeta(prefix + "LUTName", attributes.getValue("LUTName"));
addMeta(prefix + "IsLUTInverted", attributes.getValue("IsLUTInverted"));
count++;
}
else if (qName.equals("DimensionDescription")) {
String prefix = series + " - Dimension " + count + " - ";
addMeta(prefix + "NumberOfElements",
attributes.getValue("NumberOfElements"));
addMeta(prefix + "Length", attributes.getValue("Length"));
addMeta(prefix + "Origin", attributes.getValue("Origin"));
addMeta(prefix + "DimID", attributes.getValue("DimID"));
}
else if (qName.equals("ScannerSettingRecord")) {
String key = attributes.getValue("Identifier") + " - " +
attributes.getValue("Description");
addMeta(series + " - " + key, attributes.getValue("Variant"));
}
else if (qName.equals("FilterSettingRecord")) {
String key = attributes.getValue("ObjectName") + " - " +
attributes.getValue("Description") + " - " +
attributes.getValue("Attribute");
addMeta(series + " - " + key, attributes.getValue("Variant"));
}
else if (qName.equals("ATLConfocalSettingDefinition")) {
if (series.indexOf("- Sequential Setting ") == -1) {
series += " - Sequential Setting 1";
}
else {
int ndx = series.indexOf(" - Sequential Setting ") + 22;
int n = Integer.parseInt(series.substring(ndx));
n++;
series = series.substring(0, ndx) + String.valueOf(n);
}
for (int i=0; i<attributes.getLength(); i++) {
addMeta(series + " - " + attributes.getQName(i),
attributes.getValue(i));
}
}
else if (qName.equals("Wheel")) {
String prefix = series + " - Wheel " + count + " - ";
addMeta(prefix + "Qualifier", attributes.getValue("Qualifier"));
addMeta(prefix + "FilterIndex", attributes.getValue("FilterIndex"));
addMeta(prefix + "FilterSpectrumPos",
attributes.getValue("FilterSpectrumPos"));
addMeta(prefix + "IsSpectrumTurnMode",
attributes.getValue("IsSpectrumTurnMode"));
addMeta(prefix + "IndexChanged", attributes.getValue("IndexChanged"));
addMeta(prefix + "SpectrumChanged",
attributes.getValue("SpectrumChanged"));
count++;
}
else if (qName.equals("WheelName")) {
String prefix = series + " - Wheel " + (count - 1) + " - WheelName ";
int ndx = 0;
while (getMeta(prefix + ndx) != null) ndx++;
addMeta(prefix + ndx, attributes.getValue("FilterName"));
}
else if (qName.equals("MultiBand")) {
String prefix = series + " - MultiBand Channel " +
attributes.getValue("Channel") + " - ";
addMeta(prefix + "LeftWorld", attributes.getValue("LeftWorld"));
addMeta(prefix + "RightWorld", attributes.getValue("RightWorld"));
addMeta(prefix + "DyeName", attributes.getValue("DyeName"));
}
else if (qName.equals("LaserLineSetting")) {
String prefix = series + " - LaserLine " +
attributes.getValue("LaserLine") + " - ";
addMeta(prefix + "IntensityDev", attributes.getValue("IntensityDev"));
addMeta(prefix + "IntensityLowDev",
attributes.getValue("IntensityLowDev"));
addMeta(prefix + "AOBSIntensityDev",
attributes.getValue("AOBSIntensityDev"));
addMeta(prefix + "AOBSIntensityLowDev",
attributes.getValue("AOBSIntensityLowDev"));
addMeta(prefix + "EnableDoubleMode",
attributes.getValue("EnableDoubleMode"));
addMeta(prefix + "LineIndex", attributes.getValue("LineIndex"));
addMeta(prefix + "Qualifier", attributes.getValue("Qualifier"));
addMeta(prefix + "SequenceIndex",
attributes.getValue("SequenceIndex"));
}
else if (qName.equals("Detector")) {
String prefix = series + " - Detector Channel " +
attributes.getValue("Channel") + " - ";
addMeta(prefix + "IsActive", attributes.getValue("IsActive"));
addMeta(prefix + "IsReferenceUnitActivatedForCorrection",
attributes.getValue("IsReferenceUnitActivatedForCorrection"));
addMeta(prefix + "Gain", attributes.getValue("Gain"));
addMeta(prefix + "Offset", attributes.getValue("Offset"));
}
else if (qName.equals("Laser")) {
String prefix = series + " Laser " + attributes.getValue("LaserName") +
" - ";
addMeta(prefix + "CanDoLinearOutputPower",
attributes.getValue("CanDoLinearOutputPower"));
addMeta(prefix + "OutputPower", attributes.getValue("OutputPower"));
addMeta(prefix + "Wavelength", attributes.getValue("Wavelength"));
}
else if (qName.equals("TimeStamp")) {
String prefix = series + " - TimeStamp " + count + " - ";
addMeta(prefix + "HighInteger", attributes.getValue("HighInteger"));
addMeta(prefix + "LowInteger", attributes.getValue("LowInteger"));
count++;
}
else if (qName.equals("ChannelScalingInfo")) {
String prefix = series + " - ChannelScalingInfo " + count + " - ";
addMeta(prefix + "WhiteValue", attributes.getValue("WhiteValue"));
addMeta(prefix + "BlackValue", attributes.getValue("BlackValue"));
addMeta(prefix + "GammaValue", attributes.getValue("GammaValue"));
addMeta(prefix + "Automatic", attributes.getValue("Automatic"));
}
else if (qName.equals("RelTimeStamp")) {
addMeta(series + " RelTimeStamp " + attributes.getValue("Frame"),
attributes.getValue("Time"));
}
else count = 0;
}
}
}
| true | true | private void initMetadata(String xml) throws FormatException, IOException {
// parse raw key/value pairs - adapted from FlexReader
LIFHandler handler = new LIFHandler();
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml +
"</LEICA>";
// strip out invalid characters
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
Vector elements = new Vector();
seriesNames = new Vector();
status("Populating native metadata");
// first parse each element in the XML string
StringTokenizer st = new StringTokenizer(xml, ">");
while (st.hasMoreTokens()) {
String token = st.nextToken();
elements.add(token.substring(1));
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
addMeta(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
String prefix = "";
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
if (token.startsWith("ScannerSettingRecord")) {
if (token.indexOf("csScanMode") != -1) {
int index = token.indexOf("Variant") + 7;
String ordering = token.substring(index + 2,
token.indexOf("\"", index + 3));
ordering = ordering.toLowerCase();
if (ordering.indexOf("x") == -1 || ordering.indexOf("y") == -1 ||
ordering.indexOf("xy") == -1)
{
int xPos = ordering.indexOf("x");
int yPos = ordering.indexOf("y");
int zPos = ordering.indexOf("z");
int tPos = ordering.indexOf("t");
if (xPos < 0) xPos = 0;
if (yPos < 0) yPos = 1;
if (zPos < 0) zPos = 2;
if (tPos < 0) tPos = 3;
int x = ((Integer) widths.get(widths.size() - 1)).intValue();
int y = ((Integer) heights.get(widths.size() - 1)).intValue();
int z = ((Integer) zs.get(widths.size() - 1)).intValue();
int t = ((Integer) ts.get(widths.size() - 1)).intValue();
int[] dimensions = {x, y, z, t};
x = dimensions[xPos];
y = dimensions[yPos];
z = dimensions[zPos];
t = dimensions[tPos];
widths.setElementAt(new Integer(x), widths.size() - 1);
heights.setElementAt(new Integer(y), heights.size() - 1);
zs.setElementAt(new Integer(z), zs.size() - 1);
ts.setElementAt(new Integer(t), ts.size() - 1);
}
}
else if (token.indexOf("dblVoxel") != -1) {
int index = token.indexOf("Variant") + 7;
String size = token.substring(index + 2,
token.indexOf("\"", index + 3));
float cal = Float.parseFloat(size) * 1000000;
if (token.indexOf("X") != -1) xcal.add(new Float(cal));
else if (token.indexOf("Y") != -1) ycal.add(new Float(cal));
else if (token.indexOf("Z") != -1) zcal.add(new Float(cal));
}
}
else if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
if (token.startsWith("Element Name")) {
// hack to override first series name
seriesNames.setElementAt(token.substring(token.indexOf("=") + 2,
token.length() - 1), seriesNames.size() - 1);
prefix = (String) seriesNames.get(seriesNames.size() - 1);
}
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
String sMin = (String) tmp.get("Min");
String sMax = (String) tmp.get("Max");
if (sMin != null && sMax != null) {
double min = Double.parseDouble(sMin);
double max = Double.parseDouble(sMax);
channelMins.add(new Integer((int) min));
channelMaxs.add(new Integer((int) max));
}
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1:
widths.add(new Integer(w));
break;
case 2:
heights.add(new Integer(w));
break;
case 3:
zs.add(new Integer(w));
break;
case 4:
ts.add(new Integer(w));
break;
default:
extras *= w;
}
}
}
ndx++;
if (elements != null && ndx < elements.size()) {
token = (String) elements.get(ndx);
}
else break;
}
extraDims.add(new Integer(extras));
if (numChannels == 0) numChannels++;
channels.add(new Integer(numChannels));
if (widths.size() < numDatasets && heights.size() < numDatasets) {
numDatasets--;
}
else {
if (widths.size() < numDatasets) widths.add(new Integer(1));
if (heights.size() < numDatasets) heights.add(new Integer(1));
if (zs.size() < numDatasets) zs.add(new Integer(1));
if (ts.size() < numDatasets) ts.add(new Integer(1));
if (bps.size() < numDatasets) bps.add(new Integer(8));
}
}
ndx++;
}
numDatasets = widths.size();
bitsPerPixel = new int[numDatasets];
extraDimensions = new int[numDatasets];
// Populate metadata store
status("Populating metadata");
// The metadata store we're working with.
MetadataStore store = getMetadataStore();
core = new CoreMetadata(numDatasets);
Arrays.fill(core.orderCertain, true);
validBits = new int[numDatasets][];
for (int i=0; i<numDatasets; i++) {
core.sizeX[i] = ((Integer) widths.get(i)).intValue();
core.sizeY[i] = ((Integer) heights.get(i)).intValue();
core.sizeZ[i] = ((Integer) zs.get(i)).intValue();
core.sizeC[i] = ((Integer) channels.get(i)).intValue();
core.sizeT[i] = ((Integer) ts.get(i)).intValue();
core.currentOrder[i] =
(core.sizeZ[i] > core.sizeT[i]) ? "XYCZT" : "XYCTZ";
bitsPerPixel[i] = ((Integer) bps.get(i)).intValue();
extraDimensions[i] = ((Integer) extraDims.get(i)).intValue();
if (extraDimensions[i] > 1) {
if (core.sizeZ[i] == 1) core.sizeZ[i] = extraDimensions[i];
else core.sizeT[i] *= extraDimensions[i];
extraDimensions[i] = 1;
}
core.littleEndian[i] = true;
core.rgb[i] = core.sizeC[i] > 1 && core.sizeC[i] < 4;
core.interleaved[i] = true;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i];
if (!core.rgb[i]) core.imageCount[i] *= core.sizeC[i];
validBits[i] = new int[core.sizeC[i] != 2 ? core.sizeC[i] : 3];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = bitsPerPixel[i];
}
while (bitsPerPixel[i] % 8 != 0) bitsPerPixel[i]++;
switch (bitsPerPixel[i]) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
Integer ii = new Integer(i);
String seriesName = (String) seriesNames.get(i);
if (seriesName == null || seriesName.trim().length() == 0) {
seriesName = "Series " + (i + 1);
}
store.setImage(seriesName, null, null, ii);
store.setPixels(
new Integer(core.sizeX[i]), // SizeX
new Integer(core.sizeY[i]), // SizeY
new Integer(core.sizeZ[i]), // SizeZ
new Integer(core.sizeC[i]), // SizeC
new Integer(core.sizeT[i]), // SizeT
new Integer(core.pixelType[i]), // PixelType
new Boolean(!core.littleEndian[i]), // BigEndian
core.currentOrder[i], // DimensionOrder
ii, // Image index
null); // Pixels index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
for (int j=0; j<core.sizeC[i]; j++) {
store.setLogicalChannel(j, null, null, null, null, null, null, ii);
}
String zoom = (String) getMeta(seriesName + " - dblZoom");
store.setDisplayOptions(zoom == null ? null : new Float(zoom),
new Boolean(core.sizeC[i] > 1), new Boolean(core.sizeC[i] > 1),
new Boolean(core.sizeC[i] > 2), new Boolean(isRGB()), null,
null, null, null, null, ii, null, null, null, null, null);
Enumeration keys = metadata.keys();
while (keys.hasMoreElements()) {
String k = (String) keys.nextElement();
boolean use = true;
for (int j=0; j<seriesNames.size(); j++) {
if (j != i && k.startsWith((String) seriesNames.get(i))) {
use = false;
break;
}
}
if (use) core.seriesMetadata[i].put(k, metadata.get(k));
}
}
}
| private void initMetadata(String xml) throws FormatException, IOException {
// parse raw key/value pairs - adapted from FlexReader
LIFHandler handler = new LIFHandler();
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml +
"</LEICA>";
// strip out invalid characters
for (int i=0; i<xml.length(); i++) {
char c = xml.charAt(i);
if (Character.isISOControl(c) || !Character.isDefined(c)) {
xml = xml.replace(c, ' ');
}
}
try {
SAXParser parser = SAX_FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
Vector elements = new Vector();
seriesNames = new Vector();
status("Populating native metadata");
// first parse each element in the XML string
StringTokenizer st = new StringTokenizer(xml, ">");
while (st.hasMoreTokens()) {
String token = st.nextToken();
elements.add(token.substring(1));
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
addMeta(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
String prefix = "";
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
if (token.startsWith("ScannerSettingRecord")) {
if (token.indexOf("csScanMode") != -1) {
int index = token.indexOf("Variant") + 7;
String ordering = token.substring(index + 2,
token.indexOf("\"", index + 3));
ordering = ordering.toLowerCase();
if (ordering.indexOf("x") == -1 || ordering.indexOf("y") == -1 ||
ordering.indexOf("xy") == -1)
{
int xPos = ordering.indexOf("x");
int yPos = ordering.indexOf("y");
int zPos = ordering.indexOf("z");
int tPos = ordering.indexOf("t");
if (xPos < 0) xPos = 0;
if (yPos < 0) yPos = 1;
if (zPos < 0) zPos = 2;
if (tPos < 0) tPos = 3;
int x = ((Integer) widths.get(widths.size() - 1)).intValue();
int y = ((Integer) heights.get(widths.size() - 1)).intValue();
int z = ((Integer) zs.get(widths.size() - 1)).intValue();
int t = ((Integer) ts.get(widths.size() - 1)).intValue();
int[] dimensions = {x, y, z, t};
x = dimensions[xPos];
y = dimensions[yPos];
z = dimensions[zPos];
t = dimensions[tPos];
widths.setElementAt(new Integer(x), widths.size() - 1);
heights.setElementAt(new Integer(y), heights.size() - 1);
zs.setElementAt(new Integer(z), zs.size() - 1);
ts.setElementAt(new Integer(t), ts.size() - 1);
}
}
else if (token.indexOf("dblVoxel") != -1) {
int index = token.indexOf("Variant") + 7;
String size = token.substring(index + 2,
token.indexOf("\"", index + 3));
float cal = Float.parseFloat(size) * 1000000;
if (token.indexOf("X") != -1) xcal.add(new Float(cal));
else if (token.indexOf("Y") != -1) ycal.add(new Float(cal));
else if (token.indexOf("Z") != -1) zcal.add(new Float(cal));
}
}
else if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
if (token.startsWith("Element Name")) {
// hack to override first series name
seriesNames.setElementAt(token.substring(token.indexOf("=") + 2,
token.length() - 1), seriesNames.size() - 1);
prefix = (String) seriesNames.get(seriesNames.size() - 1);
}
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
String sMin = (String) tmp.get("Min");
String sMax = (String) tmp.get("Max");
if (sMin != null && sMax != null) {
double min = Double.parseDouble(sMin);
double max = Double.parseDouble(sMax);
channelMins.add(new Integer((int) min));
channelMaxs.add(new Integer((int) max));
}
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1:
widths.add(new Integer(w));
break;
case 2:
heights.add(new Integer(w));
break;
case 3:
zs.add(new Integer(w));
break;
case 4:
ts.add(new Integer(w));
break;
default:
extras *= w;
}
}
}
ndx++;
if (elements != null && ndx < elements.size()) {
token = (String) elements.get(ndx);
}
else break;
}
extraDims.add(new Integer(extras));
if (numChannels == 0) numChannels++;
channels.add(new Integer(numChannels));
if (widths.size() < numDatasets && heights.size() < numDatasets) {
numDatasets--;
}
else {
if (widths.size() < numDatasets) widths.add(new Integer(1));
if (heights.size() < numDatasets) heights.add(new Integer(1));
if (zs.size() < numDatasets) zs.add(new Integer(1));
if (ts.size() < numDatasets) ts.add(new Integer(1));
if (bps.size() < numDatasets) bps.add(new Integer(8));
}
}
ndx++;
}
numDatasets = widths.size();
bitsPerPixel = new int[numDatasets];
extraDimensions = new int[numDatasets];
// Populate metadata store
status("Populating metadata");
// The metadata store we're working with.
MetadataStore store = getMetadataStore();
core = new CoreMetadata(numDatasets);
Arrays.fill(core.orderCertain, true);
validBits = new int[numDatasets][];
for (int i=0; i<numDatasets; i++) {
core.sizeX[i] = ((Integer) widths.get(i)).intValue();
core.sizeY[i] = ((Integer) heights.get(i)).intValue();
core.sizeZ[i] = ((Integer) zs.get(i)).intValue();
core.sizeC[i] = ((Integer) channels.get(i)).intValue();
core.sizeT[i] = ((Integer) ts.get(i)).intValue();
core.currentOrder[i] =
(core.sizeZ[i] > core.sizeT[i]) ? "XYCZT" : "XYCTZ";
bitsPerPixel[i] = ((Integer) bps.get(i)).intValue();
extraDimensions[i] = ((Integer) extraDims.get(i)).intValue();
if (extraDimensions[i] > 1) {
if (core.sizeZ[i] == 1) core.sizeZ[i] = extraDimensions[i];
else core.sizeT[i] *= extraDimensions[i];
extraDimensions[i] = 1;
}
core.littleEndian[i] = true;
core.rgb[i] = core.sizeC[i] > 1 && core.sizeC[i] < 4;
core.interleaved[i] = true;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i];
if (!core.rgb[i]) core.imageCount[i] *= core.sizeC[i];
validBits[i] = new int[core.sizeC[i] != 2 ? core.sizeC[i] : 3];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = bitsPerPixel[i];
}
while (bitsPerPixel[i] % 8 != 0) bitsPerPixel[i]++;
switch (bitsPerPixel[i]) {
case 8:
core.pixelType[i] = FormatTools.UINT8;
break;
case 16:
core.pixelType[i] = FormatTools.UINT16;
break;
case 32:
core.pixelType[i] = FormatTools.FLOAT;
break;
}
Integer ii = new Integer(i);
String seriesName = (String) seriesNames.get(i);
if (seriesName == null || seriesName.trim().length() == 0) {
seriesName = "Series " + (i + 1);
}
store.setImage(seriesName, null, null, ii);
store.setPixels(
new Integer(core.sizeX[i]), // SizeX
new Integer(core.sizeY[i]), // SizeY
new Integer(core.sizeZ[i]), // SizeZ
new Integer(core.sizeC[i]), // SizeC
new Integer(core.sizeT[i]), // SizeT
new Integer(core.pixelType[i]), // PixelType
new Boolean(!core.littleEndian[i]), // BigEndian
core.currentOrder[i], // DimensionOrder
ii, // Image index
null); // Pixels index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
for (int j=0; j<core.sizeC[i]; j++) {
store.setLogicalChannel(j, null, null, null, null, null, null, ii);
}
String zoom = (String) getMeta(seriesName + " - dblZoom");
store.setDisplayOptions(zoom == null ? null : new Float(zoom),
new Boolean(core.sizeC[i] > 1), new Boolean(core.sizeC[i] > 1),
new Boolean(core.sizeC[i] > 2), new Boolean(isRGB()), null,
null, null, null, null, ii, null, null, null, null, null);
Enumeration keys = metadata.keys();
while (keys.hasMoreElements()) {
String k = (String) keys.nextElement();
boolean use = true;
for (int j=0; j<seriesNames.size(); j++) {
if (j != i && k.startsWith((String) seriesNames.get(j))) {
use = false;
break;
}
}
if (use) core.seriesMetadata[i].put(k, metadata.get(k));
}
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/InvitationProcess.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/InvitationProcess.java
index 53c7c2515..559bec438 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/InvitationProcess.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/InvitationProcess.java
@@ -1,189 +1,190 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.invitation.internal;
import org.apache.log4j.Logger;
import de.fu_berlin.inf.dpp.invitation.IInvitationProcess;
import de.fu_berlin.inf.dpp.net.ITransmitter;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.observables.InvitationProcessObservable;
import de.fu_berlin.inf.dpp.util.StackTrace;
/**
* @author rdjemili
*/
public abstract class InvitationProcess implements IInvitationProcess {
private static Logger log = Logger.getLogger(InvitationProcess.class);
protected final ITransmitter transmitter;
protected State state;
private Exception exception;
protected JID peer;
protected IInvitationUI invitationUI = null;
protected String description;
protected String peersSarosVersion;
protected final int colorID;
protected InvitationProcessObservable invitationProcesses;
public InvitationProcess(ITransmitter transmitter, JID peer,
String description, int colorID, String peersSarosVersion,
InvitationProcessObservable invitationProcesses) {
this.transmitter = transmitter;
this.peer = peer;
this.description = description;
this.peersSarosVersion = peersSarosVersion;
this.colorID = colorID;
this.invitationProcesses = invitationProcesses;
this.invitationProcesses.addInvitationProcess(this);
}
/**
* {@inheritDoc}
*/
public Exception getException() {
return this.exception;
}
/**
* {@inheritDoc}
*/
public State getState() {
return this.state;
}
public void setState(State newstate) {
this.state = newstate;
if (this.invitationUI != null) {
this.invitationUI.updateInvitationProgress(this.peer);
}
}
/**
* {@inheritDoc}
*/
public JID getPeer() {
return this.peer;
}
public String getPeersSarosVersion() {
return this.peersSarosVersion;
}
/**
* {@inheritDoc}
*/
public String getDescription() {
return this.description;
}
/**
* We are called because the invitation was canceled.
*
* @param replicated
* true if the message originated remotely, false if locally.
*/
public void cancel(String errorMsg, boolean replicated) {
synchronized (this) {
if (this.state == State.CANCELED) {
return;
}
setState(State.CANCELED);
}
if (replicated) {
if (errorMsg != null) {
InvitationProcess.log
.error("Invitation was canceled by remote user because of an error on his/her side: "
+ errorMsg);
} else {
InvitationProcess.log
.info("Invitation was canceled by remote user.");
}
} else {
if (errorMsg != null) {
InvitationProcess.log.error(
"Invitation was canceled locally because of an error: "
+ errorMsg, new StackTrace());
} else {
InvitationProcess.log
.info("Invitation was canceled by local user.");
}
}
if (!replicated) {
this.transmitter.sendCancelInvitationMessage(this.peer, errorMsg);
}
- this.invitationUI.cancel(this.peer, errorMsg, replicated);
+ if (invitationUI != null)
+ this.invitationUI.cancel(this.peer, errorMsg, replicated);
this.invitationProcesses.removeInvitationProcess(this);
}
@Override
public String toString() {
return "InvitationProcess(peer:" + this.peer + ", state:" + this.state
+ ")";
}
/**
* Should be called if an exception occurred. This saves the exception and
* sets the invitation to canceled.
*/
protected void failed(Exception e) {
this.exception = e;
log.error("Invitation process failed", e);
cancel(e.getMessage(), false);
}
/**
* Assert that the process is in given state or throw an exception
* otherwise.
*
* @param expected
* the state that the process should currently have.
*/
protected void assertState(State expected) {
if (this.state != expected) {
cancel("Unexpected state(" + this.state + ")", false);
}
}
protected void failState() {
throw new IllegalStateException("Bad input while in state "
+ this.state);
}
public void setInvitationUI(IInvitationUI inviteUI) {
this.invitationUI = inviteUI;
}
}
| true | true | public void cancel(String errorMsg, boolean replicated) {
synchronized (this) {
if (this.state == State.CANCELED) {
return;
}
setState(State.CANCELED);
}
if (replicated) {
if (errorMsg != null) {
InvitationProcess.log
.error("Invitation was canceled by remote user because of an error on his/her side: "
+ errorMsg);
} else {
InvitationProcess.log
.info("Invitation was canceled by remote user.");
}
} else {
if (errorMsg != null) {
InvitationProcess.log.error(
"Invitation was canceled locally because of an error: "
+ errorMsg, new StackTrace());
} else {
InvitationProcess.log
.info("Invitation was canceled by local user.");
}
}
if (!replicated) {
this.transmitter.sendCancelInvitationMessage(this.peer, errorMsg);
}
this.invitationUI.cancel(this.peer, errorMsg, replicated);
this.invitationProcesses.removeInvitationProcess(this);
}
| public void cancel(String errorMsg, boolean replicated) {
synchronized (this) {
if (this.state == State.CANCELED) {
return;
}
setState(State.CANCELED);
}
if (replicated) {
if (errorMsg != null) {
InvitationProcess.log
.error("Invitation was canceled by remote user because of an error on his/her side: "
+ errorMsg);
} else {
InvitationProcess.log
.info("Invitation was canceled by remote user.");
}
} else {
if (errorMsg != null) {
InvitationProcess.log.error(
"Invitation was canceled locally because of an error: "
+ errorMsg, new StackTrace());
} else {
InvitationProcess.log
.info("Invitation was canceled by local user.");
}
}
if (!replicated) {
this.transmitter.sendCancelInvitationMessage(this.peer, errorMsg);
}
if (invitationUI != null)
this.invitationUI.cancel(this.peer, errorMsg, replicated);
this.invitationProcesses.removeInvitationProcess(this);
}
|
diff --git a/JavaSource/org/unitime/timetable/backup/SessionBackup.java b/JavaSource/org/unitime/timetable/backup/SessionBackup.java
index 739f4b3b..6dab9898 100644
--- a/JavaSource/org/unitime/timetable/backup/SessionBackup.java
+++ b/JavaSource/org/unitime/timetable/backup/SessionBackup.java
@@ -1,610 +1,610 @@
/*
* UniTime 3.3 (University Timetabling Application)
* Copyright (C) 2011, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.backup;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
import net.sf.cpsolver.ifs.util.Progress;
import net.sf.cpsolver.ifs.util.ProgressWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.hibernate.EntityMode;
import org.hibernate.SessionFactory;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.BinaryType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.CustomType;
import org.hibernate.type.DateType;
import org.hibernate.type.EmbeddedComponentType;
import org.hibernate.type.EntityType;
import org.hibernate.type.PrimitiveType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.Type;
import org.unitime.commons.hibernate.util.HibernateUtil;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.model.Assignment;
import org.unitime.timetable.model.AssignmentInfo;
import org.unitime.timetable.model.ChangeLog;
import org.unitime.timetable.model.ConstraintInfo;
import org.unitime.timetable.model.CurriculumClassification;
import org.unitime.timetable.model.DepartmentalInstructor;
import org.unitime.timetable.model.DistributionPref;
import org.unitime.timetable.model.DistributionType;
import org.unitime.timetable.model.LastLikeCourseDemand;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.Solution;
import org.unitime.timetable.model.SolutionInfo;
import org.unitime.timetable.model.Student;
import org.unitime.timetable.model.TimetableManager;
import org.unitime.timetable.model.dao._RootDAO;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
public class SessionBackup {
private static Log sLog = LogFactory.getLog(SessionBackup.class);
private SessionFactory iHibSessionFactory = null;
private org.hibernate.Session iHibSession = null;
private CodedOutputStream iOut = null;
private PrintWriter iDebug = null;
private Long iSessionId = null;
private Progress iProgress = null;
public SessionBackup(OutputStream out, Progress progress) {
iOut = CodedOutputStream.newInstance(out);
iProgress = progress;
}
public Progress getProgress() {
return iProgress;
}
private void add(TableData.Table table) throws IOException {
iProgress.info("Writing " + table.getName().substring(table.getName().lastIndexOf('.') + 1) + " [" + table.getRecordCount() + " records, " + table.getSerializedSize() + " bytes]");
iOut.writeInt32NoTag(table.getSerializedSize());
table.writeTo(iOut);
iOut.flush();
if (iDebug != null) {
iDebug.println("## " + table.getName() + " ##");
iDebug.print(table.toString());
iDebug.flush();
}
}
public void debug(PrintWriter pw) {
iDebug = pw;
}
public void backup(Long sessionId) throws IOException {
iSessionId = sessionId;
iHibSession = new _RootDAO().createNewSession();
iHibSessionFactory = iHibSession.getSessionFactory();
try {
iProgress.setStatus("Exporting Session");
- iProgress.setPhase("Loding Model", 3);
+ iProgress.setPhase("Loading Model", 3);
TreeSet<ClassMetadata> allMeta = new TreeSet<ClassMetadata>(new Comparator<ClassMetadata>() {
@Override
public int compare(ClassMetadata m1, ClassMetadata m2) {
return m1.getEntityName().compareTo(m2.getEntityName());
}
});
allMeta.addAll(iHibSessionFactory.getAllClassMetadata().values());
iProgress.incProgress();
Queue<QueueItem> queue = new LinkedList<QueueItem>();
queue.add(new QueueItem(iHibSessionFactory.getClassMetadata(Session.class), null, "uniqueId", Relation.None));
Set<String> avoid = new HashSet<String>();
// avoid following relations
avoid.add(TimetableManager.class.getName() + ".departments");
avoid.add(TimetableManager.class.getName() + ".solverGroups");
avoid.add(DistributionType.class.getName() + ".departments");
avoid.add(LastLikeCourseDemand.class.getName() + ".student");
avoid.add(Student.class.getName() + ".lastLikeCourseDemands");
Set<String> disallowedNotNullRelations = new HashSet<String>();
disallowedNotNullRelations.add(Assignment.class.getName() + ".datePattern");
disallowedNotNullRelations.add(Assignment.class.getName() + ".timePattern");
disallowedNotNullRelations.add(LastLikeCourseDemand.class.getName() + ".student");
Map<String, List<QueueItem>> data = new HashMap<String, List<QueueItem>>();
List<QueueItem> sessions = new ArrayList<QueueItem>();
sessions.add(queue.peek());
data.put(queue.peek().name(), sessions);
QueueItem item = null;
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (ClassMetadata meta: allMeta) {
if (meta.hasSubclasses()) continue;
for (int i = 0; i < meta.getPropertyNames().length; i++) {
String property = meta.getPropertyNames()[i];
if (disallowedNotNullRelations.contains(meta.getEntityName() + "." + property) || meta.getPropertyNullability()[i]) continue;
Type type = meta.getPropertyTypes()[i];
if (type instanceof EntityType && type.getReturnedClass().equals(item.clazz())) {
QueueItem qi = new QueueItem(meta, item, property, Relation.Parent);
if (!data.containsKey(qi.name())) {
List<QueueItem> items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Parent: " + qi);
}
}
}
}
}
iProgress.incProgress();
for (List<QueueItem> list: data.values())
queue.addAll(list);
// The following part is needed to ensure that instructor distribution preferences are saved including their distribution types
List<QueueItem> distributions = new ArrayList<QueueItem>();
for (QueueItem instructor: data.get(DepartmentalInstructor.class.getName())) {
QueueItem qi = new QueueItem(iHibSessionFactory.getClassMetadata(DistributionPref.class), instructor, "owner", Relation.Parent);
distributions.add(qi);
queue.add(qi);
if (qi.size() > 0)
iProgress.info("Extra: " + qi);
}
data.put(DistributionPref.class.getName(), distributions);
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (int i = 0; i < item.meta().getPropertyNames().length; i++) {
String property = item.meta().getPropertyNames()[i];
Type type = item.meta().getPropertyTypes()[i];
if (type instanceof EntityType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(type.getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.One);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("One: " + qi);
}
if (type instanceof CollectionType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(((CollectionType)type).getElementType((SessionFactoryImplementor)iHibSessionFactory).getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.Many);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Many: " + qi);
}
}
}
iProgress.incProgress();
Map<String, Set<Serializable>> allExportedIds = new HashMap<String, Set<Serializable>>();
for (String name: new TreeSet<String>(data.keySet())) {
List<QueueItem> list = data.get(name);
Map<String, TableData.Table.Builder> tables = new HashMap<String, TableData.Table.Builder>();
for (QueueItem current: list) {
if (current.size() == 0) continue;
iProgress.info("Loading " + current);
List<Object> objects = current.list();
if (objects == null || objects.isEmpty()) continue;
iProgress.setPhase(current.abbv() + " [" + objects.size() + "]", objects.size());
objects: for (Object object: objects) {
iProgress.incProgress();
// Get meta data (check for sub-classes)
ClassMetadata meta = iHibSessionFactory.getClassMetadata(object.getClass());
if (meta == null) meta = current.meta();
if (meta.hasSubclasses()) {
for (Iterator i=iHibSessionFactory.getAllClassMetadata().entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
ClassMetadata classMetadata = (ClassMetadata)entry.getValue();
if (classMetadata.getMappedClass(EntityMode.POJO).isInstance(object) && !classMetadata.hasSubclasses()) {
meta = classMetadata; break;
}
}
}
// Get unique identifier
Serializable id = meta.getIdentifier(object, (SessionImplementor)iHibSession);
// Check if already exported
Set<Serializable> exportedIds = allExportedIds.get(meta.getEntityName());
if (exportedIds == null) {
exportedIds = new HashSet<Serializable>();
allExportedIds.put(meta.getEntityName(), exportedIds);
}
if (!exportedIds.add(id)) continue;
// Check relation to an academic session (if exists)
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
if (type instanceof EntityType && type.getReturnedClass().equals(Session.class)) {
Session s = (Session)meta.getPropertyValue(object, property, EntityMode.POJO);
if (s != null && !s.getUniqueId().equals(iSessionId)) {
iProgress.warn(meta.getEntityName().substring(meta.getEntityName().lastIndexOf('.') + 1) + "@" + id + " belongs to a different academic session (" + s + ")");
continue objects; // wrong session
}
}
}
// Get appropriate table
TableData.Table.Builder table = tables.get(meta.getEntityName());
if (table == null) {
table = TableData.Table.newBuilder();
tables.put(meta.getEntityName(), table);
table.setName(meta.getEntityName());
}
// Export object
TableData.Record.Builder record = TableData.Record.newBuilder();
record.setId(id.toString());
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
Object value = meta.getPropertyValue(object, property, EntityMode.POJO);
if (value == null) continue;
TableData.Element.Builder element = TableData.Element.newBuilder();
element.setName(property);
if (type instanceof PrimitiveType) {
element.addValue(((PrimitiveType)type).toString(value));
} else if (type instanceof StringType) {
element.addValue(((StringType)type).toString(value));
} else if (type instanceof BinaryType) {
element.addValue(ByteString.copyFrom((byte[])value));
} else if (type instanceof TimestampType) {
element.addValue(((TimestampType)type).toString(value));
} else if (type instanceof DateType) {
element.addValue(((DateType)type).toString(value));
} else if (type instanceof EntityType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
iHibSession.evict(value);
} else if (type instanceof CustomType && value instanceof Document) {
if (object instanceof CurriculumClassification && property.equals("students")) continue;
StringWriter w = new StringWriter();
XMLWriter x = new XMLWriter(w, OutputFormat.createCompactFormat());
x.write((Document)value);
x.flush(); x.close();
element.addValue(w.toString());
} else if (type instanceof CollectionType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
} else if (type instanceof EmbeddedComponentType && property.equalsIgnoreCase("uniqueCourseNbr")) {
continue;
} else {
iProgress.warn("Unknown data type: " + type + " (property " + meta.getEntityName() + "." + property + ", class " + value.getClass() + ")");
continue;
}
record.addElement(element.build());
}
table.addRecord(record.build());
iHibSession.evict(object);
}
current.clearCache();
}
for (TableData.Table.Builder table: tables.values()) {
add(table.build());
}
}
/*
// Skip ConstraintInfo
if (!iData.containsKey(ConstraintInfo.class.getName()))
iData.put(ConstraintInfo.class.getName(), new QueueItem(iHibSessionFactory.getClassMetadata(ConstraintInfo.class), null, null, Relation.Empty));
for (String name: items)
export(iData.get(name));
while (true) {
List<Object> objects = new ArrayList<Object>();
ClassMetadata meta = null;
for (Entity e: iObjects) {
if (e.exported()) continue;
if (objects.isEmpty() || meta.getEntityName().equals(e.name())) {
meta = e.meta();
objects.add(e.object());
e.notifyExported();
}
}
if (objects.isEmpty()) break;
export(meta, objects, null);
}
*/
iProgress.setStatus("All done.");
} finally {
iHibSession.close();
}
}
enum Relation {
None, Parent, One, Many, Empty
}
private int iQueueItemCoutner = 0;
private Map<String, Set<Serializable>> iExclude = new HashMap<String, Set<Serializable>>();
class QueueItem {
QueueItem iParent;
ClassMetadata iMeta;
String iProperty;
int iQueueItemId = iQueueItemCoutner++;
Relation iRelation;
int size = -1;
QueueItem(ClassMetadata meta, QueueItem parent, String property, Relation relation) {
iMeta = meta;
iParent = parent;
iProperty = property;
iRelation = relation;
}
String property() { return iProperty; }
QueueItem parent() { return iParent; }
ClassMetadata meta() { return iMeta; }
String name() { return meta().getEntityName(); }
String abbv() { return meta().getEntityName().substring(meta().getEntityName().lastIndexOf('.') + 1); }
Class clazz() { return meta().getMappedClass(EntityMode.POJO); }
int qid() { return iQueueItemId; }
Relation relation() { return iRelation; }
boolean contains(String name) {
if (name.equals(name())) return true;
if (parent() == null) return false;
return parent().contains(name);
}
int depth() { return parent() == null ? 0 : 1 + parent().depth(); }
public String toString() { return abbv() + ": " + chain() + " [" + size() + "]"; }
public String chain() {
switch (relation()) {
case None:
return property();
case Parent:
return property() + "." + parent().chain();
default:
switch (parent().relation()) {
case Parent:
return "(" + parent().abbv() + "." + parent().chain() + ")." + property();
case None:
return parent().abbv() + "." + property();
default:
return parent().chain() + "." + property();
}
}
}
String hqlName() { return "q" + qid(); }
String hqlFrom() {
switch (relation()) {
case One:
case Many:
return parent().hqlFrom() + " inner join " + parent().hqlName() + "." + property() + " " + hqlName();
default:
return (parent() == null ? "" : parent().hqlFrom() + ", ") + name() + " " + hqlName();
}
}
String hqlWhere() {
String where = null;
switch (relation()) {
case None:
where = hqlName() + "." + property() + " = :sessionId";
break;
case Parent:
where = hqlName() + "." + property() + " = " + parent().hqlName() + " and " + parent().hqlWhere();
break;
default:
where = parent().hqlWhere();
break;
}
if (Solution.class.getName().equals(name()))
where += " and " + hqlName() + ".commited = true";
if (Assignment.class.getName().equals(name()))
where += " and " + hqlName() + ".solution.commited = true";
if (SolutionInfo.class.getName().equals(name()))
where += " and " + hqlName() + ".definition.name = 'GlobalInfo'";
return where;
}
int size() {
if (relation() == Relation.Empty) return 0;
if (AssignmentInfo.class.getName().equals(name())) return 0;
if (ConstraintInfo.class.getName().equals(name())) return 0;
if (ChangeLog.class.getName().equals(name())) return 0;
if (size < 0) {
Set<Serializable> ids = iExclude.get(name());
if (ids == null) {
ids = new HashSet<Serializable>();
iExclude.put(name(), ids);
}
size = 0;
for (Serializable id: (List<Serializable>)iHibSession.createQuery(
"select distinct " + hqlName() + "." + meta().getIdentifierPropertyName() + " from " + hqlFrom() + " where " + hqlWhere()
).setLong("sessionId", iSessionId).list()) {
if (ids.add(id)) size++;
}
}
return size;
}
boolean distinct() {
switch (relation()) {
case Many:
return false;
case One:
return parent().distinct();
default:
return true;
}
}
List<Object> list() {
if (relation() == Relation.Empty) return null;
if (AssignmentInfo.class.getName().equals(name())) return null;
if (ConstraintInfo.class.getName().equals(name())) return null;
if (ChangeLog.class.getName().equals(name())) return null;
return iHibSession.createQuery(
"select " + (distinct() ? "" : "distinct ") + hqlName() + " from " + hqlFrom() + " where " + hqlWhere()
).setLong("sessionId", iSessionId).list();
}
Map<String, Map<Serializable, List<Object>>> iRelationCache = new HashMap<String, Map<Serializable,List<Object>>>();
List<Object> relation(String property, Serializable id, boolean data) {
Map<Serializable, List<Object>> relation = iRelationCache.get(property);
if (relation == null) {
Type type = meta().getPropertyType(property);
ClassMetadata meta = null;
if (type instanceof CollectionType)
meta = iHibSessionFactory.getClassMetadata(((CollectionType)type).getElementType((SessionFactoryImplementor)iHibSessionFactory).getReturnedClass());
else
meta = iHibSessionFactory.getClassMetadata(type.getReturnedClass());
relation = new HashMap<Serializable, List<Object>>();
int cnt = 0;
String idProperty = meta.getIdentifierPropertyName();
if (name().equals(LastLikeCourseDemand.class.getName()) && "student".equals(property))
idProperty = "externalUniqueId";
for (Object[] o: (List<Object[]>)iHibSession.createQuery(
"select distinct " + hqlName() + "." + meta().getIdentifierPropertyName() + (data ? ", p" : ", p." + idProperty) +
" from " + hqlFrom() + " inner join " + hqlName() + "." + property + " p where " + hqlWhere()
).setLong("sessionId", iSessionId).list()) {
List<Object> list = relation.get((Serializable)o[0]);
if (list == null) {
list = new ArrayList<Object>();
relation.put((Serializable)o[0], list);
}
list.add(o[1]);
cnt++;
}
iRelationCache.put(property, relation);
// iProgress.info("Fetched " + property + " (" + cnt + (data ? " items" : " ids") + ")");
}
return relation.get(id);
}
private void clearCache() { iRelationCache.clear(); }
}
public static void main(String[] args) {
try {
Properties props = new Properties();
props.setProperty("log4j.rootLogger", "DEBUG, A1");
props.setProperty("log4j.appender.A1", "org.apache.log4j.ConsoleAppender");
props.setProperty("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout");
props.setProperty("log4j.appender.A1.layout.ConversionPattern","%-5p %m%n");
props.setProperty("log4j.logger.org.hibernate","INFO");
props.setProperty("log4j.logger.org.hibernate.cfg","WARN");
props.setProperty("log4j.logger.org.hibernate.cache.EhCacheProvider","ERROR");
props.setProperty("log4j.logger.org.unitime.commons.hibernate","INFO");
props.setProperty("log4j.logger.net","INFO");
PropertyConfigurator.configure(props);
HibernateUtil.configureHibernate(ApplicationProperties.getProperties());
Session session = Session.getSessionUsingInitiativeYearTerm(
ApplicationProperties.getProperty("initiative", "PWL"),
ApplicationProperties.getProperty("year","2010"),
ApplicationProperties.getProperty("term","Spring")
);
if (session==null) {
sLog.error("Academic session not found, use properties initiative, year, and term to set academic session.");
System.exit(0);
} else {
sLog.info("Session: "+session);
}
FileOutputStream out = new FileOutputStream(args.length == 0
? session.getAcademicTerm() + session.getAcademicYear() + session.getAcademicInitiative() + ".dat"
: args[0]);
SessionBackup backup = new SessionBackup(out, Progress.getInstance());
PrintWriter debug = null;
if (args.length >= 2) {
debug = new PrintWriter(args[1]);
backup.debug(debug);
}
backup.getProgress().addProgressListener(new ProgressWriter(System.out));
backup.backup(session.getUniqueId());
out.close();
if (debug != null) debug.close();
} catch (Exception e) {
sLog.fatal("Backup failed: " + e.getMessage(), e);
}
}
}
| true | true | public void backup(Long sessionId) throws IOException {
iSessionId = sessionId;
iHibSession = new _RootDAO().createNewSession();
iHibSessionFactory = iHibSession.getSessionFactory();
try {
iProgress.setStatus("Exporting Session");
iProgress.setPhase("Loding Model", 3);
TreeSet<ClassMetadata> allMeta = new TreeSet<ClassMetadata>(new Comparator<ClassMetadata>() {
@Override
public int compare(ClassMetadata m1, ClassMetadata m2) {
return m1.getEntityName().compareTo(m2.getEntityName());
}
});
allMeta.addAll(iHibSessionFactory.getAllClassMetadata().values());
iProgress.incProgress();
Queue<QueueItem> queue = new LinkedList<QueueItem>();
queue.add(new QueueItem(iHibSessionFactory.getClassMetadata(Session.class), null, "uniqueId", Relation.None));
Set<String> avoid = new HashSet<String>();
// avoid following relations
avoid.add(TimetableManager.class.getName() + ".departments");
avoid.add(TimetableManager.class.getName() + ".solverGroups");
avoid.add(DistributionType.class.getName() + ".departments");
avoid.add(LastLikeCourseDemand.class.getName() + ".student");
avoid.add(Student.class.getName() + ".lastLikeCourseDemands");
Set<String> disallowedNotNullRelations = new HashSet<String>();
disallowedNotNullRelations.add(Assignment.class.getName() + ".datePattern");
disallowedNotNullRelations.add(Assignment.class.getName() + ".timePattern");
disallowedNotNullRelations.add(LastLikeCourseDemand.class.getName() + ".student");
Map<String, List<QueueItem>> data = new HashMap<String, List<QueueItem>>();
List<QueueItem> sessions = new ArrayList<QueueItem>();
sessions.add(queue.peek());
data.put(queue.peek().name(), sessions);
QueueItem item = null;
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (ClassMetadata meta: allMeta) {
if (meta.hasSubclasses()) continue;
for (int i = 0; i < meta.getPropertyNames().length; i++) {
String property = meta.getPropertyNames()[i];
if (disallowedNotNullRelations.contains(meta.getEntityName() + "." + property) || meta.getPropertyNullability()[i]) continue;
Type type = meta.getPropertyTypes()[i];
if (type instanceof EntityType && type.getReturnedClass().equals(item.clazz())) {
QueueItem qi = new QueueItem(meta, item, property, Relation.Parent);
if (!data.containsKey(qi.name())) {
List<QueueItem> items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Parent: " + qi);
}
}
}
}
}
iProgress.incProgress();
for (List<QueueItem> list: data.values())
queue.addAll(list);
// The following part is needed to ensure that instructor distribution preferences are saved including their distribution types
List<QueueItem> distributions = new ArrayList<QueueItem>();
for (QueueItem instructor: data.get(DepartmentalInstructor.class.getName())) {
QueueItem qi = new QueueItem(iHibSessionFactory.getClassMetadata(DistributionPref.class), instructor, "owner", Relation.Parent);
distributions.add(qi);
queue.add(qi);
if (qi.size() > 0)
iProgress.info("Extra: " + qi);
}
data.put(DistributionPref.class.getName(), distributions);
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (int i = 0; i < item.meta().getPropertyNames().length; i++) {
String property = item.meta().getPropertyNames()[i];
Type type = item.meta().getPropertyTypes()[i];
if (type instanceof EntityType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(type.getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.One);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("One: " + qi);
}
if (type instanceof CollectionType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(((CollectionType)type).getElementType((SessionFactoryImplementor)iHibSessionFactory).getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.Many);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Many: " + qi);
}
}
}
iProgress.incProgress();
Map<String, Set<Serializable>> allExportedIds = new HashMap<String, Set<Serializable>>();
for (String name: new TreeSet<String>(data.keySet())) {
List<QueueItem> list = data.get(name);
Map<String, TableData.Table.Builder> tables = new HashMap<String, TableData.Table.Builder>();
for (QueueItem current: list) {
if (current.size() == 0) continue;
iProgress.info("Loading " + current);
List<Object> objects = current.list();
if (objects == null || objects.isEmpty()) continue;
iProgress.setPhase(current.abbv() + " [" + objects.size() + "]", objects.size());
objects: for (Object object: objects) {
iProgress.incProgress();
// Get meta data (check for sub-classes)
ClassMetadata meta = iHibSessionFactory.getClassMetadata(object.getClass());
if (meta == null) meta = current.meta();
if (meta.hasSubclasses()) {
for (Iterator i=iHibSessionFactory.getAllClassMetadata().entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
ClassMetadata classMetadata = (ClassMetadata)entry.getValue();
if (classMetadata.getMappedClass(EntityMode.POJO).isInstance(object) && !classMetadata.hasSubclasses()) {
meta = classMetadata; break;
}
}
}
// Get unique identifier
Serializable id = meta.getIdentifier(object, (SessionImplementor)iHibSession);
// Check if already exported
Set<Serializable> exportedIds = allExportedIds.get(meta.getEntityName());
if (exportedIds == null) {
exportedIds = new HashSet<Serializable>();
allExportedIds.put(meta.getEntityName(), exportedIds);
}
if (!exportedIds.add(id)) continue;
// Check relation to an academic session (if exists)
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
if (type instanceof EntityType && type.getReturnedClass().equals(Session.class)) {
Session s = (Session)meta.getPropertyValue(object, property, EntityMode.POJO);
if (s != null && !s.getUniqueId().equals(iSessionId)) {
iProgress.warn(meta.getEntityName().substring(meta.getEntityName().lastIndexOf('.') + 1) + "@" + id + " belongs to a different academic session (" + s + ")");
continue objects; // wrong session
}
}
}
// Get appropriate table
TableData.Table.Builder table = tables.get(meta.getEntityName());
if (table == null) {
table = TableData.Table.newBuilder();
tables.put(meta.getEntityName(), table);
table.setName(meta.getEntityName());
}
// Export object
TableData.Record.Builder record = TableData.Record.newBuilder();
record.setId(id.toString());
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
Object value = meta.getPropertyValue(object, property, EntityMode.POJO);
if (value == null) continue;
TableData.Element.Builder element = TableData.Element.newBuilder();
element.setName(property);
if (type instanceof PrimitiveType) {
element.addValue(((PrimitiveType)type).toString(value));
} else if (type instanceof StringType) {
element.addValue(((StringType)type).toString(value));
} else if (type instanceof BinaryType) {
element.addValue(ByteString.copyFrom((byte[])value));
} else if (type instanceof TimestampType) {
element.addValue(((TimestampType)type).toString(value));
} else if (type instanceof DateType) {
element.addValue(((DateType)type).toString(value));
} else if (type instanceof EntityType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
iHibSession.evict(value);
} else if (type instanceof CustomType && value instanceof Document) {
if (object instanceof CurriculumClassification && property.equals("students")) continue;
StringWriter w = new StringWriter();
XMLWriter x = new XMLWriter(w, OutputFormat.createCompactFormat());
x.write((Document)value);
x.flush(); x.close();
element.addValue(w.toString());
} else if (type instanceof CollectionType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
} else if (type instanceof EmbeddedComponentType && property.equalsIgnoreCase("uniqueCourseNbr")) {
continue;
} else {
iProgress.warn("Unknown data type: " + type + " (property " + meta.getEntityName() + "." + property + ", class " + value.getClass() + ")");
continue;
}
record.addElement(element.build());
}
table.addRecord(record.build());
iHibSession.evict(object);
}
current.clearCache();
}
for (TableData.Table.Builder table: tables.values()) {
add(table.build());
}
}
/*
// Skip ConstraintInfo
if (!iData.containsKey(ConstraintInfo.class.getName()))
iData.put(ConstraintInfo.class.getName(), new QueueItem(iHibSessionFactory.getClassMetadata(ConstraintInfo.class), null, null, Relation.Empty));
for (String name: items)
export(iData.get(name));
while (true) {
List<Object> objects = new ArrayList<Object>();
ClassMetadata meta = null;
for (Entity e: iObjects) {
if (e.exported()) continue;
if (objects.isEmpty() || meta.getEntityName().equals(e.name())) {
meta = e.meta();
objects.add(e.object());
e.notifyExported();
}
}
if (objects.isEmpty()) break;
export(meta, objects, null);
}
*/
iProgress.setStatus("All done.");
} finally {
iHibSession.close();
}
}
| public void backup(Long sessionId) throws IOException {
iSessionId = sessionId;
iHibSession = new _RootDAO().createNewSession();
iHibSessionFactory = iHibSession.getSessionFactory();
try {
iProgress.setStatus("Exporting Session");
iProgress.setPhase("Loading Model", 3);
TreeSet<ClassMetadata> allMeta = new TreeSet<ClassMetadata>(new Comparator<ClassMetadata>() {
@Override
public int compare(ClassMetadata m1, ClassMetadata m2) {
return m1.getEntityName().compareTo(m2.getEntityName());
}
});
allMeta.addAll(iHibSessionFactory.getAllClassMetadata().values());
iProgress.incProgress();
Queue<QueueItem> queue = new LinkedList<QueueItem>();
queue.add(new QueueItem(iHibSessionFactory.getClassMetadata(Session.class), null, "uniqueId", Relation.None));
Set<String> avoid = new HashSet<String>();
// avoid following relations
avoid.add(TimetableManager.class.getName() + ".departments");
avoid.add(TimetableManager.class.getName() + ".solverGroups");
avoid.add(DistributionType.class.getName() + ".departments");
avoid.add(LastLikeCourseDemand.class.getName() + ".student");
avoid.add(Student.class.getName() + ".lastLikeCourseDemands");
Set<String> disallowedNotNullRelations = new HashSet<String>();
disallowedNotNullRelations.add(Assignment.class.getName() + ".datePattern");
disallowedNotNullRelations.add(Assignment.class.getName() + ".timePattern");
disallowedNotNullRelations.add(LastLikeCourseDemand.class.getName() + ".student");
Map<String, List<QueueItem>> data = new HashMap<String, List<QueueItem>>();
List<QueueItem> sessions = new ArrayList<QueueItem>();
sessions.add(queue.peek());
data.put(queue.peek().name(), sessions);
QueueItem item = null;
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (ClassMetadata meta: allMeta) {
if (meta.hasSubclasses()) continue;
for (int i = 0; i < meta.getPropertyNames().length; i++) {
String property = meta.getPropertyNames()[i];
if (disallowedNotNullRelations.contains(meta.getEntityName() + "." + property) || meta.getPropertyNullability()[i]) continue;
Type type = meta.getPropertyTypes()[i];
if (type instanceof EntityType && type.getReturnedClass().equals(item.clazz())) {
QueueItem qi = new QueueItem(meta, item, property, Relation.Parent);
if (!data.containsKey(qi.name())) {
List<QueueItem> items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Parent: " + qi);
}
}
}
}
}
iProgress.incProgress();
for (List<QueueItem> list: data.values())
queue.addAll(list);
// The following part is needed to ensure that instructor distribution preferences are saved including their distribution types
List<QueueItem> distributions = new ArrayList<QueueItem>();
for (QueueItem instructor: data.get(DepartmentalInstructor.class.getName())) {
QueueItem qi = new QueueItem(iHibSessionFactory.getClassMetadata(DistributionPref.class), instructor, "owner", Relation.Parent);
distributions.add(qi);
queue.add(qi);
if (qi.size() > 0)
iProgress.info("Extra: " + qi);
}
data.put(DistributionPref.class.getName(), distributions);
while ((item = queue.poll()) != null) {
if (item.size() == 0) continue;
for (int i = 0; i < item.meta().getPropertyNames().length; i++) {
String property = item.meta().getPropertyNames()[i];
Type type = item.meta().getPropertyTypes()[i];
if (type instanceof EntityType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(type.getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.One);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("One: " + qi);
}
if (type instanceof CollectionType) {
if (avoid.contains(item.name() + "." + property)) continue;
ClassMetadata meta = iHibSessionFactory.getClassMetadata(((CollectionType)type).getElementType((SessionFactoryImplementor)iHibSessionFactory).getReturnedClass());
if (item.contains(meta.getEntityName())) continue;
QueueItem qi = new QueueItem(meta, item, property, Relation.Many);
List<QueueItem> items = data.get(qi.name());
if (items == null) {
items = new ArrayList<QueueItem>();
data.put(qi.name(), items);
}
queue.add(qi);
items.add(qi);
if (qi.size() > 0)
iProgress.info("Many: " + qi);
}
}
}
iProgress.incProgress();
Map<String, Set<Serializable>> allExportedIds = new HashMap<String, Set<Serializable>>();
for (String name: new TreeSet<String>(data.keySet())) {
List<QueueItem> list = data.get(name);
Map<String, TableData.Table.Builder> tables = new HashMap<String, TableData.Table.Builder>();
for (QueueItem current: list) {
if (current.size() == 0) continue;
iProgress.info("Loading " + current);
List<Object> objects = current.list();
if (objects == null || objects.isEmpty()) continue;
iProgress.setPhase(current.abbv() + " [" + objects.size() + "]", objects.size());
objects: for (Object object: objects) {
iProgress.incProgress();
// Get meta data (check for sub-classes)
ClassMetadata meta = iHibSessionFactory.getClassMetadata(object.getClass());
if (meta == null) meta = current.meta();
if (meta.hasSubclasses()) {
for (Iterator i=iHibSessionFactory.getAllClassMetadata().entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
ClassMetadata classMetadata = (ClassMetadata)entry.getValue();
if (classMetadata.getMappedClass(EntityMode.POJO).isInstance(object) && !classMetadata.hasSubclasses()) {
meta = classMetadata; break;
}
}
}
// Get unique identifier
Serializable id = meta.getIdentifier(object, (SessionImplementor)iHibSession);
// Check if already exported
Set<Serializable> exportedIds = allExportedIds.get(meta.getEntityName());
if (exportedIds == null) {
exportedIds = new HashSet<Serializable>();
allExportedIds.put(meta.getEntityName(), exportedIds);
}
if (!exportedIds.add(id)) continue;
// Check relation to an academic session (if exists)
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
if (type instanceof EntityType && type.getReturnedClass().equals(Session.class)) {
Session s = (Session)meta.getPropertyValue(object, property, EntityMode.POJO);
if (s != null && !s.getUniqueId().equals(iSessionId)) {
iProgress.warn(meta.getEntityName().substring(meta.getEntityName().lastIndexOf('.') + 1) + "@" + id + " belongs to a different academic session (" + s + ")");
continue objects; // wrong session
}
}
}
// Get appropriate table
TableData.Table.Builder table = tables.get(meta.getEntityName());
if (table == null) {
table = TableData.Table.newBuilder();
tables.put(meta.getEntityName(), table);
table.setName(meta.getEntityName());
}
// Export object
TableData.Record.Builder record = TableData.Record.newBuilder();
record.setId(id.toString());
for (String property: meta.getPropertyNames()) {
Type type = meta.getPropertyType(property);
Object value = meta.getPropertyValue(object, property, EntityMode.POJO);
if (value == null) continue;
TableData.Element.Builder element = TableData.Element.newBuilder();
element.setName(property);
if (type instanceof PrimitiveType) {
element.addValue(((PrimitiveType)type).toString(value));
} else if (type instanceof StringType) {
element.addValue(((StringType)type).toString(value));
} else if (type instanceof BinaryType) {
element.addValue(ByteString.copyFrom((byte[])value));
} else if (type instanceof TimestampType) {
element.addValue(((TimestampType)type).toString(value));
} else if (type instanceof DateType) {
element.addValue(((DateType)type).toString(value));
} else if (type instanceof EntityType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
iHibSession.evict(value);
} else if (type instanceof CustomType && value instanceof Document) {
if (object instanceof CurriculumClassification && property.equals("students")) continue;
StringWriter w = new StringWriter();
XMLWriter x = new XMLWriter(w, OutputFormat.createCompactFormat());
x.write((Document)value);
x.flush(); x.close();
element.addValue(w.toString());
} else if (type instanceof CollectionType) {
List<Object> ids = current.relation(property, id, false);
if (ids != null)
for (Object i: ids)
element.addValue(i.toString());
} else if (type instanceof EmbeddedComponentType && property.equalsIgnoreCase("uniqueCourseNbr")) {
continue;
} else {
iProgress.warn("Unknown data type: " + type + " (property " + meta.getEntityName() + "." + property + ", class " + value.getClass() + ")");
continue;
}
record.addElement(element.build());
}
table.addRecord(record.build());
iHibSession.evict(object);
}
current.clearCache();
}
for (TableData.Table.Builder table: tables.values()) {
add(table.build());
}
}
/*
// Skip ConstraintInfo
if (!iData.containsKey(ConstraintInfo.class.getName()))
iData.put(ConstraintInfo.class.getName(), new QueueItem(iHibSessionFactory.getClassMetadata(ConstraintInfo.class), null, null, Relation.Empty));
for (String name: items)
export(iData.get(name));
while (true) {
List<Object> objects = new ArrayList<Object>();
ClassMetadata meta = null;
for (Entity e: iObjects) {
if (e.exported()) continue;
if (objects.isEmpty() || meta.getEntityName().equals(e.name())) {
meta = e.meta();
objects.add(e.object());
e.notifyExported();
}
}
if (objects.isEmpty()) break;
export(meta, objects, null);
}
*/
iProgress.setStatus("All done.");
} finally {
iHibSession.close();
}
}
|
diff --git a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/model/TreePropertyProvider.java b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/model/TreePropertyProvider.java
index e975d9e1..7cc21a2a 100644
--- a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/model/TreePropertyProvider.java
+++ b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/model/TreePropertyProvider.java
@@ -1,95 +1,97 @@
/*
* Copyright (C) 2010 Evgeny Mandrikov
*
* Sonar-IDE 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.
*
* Sonar-IDE 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 Sonar-IDE; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.ide.eclipse.views.model;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.TextPropertyDescriptor;
import org.sonar.ide.eclipse.Messages;
/**
* @author Jérémie Lagarde
*/
public class TreePropertyProvider implements IPropertySource {
private final TreeObject node;
public TreePropertyProvider(TreeObject node) {
this.node = node;
}
public Object getEditableValue() {
return null;
}
public IPropertyDescriptor[] getPropertyDescriptors() {
return new IPropertyDescriptor[]{
new TextPropertyDescriptor("id", Messages.getString("prop.resource.id")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("key", Messages.getString("prop.resource.key")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("language", Messages.getString("prop.resource.language")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("longname", Messages.getString("prop.resource.longname")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("name", Messages.getString("prop.resource.name")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("qualifier", Messages.getString("prop.resource.qualifier")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("scope", Messages.getString("prop.resource.scope")), //$NON-NLS-1$ //$NON-NLS-2$
new TextPropertyDescriptor("version", Messages.getString("prop.resource.version")), //$NON-NLS-1$ //$NON-NLS-2$
};
}
public Object getPropertyValue(Object id) {
+ if (node == null || node.getResource() == null)
+ return "";
if (id.equals("id")) { //$NON-NLS-1$
return node.getResource().getId();
}
if (id.equals("key")) { //$NON-NLS-1$
return node.getResource().getKey();
}
if (id.equals("language")) { //$NON-NLS-1$
return node.getResource().getLanguage();
}
if (id.equals("longname")) { //$NON-NLS-1$
return node.getResource().getLongName();
}
if (id.equals("name")) { //$NON-NLS-1$
return node.getResource().getName();
}
if (id.equals("qualifier")) { //$NON-NLS-1$
return node.getResource().getQualifier();
}
if (id.equals("scope")) { //$NON-NLS-1$
return node.getResource().getScope();
}
if (id.equals("version")) { //$NON-NLS-1$
return node.getVersion();
}
return ""; //$NON-NLS-1$
}
public boolean isPropertySet(Object id) {
// Sonar Resource properties are read-only, so do nothing
return false;
}
public void resetPropertyValue(Object id) {
// Sonar Resource properties are read-only, so do nothing
}
public void setPropertyValue(Object id, Object value) {
// Sonar Resource properties are read-only, so do nothing
}
}
| true | true | public Object getPropertyValue(Object id) {
if (id.equals("id")) { //$NON-NLS-1$
return node.getResource().getId();
}
if (id.equals("key")) { //$NON-NLS-1$
return node.getResource().getKey();
}
if (id.equals("language")) { //$NON-NLS-1$
return node.getResource().getLanguage();
}
if (id.equals("longname")) { //$NON-NLS-1$
return node.getResource().getLongName();
}
if (id.equals("name")) { //$NON-NLS-1$
return node.getResource().getName();
}
if (id.equals("qualifier")) { //$NON-NLS-1$
return node.getResource().getQualifier();
}
if (id.equals("scope")) { //$NON-NLS-1$
return node.getResource().getScope();
}
if (id.equals("version")) { //$NON-NLS-1$
return node.getVersion();
}
return ""; //$NON-NLS-1$
}
| public Object getPropertyValue(Object id) {
if (node == null || node.getResource() == null)
return "";
if (id.equals("id")) { //$NON-NLS-1$
return node.getResource().getId();
}
if (id.equals("key")) { //$NON-NLS-1$
return node.getResource().getKey();
}
if (id.equals("language")) { //$NON-NLS-1$
return node.getResource().getLanguage();
}
if (id.equals("longname")) { //$NON-NLS-1$
return node.getResource().getLongName();
}
if (id.equals("name")) { //$NON-NLS-1$
return node.getResource().getName();
}
if (id.equals("qualifier")) { //$NON-NLS-1$
return node.getResource().getQualifier();
}
if (id.equals("scope")) { //$NON-NLS-1$
return node.getResource().getScope();
}
if (id.equals("version")) { //$NON-NLS-1$
return node.getVersion();
}
return ""; //$NON-NLS-1$
}
|
diff --git a/src/net/mdcreator/tpplus/home/HomeExecutor.java b/src/net/mdcreator/tpplus/home/HomeExecutor.java
index 6c3c902..1864132 100644
--- a/src/net/mdcreator/tpplus/home/HomeExecutor.java
+++ b/src/net/mdcreator/tpplus/home/HomeExecutor.java
@@ -1,174 +1,176 @@
package net.mdcreator.tpplus.home;
import net.mdcreator.tpplus.Home;
import net.mdcreator.tpplus.TPPlus;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
public class HomeExecutor implements CommandExecutor{
private TPPlus plugin;
private String title = ChatColor.DARK_GRAY + "[" + ChatColor.BLUE + "TP+" + ChatColor.DARK_GRAY + "] " + ChatColor.GRAY;
public HomeExecutor(TPPlus plugin){
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player send;
if(!(sender instanceof Player)){
sender.sendMessage(title + ChatColor.RED + "Player context is required!");
return true;
}
send = (Player) sender;
// /home
if(args.length==0){
if(plugin.homesManager.homes.containsKey(send.getName())){
Home home = plugin.homesManager.homes.get(send.getName());
Location loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
+ home.pos.getWorld().refreshChunk(home.pos.getWorld().getChunkAt(loc).getX(), home.pos.getWorld().getChunkAt(loc).getZ());
send.teleport(home.pos);
loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home, sweet home.");
} else{
sender.sendMessage(title + ChatColor.RED + "You need a home!");
}
return true;
}else if(args.length==1){
// /home help
if(args[0].equals("help")){
return false;
} else
// /home set
if(args[0].equals("set")){
Location loc = send.getLocation();
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set.");
} else
// /home open
if(args[0].equals("open")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.add(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", true);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 111);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home close
if(args[0].equals("close")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.remove(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", false);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 40);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home [player]
{
Player target = plugin.getServer().getPlayer(args[0]);
String name;
if(target==null){
if(plugin.homesManager.homes.containsKey(args[0])){
name = args[0];
} else{
send.sendMessage(title + ChatColor.RED + "That player does not exist!");
return true;
}
}
name = target.getName();
if(!plugin.homesManager.homes.containsKey(name)){
send.sendMessage(title + ChatColor.RED + "That player does not have a home!");
}else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){
send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!");
} else{
Location loc = send.getLocation();
Home home = plugin.homesManager.homes.get(name);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
+ home.pos.getWorld().refreshChunk(home.pos.getWorld().getChunkAt(loc).getX(), home.pos.getWorld().getChunkAt(loc).getZ());
send.teleport(plugin.homesManager.homes.get(name).pos);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Welcome.");
}
}
return true;
} else if(args.length==2){
if(args[0].equals("set")&&args[1].equals("bed")){
Location loc = send.getBedSpawnLocation();
if(loc==null){
send.sendMessage(title + ChatColor.RED + "You need a bed!");
return true;
}
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set to bed.");
return true;
}
return false;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player send;
if(!(sender instanceof Player)){
sender.sendMessage(title + ChatColor.RED + "Player context is required!");
return true;
}
send = (Player) sender;
// /home
if(args.length==0){
if(plugin.homesManager.homes.containsKey(send.getName())){
Home home = plugin.homesManager.homes.get(send.getName());
Location loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
send.teleport(home.pos);
loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home, sweet home.");
} else{
sender.sendMessage(title + ChatColor.RED + "You need a home!");
}
return true;
}else if(args.length==1){
// /home help
if(args[0].equals("help")){
return false;
} else
// /home set
if(args[0].equals("set")){
Location loc = send.getLocation();
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set.");
} else
// /home open
if(args[0].equals("open")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.add(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", true);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 111);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home close
if(args[0].equals("close")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.remove(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", false);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 40);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home [player]
{
Player target = plugin.getServer().getPlayer(args[0]);
String name;
if(target==null){
if(plugin.homesManager.homes.containsKey(args[0])){
name = args[0];
} else{
send.sendMessage(title + ChatColor.RED + "That player does not exist!");
return true;
}
}
name = target.getName();
if(!plugin.homesManager.homes.containsKey(name)){
send.sendMessage(title + ChatColor.RED + "That player does not have a home!");
}else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){
send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!");
} else{
Location loc = send.getLocation();
Home home = plugin.homesManager.homes.get(name);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
send.teleport(plugin.homesManager.homes.get(name).pos);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Welcome.");
}
}
return true;
} else if(args.length==2){
if(args[0].equals("set")&&args[1].equals("bed")){
Location loc = send.getBedSpawnLocation();
if(loc==null){
send.sendMessage(title + ChatColor.RED + "You need a bed!");
return true;
}
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set to bed.");
return true;
}
return false;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player send;
if(!(sender instanceof Player)){
sender.sendMessage(title + ChatColor.RED + "Player context is required!");
return true;
}
send = (Player) sender;
// /home
if(args.length==0){
if(plugin.homesManager.homes.containsKey(send.getName())){
Home home = plugin.homesManager.homes.get(send.getName());
Location loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
home.pos.getWorld().refreshChunk(home.pos.getWorld().getChunkAt(loc).getX(), home.pos.getWorld().getChunkAt(loc).getZ());
send.teleport(home.pos);
loc = send.getLocation();
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home, sweet home.");
} else{
sender.sendMessage(title + ChatColor.RED + "You need a home!");
}
return true;
}else if(args.length==1){
// /home help
if(args[0].equals("help")){
return false;
} else
// /home set
if(args[0].equals("set")){
Location loc = send.getLocation();
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set.");
} else
// /home open
if(args[0].equals("open")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.add(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", true);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 111);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home close
if(args[0].equals("close")){
if(plugin.homesManager.homes.containsKey(send.getName())){
plugin.homesManager.openHomes.remove(send.getName());
FileConfiguration config = plugin.homesYML;
config.set(send.getName() + ".open", false);
plugin.saveHomes();
Location home = plugin.homesManager.homes.get(send.getName()).pos;
home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1);
home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1);
home.getWorld().playEffect(home, Effect.STEP_SOUND, 40);
send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests.");
} else{
send.sendMessage(title + ChatColor.RED + "You need a home!");
}
} else
// /home [player]
{
Player target = plugin.getServer().getPlayer(args[0]);
String name;
if(target==null){
if(plugin.homesManager.homes.containsKey(args[0])){
name = args[0];
} else{
send.sendMessage(title + ChatColor.RED + "That player does not exist!");
return true;
}
}
name = target.getName();
if(!plugin.homesManager.homes.containsKey(name)){
send.sendMessage(title + ChatColor.RED + "That player does not have a home!");
}else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){
send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!");
} else{
Location loc = send.getLocation();
Home home = plugin.homesManager.homes.get(name);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
home.pos.getWorld().loadChunk(home.pos.getWorld().getChunkAt(loc));
home.pos.getWorld().refreshChunk(home.pos.getWorld().getChunkAt(loc).getX(), home.pos.getWorld().getChunkAt(loc).getZ());
send.teleport(plugin.homesManager.homes.get(name).pos);
send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Welcome.");
}
}
return true;
} else if(args.length==2){
if(args[0].equals("set")&&args[1].equals("bed")){
Location loc = send.getBedSpawnLocation();
if(loc==null){
send.sendMessage(title + ChatColor.RED + "You need a bed!");
return true;
}
plugin.homesManager.homes.put(send.getName(), new Home(loc));
FileConfiguration config = plugin.homesYML;
String name = send.getName();
boolean newHome;
newHome = config.getString(send.getName()) == null;
config.set(name + ".x", loc.getX());
config.set(name + ".y", loc.getY());
config.set(name + ".z", loc.getZ());
config.set(name + ".yaw", loc.getPitch());
config.set(name + ".pitch", loc.getYaw());
config.set(name + ".world", loc.getWorld().getName());
if(newHome) config.set(name + ".open", false);
plugin.saveHomes();
loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1);
loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1);
loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51);
send.sendMessage(title + "Home set to bed.");
return true;
}
return false;
}
return false;
}
|
diff --git a/projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java b/projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java
index c66c61c..1f5c4f9 100644
--- a/projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java
+++ b/projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java
@@ -1,58 +1,58 @@
package org.nohope.akka.spring;
import akka.actor.UntypedActor;
import javax.inject.Inject;
import javax.inject.Named;
/**
* @author <a href="mailto:[email protected]">ketoth xupack</a>
* @since 9/16/12 11:12 PM
*/
public class Bean extends UntypedActor {
private final Integer param1;
private final String param2;
private final String param3;
@Inject
public Bean(final Integer param1,
@Named("param2") final String param2,
@Named("param3") final String param3) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
public Integer getParam1() {
return param1;
}
public String getParam2() {
return param2;
}
public String getParam3() {
return param3;
}
@Override
public void onReceive(final Object message) {
if (message instanceof Props) {
switch ((Props) message) {
case PARAM1:
- getSender().tell(param1);
+ getSender().tell(param1, getSelf());
break;
case PARAM2:
- getSender().tell(param2);
+ getSender().tell(param2, getSelf());
break;
case PARAM3:
- getSender().tell(param3);
+ getSender().tell(param3, getSelf());
break;
}
}
}
public static enum Props {
PARAM1, PARAM2, PARAM3
}
}
| false | true | public void onReceive(final Object message) {
if (message instanceof Props) {
switch ((Props) message) {
case PARAM1:
getSender().tell(param1);
break;
case PARAM2:
getSender().tell(param2);
break;
case PARAM3:
getSender().tell(param3);
break;
}
}
}
| public void onReceive(final Object message) {
if (message instanceof Props) {
switch ((Props) message) {
case PARAM1:
getSender().tell(param1, getSelf());
break;
case PARAM2:
getSender().tell(param2, getSelf());
break;
case PARAM3:
getSender().tell(param3, getSelf());
break;
}
}
}
|
diff --git a/src/com/android/browser/SuggestionsAdapter.java b/src/com/android/browser/SuggestionsAdapter.java
index 30b4738c..e1511b9d 100644
--- a/src/com/android/browser/SuggestionsAdapter.java
+++ b/src/com/android/browser/SuggestionsAdapter.java
@@ -1,597 +1,599 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import com.android.browser.provider.BrowserProvider2;
import com.android.browser.provider.BrowserProvider2.OmniboxSuggestions;
import com.android.browser.search.SearchEngine;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.BrowserContract;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* adapter to wrap multiple cursors for url/search completions
*/
public class SuggestionsAdapter extends BaseAdapter implements Filterable,
OnClickListener {
public static final int TYPE_BOOKMARK = 0;
public static final int TYPE_HISTORY = 1;
public static final int TYPE_SUGGEST_URL = 2;
public static final int TYPE_SEARCH = 3;
public static final int TYPE_SUGGEST = 4;
public static final int TYPE_VOICE_SEARCH = 5;
private static final String[] COMBINED_PROJECTION = {
OmniboxSuggestions._ID,
OmniboxSuggestions.TITLE,
OmniboxSuggestions.URL,
OmniboxSuggestions.IS_BOOKMARK
};
private static final String COMBINED_SELECTION =
"(url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ? OR title LIKE ?)";
final Context mContext;
final Filter mFilter;
SuggestionResults mMixedResults;
List<SuggestItem> mSuggestResults, mFilterResults;
List<CursorSource> mSources;
boolean mLandscapeMode;
final CompletionListener mListener;
final int mLinesPortrait;
final int mLinesLandscape;
final Object mResultsLock = new Object();
List<String> mVoiceResults;
boolean mIncognitoMode;
BrowserSettings mSettings;
interface CompletionListener {
public void onSearch(String txt);
public void onSelect(String txt, int type, String extraData);
}
public SuggestionsAdapter(Context ctx, CompletionListener listener) {
mContext = ctx;
mSettings = BrowserSettings.getInstance();
mListener = listener;
mLinesPortrait = mContext.getResources().
getInteger(R.integer.max_suggest_lines_portrait);
mLinesLandscape = mContext.getResources().
getInteger(R.integer.max_suggest_lines_landscape);
mFilter = new SuggestFilter();
addSource(new CombinedCursor());
}
void setVoiceResults(List<String> voiceResults) {
mVoiceResults = voiceResults;
notifyDataSetChanged();
}
public void setLandscapeMode(boolean mode) {
mLandscapeMode = mode;
notifyDataSetChanged();
}
public void addSource(CursorSource c) {
if (mSources == null) {
mSources = new ArrayList<CursorSource>(5);
}
mSources.add(c);
}
@Override
public void onClick(View v) {
SuggestItem item = (SuggestItem) ((View) v.getParent()).getTag();
if (R.id.icon2 == v.getId()) {
// replace input field text with suggestion text
mListener.onSearch(getSuggestionUrl(item));
} else {
mListener.onSelect(getSuggestionUrl(item), item.type, item.extra);
}
}
@Override
public Filter getFilter() {
return mFilter;
}
@Override
public int getCount() {
if (mVoiceResults != null) {
return mVoiceResults.size();
}
return (mMixedResults == null) ? 0 : mMixedResults.getLineCount();
}
@Override
public SuggestItem getItem(int position) {
if (mVoiceResults != null) {
SuggestItem item = new SuggestItem(mVoiceResults.get(position),
null, TYPE_VOICE_SEARCH);
item.extra = Integer.toString(position);
return item;
}
if (mMixedResults == null) {
return null;
}
return mMixedResults.items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(mContext);
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.suggestion_item, parent, false);
}
bindView(view, getItem(position));
return view;
}
private void bindView(View view, SuggestItem item) {
// store item for click handling
view.setTag(item);
TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
ImageView ic1 = (ImageView) view.findViewById(R.id.icon1);
View ic2 = view.findViewById(R.id.icon2);
View div = view.findViewById(R.id.divider);
tv1.setText(Html.fromHtml(item.title));
if (TextUtils.isEmpty(item.url)) {
tv2.setVisibility(View.GONE);
+ tv1.setMaxLines(2);
} else {
tv2.setVisibility(View.VISIBLE);
tv2.setText(item.url);
+ tv1.setMaxLines(1);
}
int id = -1;
switch (item.type) {
case TYPE_SUGGEST:
case TYPE_SEARCH:
case TYPE_VOICE_SEARCH:
id = R.drawable.ic_search_category_suggest;
break;
case TYPE_BOOKMARK:
id = R.drawable.ic_search_category_bookmark;
break;
case TYPE_HISTORY:
id = R.drawable.ic_search_category_history;
break;
case TYPE_SUGGEST_URL:
id = R.drawable.ic_search_category_browser;
break;
default:
id = -1;
}
if (id != -1) {
ic1.setImageDrawable(mContext.getResources().getDrawable(id));
}
ic2.setVisibility(((TYPE_SUGGEST == item.type)
|| (TYPE_SEARCH == item.type)
|| (TYPE_VOICE_SEARCH == item.type))
? View.VISIBLE : View.GONE);
div.setVisibility(ic2.getVisibility());
ic2.setOnClickListener(this);
view.findViewById(R.id.suggestion).setOnClickListener(this);
}
class SlowFilterTask extends AsyncTask<CharSequence, Void, List<SuggestItem>> {
@Override
protected List<SuggestItem> doInBackground(CharSequence... params) {
SuggestCursor cursor = new SuggestCursor();
cursor.runQuery(params[0]);
List<SuggestItem> results = new ArrayList<SuggestItem>();
int count = cursor.getCount();
for (int i = 0; i < count; i++) {
results.add(cursor.getItem());
cursor.moveToNext();
}
cursor.close();
return results;
}
@Override
protected void onPostExecute(List<SuggestItem> items) {
mSuggestResults = items;
mMixedResults = buildSuggestionResults();
notifyDataSetChanged();
}
}
SuggestionResults buildSuggestionResults() {
SuggestionResults mixed = new SuggestionResults();
List<SuggestItem> filter, suggest;
synchronized (mResultsLock) {
filter = mFilterResults;
suggest = mSuggestResults;
}
if (filter != null) {
for (SuggestItem item : filter) {
mixed.addResult(item);
}
}
if (suggest != null) {
for (SuggestItem item : suggest) {
mixed.addResult(item);
}
}
return mixed;
}
class SuggestFilter extends Filter {
@Override
public CharSequence convertResultToString(Object item) {
if (item == null) {
return "";
}
SuggestItem sitem = (SuggestItem) item;
if (sitem.title != null) {
return sitem.title;
} else {
return sitem.url;
}
}
void startSuggestionsAsync(final CharSequence constraint) {
if (!mIncognitoMode) {
new SlowFilterTask().execute(constraint);
}
}
private boolean shouldProcessEmptyQuery() {
final SearchEngine searchEngine = mSettings.getSearchEngine();
return searchEngine.wantsEmptyQuery();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults res = new FilterResults();
if (mVoiceResults == null) {
if (TextUtils.isEmpty(constraint) && !shouldProcessEmptyQuery()) {
res.count = 0;
res.values = null;
return res;
}
startSuggestionsAsync(constraint);
List<SuggestItem> filterResults = new ArrayList<SuggestItem>();
if (constraint != null) {
for (CursorSource sc : mSources) {
sc.runQuery(constraint);
}
mixResults(filterResults);
}
synchronized (mResultsLock) {
mFilterResults = filterResults;
}
SuggestionResults mixed = buildSuggestionResults();
res.count = mixed.getLineCount();
res.values = mixed;
} else {
res.count = mVoiceResults.size();
res.values = mVoiceResults;
}
return res;
}
void mixResults(List<SuggestItem> results) {
int maxLines = getMaxLines();
for (int i = 0; i < mSources.size(); i++) {
CursorSource s = mSources.get(i);
int n = Math.min(s.getCount(), maxLines);
maxLines -= n;
boolean more = false;
for (int j = 0; j < n; j++) {
results.add(s.getItem());
more = s.moveToNext();
}
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults fresults) {
if (fresults.values instanceof SuggestionResults) {
mMixedResults = (SuggestionResults) fresults.values;
notifyDataSetChanged();
}
}
}
private int getMaxLines() {
int maxLines = mLandscapeMode ? mLinesLandscape : mLinesPortrait;
maxLines = (int) Math.ceil(maxLines / 2.0);
return maxLines;
}
/**
* sorted list of results of a suggestion query
*
*/
class SuggestionResults {
ArrayList<SuggestItem> items;
// count per type
int[] counts;
SuggestionResults() {
items = new ArrayList<SuggestItem>(24);
// n of types:
counts = new int[5];
}
int getTypeCount(int type) {
return counts[type];
}
void addResult(SuggestItem item) {
int ix = 0;
while ((ix < items.size()) && (item.type >= items.get(ix).type))
ix++;
items.add(ix, item);
counts[item.type]++;
}
int getLineCount() {
return Math.min((mLandscapeMode ? mLinesLandscape : mLinesPortrait), items.size());
}
@Override
public String toString() {
if (items == null) return null;
if (items.size() == 0) return "[]";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
SuggestItem item = items.get(i);
sb.append(item.type + ": " + item.title);
if (i < items.size() - 1) {
sb.append(", ");
}
}
return sb.toString();
}
}
/**
* data object to hold suggestion values
*/
public class SuggestItem {
public String title;
public String url;
public int type;
public String extra;
public SuggestItem(String text, String u, int t) {
title = text;
url = u;
type = t;
}
}
abstract class CursorSource {
Cursor mCursor;
boolean moveToNext() {
return mCursor.moveToNext();
}
public abstract void runQuery(CharSequence constraint);
public abstract SuggestItem getItem();
public int getCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
public void close() {
if (mCursor != null) {
mCursor.close();
}
}
}
/**
* combined bookmark & history source
*/
class CombinedCursor extends CursorSource {
@Override
public SuggestItem getItem() {
if ((mCursor != null) && (!mCursor.isAfterLast())) {
String title = mCursor.getString(1);
String url = mCursor.getString(2);
boolean isBookmark = (mCursor.getInt(3) == 1);
return new SuggestItem(getTitle(title, url), getUrl(title, url),
isBookmark ? TYPE_BOOKMARK : TYPE_HISTORY);
}
return null;
}
@Override
public void runQuery(CharSequence constraint) {
// constraint != null
if (mCursor != null) {
mCursor.close();
}
String like = constraint + "%";
String[] args = null;
String selection = null;
if (like.startsWith("http") || like.startsWith("file")) {
args = new String[1];
args[0] = like;
selection = "url LIKE ?";
} else {
args = new String[5];
args[0] = "http://" + like;
args[1] = "http://www." + like;
args[2] = "https://" + like;
args[3] = "https://www." + like;
// To match against titles.
args[4] = like;
selection = COMBINED_SELECTION;
}
Uri.Builder ub = OmniboxSuggestions.CONTENT_URI.buildUpon();
ub.appendQueryParameter(BrowserContract.PARAM_LIMIT,
Integer.toString(Math.max(mLinesLandscape, mLinesPortrait)));
ub.appendQueryParameter(BrowserProvider2.PARAM_GROUP_BY,
OmniboxSuggestions.URL);
mCursor =
mContext.getContentResolver().query(ub.build(), COMBINED_PROJECTION,
selection, (constraint != null) ? args : null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
}
/**
* Provides the title (text line 1) for a browser suggestion, which should be the
* webpage title. If the webpage title is empty, returns the stripped url instead.
*
* @return the title string to use
*/
private String getTitle(String title, String url) {
if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
title = UrlUtils.stripUrl(url);
}
return title;
}
/**
* Provides the subtitle (text line 2) for a browser suggestion, which should be the
* webpage url. If the webpage title is empty, then the url should go in the title
* instead, and the subtitle should be empty, so this would return null.
*
* @return the subtitle string to use, or null if none
*/
private String getUrl(String title, String url) {
if (TextUtils.isEmpty(title)
|| TextUtils.getTrimmedLength(title) == 0
|| title.equals(url)) {
return null;
} else {
return UrlUtils.stripUrl(url);
}
}
}
class SuggestCursor extends CursorSource {
@Override
public SuggestItem getItem() {
if (mCursor != null) {
String title = mCursor.getString(
mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
String text2 = mCursor.getString(
mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2));
String url = mCursor.getString(
mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2_URL));
String uri = mCursor.getString(
mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA));
int type = (TextUtils.isEmpty(url)) ? TYPE_SUGGEST : TYPE_SUGGEST_URL;
SuggestItem item = new SuggestItem(title, url, type);
item.extra = mCursor.getString(
mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA));
return item;
}
return null;
}
@Override
public void runQuery(CharSequence constraint) {
if (mCursor != null) {
mCursor.close();
}
SearchEngine searchEngine = mSettings.getSearchEngine();
if (!TextUtils.isEmpty(constraint)) {
if (searchEngine != null && searchEngine.supportsSuggestions()) {
mCursor = searchEngine.getSuggestions(mContext, constraint.toString());
if (mCursor != null) {
mCursor.moveToFirst();
}
}
} else {
if (searchEngine.wantsEmptyQuery()) {
mCursor = searchEngine.getSuggestions(mContext, "");
}
mCursor = null;
}
}
}
private boolean useInstant() {
return mSettings.useInstantSearch();
}
public void clearCache() {
mFilterResults = null;
mSuggestResults = null;
notifyDataSetInvalidated();
}
public void setIncognitoMode(boolean incognito) {
mIncognitoMode = incognito;
clearCache();
}
static String getSuggestionTitle(SuggestItem item) {
// There must be a better way to strip HTML from things.
// This method is used in multiple places. It is also more
// expensive than a standard html escaper.
return (item.title != null) ? Html.fromHtml(item.title).toString() : null;
}
static String getSuggestionUrl(SuggestItem item) {
final String title = SuggestionsAdapter.getSuggestionTitle(item);
if (TextUtils.isEmpty(item.url)) {
return title;
}
return item.url;
}
}
| false | true | private void bindView(View view, SuggestItem item) {
// store item for click handling
view.setTag(item);
TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
ImageView ic1 = (ImageView) view.findViewById(R.id.icon1);
View ic2 = view.findViewById(R.id.icon2);
View div = view.findViewById(R.id.divider);
tv1.setText(Html.fromHtml(item.title));
if (TextUtils.isEmpty(item.url)) {
tv2.setVisibility(View.GONE);
} else {
tv2.setVisibility(View.VISIBLE);
tv2.setText(item.url);
}
int id = -1;
switch (item.type) {
case TYPE_SUGGEST:
case TYPE_SEARCH:
case TYPE_VOICE_SEARCH:
id = R.drawable.ic_search_category_suggest;
break;
case TYPE_BOOKMARK:
id = R.drawable.ic_search_category_bookmark;
break;
case TYPE_HISTORY:
id = R.drawable.ic_search_category_history;
break;
case TYPE_SUGGEST_URL:
id = R.drawable.ic_search_category_browser;
break;
default:
id = -1;
}
if (id != -1) {
ic1.setImageDrawable(mContext.getResources().getDrawable(id));
}
ic2.setVisibility(((TYPE_SUGGEST == item.type)
|| (TYPE_SEARCH == item.type)
|| (TYPE_VOICE_SEARCH == item.type))
? View.VISIBLE : View.GONE);
div.setVisibility(ic2.getVisibility());
ic2.setOnClickListener(this);
view.findViewById(R.id.suggestion).setOnClickListener(this);
}
| private void bindView(View view, SuggestItem item) {
// store item for click handling
view.setTag(item);
TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
ImageView ic1 = (ImageView) view.findViewById(R.id.icon1);
View ic2 = view.findViewById(R.id.icon2);
View div = view.findViewById(R.id.divider);
tv1.setText(Html.fromHtml(item.title));
if (TextUtils.isEmpty(item.url)) {
tv2.setVisibility(View.GONE);
tv1.setMaxLines(2);
} else {
tv2.setVisibility(View.VISIBLE);
tv2.setText(item.url);
tv1.setMaxLines(1);
}
int id = -1;
switch (item.type) {
case TYPE_SUGGEST:
case TYPE_SEARCH:
case TYPE_VOICE_SEARCH:
id = R.drawable.ic_search_category_suggest;
break;
case TYPE_BOOKMARK:
id = R.drawable.ic_search_category_bookmark;
break;
case TYPE_HISTORY:
id = R.drawable.ic_search_category_history;
break;
case TYPE_SUGGEST_URL:
id = R.drawable.ic_search_category_browser;
break;
default:
id = -1;
}
if (id != -1) {
ic1.setImageDrawable(mContext.getResources().getDrawable(id));
}
ic2.setVisibility(((TYPE_SUGGEST == item.type)
|| (TYPE_SEARCH == item.type)
|| (TYPE_VOICE_SEARCH == item.type))
? View.VISIBLE : View.GONE);
div.setVisibility(ic2.getVisibility());
ic2.setOnClickListener(this);
view.findViewById(R.id.suggestion).setOnClickListener(this);
}
|
diff --git a/GSP/GSPFramework/src/main/java/fr/prima/gsp/demo/Grabber.java b/GSP/GSPFramework/src/main/java/fr/prima/gsp/demo/Grabber.java
index 7806dbd..4bb9dea 100644
--- a/GSP/GSPFramework/src/main/java/fr/prima/gsp/demo/Grabber.java
+++ b/GSP/GSPFramework/src/main/java/fr/prima/gsp/demo/Grabber.java
@@ -1,65 +1,65 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package fr.prima.gsp.demo;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import fr.prima.gsp.framework.Assembly;
import fr.prima.gsp.framework.ModuleParameter;
import fr.prima.gsp.framework.spi.AbstractModuleEnablable;
import fr.prima.videoserviceclient.BufferedImageSourceListener;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
/**
*
* @author emonet
*/
public class Grabber extends AbstractModuleEnablable implements BufferedImageSourceListener {
@ModuleParameter(initOnly=true)
public Assembly assembly;
public void stopped() {
// BufferedImageSourceListener method
}
public synchronized void bufferedImageReceived(BufferedImage image, ByteBuffer imageDataOrNull) {
if (!isEnabled()) return;
tick();
output(image);
Pointer imageDataPointer;
if (imageDataOrNull != null && imageDataOrNull.isDirect()) {
imageDataPointer = Native.getDirectBufferPointer(imageDataOrNull);
} else {
WritableRaster raster = image.getRaster();
int bufferSize = raster.getWidth() * raster.getHeight() * raster.getNumDataElements();
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
buffer.put((byte[]) raster.getDataElements(0, 0, raster.getWidth(), raster.getHeight(), null));
imageDataPointer = Native.getDirectBufferPointer(buffer);
}
- outputRaw(imageDataPointer, image.getWidth(), image.getWidth(), image.getHeight(), 24);
+ outputRaw(imageDataPointer, image.getWidth(), image.getHeight(), image.getWidth(), 24);
}
// Type = 24 for BGR
private void outputRaw(Pointer data, int w, int h, int widthStep, int type) {
emitEvent(data, w, h, widthStep, type);
}
private void output(BufferedImage im) {
emitEvent(im);
}
private void tick() {
emitEvent();
}
// helpers for pipeline destruction
public void closePipeline() {assembly.stop();}
public void closePipeline1(Object o1) {assembly.stop();}
public void closePipeline2(Object o1, Object o2) {assembly.stop();}
public void closePipeline3(Object o1, Object o2, Object o3) {assembly.stop();}
public void closePipeline4(Object o1, Object o2, Object o3, Object o4) {assembly.stop();}
}
| true | true | public synchronized void bufferedImageReceived(BufferedImage image, ByteBuffer imageDataOrNull) {
if (!isEnabled()) return;
tick();
output(image);
Pointer imageDataPointer;
if (imageDataOrNull != null && imageDataOrNull.isDirect()) {
imageDataPointer = Native.getDirectBufferPointer(imageDataOrNull);
} else {
WritableRaster raster = image.getRaster();
int bufferSize = raster.getWidth() * raster.getHeight() * raster.getNumDataElements();
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
buffer.put((byte[]) raster.getDataElements(0, 0, raster.getWidth(), raster.getHeight(), null));
imageDataPointer = Native.getDirectBufferPointer(buffer);
}
outputRaw(imageDataPointer, image.getWidth(), image.getWidth(), image.getHeight(), 24);
}
| public synchronized void bufferedImageReceived(BufferedImage image, ByteBuffer imageDataOrNull) {
if (!isEnabled()) return;
tick();
output(image);
Pointer imageDataPointer;
if (imageDataOrNull != null && imageDataOrNull.isDirect()) {
imageDataPointer = Native.getDirectBufferPointer(imageDataOrNull);
} else {
WritableRaster raster = image.getRaster();
int bufferSize = raster.getWidth() * raster.getHeight() * raster.getNumDataElements();
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
buffer.put((byte[]) raster.getDataElements(0, 0, raster.getWidth(), raster.getHeight(), null));
imageDataPointer = Native.getDirectBufferPointer(buffer);
}
outputRaw(imageDataPointer, image.getWidth(), image.getHeight(), image.getWidth(), 24);
}
|
diff --git a/src/pl/edu/pk/nurse/constraints/hard/FullCoverConstraint.java b/src/pl/edu/pk/nurse/constraints/hard/FullCoverConstraint.java
index a2e0371..6928481 100644
--- a/src/pl/edu/pk/nurse/constraints/hard/FullCoverConstraint.java
+++ b/src/pl/edu/pk/nurse/constraints/hard/FullCoverConstraint.java
@@ -1,80 +1,80 @@
package pl.edu.pk.nurse.constraints.hard;
import pl.edu.pk.nurse.Configuration;
import pl.edu.pk.nurse.data.Nurse;
import pl.edu.pk.nurse.data.Schedule;
import pl.edu.pk.nurse.data.util.Fitness;
import pl.edu.pk.nurse.data.util.Shift;
import pl.edu.pk.nurse.data.util.Week;
import pl.edu.pk.nurse.data.util.Weekday;
import java.util.ArrayList;
import java.util.List;
/**
* User: msendyka
* Date: 24.05.13
* Time: 21:48
* • Cover needs to be fulfilled (i.e. no shifts must be left unassigned).
*/
public class FullCoverConstraint extends HardConstraint {
@Override
public Fitness measure(Schedule schedule) {
int violated = 0;
for (int i = 0; i < 5; i++) {
List<Week> weeks = new ArrayList<Week>();
for (Nurse nurse : schedule.toEntity()) {
weeks.add(nurse.getWeek(i));
}
violated += new WeekShiftValidator(weeks).validate();
}
return new Fitness(violated * Configuration.HARD_CONSTRAINT_WEIGHT);
}
private class WeekShiftValidator {
private List<Week> week;
private WeekShiftValidator(List<Week> week) {
this.week = week;
}
private int validate() {
int result = 0;
result += weekDay(Weekday.MONDAY);
result += weekDay(Weekday.TUESDAY);
result += weekDay(Weekday.WEDNESDAY);
result += weekDay(Weekday.THURSDAY);
result += weekDay(Weekday.FRIDAY);
result += weekDay(Weekday.SATURDAY);
result += weekend(Weekday.SUNDAY);
- return result;
+ return result != 0 ? 1 : 0;
}
private int weekend(Weekday weekday) {
int result = findShifts(weekday, Shift.DAY) - 2;
result += findShifts(weekday, Shift.EARLY) - 2;
result += findShifts(weekday, Shift.LATE) - 2;
result += findShifts(weekday, Shift.NIGHT) - 1;
return result;
}
private int weekDay(Weekday weekday) {
int result = findShifts(weekday, Shift.DAY) - 3;
result += findShifts(weekday, Shift.EARLY) - 3;
result += findShifts(weekday, Shift.LATE) - 3;
result += findShifts(weekday, Shift.NIGHT) - 1;
return result;
}
private int findShifts(Weekday weekday, Shift shift) {
int result = 0;
for (Week week : this.week) {
if (week.getShiftForDay(weekday) == shift) {
result++;
}
}
return result;
}
}
}
| true | true | private int validate() {
int result = 0;
result += weekDay(Weekday.MONDAY);
result += weekDay(Weekday.TUESDAY);
result += weekDay(Weekday.WEDNESDAY);
result += weekDay(Weekday.THURSDAY);
result += weekDay(Weekday.FRIDAY);
result += weekDay(Weekday.SATURDAY);
result += weekend(Weekday.SUNDAY);
return result;
}
| private int validate() {
int result = 0;
result += weekDay(Weekday.MONDAY);
result += weekDay(Weekday.TUESDAY);
result += weekDay(Weekday.WEDNESDAY);
result += weekDay(Weekday.THURSDAY);
result += weekDay(Weekday.FRIDAY);
result += weekDay(Weekday.SATURDAY);
result += weekend(Weekday.SUNDAY);
return result != 0 ? 1 : 0;
}
|
diff --git a/src/com/android/launcher2/BubbleTextView.java b/src/com/android/launcher2/BubbleTextView.java
index d02f597b..ad01fac4 100644
--- a/src/com/android/launcher2/BubbleTextView.java
+++ b/src/com/android/launcher2/BubbleTextView.java
@@ -1,313 +1,313 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import com.android.launcher.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
/**
* TextView that draws a bubble behind the text. We cannot use a LineBackgroundSpan
* because we want to make the bubble taller than the text and TextView's clip is
* too aggressive.
*/
public class BubbleTextView extends TextView implements VisibilityChangedBroadcaster {
static final float CORNER_RADIUS = 4.0f;
static final float SHADOW_LARGE_RADIUS = 4.0f;
static final float SHADOW_SMALL_RADIUS = 1.75f;
static final float SHADOW_Y_OFFSET = 2.0f;
static final int SHADOW_LARGE_COLOUR = 0xCC000000;
static final int SHADOW_SMALL_COLOUR = 0xBB000000;
static final float PADDING_H = 8.0f;
static final float PADDING_V = 3.0f;
private Paint mPaint;
private float mBubbleColorAlpha;
private int mPrevAlpha = -1;
private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
private final Canvas mTempCanvas = new Canvas();
private final Rect mTempRect = new Rect();
private final Paint mTempPaint = new Paint();
private boolean mDidInvalidateForPressedState;
private Bitmap mPressedOrFocusedBackground;
private int mFocusedOutlineColor;
private int mFocusedGlowColor;
private int mPressedOutlineColor;
private int mPressedGlowColor;
private boolean mBackgroundSizeChanged;
private Drawable mBackground;
private VisibilityChangedListener mOnVisibilityChangedListener;
public BubbleTextView(Context context) {
super(context);
init();
}
public BubbleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mBackground = getBackground();
setFocusable(true);
setBackgroundDrawable(null);
final Resources res = getContext().getResources();
int bubbleColor = res.getColor(R.color.bubble_dark_background);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(bubbleColor);
mBubbleColorAlpha = Color.alpha(bubbleColor) / 255.0f;
mFocusedOutlineColor = res.getColor(R.color.workspace_item_focused_outline_color);
mFocusedGlowColor = res.getColor(R.color.workspace_item_focused_glow_color);
mPressedOutlineColor = res.getColor(R.color.workspace_item_pressed_outline_color);
mPressedGlowColor = res.getColor(R.color.workspace_item_pressed_glow_color);
setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
}
public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) {
Bitmap b = info.getIcon(iconCache);
setCompoundDrawablesWithIntrinsicBounds(null,
new FastBitmapDrawable(b),
null, null);
setText(info.title);
setTag(info);
}
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
mBackgroundSizeChanged = true;
}
return super.setFrame(left, top, right, bottom);
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mBackground || super.verifyDrawable(who);
}
@Override
protected void drawableStateChanged() {
if (isPressed()) {
// In this case, we have already created the pressed outline on ACTION_DOWN,
// so we just need to do an invalidate to trigger draw
if (!mDidInvalidateForPressedState) {
invalidate();
}
} else {
// Otherwise, either clear the pressed/focused background, or create a background
// for the focused state
final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null;
mPressedOrFocusedBackground = null;
if (isFocused()) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor);
invalidate();
}
final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null;
if (!backgroundEmptyBefore && backgroundEmptyNow) {
invalidate();
}
}
Drawable d = mBackground;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
super.drawableStateChanged();
}
/**
* Draw the View v into the given Canvas.
*
* @param v the view to draw
* @param destCanvas the canvas to draw on
* @param padding the horizontal and vertical padding to use when drawing
*/
private void drawWithPadding(Canvas destCanvas, int padding) {
final Rect clipRect = mTempRect;
getDrawingRect(clipRect);
// adjust the clip rect so that we don't include the text label
clipRect.bottom =
getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0);
// Draw the View into the bitmap.
// The translate of scrollX and scrollY is necessary when drawing TextViews, because
// they set scrollX and scrollY to large values to achieve centered text
destCanvas.save();
destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2);
destCanvas.clipRect(clipRect, Op.REPLACE);
draw(destCanvas);
destCanvas.restore();
}
/**
* Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) {
final int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
final Bitmap b = Bitmap.createBitmap(
getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
drawWithPadding(canvas, padding);
mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor);
return b;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// So that the pressed outline is visible immediately when isPressed() is true,
// we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time
// to create it)
if (mPressedOrFocusedBackground == null) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mPressedGlowColor, mPressedOutlineColor);
}
// Invalidate so the pressed state is visible, or set a flag so we know that we
// have to call invalidate as soon as the state is "pressed"
if (isPressed()) {
mDidInvalidateForPressedState = true;
invalidate();
} else {
mDidInvalidateForPressedState = false;
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// If we've touched down and up on an item, and it's still not "pressed", then
// destroy the pressed outline
if (!isPressed()) {
mPressedOrFocusedBackground = null;
}
break;
}
return result;
}
public void setVisibilityChangedListener(VisibilityChangedListener listener) {
mOnVisibilityChangedListener = listener;
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
if (mOnVisibilityChangedListener != null) {
mOnVisibilityChangedListener.receiveVisibilityChangedMessage(this);
}
super.onVisibilityChanged(changedView, visibility);
}
@Override
public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
- mScrollY + getHeight(), Region.Op.REPLACE);
+ mScrollY + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mBackground != null) mBackground.setCallback(null);
}
@Override
protected boolean onSetAlpha(int alpha) {
if (mPrevAlpha != alpha) {
mPrevAlpha = alpha;
mPaint.setAlpha((int) (alpha * mBubbleColorAlpha));
super.onSetAlpha(alpha);
}
return true;
}
}
| true | true | public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
mScrollY + getHeight(), Region.Op.REPLACE);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
| public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
mScrollY + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
|
diff --git a/src/com/dmdirc/plugins/PluginInfo.java b/src/com/dmdirc/plugins/PluginInfo.java
index 424322a21..ba06ce2ae 100644
--- a/src/com/dmdirc/plugins/PluginInfo.java
+++ b/src/com/dmdirc/plugins/PluginInfo.java
@@ -1,791 +1,789 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.
*
* SVN: $Id$
*/
package com.dmdirc.plugins;
import com.dmdirc.Main;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.util.resourcemanager.ResourceManager;
import com.dmdirc.logger.Logger;
import com.dmdirc.logger.ErrorLevel;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;
public class PluginInfo implements Comparable<PluginInfo> {
/** Plugin Meta Data */
private Properties metaData = null;
/** File that this plugin was loaded from */
private final String filename;
/** The actual Plugin from this jar */
private Plugin plugin = null;
/** The classloader used for this Plugin */
private PluginClassLoader classloader = null;
/** The resource manager used by this pluginInfo */
private ResourceManager myResourceManager = null;
/** Is this plugin only loaded temporarily? */
private boolean tempLoaded = false;
/** List of classes this plugin has */
private List<String> myClasses = new ArrayList<String>();
/** Requirements error message. */
private String requirementsError = "";
/**
* Create a new PluginInfo.
*
* @param filename File that this plugin is stored in.
* @throws PluginException if there is an error loading the Plugin
*/
public PluginInfo(final String filename) throws PluginException {
this(filename, true);
}
/**
* Create a new PluginInfo.
*
* @param filename File that this plugin is stored in.
* @param load Should this plugin be loaded, or is this just a placeholder? (true for load, false for placeholder)
* @throws PluginException if there is an error loading the Plugin
*/
public PluginInfo(final String filename, final boolean load) throws PluginException {
this.filename = filename;
if (!load) { return; }
// Check for updates.
if (new File(getFullFilename()+".update").exists() && new File(getFullFilename()).delete()) {
new File(getFullFilename()+".update").renameTo(new File(getFullFilename()));
}
ResourceManager res;
try {
res = getResourceManager();
} catch (IOException ioe) {
throw new PluginException("Plugin "+filename+" failed to load, error with resourcemanager: "+ioe.getMessage(), ioe);
}
try {
if (res.resourceExists("META-INF/plugin.info")) {
metaData = new Properties();
metaData.load(res.getResourceInputStream("META-INF/plugin.info"));
} else {
throw new PluginException("Plugin "+filename+" failed to load, plugin.info doesn't exist in jar");
}
} catch (PluginException pe) {
// Stop the next catch Catching the one we threw ourself
throw pe;
} catch (Exception e) {
throw new PluginException("Plugin "+filename+" failed to load, plugin.info failed to open - "+e.getMessage(), e);
}
if (getVersion() < 0) {
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing or invalid 'version')");
} else if (getAuthor().isEmpty()) {
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'author')");
} else if (getName().isEmpty()) {
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'name')");
} else if (getMinVersion().isEmpty()) {
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'minversion')");
} else if (getMainClass().isEmpty()) {
throw new PluginException("Plugin "+filename+" failed to load, incomplete plugin.info (Missing 'mainclass')");
}
if (checkRequirements()) {
final String mainClass = getMainClass().replace('.', '/')+".class";
if (!res.resourceExists(mainClass)) {
throw new PluginException("Plugin "+filename+" failed to load, main class file ("+mainClass+") not found in jar.");
}
for (final String classfilename : res.getResourcesStartingWith("")) {
String classname = classfilename.replace('/', '.');
if (classname.matches("^.*\\.class$")) {
classname = classname.replaceAll("\\.class$", "");
myClasses.add(classname);
}
}
if (isPersistant()) { loadEntirePlugin(); }
} else {
// throw new PluginException("Plugin "+filename+" was not loaded, one or more requirements not met ("+requirements+")");
}
myResourceManager = null;
}
/**
* Get the contents of requirementsError
*
* @return requirementsError
*/
public String getRequirementsError() {
return requirementsError;
}
/**
* Get the resource manager for this plugin
*
* @throws IOException if there is any problem getting a ResourceManager for this plugin
*/
protected synchronized ResourceManager getResourceManager() throws IOException {
if (myResourceManager == null) {
final String directory = PluginManager.getPluginManager().getDirectory();
myResourceManager = ResourceManager.getResourceManager("jar://"+directory+filename);
}
return myResourceManager;
}
/**
* Checks to see if the minimum version requirement of the plugin is
* satisfied.
* If either version is non-positive, the test passes.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired minimum version of DMDirc.
* @param actual The actual current version of DMDirc.
* @return True if the test passed, false otherwise
*/
protected boolean checkMinimumVersion(final String desired, final int actual) {
int idesired;
try {
idesired = Integer.parseInt(desired);
} catch (NumberFormatException ex) {
requirementsError = "'minversion' is a non-integer";
return false;
}
if (actual > 0 && idesired > 0 && actual < idesired) {
requirementsError = "Plugin is for a newer version of DMDirc";
return false;
} else {
return true;
}
}
/**
* Checks to see if the maximum version requirement of the plugin is
* satisfied.
* If either version is non-positive, the test passes.
* If the desired version is empty, the test passes.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired maximum version of DMDirc.
* @param actual The actual current version of DMDirc.
* @return True if the test passed, false otherwise
*/
protected boolean checkMaximumVersion(final String desired, final int actual) {
int idesired;
if (desired.isEmpty()) {
return true;
}
try {
idesired = Integer.parseInt(desired);
} catch (NumberFormatException ex) {
requirementsError = "'maxversion' is a non-integer";
return false;
}
if (actual > 0 && idesired > 0 && actual > idesired) {
requirementsError = "Plugin is for an older version of DMDirc";
return false;
} else {
return true;
}
}
/**
* Checks to see if the OS requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is used as one to three colon-delimited regular expressions,
* to test the name, version and architecture of the OS, respectively.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired OS requirements
* @param actualName The actual name of the OS
* @param actualVersion The actual version of the OS
* @param actualArch The actual architecture of the OS
* @return True if the test passes, false otherwise
*/
protected boolean checkOS(final String desired, final String actualName, final String actualVersion, final String actualArch) {
if (desired.isEmpty()) {
return true;
}
final String[] desiredParts = desired.split(":");
if (!actualName.toLowerCase().matches(desiredParts[0])) {
requirementsError = "Invalid OS. (Wanted: '" + desiredParts[0] + "', actual: '" + actualName + "')";
return false;
} else if (desiredParts.length > 1 && !actualVersion.toLowerCase().matches(desiredParts[1])) {
requirementsError = "Invalid OS version. (Wanted: '" + desiredParts[1] + "', actual: '" + actualVersion + "')";
return false;
} else if (desiredParts.length > 2 && !actualArch.toLowerCase().matches(desiredParts[2])) {
requirementsError = "Invalid OS architecture. (Wanted: '" + desiredParts[2] + "', actual: '" + actualArch + "')";
return false;
}
return true;
}
/**
* Checks to see if the UI requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is used as a regular expressions against the package of the
* UIController to test what UI is currently in use.
* On failure, the requirementsError field will contain a user-friendly
* error message.
*
* @param desired The desired UI requirements
* @param actual The package of the current UI in use.
* @return True if the test passes, false otherwise
*/
protected boolean checkUI(final String desired, final String actual) {
if (desired.isEmpty()) {
return true;
}
if (!actual.toLowerCase().matches(desired)) {
requirementsError = "Invalid UI. (Wanted: '" + desired + "', actual: '" + actual + "')";
return false;
}
return true;
}
/**
* Checks to see if the file requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Otherwise it is passed to File.exists() to see if the file is valid.
* Multiple files can be specified by using a "," to separate. And either/or
* files can be specified using a "|" (eg /usr/bin/bash|/bin/bash)
* If the test fails, the requirementsError field will contain a
* user-friendly error message.
*
* @param desired The desired file requirements
* @return True if the test passes, false otherwise
*/
protected boolean checkFiles(final String desired) {
if (desired.isEmpty()) {
return true;
}
for (String files : desired.split(",")) {
final String[] filelist = files.split("\\|");
boolean foundFile = false;
for (String file : filelist) {
if ((new File(file)).exists()) {
foundFile = true;
break;
}
}
if (!foundFile) {
requirementsError = "Required file '"+files+"' not found";
return false;
}
}
return true;
}
/**
* Checks to see if the plugin requirements of the plugin are satisfied.
* If the desired string is empty, the test passes.
* Plugins should be specified as:
* plugin1[:minversion[:maxversion]],plugin2[:minversion[:maxversion]]
* Plugins will be attempted to be loaded if not loaded, else the test will
* fail if the versions don't match, or the plugin isn't known.
* If the test fails, the requirementsError field will contain a
* user-friendly error message.
*
* @param desired The desired file requirements
* @return True if the test passes, false otherwise
*/
protected boolean checkPlugins(final String desired) {
if (desired.isEmpty()) {
return true;
}
for (String plugin : desired.split(",")) {
final String[] data = plugin.split(":");
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(data[0]);
if (pi == null) {
requirementsError = "Required plugin '"+data[0]+"' was not found";
return false;
} else {
if (data.length > 1) {
// Check plugin minimum version matches.
try {
final int minversion = Integer.parseInt(data[1]);
if (pi.getVersion() < minversion) {
requirementsError = "Plugin '"+data[0]+"' is too old (Required Version: "+minversion+", Actual Version: "+pi.getVersion()+")";
return false;
} else {
if (data.length > 2) {
// Check plugin maximum version matches.
try {
final int maxversion = Integer.parseInt(data[2]);
if (pi.getVersion() > maxversion) {
requirementsError = "Plugin '"+data[0]+"' is too new (Required Version: "+maxversion+", Actual Version: "+pi.getVersion()+")";
return false;
}
} catch (NumberFormatException nfe) {
requirementsError = "Plugin max-version '"+data[2]+"' for plugin ('"+data[0]+"') is a non-integer";
return false;
}
}
}
} catch (NumberFormatException nfe) {
requirementsError = "Plugin min-version '"+data[1]+"' for plugin ('"+data[0]+"') is a non-integer";
return false;
}
}
// Make sure the required plugin is loaded if its not already,
pi.loadPlugin();
}
}
return true;
}
/**
* Are the requirements for this plugin met?
*
* @return true/false (Actual error if false is in the requirementsError field)
*/
public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), Main.getUI().getClass().getPackage().getName()) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
myResourceManager = null;
}
/**
* Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load a plugin permanently, if it was previously loaded as temp
*/
public void loadPluginPerm() {
if (isTempLoaded()) {
tempLoaded = false;
plugin.onLoad();
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isLoaded() || isTempLoaded() || metaData == null) {
return;
}
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
myResourceManager = null;
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
classloader = new PluginClassLoader(this);
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
plugin.onLoad();
}
} else {
if (!tempLoaded) {
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
} catch (ClassNotFoundException cnfe) {
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+getMainClass()+"')", cnfe);
} catch (NoSuchMethodException nsme) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+getMainClass()+"')", nsme);
} catch (IllegalAccessException iae) {
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+getMainClass()+"')", iae);
} catch (InvocationTargetException ite) {
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+getMainClass()+"')", ite);
} catch (InstantiationException ie) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"')", ie);
} catch (NoClassDefFoundError ncdf) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"'): Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"') - Incompatible", ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
public String getFriendlyVersion() { return metaData.getProperty("friendlyversion",""); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
- String classname = filename.replace('.', '/');
- if (classname.matches("^.*\\.class$")) {
- classname = classname.replaceAll("\\.class$", "");
- result.add(classname);
+ if (filename.matches("^.*\\.class$")) {
+ result.add(filename.replaceAll("\\.class$", "").replace('/', '.'));
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return PluginManager.getPluginManager().getDirectory()+filename; }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
| true | true | public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), Main.getUI().getClass().getPackage().getName()) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
myResourceManager = null;
}
/**
* Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load a plugin permanently, if it was previously loaded as temp
*/
public void loadPluginPerm() {
if (isTempLoaded()) {
tempLoaded = false;
plugin.onLoad();
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isLoaded() || isTempLoaded() || metaData == null) {
return;
}
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
myResourceManager = null;
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
classloader = new PluginClassLoader(this);
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
plugin.onLoad();
}
} else {
if (!tempLoaded) {
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
} catch (ClassNotFoundException cnfe) {
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+getMainClass()+"')", cnfe);
} catch (NoSuchMethodException nsme) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+getMainClass()+"')", nsme);
} catch (IllegalAccessException iae) {
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+getMainClass()+"')", iae);
} catch (InvocationTargetException ite) {
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+getMainClass()+"')", ite);
} catch (InstantiationException ie) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"')", ie);
} catch (NoClassDefFoundError ncdf) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"'): Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"') - Incompatible", ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
public String getFriendlyVersion() { return metaData.getProperty("friendlyversion",""); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
String classname = filename.replace('.', '/');
if (classname.matches("^.*\\.class$")) {
classname = classname.replaceAll("\\.class$", "");
result.add(classname);
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return PluginManager.getPluginManager().getDirectory()+filename; }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
| public boolean checkRequirements() {
if (metaData == null) {
// No meta-data, so no requirements.
return true;
}
if (!checkMinimumVersion(getMinVersion(), Main.SVN_REVISION) ||
!checkMaximumVersion(getMaxVersion(), Main.SVN_REVISION) ||
!checkFiles(getMetaInfo(new String[]{"required-files", "require-files", "required-file", "require-file"})) ||
!checkUI(getMetaInfo(new String[]{"required-ui", "require-ui"}), Main.getUI().getClass().getPackage().getName()) ||
!checkPlugins(getMetaInfo(new String[]{"required-plugins", "require-plugins", "required-plugin", "require-plugin"})) ||
!checkOS(getMetaInfo(new String[]{"required-os", "require-os"}), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))
) {
return false;
}
// All requirements passed, woo \o
return true;
}
/**
* Is this plugin loaded?
*/
public boolean isLoaded() {
return (plugin != null) && !tempLoaded;
}
/**
* Is this plugin temporarily loaded?
*/
public boolean isTempLoaded() {
return (plugin != null) && tempLoaded;
}
/**
* Load entire plugin.
* This loads all files in the jar immediately.
*
* @throws PluginException if there is an error with the resourcemanager
*/
private void loadEntirePlugin() throws PluginException {
// Load the main "Plugin" from the jar
loadPlugin();
// Now load all the rest.
for (String classname : myClasses) {
loadClass(classname);
}
myResourceManager = null;
}
/**
* Load the plugin files temporarily.
*/
public void loadPluginTemp() {
tempLoaded = true;
loadPlugin();
}
/**
* Load a plugin permanently, if it was previously loaded as temp
*/
public void loadPluginPerm() {
if (isTempLoaded()) {
tempLoaded = false;
plugin.onLoad();
}
}
/**
* Load the plugin files.
*/
public void loadPlugin() {
if (isLoaded() || isTempLoaded() || metaData == null) {
return;
}
loadClass(getMainClass());
if (isLoaded()) {
ActionManager.processEvent(CoreActionType.PLUGIN_LOADED, null, this);
}
myResourceManager = null;
}
/**
* Load the given classname.
*
* @param classname Class to load
*/
private void loadClass(final String classname) {
try {
classloader = new PluginClassLoader(this);
final Class<?> c = classloader.loadClass(classname);
final Constructor<?> constructor = c.getConstructor(new Class[] {});
final Object temp = constructor.newInstance(new Object[] {});
if (temp instanceof Plugin) {
if (((Plugin) temp).checkPrerequisites()) {
plugin = (Plugin) temp;
if (!tempLoaded) {
plugin.onLoad();
}
} else {
if (!tempLoaded) {
Logger.userError(ErrorLevel.LOW, "Prerequisites for plugin not met. ('"+filename+":"+getMainClass()+"')");
}
}
}
} catch (ClassNotFoundException cnfe) {
Logger.userError(ErrorLevel.LOW, "Class not found ('"+filename+":"+getMainClass()+"')", cnfe);
} catch (NoSuchMethodException nsme) {
Logger.userError(ErrorLevel.LOW, "Constructor missing ('"+filename+":"+getMainClass()+"')", nsme);
} catch (IllegalAccessException iae) {
Logger.userError(ErrorLevel.LOW, "Unable to access constructor ('"+filename+":"+getMainClass()+"')", iae);
} catch (InvocationTargetException ite) {
Logger.userError(ErrorLevel.LOW, "Unable to invoke target ('"+filename+":"+getMainClass()+"')", ite);
} catch (InstantiationException ie) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"')", ie);
} catch (NoClassDefFoundError ncdf) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"'): Unable to find class: " + ncdf.getMessage(), ncdf);
} catch (VerifyError ve) {
Logger.userError(ErrorLevel.LOW, "Unable to instantiate plugin ('"+filename+":"+getMainClass()+"') - Incompatible", ve);
}
}
/**
* Unload the plugin if possible.
*/
public void unloadPlugin() {
if (!isPersistant() && (isLoaded() || isTempLoaded())) {
if (!isTempLoaded()) {
try {
plugin.onUnload();
} catch (Exception e) {
Logger.userError(ErrorLevel.MEDIUM, "Error in onUnload for "+getName()+":"+e.getMessage(), e);
}
ActionManager.processEvent(CoreActionType.PLUGIN_UNLOADED, null, this);
}
tempLoaded = false;
plugin = null;
classloader = null;
}
}
/**
* Get the list of Classes
*
* @return Classes this plugin has
*/
public List<String> getClassList() {
return myClasses;
}
/**
* Get the main Class
*
* @return Main Class to begin loading.
*/
public String getMainClass() { return metaData.getProperty("mainclass",""); }
/**
* Get the Plugin for this plugin.
*
* @return Plugin
*/
public Plugin getPlugin() { return plugin; }
/**
* Get the PluginClassLoader for this plugin.
*
* @return PluginClassLoader
*/
protected PluginClassLoader getPluginClassLoader() { return classloader; }
/**
* Get the plugin friendly version
*
* @return Plugin friendly Version
*/
public String getFriendlyVersion() { return metaData.getProperty("friendlyversion",""); }
/**
* Get the plugin version
*
* @return Plugin Version
*/
public int getVersion() {
try {
return Integer.parseInt(metaData.getProperty("version","0"));
} catch (NumberFormatException nfe) {
return -1;
}
}
/**
* Get the id for this plugin on the addons site.
* If a plugin has been submitted to addons.dmdirc.com, and plugin.info
* contains a property addonid then this will return it.
* This is used along with the version property to allow the auto-updater to
* update the addon if the author submits a new version to the addons site.
*
* @return Addon Site ID number
* -1 If not present
* -2 If non-integer
*/
public int getAddonID() {
try {
return Integer.parseInt(metaData.getProperty("addonid","-1"));
} catch (NumberFormatException nfe) {
return -2;
}
}
/**
* Is this a persistant plugin?
*
* @return true if persistant, else false
*/
public boolean isPersistant() {
final String persistance = metaData.getProperty("persistant","no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
/**
* Does this plugin contain any persistant classes?
*
* @return true if this plugin contains any persistant classes, else false
*/
public boolean hasPersistant() {
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
return true;
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
return true;
}
}
}
return false;
}
/**
* Get a list of all persistant classes in this plugin
*
* @return List of all persistant classes in this plugin
*/
public List<String> getPersistantClasses() {
final List<String> result = new ArrayList<String>();
final String persistance = metaData.getProperty("persistant","no");
if (persistance.equalsIgnoreCase("true")) {
try {
ResourceManager res = getResourceManager();
for (final String filename : res.getResourcesStartingWith("")) {
if (filename.matches("^.*\\.class$")) {
result.add(filename.replaceAll("\\.class$", "").replace('/', '.'));
}
}
} catch (IOException e) {
// Jar no longer exists?
}
} else {
for (Object keyObject : metaData.keySet()) {
if (keyObject.toString().toLowerCase().startsWith("persistant-")) {
result.add(keyObject.toString().substring(11));
}
}
}
return result;
}
/**
* Is this a persistant class?
*
* @param classname class to check persistance of
* @return true if file (or whole plugin) is persistant, else false
*/
public boolean isPersistant(final String classname) {
if (isPersistant()) {
return true;
} else {
final String persistance = metaData.getProperty("persistant-"+classname,"no");
return persistance.equalsIgnoreCase("true") || persistance.equalsIgnoreCase("yes");
}
}
/**
* Get the plugin Filename.
*
* @return Filename of plugin
*/
public String getFilename() { return filename; }
/**
* Get the full plugin Filename (inc dirname)
*
* @return Filename of plugin
*/
public String getFullFilename() { return PluginManager.getPluginManager().getDirectory()+filename; }
/**
* Get the plugin Author.
*
* @return Author of plugin
*/
public String getAuthor() { return getMetaInfo("author",""); }
/**
* Get the plugin Description.
*
* @return Description of plugin
*/
public String getDescription() { return getMetaInfo("description",""); }
/**
* Get the minimum dmdirc version required to run the plugin.
*
* @return minimum dmdirc version required to run the plugin.
*/
public String getMinVersion() { return getMetaInfo("minversion",""); }
/**
* Get the (optional) maximum dmdirc version on which this plugin can run
*
* @return optional maximum dmdirc version on which this plugin can run
*/
public String getMaxVersion() { return getMetaInfo("maxversion",""); }
/**
* Get the name of the plugin. (Used to identify the plugin)
*
* @return Name of plugin
*/
public String getName() { return getMetaInfo("name",""); }
/**
* Get the nice name of the plugin. (Displayed to users)
*
* @return Nice Name of plugin
*/
public String getNiceName() { return getMetaInfo("nicename",getName()); }
/**
* String Representation of this plugin
*
* @return String Representation of this plugin
*/
@Override
public String toString() { return getNiceName()+" - "+filename; }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @return Misc Meta Info (or "" if not found);
*/
public String getMetaInfo(final String metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfo to return
* @param fallback Fallback value if requested value is not found
* @return Misc Meta Info (or fallback if not found);
*/
public String getMetaInfo(final String metainfo, final String fallback) { return metaData.getProperty(metainfo,fallback); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo) { return getMetaInfo(metainfo,""); }
/**
* Get misc meta-information.
*
* @param metainfo The metainfos to look for in order. If the first item in
* the array is not found, the next will be looked for, and
* so on until either one is found, or none are found.
* @param fallback Fallback value if requested values are not found
* @return Misc Meta Info (or "" if none are found);
*/
public String getMetaInfo(final String[] metainfo, final String fallback) {
for (String meta : metainfo) {
String result = metaData.getProperty(meta);
if (result != null) { return result; }
}
return fallback;
}
/**
* Compares this object with the specified object for order.
* Returns a negative integer, zero, or a positive integer as per String.compareTo();
*
* @param o Object to compare to
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(final PluginInfo o) {
return toString().compareTo(o.toString());
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java b/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
index 39bd7463..3fb32018 100644
--- a/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
+++ b/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
@@ -1,270 +1,270 @@
package powercrystals.minefactoryreloaded.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import powercrystals.minefactoryreloaded.api.IToolHammer;
import powercrystals.minefactoryreloaded.gui.MFRCreativeTab;
import powercrystals.minefactoryreloaded.tile.TileRedstoneCable;
import powercrystals.minefactoryreloaded.tile.TileRedstoneCable.ConnectionState;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
public class BlockRedstoneCable extends BlockContainer
{
private static float _wireSize = 0.25F;
private static float _plateWidth = 14.0F / 16.0F;
private static float _plateDepth = 1.0F / 16.0F;
private static float _bandWidth = 5.0F / 16.0F;
private static float _bandOffset = 2.0F / 16.0F;
private static float _bandDepth = 1.0F / 16.0F;
private static float _wireStart = 0.5F - _wireSize / 2.0F;
private static float _wireEnd = 0.5F + _wireSize / 2.0F;
private static float _plateStart = 0.5F - _plateWidth / 2.0F;
private static float _plateEnd = 0.5F + _plateWidth / 2.0F;
private static float _bandWidthStart = 0.5F - _bandWidth / 2.0F;
private static float _bandWidthEnd = 0.5F + _bandWidth / 2.0F;
private static float _bandDepthStart = _bandOffset;
private static float _bandDepthEnd = _bandOffset + _bandDepth;
private static int[] _partSideMappings = new int[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 5, 0, 1, 2, 3 };
public BlockRedstoneCable(int id)
{
super(id, Material.clay);
setUnlocalizedName("mfr.cable.redstone");
setHardness(0.8F);
setCreativeTab(MFRCreativeTab.tab);
}
private AxisAlignedBB[] getParts(TileRedstoneCable cable)
{
ConnectionState csu = cable.getConnectionState(ForgeDirection.UP);
ConnectionState csd = cable.getConnectionState(ForgeDirection.DOWN);
ConnectionState csn = cable.getConnectionState(ForgeDirection.NORTH);
ConnectionState css = cable.getConnectionState(ForgeDirection.SOUTH);
ConnectionState csw = cable.getConnectionState(ForgeDirection.WEST);
ConnectionState cse = cable.getConnectionState(ForgeDirection.EAST);
AxisAlignedBB[] parts = new AxisAlignedBB[15];
parts[0] = AxisAlignedBB.getBoundingBox(csw != ConnectionState.None ? 0 : _wireStart, _wireStart, _wireStart, cse != ConnectionState.None ? 1 : _wireEnd, _wireEnd, _wireEnd);
parts[1] = AxisAlignedBB.getBoundingBox(_wireStart, csd != ConnectionState.None ? 0 : _wireStart, _wireStart, _wireEnd, csu != ConnectionState.None ? 1 : _wireEnd, _wireEnd);
parts[2] = AxisAlignedBB.getBoundingBox(_wireStart, _wireStart, csn != ConnectionState.None ? 0 : _wireStart, _wireEnd, _wireEnd, css != ConnectionState.None ? 1 : _wireEnd);
parts[3] = csw != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(0, _plateStart, _plateStart, _plateDepth, _plateEnd, _plateEnd);
parts[4] = cse != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(1.0F - _plateDepth, _plateStart, _plateStart, 1.0F, _plateEnd, _plateEnd);
parts[5] = csd != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, 0 , _plateStart, _plateEnd, _plateDepth, _plateEnd);
parts[6] = csu != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, 1.0F - _plateDepth, _plateStart, _plateEnd, 1.0F, _plateEnd);
parts[7] = csn != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, _plateStart, 0, _plateEnd, _plateDepth, _plateEnd);
parts[8] = css != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, _plateStart, 1.0F - _plateDepth, _plateEnd, _plateEnd, 1.0F);
parts[9] = csw != ConnectionState.FlatSingle && csw != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandDepthStart, _bandWidthStart, _bandWidthStart, _bandDepthEnd, _bandWidthEnd, _bandWidthEnd);
parts[10] = cse != ConnectionState.FlatSingle && cse != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(1.0F - _bandDepthEnd, _bandWidthStart, _bandWidthStart, 1.0F - _bandDepthStart, _bandDepthEnd, _bandWidthEnd);
parts[11] = csd != ConnectionState.FlatSingle && csd != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandDepthStart, _bandWidthStart, _bandWidthEnd, _bandDepthEnd, _bandWidthEnd);
parts[12] = csu != ConnectionState.FlatSingle && csu != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, 1.0F - _bandDepthEnd, _bandWidthStart, _bandWidthEnd, 1.0F - _bandDepthStart, _bandWidthEnd);
parts[13] = csn != ConnectionState.FlatSingle && csn != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandWidthStart, _bandDepthStart, _bandWidthEnd, _bandWidthEnd, _bandDepthEnd);
parts[14] = css != ConnectionState.FlatSingle && css != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandWidthStart, 1.0F - _bandDepthEnd, _bandWidthEnd, _bandWidthEnd, 1.0F - _bandDepthStart);
return parts;
}
private int getPartClicked(EntityPlayer player, double reachDistance, TileRedstoneCable cable)
{
AxisAlignedBB[] wireparts = getParts(cable);
Vec3 playerPosition = Vec3.createVectorHelper(player.posX - cable.xCoord, player.posY - cable.yCoord + player.getEyeHeight(), player.posZ - cable.zCoord);
Vec3 playerLook = player.getLookVec();
Vec3 playerViewOffset = Vec3.createVectorHelper(playerPosition.xCoord + playerLook.xCoord * reachDistance, playerPosition.yCoord + playerLook.yCoord * reachDistance, playerPosition.zCoord + playerLook.zCoord * reachDistance);
int closest = -1;
double closestdistance = Double.MAX_VALUE;
for(int i = 0; i < wireparts.length; i++)
{
AxisAlignedBB part = wireparts[i];
if(part == null)
{
continue;
}
MovingObjectPosition hit = part.calculateIntercept(playerPosition, playerViewOffset);
if(hit != null)
{
double distance = playerPosition.distanceTo(hit.hitVec);
if(distance < closestdistance)
{
distance = closestdistance;
closest = i;
}
}
}
return closest;
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
ItemStack s = player.inventory.getCurrentItem();
if(s != null && s.getItem() instanceof IToolHammer)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
return true;
}
}
else if(s != null && s.itemID == Item.dyePowder.itemID)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
- cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], s.getItemDamage());
+ cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], 15 - s.getItemDamage());
world.markBlockForUpdate(x, y, z);
return true;
}
}
}
}
return false;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
super.setBlockBoundsBasedOnState(world, x, y, z);
/*
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
float xMin = cable.getConnectionState(ForgeDirection.WEST) != ConnectionState.None ? 0 : 0.375F;
float xMax = cable.getConnectionState(ForgeDirection.EAST) != ConnectionState.None ? 1 : 0.625F;
float yMin = cable.getConnectionState(ForgeDirection.DOWN) != ConnectionState.None ? 0 : 0.375F;
float yMax = cable.getConnectionState(ForgeDirection.UP) != ConnectionState.None ? 1 : 0.625F;
float zMin = cable.getConnectionState(ForgeDirection.NORTH) != ConnectionState.None ? 0 : 0.375F;
float zMax = cable.getConnectionState(ForgeDirection.SOUTH) != ConnectionState.None ? 1 : 0.625F;
setBlockBounds(xMin, yMin, zMin, xMax, yMax, zMax);
}*/
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, int blockId)
{
super.onNeighborBlockChange(world, x, y, z, blockId);
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
((TileRedstoneCable)te).onNeighboorChanged();
}
}
@Override
public void breakBlock(World world, int x, int y, int z, int id, int meta)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
((TileRedstoneCable)te).getNetwork().setInvalid();
}
super.breakBlock(world, x, y, z, id, meta);
}
@Override
public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int side)
{
int power = 0;
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
int subnet = ((TileRedstoneCable)te).getSideColor(ForgeDirection.VALID_DIRECTIONS[side].getOpposite());
power = ((TileRedstoneCable)te).getNetwork().getPowerLevelOutput(subnet);
//System.out.println("Asked for weak power at " + x + "," + y + "," + z + " - got " + power + " from network " + ((TileRedstoneCable)te).getNetwork().getId() + ":" + subnet);
}
return power;
}
@Override
public int isProvidingStrongPower(IBlockAccess world, int x, int y, int z, int side)
{
int power = 0;
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
int subnet = ((TileRedstoneCable)te).getSideColor(ForgeDirection.VALID_DIRECTIONS[side].getOpposite());
power = ((TileRedstoneCable)te).getNetwork().getPowerLevelOutput(subnet);
//System.out.println("Asked for strong power at " + x + "," + y + "," + z + " - got " + power + " from network " + ((TileRedstoneCable)te).getNetwork().getId() + ":" + subnet);
}
return power;
}
@Override
public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side)
{
return true;
}
@Override
public boolean canProvidePower()
{
return true;
}
@Override
public TileEntity createNewTileEntity(World world)
{
return new TileRedstoneCable();
}
@Override
public int getRenderType()
{
return MineFactoryReloadedCore.renderIdRedstoneCable;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister ir)
{
blockIcon = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName());
}
}
| true | true | public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
ItemStack s = player.inventory.getCurrentItem();
if(s != null && s.getItem() instanceof IToolHammer)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
return true;
}
}
else if(s != null && s.itemID == Item.dyePowder.itemID)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], s.getItemDamage());
world.markBlockForUpdate(x, y, z);
return true;
}
}
}
}
return false;
}
| public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
ItemStack s = player.inventory.getCurrentItem();
if(s != null && s.getItem() instanceof IToolHammer)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
return true;
}
}
else if(s != null && s.itemID == Item.dyePowder.itemID)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], 15 - s.getItemDamage());
world.markBlockForUpdate(x, y, z);
return true;
}
}
}
}
return false;
}
|
diff --git a/web/src/main/java/org/openmrs/web/form/visit/VisitEncounterHandlerFormValidator.java b/web/src/main/java/org/openmrs/web/form/visit/VisitEncounterHandlerFormValidator.java
index 7a155ac2..93a05e1d 100644
--- a/web/src/main/java/org/openmrs/web/form/visit/VisitEncounterHandlerFormValidator.java
+++ b/web/src/main/java/org/openmrs/web/form/visit/VisitEncounterHandlerFormValidator.java
@@ -1,40 +1,40 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.form.visit;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Validates {@link VisitEncounterHandlerForm}
*/
public class VisitEncounterHandlerFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return VisitEncounterHandlerForm.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
VisitEncounterHandlerForm form = (VisitEncounterHandlerForm) target;
if (form.isEnableVisits()) {
- ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterVisitHandler",
+ ValidationUtils.rejectIfEmptyOrWhitespace(errors, "visitEncounterHandler",
"Encounter.error.visits.handler.empty");
}
}
}
| true | true | public void validate(Object target, Errors errors) {
VisitEncounterHandlerForm form = (VisitEncounterHandlerForm) target;
if (form.isEnableVisits()) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterVisitHandler",
"Encounter.error.visits.handler.empty");
}
}
| public void validate(Object target, Errors errors) {
VisitEncounterHandlerForm form = (VisitEncounterHandlerForm) target;
if (form.isEnableVisits()) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "visitEncounterHandler",
"Encounter.error.visits.handler.empty");
}
}
|
diff --git a/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java b/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
index 4dacab2..daf4a42 100644
--- a/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
+++ b/Interpreter/src/edu/tum/lua/junit/stdlib/ToNumberTest.java
@@ -1,67 +1,67 @@
package edu.tum.lua.junit.stdlib;
import static org.junit.Assert.*;
import java.util.LinkedList;
import org.junit.Test;
import edu.tum.lua.LuaRuntimeException;
import edu.tum.lua.stdlib.ToNumber;
public class ToNumberTest {
@Test
public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
- l = new LinkedList<Object>();
- l.add("Hello123");
- assertEquals("Translating a false String", null, p.apply(l).get(0));
+ // l = new LinkedList<Object>();
+ // l.add("Hello123");
+ // assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
}
| true | true | public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("Hello123");
assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
| public void test() {
ToNumber p = new ToNumber();
LinkedList<Object> l;
l = new LinkedList<Object>();
try {
p.apply(l);
fail("Accept empty input");
} catch (LuaRuntimeException e) {
assertTrue("Don't accept empty input", true);
} catch (Exception e) {
fail("Unknow exception");
}
l.add("1234");
assertEquals("Translating a true int String", 1234, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("42.21");
assertEquals("Translating a true double String", new Double(42.21), p.apply(l).get(0));
// l = new LinkedList<Object>();
// l.add("Hello123");
// assertEquals("Translating a false String", null, p.apply(l).get(0));
l = new LinkedList<Object>();
l.add("FF");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 255, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("10");
l.add(new Integer(16));
assertEquals("Translating a String, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add("Z");
l.add(new Integer(36));
assertEquals("Translating a String, Base", 35, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(16));
assertEquals("Translating a Number, Base", 10, (int) Math.ceil((double) p.apply(l).get(0)));
l = new LinkedList<Object>();
l.add(new Integer(10));
l.add(new Integer(5));
assertEquals("Translating a Number, Base < Number", null, (double) p.apply(l).get(0));
}
|
diff --git a/projects/samskivert/src/java/com/samskivert/util/OneLineLogFormatter.java b/projects/samskivert/src/java/com/samskivert/util/OneLineLogFormatter.java
index 4ec33076..15ec58a8 100644
--- a/projects/samskivert/src/java/com/samskivert/util/OneLineLogFormatter.java
+++ b/projects/samskivert/src/java/com/samskivert/util/OneLineLogFormatter.java
@@ -1,120 +1,121 @@
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2004 Michael Bayne
//
// 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.
//
// 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.samskivert.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* A briefer formatter than the default Java {@link SimpleFormatter}.
*/
public class OneLineLogFormatter extends Formatter
{
// documentation inherited
public String format (LogRecord record)
{
StringBuffer buf = new StringBuffer();
// append the timestamp
_date.setTime(record.getMillis());
_format.format(_date, buf, _fpos);
// append the log level
buf.append(" ");
buf.append(record.getLevel().getLocalizedName());
// append the log method call context
buf.append(" ");
String where = record.getSourceClassName();
boolean legacy = (where.indexOf("LoggingLogProvider") != -1);
if (where != null && !legacy) {
String logger = record.getLoggerName();
- if (logger != null && where.startsWith(logger)) {
+ if (logger != null && where.startsWith(logger) &&
+ where.length() > logger.length()) {
where = where.substring(logger.length()+1);
}
} else {
where = record.getLoggerName();
}
buf.append(where);
if (record.getSourceMethodName() != null && !legacy) {
buf.append(".");
buf.append(record.getSourceMethodName());
}
// append the message itself
buf.append(": ");
buf.append(formatMessage(record));
buf.append(LINE_SEPARATOR);
// if an exception was also provided, append that
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
buf.append(sw.toString());
} catch (Exception ex) {
}
}
return buf.toString();
}
/**
* Configures the default logging handler to use an instance of this
* formatter when formatting messages.
*/
public static void configureDefaultHandler ()
{
Logger logger = LogManager.getLogManager().getLogger("");
Handler[] handlers = logger.getHandlers();
OneLineLogFormatter formatter = new OneLineLogFormatter();
for (int ii = 0; ii < handlers.length; ii++) {
handlers[ii].setFormatter(formatter);
}
}
protected Date _date = new Date();
protected SimpleDateFormat _format =
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
protected FieldPosition _fpos =
new FieldPosition(SimpleDateFormat.DATE_FIELD);
protected static String LINE_SEPARATOR = "\n";
protected static final String DATE_FORMAT = "{0,date} {0,time}";
static {
try {
LINE_SEPARATOR = System.getProperty("line.separator");
} catch (Exception e) {
}
}
}
| true | true | public String format (LogRecord record)
{
StringBuffer buf = new StringBuffer();
// append the timestamp
_date.setTime(record.getMillis());
_format.format(_date, buf, _fpos);
// append the log level
buf.append(" ");
buf.append(record.getLevel().getLocalizedName());
// append the log method call context
buf.append(" ");
String where = record.getSourceClassName();
boolean legacy = (where.indexOf("LoggingLogProvider") != -1);
if (where != null && !legacy) {
String logger = record.getLoggerName();
if (logger != null && where.startsWith(logger)) {
where = where.substring(logger.length()+1);
}
} else {
where = record.getLoggerName();
}
buf.append(where);
if (record.getSourceMethodName() != null && !legacy) {
buf.append(".");
buf.append(record.getSourceMethodName());
}
// append the message itself
buf.append(": ");
buf.append(formatMessage(record));
buf.append(LINE_SEPARATOR);
// if an exception was also provided, append that
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
buf.append(sw.toString());
} catch (Exception ex) {
}
}
return buf.toString();
}
| public String format (LogRecord record)
{
StringBuffer buf = new StringBuffer();
// append the timestamp
_date.setTime(record.getMillis());
_format.format(_date, buf, _fpos);
// append the log level
buf.append(" ");
buf.append(record.getLevel().getLocalizedName());
// append the log method call context
buf.append(" ");
String where = record.getSourceClassName();
boolean legacy = (where.indexOf("LoggingLogProvider") != -1);
if (where != null && !legacy) {
String logger = record.getLoggerName();
if (logger != null && where.startsWith(logger) &&
where.length() > logger.length()) {
where = where.substring(logger.length()+1);
}
} else {
where = record.getLoggerName();
}
buf.append(where);
if (record.getSourceMethodName() != null && !legacy) {
buf.append(".");
buf.append(record.getSourceMethodName());
}
// append the message itself
buf.append(": ");
buf.append(formatMessage(record));
buf.append(LINE_SEPARATOR);
// if an exception was also provided, append that
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
buf.append(sw.toString());
} catch (Exception ex) {
}
}
return buf.toString();
}
|
diff --git a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
index 100a804e6f..5bf246cddd 100644
--- a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
+++ b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
@@ -1,1660 +1,1661 @@
package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import org.eclipse.imp.pdb.facts.IBool;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IDateTime;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.INode;
import org.eclipse.imp.pdb.facts.INumber;
import org.eclipse.imp.pdb.facts.IRational;
import org.eclipse.imp.pdb.facts.IReal;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.ISourceLocation;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.IValueFactory;
import org.eclipse.imp.pdb.facts.type.ITypeVisitor;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.interpreter.IEvaluatorContext;
import org.rascalmpl.interpreter.control_exceptions.Throw;
import org.rascalmpl.interpreter.types.FunctionType;
import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.Instructions.Opcode;
public class RVM {
public final IValueFactory vf;
private final TypeFactory tf;
private final Boolean TRUE;
private final Boolean FALSE;
private final IBool Rascal_TRUE;
private final IBool Rascal_FALSE;
private final IString NONE;
private final Failure FAILURE = Failure.getInstance();
private boolean debug = true;
private boolean listing = false;
private boolean finalized = false;
private final ArrayList<Function> functionStore;
private final Map<String, Integer> functionMap;
// Function overloading
private final Map<String, Integer> resolver;
private final ArrayList<OverloadedFunction> overloadedStore;
private final TypeStore typeStore = new TypeStore();
private final Types types;
private final ArrayList<Type> constructorStore;
private final Map<String, Integer> constructorMap;
private IMap grammars;
private final Map<IValue, IValue> moduleVariables;
PrintWriter stdout;
PrintWriter stderr;
// Management of active coroutines
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (of the coroutine's main function) of the current active coroutine
IEvaluatorContext ctx;
public RVM(IValueFactory vf, IEvaluatorContext ctx, boolean debug, boolean profile) {
super();
this.vf = vf;
tf = TypeFactory.getInstance();
this.ctx = ctx;
this.stdout = ctx.getStdOut();
this.stderr = ctx.getStdErr();
this.debug = debug;
this.finalized = false;
this.types = new Types(this.vf);
TRUE = true;
FALSE = false;
Rascal_TRUE = vf.bool(true);
Rascal_FALSE = vf.bool(false);
NONE = vf.string("$nothing$");
functionStore = new ArrayList<Function>();
constructorStore = new ArrayList<Type>();
functionMap = new HashMap<String, Integer>();
constructorMap = new HashMap<String, Integer>();
resolver = new HashMap<String,Integer>();
overloadedStore = new ArrayList<OverloadedFunction>();
moduleVariables = new HashMap<IValue,IValue>();
MuPrimitive.init(vf, stdout, profile);
RascalPrimitive.init(vf, this, profile);
Opcode.init(stdout, profile);
}
public RVM(IValueFactory vf){
this(vf, null, false, false);
}
public void declare(Function f){
if(functionMap.get(f.getName()) != null){
throw new RuntimeException("PANIC: Double declaration of function: " + f.getName());
}
functionMap.put(f.getName(), functionStore.size());
functionStore.add(f);
}
public void declareConstructor(String name, IConstructor symbol) {
Type constr = types.symbolToType(symbol, typeStore);
if(constructorMap.get(name) != null) {
throw new RuntimeException("PANIC: Double declaration of constructor: " + name);
}
constructorMap.put(name, constructorStore.size());
constructorStore.add(constr);
}
public Type symbolToType(IConstructor symbol) {
return types.symbolToType(symbol, typeStore);
}
public void addResolver(IMap resolver) {
for(IValue fuid : resolver) {
String of = ((IString) fuid).getValue();
int index = ((IInteger) resolver.get(fuid)).intValue();
this.resolver.put(of, index);
}
}
public void fillOverloadedStore(IList overloadedStore) {
for(IValue of : overloadedStore) {
ITuple ofTuple = (ITuple) of;
String scopeIn = ((IString) ofTuple.get(0)).getValue();
if(scopeIn.equals("")) {
scopeIn = null;
}
IList fuids = (IList) ofTuple.get(1);
int[] funs = new int[fuids.length()];
int i = 0;
for(IValue fuid : fuids) {
Integer index = functionMap.get(((IString) fuid).getValue());
if(index == null){
throw new RuntimeException("No definition for " + fuid + " in functionMap");
}
funs[i++] = index;
}
fuids = (IList) ofTuple.get(2);
int[] constrs = new int[fuids.length()];
i = 0;
for(IValue fuid : fuids) {
Integer index = constructorMap.get(((IString) fuid).getValue());
if(index == null){
throw new RuntimeException("No definition for " + fuid + " in constructorMap");
}
constrs[i++] = index;
}
this.overloadedStore.add(new OverloadedFunction(funs, constrs, scopeIn));
}
}
public void setGrammars(IMap grammer){
this.grammars = grammars;
}
public IMap getGrammars(){
return grammars;
}
/**
* Narrow an Object as occurring on the RVM runtime stack to an IValue that can be returned.
* Note that various non-IValues can occur:
* - Coroutine
* - Reference
* - FunctionInstance
* - Object[] (is converted to an IList)
* @param result to be returned
* @return converted result or an exception
*/
private IValue narrow(Object result){
if(result instanceof Boolean) {
return vf.bool((Boolean) result);
}
if(result instanceof Integer) {
return vf.integer((Integer)result);
}
if(result instanceof IValue) {
return (IValue) result;
}
if(result instanceof Thrown) {
((Thrown) result).printStackTrace(stdout);
return vf.string(((Thrown) result).toString());
}
if(result instanceof Object[]) {
IListWriter w = vf.listWriter();
Object[] lst = (Object[]) result;
for(int i = 0; i < lst.length; i++){
w.append(narrow(lst[i]));
}
return w.done();
}
throw new RuntimeException("PANIC: Cannot convert object back to IValue: " + result);
}
/**
* Represent any object that can occur on the RVM stack stack as string
* @param some stack object
* @return its string representation
*/
private String asString(Object o){
if(o == null)
return "null";
if(o instanceof Boolean)
return ((Boolean) o).toString() + " [Java]";
if(o instanceof Integer)
return ((Integer)o).toString() + " [Java]";
if(o instanceof IValue)
return ((IValue) o).toString() +" [IValue]";
if(o instanceof Type)
return ((Type) o).toString() + " [Type]";
if(o instanceof Object[]){
StringBuilder w = new StringBuilder();
Object[] lst = (Object[]) o;
w.append("[");
for(int i = 0; i < lst.length; i++){
w.append(asString(lst[i]));
if(i < lst.length - 1)
w.append(", ");
}
w.append("]");
return w.toString() + " [Object[]]";
}
if(o instanceof Coroutine){
return "Coroutine[" + ((Coroutine)o).frame.function.getName() + "]";
}
if(o instanceof Function){
return "Function[" + ((Function)o).getName() + "]";
}
if(o instanceof FunctionInstance){
return "Function[" + ((FunctionInstance)o).function.getName() + "]";
}
if(o instanceof OverloadedFunctionInstance) {
OverloadedFunctionInstance of = (OverloadedFunctionInstance) o;
String alts = "";
for(Integer fun : of.functions) {
alts = alts + functionStore.get(fun).getName() + "; ";
}
return "OverloadedFunction[ alts: " + alts + "]";
}
if(o instanceof Reference){
Reference ref = (Reference) o;
return "Reference[" + ref.stack + ", " + ref.pos + "]";
}
if(o instanceof IListWriter){
return "ListWriter[" + ((IListWriter) o).toString() + "]";
}
if(o instanceof ISetWriter){
return "SetWriter[" + ((ISetWriter) o).toString() + "]";
}
if(o instanceof IMapWriter){
return "MapWriter[" + ((IMapWriter) o).toString() + "]";
}
if(o instanceof Matcher){
return "Matcher[" + ((Matcher) o).pattern() + "]";
}
if(o instanceof Thrown) {
return "THROWN[ " + asString(((Thrown) o).value) + " ]";
}
if(o instanceof StringBuilder){
return "StringBuilder[" + ((StringBuilder) o).toString() + "]";
}
if(o instanceof HashSet){
return "HashSet[" + ((HashSet) o).toString() + "]";
}
throw new RuntimeException("PANIC: asString cannot convert: " + o);
}
public void finalize(){
// Finalize the instruction generation of all functions, if needed
if(!finalized){
finalized = true;
for(Function f : functionStore) {
f.finalize(functionMap, constructorMap, resolver, listing);
}
for(OverloadedFunction of : overloadedStore) {
of.finalize(functionMap);
}
}
}
public String getFunctionName(int n) {
for(String fname : functionMap.keySet()) {
if(functionMap.get(fname) == n) {
return fname;
}
}
throw new RuntimeException("PANIC: undefined function index " + n);
}
public String getConstructorName(int n) {
for(String cname : constructorMap.keySet()) {
if(constructorMap.get(cname) == n) {
return cname;
}
}
throw new RuntimeException("PANIC: undefined constructor index " + n);
}
public String getOverloadedFunctionName(int n) {
for(String ofname : resolver.keySet()) {
if(resolver.get(ofname) == n) {
return ofname;
}
}
throw new RuntimeException("PANIC: undefined overloaded function index " + n);
}
public IValue executeFunction(String uid_func, IValue[] args){
// Assumption here is that the function called is not nested one
// and does not use global variables
Function func = functionStore.get(functionMap.get(uid_func));
Frame root = new Frame(func.scopeId, null, func.maxstack, func);
Frame cf = root;
// Pass the program arguments to main
for(int i = 0; i < args.length; i++){
cf.stack[i] = args[i];
}
Object o = executeProgram(root, cf);
if(o instanceof Thrown){
throw (Thrown) o;
}
return narrow(o);
}
private Frame pushArguments(Frame cf, Function func, Frame env, IValue[] args) {
cf = new Frame(func.scopeId, cf, env, func.maxstack, func);
if(func.isVarArgs) { // VarArgs
for(int i = 0; i < func.nformals - 2; i++) {
cf.stack[i] = args[i];
}
Type argTypes = ((FunctionType) func.ftype).getArgumentTypes();
if(args.length == func.nformals
&& args[func.nformals - 2].getType().isSubtypeOf(argTypes.getFieldType(func.nformals - 2))) {
cf.stack[func.nformals - 2] = args[func.nformals - 2];
} else {
IListWriter writer = vf.listWriter();
for(int i = func.nformals - 2; i < args.length - 1; i++) {
writer.append((IValue) args[i]);
}
cf.stack[func.nformals - 2] = writer.done();
}
cf.stack[func.nformals - 1] = args[args.length - 1]; // Keyword arguments
} else {
for(int i = 0; i < args.length; i++){
cf.stack[i] = args[i];
}
}
cf.sp = func.nlocals;
return cf;
}
private String trace = "";
public String getTrace() {
return trace;
}
public void appendToTrace(String trace) {
this.trace = this.trace + trace + "\n";
}
public IValue executeProgram(String uid_main, IValue[] args) {
finalize();
Function main_function = functionStore.get(functionMap.get(uid_main));
if (main_function == null) {
throw new RuntimeException("PANIC: No function " + uid_main + " found");
}
if (main_function.nformals != 2) { // List of IValues and empty map of keyword parameters
throw new RuntimeException("PANIC: function " + uid_main + " should have two arguments");
}
Frame root = new Frame(main_function.scopeId, null, main_function.maxstack, main_function);
Frame cf = root;
cf.stack[0] = vf.list(args); // pass the program argument to main_function as a IList object
cf.stack[1] = vf.mapWriter().done();
Object o = executeProgram(root, cf);
if(o != null && o instanceof Thrown){
throw (Thrown) o;
}
IValue res = narrow(o);
if(debug) {
stdout.println("TRACE:");
stdout.println(getTrace());
}
return res;
}
private Object executeProgram(Frame root, Frame cf) {
Object[] stack = cf.stack; // current stack
int sp = cf.function.nlocals; // current stack pointer
int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence
int pc = 0; // current program counter
int postOp = 0;
int pos = 0;
ArrayList<Frame> stacktrace;
Thrown thrown;
int arity;
String last_function_name = "";
// Overloading specific
Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>();
OverloadedFunctionInstanceCall c_ofun_call = null;
try {
NEXT_INSTRUCTION: while (true) {
// if(pc < 0 || pc >= instructions.length){
// throw new RuntimeException(cf.function.name + " illegal pc: " + pc);
// }
int instruction = instructions[pc++];
int op = CodeBlock.fetchOp(instruction);
if (debug) {
int startpc = pc - 1;
if(!last_function_name.equals(cf.function.name))
stdout.printf("[%03d] %s\n", startpc, cf.function.name);
for (int i = 0; i < sp; i++) {
stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i]));
}
stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc));
}
Opcode.use(instruction);
switch (op) {
case Opcode.OP_POP:
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOC0:
if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; }
pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC1:
if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; }
pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC2:
if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; }
pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC3:
if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; }
pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC4:
if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; }
pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC5:
if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; }
pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC6:
if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; }
pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC7:
if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; }
pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC8:
if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; }
pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC9:
if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; }
pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC:
pos = CodeBlock.fetchArg1(instruction);
Object rval = stack[pos];
if(rval != null){
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
postOp = Opcode.POSTOP_CHECKUNDEF;
break;
case Opcode.OP_LOADBOOL:
stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADINT:
stack[sp++] = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCREF:
stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLMUPRIM:
MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_JMP:
pc = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPESWITCH:
IValue val = (IValue) stack[--sp];
Type t = null;
if(val instanceof IConstructor) {
t = ((IConstructor) val).getConstructorType();
} else {
t = val.getType();
}
int labelIndex = ToplevelType.getToplevelTypeAsInt(t);
IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPINDEXED:
labelIndex = ((IInteger) stack[--sp]).intValue();
labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADTYPE:
stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCDEREF: {
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOC: {
stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_UNWRAPTHROWN: {
stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value;
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOCDEREF:
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, get the function code
Function fun = functionStore.get(CodeBlock.fetchArg1(instruction));
int scopeIn = CodeBlock.fetchArg2(instruction);
// Second, look up the function environment frame into the stack of caller frames
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scopeIn) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn);
}
case Opcode.OP_LOADOFUN:
OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
if(of.scopeIn == -1) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root);
continue NEXT_INSTRUCTION;
}
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == of.scopeIn) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn);
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
stack[sp++] = constructor;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVARREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
rval = moduleVariables.get(cf.function.constantStore[s]);
if(op == Opcode.OP_LOADVAR && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
if(op == Opcode.OP_LOADLOC && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARDEREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s);
}
case Opcode.OP_STOREVAR:
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
IValue mvar = cf.function.constantStore[s];
moduleVariables.put(mvar, (IValue)stack[sp -1]);
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARDEREF:
s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s);
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == constructor.getArity();
IValue[] args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
arity = CodeBlock.fetchArg1(instruction); // TODO: add assert
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == fun.nformals;
previousScope = cf;
} else {
throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1]));
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue NEXT_INSTRUCTION;
case Opcode.OP_OCALLDYN:
case Opcode.OP_OCALL:
Object funcObject = (op == Opcode.OP_OCALLDYN) ? stack[--sp] : null;
// Get function arguments from the stack
arity = CodeBlock.fetchArg2(instruction);
args = new IValue[arity];
for(int i = arity - 1; i >= 0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
if(op == Opcode.OP_OCALLDYN) {
// Get function types to perform a type-based dynamic resolution
Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction));
// Objects of three types may appear on the stack:
// 1. FunctionInstance due to closures
// 2. OverloadedFunctionInstance due to named Rascal functions
if(funcObject instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) funcObject;
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(cf, fun_instance.function, fun_instance.env, args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject;
c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types);
} else {
of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null);
}
ocalls.push(c_ofun_call);
if(debug) {
if(op == Opcode.OP_OCALL) {
this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction)));
} else {
this.appendToTrace("OVERLOADED FUNCTION CALLDYN: ");
}
this.appendToTrace(" with alternatives:");
for(int index : c_ofun_call.functions) {
this.appendToTrace(" " + getFunctionName(index));
}
}
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = fun.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FAILRETURN:
assert cf.previousCallFrame == c_ofun_call.cf;
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
cf = c_ofun_call.cf;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FILTERRETURN:
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
// Overloading specific
if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
rval = null;
boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN;
if(op == Opcode.OP_RETURN1 || cf.isCoroutine) {
if(cf.isCoroutine) {
rval = Rascal_TRUE;
if(op == Opcode.OP_RETURN1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = cf.function.refs;
if(arity != refs.length) {
throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")");
}
for(int i = 0; i < arity; i++) {
ref = (Reference) stack[refs[arity - 1 - i]];
ref.stack[ref.pos] = stack[--sp];
}
}
} else {
rval = stack[sp - 1];
}
}
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns) {
return rval;
} else {
return NONE;
}
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns) {
stack[sp++] = rval;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLJAVA:
String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]];
int reflect = instructions[pc++];
arity = parameterTypes.getArity();
try {
sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp);
} catch(Throw e) {
thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>());
// EXCEPTION HANDLING
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_INIT:
arity = CodeBlock.fetchArg1(instruction);
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src);
}
if(coroutine.isInitialized()) {
throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName());
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp) {
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName());
}
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
sp = sp - arity; /* Place coroutine back on stack */
stack[sp++] = newCoroutine;
// Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension
newCoroutine.suspend(newCoroutine.frame);
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(newCoroutine);
ccf = newCoroutine.start;
newCoroutine.next(cf);
fun = newCoroutine.frame.function;
instructions = newCoroutine.frame.function.codeblock.getInstructions();
cf.pc = pc;
cf.sp = sp;
cf = newCoroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_GUARD:
rval = stack[sp - 1];
boolean precondition;
if(rval instanceof IBool) {
precondition = ((IBool) rval).getValue();
} else if(rval instanceof Boolean) {
precondition = (Boolean) rval;
} else {
throw new RuntimeException("Guard's expression has to be boolean!");
}
if(cf == ccf) {
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = cf.previousCallFrame;
if(precondition) {
coroutine.suspend(cf);
}
--sp;
cf.pc = pc;
cf.sp = sp;
cf = prev;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
if(!precondition) {
cf.pc = pc;
cf.sp = sp;
cf = cf.previousCallFrame;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE;
continue NEXT_INSTRUCTION;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
if(op == Opcode.OP_CREATE){
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
previousScope = null;
if(fun.scopeIn != -1) {
for(Frame f = cf; f != null; f = f.previousCallFrame) {
if (f.scopeId == fun.scopeIn) {
previousScope = f;
+ break;
}
}
if(previousScope == null) {
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + fun.scopeIn);
}
}
} else {
arity = CodeBlock.fetchArg1(instruction);
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src));
}
}
Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue NEXT_INSTRUCTION;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// Merged the hasNext and next semantics
if(!coroutine.hasNext()) {
if(op == Opcode.OP_NEXT1) {
--sp;
}
stack[sp++] = FALSE;
continue NEXT_INSTRUCTION;
}
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = Rascal_TRUE; // In fact, yield has to always return TRUE
if(op == Opcode.OP_YIELD1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance
if(cf != coroutine.start && cf.function.refs.length != refs.length) {
throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length);
}
if(arity != refs.length) {
throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length);
}
for(int i = 0; i < arity; i++) {
ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance
ref.stack[ref.pos] = stack[--sp];
}
}
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = rval; // Corresponding next will always find an entry on the stack
continue NEXT_INSTRUCTION;
case Opcode.OP_EXHAUST:
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
continue NEXT_INSTRUCTION;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLPRIM:
RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
try {
sp = prim.invoke(stack, sp, arity);
} catch(InvocationTargetException targetException) {
if(!(targetException.getTargetException() instanceof Thrown)) {
throw targetException;
}
// EXCEPTION HANDLING
thrown = (Thrown) targetException.getTargetException();
thrown.stacktrace.add(cf);
sp = sp - arity;
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
// Some specialized MuPrimitives
case Opcode.OP_SUBSCRIPTARRAY:
stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])];
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBSCRIPTLIST:
stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LESSINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_GREATEREQUALINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ADDINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTRACTINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ANDBOOL:
boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue();
boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue();
stack[sp - 2] = b1 && b2;
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPEOF:
if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching
@SuppressWarnings("unchecked")
HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1];
if(mset.isEmpty()){
stack[sp - 1] = tf.setType(tf.voidType());
} else {
IValue v = mset.iterator().next();
stack[sp - 1] = tf.setType(v.getType());
}
} else {
stack[sp - 1] = ((IValue) stack[sp - 1]).getType();
}
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTYPE:
stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_CHECKARGTYPE:
Type argType = ((IValue) stack[sp - 2]).getType();
Type paramType = ((Type) stack[sp - 1]);
stack[sp - 2] = argType.isSubtypeOf(paramType);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LABEL:
throw new RuntimeException("label instruction at runtime");
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
arity = CodeBlock.fetchArg1(instruction);
StringBuilder w = new StringBuilder();
for(int i = arity - 1; i >= 0; i--){
String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]);
w.append(str).append(" ");
}
stdout.println(w.toString());
sp = sp - arity + 1;
continue NEXT_INSTRUCTION;
case Opcode.OP_THROW:
Object obj = stack[--sp];
thrown = null;
if(obj instanceof IValue) {
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = Thrown.getInstance((IValue) obj, null, stacktrace);
} else {
// Then, an object of type 'Thrown' is on top of the stack
thrown = (Thrown) obj;
}
// First, try to find a handler in the current frame function,
// given the current instruction index and the value type,
// then, if not found, look up the caller function(s)
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
case Opcode.OP_LOADLOCKWP:
IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
@SuppressWarnings("unchecked")
Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals];
Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue());
for(Frame f = cf; f != null; f = f.previousCallFrame) {
IMap kargs = (IMap) f.stack[f.function.nformals - 1];
if(kargs.containsKey(name)) {
val = kargs.get(name);
if(val.getType().isSubtypeOf(defaultValue.getKey())) {
stack[sp++] = val;
continue NEXT_INSTRUCTION;
}
}
}
stack[sp++] = defaultValue.getValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVARKWP:
continue NEXT_INSTRUCTION;
case Opcode.OP_STORELOCKWP:
val = (IValue) stack[sp - 1];
name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
IMap kargs = (IMap) stack[cf.function.nformals - 1];
stack[cf.function.nformals - 1] = kargs.put(name, val);
continue NEXT_INSTRUCTION;
case Opcode.OP_STOREVARKWP:
continue NEXT_INSTRUCTION;
default:
throw new RuntimeException("RVM main loop -- cannot decode instruction");
}
switch(postOp){
case Opcode.POSTOP_CHECKUNDEF:
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
}
} catch (Exception e) {
e.printStackTrace(stderr);
throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() );
//stdout.println("PANIC: (instruction execution): " + e.getMessage());
//e.printStackTrace();
//stderr.println(e.getStackTrace());
}
}
int callJavaMethod(String methodName, String className, Type parameterTypes, int reflect, Object[] stack, int sp) throws Throw {
Class<?> clazz = null;
try {
try {
clazz = this.getClass().getClassLoader().loadClass(className);
} catch(ClassNotFoundException e1) {
// If the class is not found, try other class loaders
for(ClassLoader loader : ctx.getEvaluator().getClassLoaders()) {
try {
clazz = loader.loadClass(className);
break;
} catch(ClassNotFoundException e2) {
;
}
}
}
if(clazz == null) {
throw new RuntimeException("Class not found: " + className);
}
Constructor<?> cons;
cons = clazz.getConstructor(IValueFactory.class);
Object instance = cons.newInstance(vf);
Method m = clazz.getMethod(methodName, makeJavaTypes(parameterTypes, reflect));
int nformals = parameterTypes.getArity();
Object[] parameters = new Object[nformals + reflect];
for(int i = 0; i < nformals; i++){
parameters[i] = stack[sp - nformals + i];
}
if(reflect == 1) {
parameters[nformals] = this.ctx;
}
stack[sp - nformals] = m.invoke(instance, parameters);
return sp - nformals + 1;
}
// catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
if(e.getTargetException() instanceof Throw) {
throw (Throw) e.getTargetException();
}
e.printStackTrace();
}
return sp;
}
Class<?>[] makeJavaTypes(Type parameterTypes, int reflect){
JavaClasses javaClasses = new JavaClasses();
int arity = parameterTypes.getArity() + reflect;
Class<?>[] jtypes = new Class<?>[arity];
for(int i = 0; i < parameterTypes.getArity(); i++){
jtypes[i] = parameterTypes.getFieldType(i).accept(javaClasses);
}
if(reflect == 1) {
try {
jtypes[arity - 1] = this.getClass().getClassLoader().loadClass("org.rascalmpl.interpreter.IEvaluatorContext");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return jtypes;
}
private static class JavaClasses implements ITypeVisitor<Class<?>, RuntimeException> {
@Override
public Class<?> visitBool(org.eclipse.imp.pdb.facts.type.Type boolType) {
return IBool.class;
}
@Override
public Class<?> visitReal(org.eclipse.imp.pdb.facts.type.Type type) {
return IReal.class;
}
@Override
public Class<?> visitInteger(org.eclipse.imp.pdb.facts.type.Type type) {
return IInteger.class;
}
@Override
public Class<?> visitRational(org.eclipse.imp.pdb.facts.type.Type type) {
return IRational.class;
}
@Override
public Class<?> visitNumber(org.eclipse.imp.pdb.facts.type.Type type) {
return INumber.class;
}
@Override
public Class<?> visitList(org.eclipse.imp.pdb.facts.type.Type type) {
return IList.class;
}
@Override
public Class<?> visitMap(org.eclipse.imp.pdb.facts.type.Type type) {
return IMap.class;
}
@Override
public Class<?> visitAlias(org.eclipse.imp.pdb.facts.type.Type type) {
return type.getAliased().accept(this);
}
@Override
public Class<?> visitAbstractData(org.eclipse.imp.pdb.facts.type.Type type) {
return IConstructor.class;
}
@Override
public Class<?> visitSet(org.eclipse.imp.pdb.facts.type.Type type) {
return ISet.class;
}
@Override
public Class<?> visitSourceLocation(org.eclipse.imp.pdb.facts.type.Type type) {
return ISourceLocation.class;
}
@Override
public Class<?> visitString(org.eclipse.imp.pdb.facts.type.Type type) {
return IString.class;
}
@Override
public Class<?> visitNode(org.eclipse.imp.pdb.facts.type.Type type) {
return INode.class;
}
@Override
public Class<?> visitConstructor(org.eclipse.imp.pdb.facts.type.Type type) {
return IConstructor.class;
}
@Override
public Class<?> visitTuple(org.eclipse.imp.pdb.facts.type.Type type) {
return ITuple.class;
}
@Override
public Class<?> visitValue(org.eclipse.imp.pdb.facts.type.Type type) {
return IValue.class;
}
@Override
public Class<?> visitVoid(org.eclipse.imp.pdb.facts.type.Type type) {
return null;
}
@Override
public Class<?> visitParameter(org.eclipse.imp.pdb.facts.type.Type parameterType) {
return parameterType.getBound().accept(this);
}
@Override
public Class<?> visitExternal(
org.eclipse.imp.pdb.facts.type.Type externalType) {
return IValue.class;
}
@Override
public Class<?> visitDateTime(Type type) {
return IDateTime.class;
}
}
}
| true | true | private Object executeProgram(Frame root, Frame cf) {
Object[] stack = cf.stack; // current stack
int sp = cf.function.nlocals; // current stack pointer
int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence
int pc = 0; // current program counter
int postOp = 0;
int pos = 0;
ArrayList<Frame> stacktrace;
Thrown thrown;
int arity;
String last_function_name = "";
// Overloading specific
Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>();
OverloadedFunctionInstanceCall c_ofun_call = null;
try {
NEXT_INSTRUCTION: while (true) {
// if(pc < 0 || pc >= instructions.length){
// throw new RuntimeException(cf.function.name + " illegal pc: " + pc);
// }
int instruction = instructions[pc++];
int op = CodeBlock.fetchOp(instruction);
if (debug) {
int startpc = pc - 1;
if(!last_function_name.equals(cf.function.name))
stdout.printf("[%03d] %s\n", startpc, cf.function.name);
for (int i = 0; i < sp; i++) {
stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i]));
}
stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc));
}
Opcode.use(instruction);
switch (op) {
case Opcode.OP_POP:
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOC0:
if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; }
pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC1:
if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; }
pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC2:
if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; }
pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC3:
if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; }
pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC4:
if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; }
pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC5:
if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; }
pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC6:
if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; }
pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC7:
if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; }
pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC8:
if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; }
pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC9:
if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; }
pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC:
pos = CodeBlock.fetchArg1(instruction);
Object rval = stack[pos];
if(rval != null){
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
postOp = Opcode.POSTOP_CHECKUNDEF;
break;
case Opcode.OP_LOADBOOL:
stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADINT:
stack[sp++] = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCREF:
stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLMUPRIM:
MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_JMP:
pc = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPESWITCH:
IValue val = (IValue) stack[--sp];
Type t = null;
if(val instanceof IConstructor) {
t = ((IConstructor) val).getConstructorType();
} else {
t = val.getType();
}
int labelIndex = ToplevelType.getToplevelTypeAsInt(t);
IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPINDEXED:
labelIndex = ((IInteger) stack[--sp]).intValue();
labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADTYPE:
stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCDEREF: {
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOC: {
stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_UNWRAPTHROWN: {
stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value;
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOCDEREF:
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, get the function code
Function fun = functionStore.get(CodeBlock.fetchArg1(instruction));
int scopeIn = CodeBlock.fetchArg2(instruction);
// Second, look up the function environment frame into the stack of caller frames
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scopeIn) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn);
}
case Opcode.OP_LOADOFUN:
OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
if(of.scopeIn == -1) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root);
continue NEXT_INSTRUCTION;
}
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == of.scopeIn) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn);
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
stack[sp++] = constructor;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVARREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
rval = moduleVariables.get(cf.function.constantStore[s]);
if(op == Opcode.OP_LOADVAR && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
if(op == Opcode.OP_LOADLOC && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARDEREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s);
}
case Opcode.OP_STOREVAR:
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
IValue mvar = cf.function.constantStore[s];
moduleVariables.put(mvar, (IValue)stack[sp -1]);
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARDEREF:
s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s);
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == constructor.getArity();
IValue[] args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
arity = CodeBlock.fetchArg1(instruction); // TODO: add assert
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == fun.nformals;
previousScope = cf;
} else {
throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1]));
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue NEXT_INSTRUCTION;
case Opcode.OP_OCALLDYN:
case Opcode.OP_OCALL:
Object funcObject = (op == Opcode.OP_OCALLDYN) ? stack[--sp] : null;
// Get function arguments from the stack
arity = CodeBlock.fetchArg2(instruction);
args = new IValue[arity];
for(int i = arity - 1; i >= 0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
if(op == Opcode.OP_OCALLDYN) {
// Get function types to perform a type-based dynamic resolution
Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction));
// Objects of three types may appear on the stack:
// 1. FunctionInstance due to closures
// 2. OverloadedFunctionInstance due to named Rascal functions
if(funcObject instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) funcObject;
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(cf, fun_instance.function, fun_instance.env, args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject;
c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types);
} else {
of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null);
}
ocalls.push(c_ofun_call);
if(debug) {
if(op == Opcode.OP_OCALL) {
this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction)));
} else {
this.appendToTrace("OVERLOADED FUNCTION CALLDYN: ");
}
this.appendToTrace(" with alternatives:");
for(int index : c_ofun_call.functions) {
this.appendToTrace(" " + getFunctionName(index));
}
}
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = fun.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FAILRETURN:
assert cf.previousCallFrame == c_ofun_call.cf;
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
cf = c_ofun_call.cf;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FILTERRETURN:
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
// Overloading specific
if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
rval = null;
boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN;
if(op == Opcode.OP_RETURN1 || cf.isCoroutine) {
if(cf.isCoroutine) {
rval = Rascal_TRUE;
if(op == Opcode.OP_RETURN1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = cf.function.refs;
if(arity != refs.length) {
throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")");
}
for(int i = 0; i < arity; i++) {
ref = (Reference) stack[refs[arity - 1 - i]];
ref.stack[ref.pos] = stack[--sp];
}
}
} else {
rval = stack[sp - 1];
}
}
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns) {
return rval;
} else {
return NONE;
}
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns) {
stack[sp++] = rval;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLJAVA:
String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]];
int reflect = instructions[pc++];
arity = parameterTypes.getArity();
try {
sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp);
} catch(Throw e) {
thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>());
// EXCEPTION HANDLING
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_INIT:
arity = CodeBlock.fetchArg1(instruction);
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src);
}
if(coroutine.isInitialized()) {
throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName());
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp) {
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName());
}
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
sp = sp - arity; /* Place coroutine back on stack */
stack[sp++] = newCoroutine;
// Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension
newCoroutine.suspend(newCoroutine.frame);
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(newCoroutine);
ccf = newCoroutine.start;
newCoroutine.next(cf);
fun = newCoroutine.frame.function;
instructions = newCoroutine.frame.function.codeblock.getInstructions();
cf.pc = pc;
cf.sp = sp;
cf = newCoroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_GUARD:
rval = stack[sp - 1];
boolean precondition;
if(rval instanceof IBool) {
precondition = ((IBool) rval).getValue();
} else if(rval instanceof Boolean) {
precondition = (Boolean) rval;
} else {
throw new RuntimeException("Guard's expression has to be boolean!");
}
if(cf == ccf) {
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = cf.previousCallFrame;
if(precondition) {
coroutine.suspend(cf);
}
--sp;
cf.pc = pc;
cf.sp = sp;
cf = prev;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
if(!precondition) {
cf.pc = pc;
cf.sp = sp;
cf = cf.previousCallFrame;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE;
continue NEXT_INSTRUCTION;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
if(op == Opcode.OP_CREATE){
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
previousScope = null;
if(fun.scopeIn != -1) {
for(Frame f = cf; f != null; f = f.previousCallFrame) {
if (f.scopeId == fun.scopeIn) {
previousScope = f;
}
}
if(previousScope == null) {
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + fun.scopeIn);
}
}
} else {
arity = CodeBlock.fetchArg1(instruction);
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src));
}
}
Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue NEXT_INSTRUCTION;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// Merged the hasNext and next semantics
if(!coroutine.hasNext()) {
if(op == Opcode.OP_NEXT1) {
--sp;
}
stack[sp++] = FALSE;
continue NEXT_INSTRUCTION;
}
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = Rascal_TRUE; // In fact, yield has to always return TRUE
if(op == Opcode.OP_YIELD1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance
if(cf != coroutine.start && cf.function.refs.length != refs.length) {
throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length);
}
if(arity != refs.length) {
throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length);
}
for(int i = 0; i < arity; i++) {
ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance
ref.stack[ref.pos] = stack[--sp];
}
}
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = rval; // Corresponding next will always find an entry on the stack
continue NEXT_INSTRUCTION;
case Opcode.OP_EXHAUST:
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
continue NEXT_INSTRUCTION;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLPRIM:
RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
try {
sp = prim.invoke(stack, sp, arity);
} catch(InvocationTargetException targetException) {
if(!(targetException.getTargetException() instanceof Thrown)) {
throw targetException;
}
// EXCEPTION HANDLING
thrown = (Thrown) targetException.getTargetException();
thrown.stacktrace.add(cf);
sp = sp - arity;
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
// Some specialized MuPrimitives
case Opcode.OP_SUBSCRIPTARRAY:
stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])];
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBSCRIPTLIST:
stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LESSINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_GREATEREQUALINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ADDINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTRACTINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ANDBOOL:
boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue();
boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue();
stack[sp - 2] = b1 && b2;
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPEOF:
if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching
@SuppressWarnings("unchecked")
HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1];
if(mset.isEmpty()){
stack[sp - 1] = tf.setType(tf.voidType());
} else {
IValue v = mset.iterator().next();
stack[sp - 1] = tf.setType(v.getType());
}
} else {
stack[sp - 1] = ((IValue) stack[sp - 1]).getType();
}
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTYPE:
stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_CHECKARGTYPE:
Type argType = ((IValue) stack[sp - 2]).getType();
Type paramType = ((Type) stack[sp - 1]);
stack[sp - 2] = argType.isSubtypeOf(paramType);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LABEL:
throw new RuntimeException("label instruction at runtime");
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
arity = CodeBlock.fetchArg1(instruction);
StringBuilder w = new StringBuilder();
for(int i = arity - 1; i >= 0; i--){
String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]);
w.append(str).append(" ");
}
stdout.println(w.toString());
sp = sp - arity + 1;
continue NEXT_INSTRUCTION;
case Opcode.OP_THROW:
Object obj = stack[--sp];
thrown = null;
if(obj instanceof IValue) {
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = Thrown.getInstance((IValue) obj, null, stacktrace);
} else {
// Then, an object of type 'Thrown' is on top of the stack
thrown = (Thrown) obj;
}
// First, try to find a handler in the current frame function,
// given the current instruction index and the value type,
// then, if not found, look up the caller function(s)
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
case Opcode.OP_LOADLOCKWP:
IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
@SuppressWarnings("unchecked")
Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals];
Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue());
for(Frame f = cf; f != null; f = f.previousCallFrame) {
IMap kargs = (IMap) f.stack[f.function.nformals - 1];
if(kargs.containsKey(name)) {
val = kargs.get(name);
if(val.getType().isSubtypeOf(defaultValue.getKey())) {
stack[sp++] = val;
continue NEXT_INSTRUCTION;
}
}
}
stack[sp++] = defaultValue.getValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVARKWP:
continue NEXT_INSTRUCTION;
case Opcode.OP_STORELOCKWP:
val = (IValue) stack[sp - 1];
name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
IMap kargs = (IMap) stack[cf.function.nformals - 1];
stack[cf.function.nformals - 1] = kargs.put(name, val);
continue NEXT_INSTRUCTION;
case Opcode.OP_STOREVARKWP:
continue NEXT_INSTRUCTION;
default:
throw new RuntimeException("RVM main loop -- cannot decode instruction");
}
switch(postOp){
case Opcode.POSTOP_CHECKUNDEF:
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
}
} catch (Exception e) {
e.printStackTrace(stderr);
throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() );
//stdout.println("PANIC: (instruction execution): " + e.getMessage());
//e.printStackTrace();
//stderr.println(e.getStackTrace());
}
}
| private Object executeProgram(Frame root, Frame cf) {
Object[] stack = cf.stack; // current stack
int sp = cf.function.nlocals; // current stack pointer
int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence
int pc = 0; // current program counter
int postOp = 0;
int pos = 0;
ArrayList<Frame> stacktrace;
Thrown thrown;
int arity;
String last_function_name = "";
// Overloading specific
Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>();
OverloadedFunctionInstanceCall c_ofun_call = null;
try {
NEXT_INSTRUCTION: while (true) {
// if(pc < 0 || pc >= instructions.length){
// throw new RuntimeException(cf.function.name + " illegal pc: " + pc);
// }
int instruction = instructions[pc++];
int op = CodeBlock.fetchOp(instruction);
if (debug) {
int startpc = pc - 1;
if(!last_function_name.equals(cf.function.name))
stdout.printf("[%03d] %s\n", startpc, cf.function.name);
for (int i = 0; i < sp; i++) {
stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i]));
}
stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc));
}
Opcode.use(instruction);
switch (op) {
case Opcode.OP_POP:
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOC0:
if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; }
pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC1:
if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; }
pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC2:
if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; }
pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC3:
if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; }
pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC4:
if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; }
pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC5:
if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; }
pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC6:
if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; }
pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC7:
if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; }
pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC8:
if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; }
pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC9:
if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; }
pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break;
case Opcode.OP_LOADLOC:
pos = CodeBlock.fetchArg1(instruction);
Object rval = stack[pos];
if(rval != null){
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
postOp = Opcode.POSTOP_CHECKUNDEF;
break;
case Opcode.OP_LOADBOOL:
stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADINT:
stack[sp++] = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCREF:
stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLMUPRIM:
MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction));
continue NEXT_INSTRUCTION;
case Opcode.OP_JMP:
pc = CodeBlock.fetchArg1(instruction);
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) {
pc = CodeBlock.fetchArg1(instruction);
}
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPESWITCH:
IValue val = (IValue) stack[--sp];
Type t = null;
if(val instanceof IConstructor) {
t = ((IConstructor) val).getConstructorType();
} else {
t = val.getType();
}
int labelIndex = ToplevelType.getToplevelTypeAsInt(t);
IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_JMPINDEXED:
labelIndex = ((IInteger) stack[--sp]).intValue();
labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)];
pc = ((IInteger) labels.get(labelIndex)).intValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADTYPE:
stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)];
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADLOCDEREF: {
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOC: {
stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
case Opcode.OP_UNWRAPTHROWN: {
stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value;
continue NEXT_INSTRUCTION;
}
case Opcode.OP_STORELOCDEREF:
Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)];
ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root);
continue NEXT_INSTRUCTION;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, get the function code
Function fun = functionStore.get(CodeBlock.fetchArg1(instruction));
int scopeIn = CodeBlock.fetchArg2(instruction);
// Second, look up the function environment frame into the stack of caller frames
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scopeIn) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn);
}
case Opcode.OP_LOADOFUN:
OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
if(of.scopeIn == -1) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root);
continue NEXT_INSTRUCTION;
}
for(Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == of.scopeIn) {
stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn);
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
stack[sp++] = constructor;
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVARREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
rval = moduleVariables.get(cf.function.constantStore[s]);
if(op == Opcode.OP_LOADVAR && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
if(op == Opcode.OP_LOADLOC && rval == null) {
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
stack[sp++] = rval;
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARDEREF: {
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s);
}
case Opcode.OP_STOREVAR:
int s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
if(CodeBlock.isMaxArg2(pos)){
IValue mvar = cf.function.constantStore[s];
moduleVariables.put(mvar, (IValue)stack[sp -1]);
continue NEXT_INSTRUCTION;
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARDEREF:
s = CodeBlock.fetchArg1(instruction);
pos = CodeBlock.fetchArg2(instruction);
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s);
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == constructor.getArity();
IValue[] args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
arity = CodeBlock.fetchArg1(instruction); // TODO: add assert
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
assert arity == fun.nformals;
previousScope = cf;
} else {
throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1]));
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue NEXT_INSTRUCTION;
case Opcode.OP_OCALLDYN:
case Opcode.OP_OCALL:
Object funcObject = (op == Opcode.OP_OCALLDYN) ? stack[--sp] : null;
// Get function arguments from the stack
arity = CodeBlock.fetchArg2(instruction);
args = new IValue[arity];
for(int i = arity - 1; i >= 0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
if(op == Opcode.OP_OCALLDYN) {
// Get function types to perform a type-based dynamic resolution
Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction));
// Objects of three types may appear on the stack:
// 1. FunctionInstance due to closures
// 2. OverloadedFunctionInstance due to named Rascal functions
if(funcObject instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) funcObject;
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(cf, fun_instance.function, fun_instance.env, args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject;
c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types);
} else {
of = overloadedStore.get(CodeBlock.fetchArg1(instruction));
c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null);
}
ocalls.push(c_ofun_call);
if(debug) {
if(op == Opcode.OP_OCALL) {
this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction)));
} else {
this.appendToTrace("OVERLOADED FUNCTION CALLDYN: ");
}
this.appendToTrace(" with alternatives:");
for(int index : c_ofun_call.functions) {
this.appendToTrace(" " + getFunctionName(index));
}
}
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = fun.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FAILRETURN:
assert cf.previousCallFrame == c_ofun_call.cf;
fun = c_ofun_call.nextFunction(functionStore);
if(fun != null) {
if(debug) {
this.appendToTrace(" " + "try alternative: " + fun.name);
}
cf.sp = sp;
cf.pc = pc;
cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args);
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
} else {
cf = c_ofun_call.cf;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args);
}
continue NEXT_INSTRUCTION;
case Opcode.OP_FILTERRETURN:
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
// Overloading specific
if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
rval = null;
boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN;
if(op == Opcode.OP_RETURN1 || cf.isCoroutine) {
if(cf.isCoroutine) {
rval = Rascal_TRUE;
if(op == Opcode.OP_RETURN1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = cf.function.refs;
if(arity != refs.length) {
throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")");
}
for(int i = 0; i < arity; i++) {
ref = (Reference) stack[refs[arity - 1 - i]];
ref.stack[ref.pos] = stack[--sp];
}
}
} else {
rval = stack[sp - 1];
}
}
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns) {
return rval;
} else {
return NONE;
}
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns) {
stack[sp++] = rval;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLJAVA:
String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue();
Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]];
int reflect = instructions[pc++];
arity = parameterTypes.getArity();
try {
sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp);
} catch(Throw e) {
thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>());
// EXCEPTION HANDLING
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_INIT:
arity = CodeBlock.fetchArg1(instruction);
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src);
}
if(coroutine.isInitialized()) {
throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName());
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp) {
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName());
}
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
sp = sp - arity; /* Place coroutine back on stack */
stack[sp++] = newCoroutine;
// Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension
newCoroutine.suspend(newCoroutine.frame);
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(newCoroutine);
ccf = newCoroutine.start;
newCoroutine.next(cf);
fun = newCoroutine.frame.function;
instructions = newCoroutine.frame.function.codeblock.getInstructions();
cf.pc = pc;
cf.sp = sp;
cf = newCoroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_GUARD:
rval = stack[sp - 1];
boolean precondition;
if(rval instanceof IBool) {
precondition = ((IBool) rval).getValue();
} else if(rval instanceof Boolean) {
precondition = (Boolean) rval;
} else {
throw new RuntimeException("Guard's expression has to be boolean!");
}
if(cf == ccf) {
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = cf.previousCallFrame;
if(precondition) {
coroutine.suspend(cf);
}
--sp;
cf.pc = pc;
cf.sp = sp;
cf = prev;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
}
if(!precondition) {
cf.pc = pc;
cf.sp = sp;
cf = cf.previousCallFrame;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE;
continue NEXT_INSTRUCTION;
}
continue NEXT_INSTRUCTION;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
if(op == Opcode.OP_CREATE){
fun = functionStore.get(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
previousScope = null;
if(fun.scopeIn != -1) {
for(Frame f = cf; f != null; f = f.previousCallFrame) {
if (f.scopeId == fun.scopeIn) {
previousScope = f;
break;
}
}
if(previousScope == null) {
throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + fun.scopeIn);
}
}
} else {
arity = CodeBlock.fetchArg1(instruction);
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src));
}
}
Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue NEXT_INSTRUCTION;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// Merged the hasNext and next semantics
if(!coroutine.hasNext()) {
if(op == Opcode.OP_NEXT1) {
--sp;
}
stack[sp++] = FALSE;
continue NEXT_INSTRUCTION;
}
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue NEXT_INSTRUCTION;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = Rascal_TRUE; // In fact, yield has to always return TRUE
if(op == Opcode.OP_YIELD1) {
arity = CodeBlock.fetchArg1(instruction);
int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance
if(cf != coroutine.start && cf.function.refs.length != refs.length) {
throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length);
}
if(arity != refs.length) {
throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length);
}
for(int i = 0; i < arity; i++) {
ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance
ref.stack[ref.pos] = stack[--sp];
}
}
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = rval; // Corresponding next will always find an entry on the stack
continue NEXT_INSTRUCTION;
case Opcode.OP_EXHAUST:
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure;
continue NEXT_INSTRUCTION;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue NEXT_INSTRUCTION;
case Opcode.OP_CALLPRIM:
RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction));
arity = CodeBlock.fetchArg2(instruction);
try {
sp = prim.invoke(stack, sp, arity);
} catch(InvocationTargetException targetException) {
if(!(targetException.getTargetException() instanceof Thrown)) {
throw targetException;
}
// EXCEPTION HANDLING
thrown = (Thrown) targetException.getTargetException();
thrown.stacktrace.add(cf);
sp = sp - arity;
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
continue NEXT_INSTRUCTION;
// Some specialized MuPrimitives
case Opcode.OP_SUBSCRIPTARRAY:
stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])];
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBSCRIPTLIST:
stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LESSINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_GREATEREQUALINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ADDINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTRACTINT:
stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_ANDBOOL:
boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue();
boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue();
stack[sp - 2] = b1 && b2;
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_TYPEOF:
if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching
@SuppressWarnings("unchecked")
HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1];
if(mset.isEmpty()){
stack[sp - 1] = tf.setType(tf.voidType());
} else {
IValue v = mset.iterator().next();
stack[sp - 1] = tf.setType(v.getType());
}
} else {
stack[sp - 1] = ((IValue) stack[sp - 1]).getType();
}
continue NEXT_INSTRUCTION;
case Opcode.OP_SUBTYPE:
stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_CHECKARGTYPE:
Type argType = ((IValue) stack[sp - 2]).getType();
Type paramType = ((Type) stack[sp - 1]);
stack[sp - 2] = argType.isSubtypeOf(paramType);
sp--;
continue NEXT_INSTRUCTION;
case Opcode.OP_LABEL:
throw new RuntimeException("label instruction at runtime");
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
arity = CodeBlock.fetchArg1(instruction);
StringBuilder w = new StringBuilder();
for(int i = arity - 1; i >= 0; i--){
String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]);
w.append(str).append(" ");
}
stdout.println(w.toString());
sp = sp - arity + 1;
continue NEXT_INSTRUCTION;
case Opcode.OP_THROW:
Object obj = stack[--sp];
thrown = null;
if(obj instanceof IValue) {
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = Thrown.getInstance((IValue) obj, null, stacktrace);
} else {
// Then, an object of type 'Thrown' is on top of the stack
thrown = (Thrown) obj;
}
// First, try to find a handler in the current frame function,
// given the current instruction index and the value type,
// then, if not found, look up the caller function(s)
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
case Opcode.OP_LOADLOCKWP:
IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
@SuppressWarnings("unchecked")
Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals];
Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue());
for(Frame f = cf; f != null; f = f.previousCallFrame) {
IMap kargs = (IMap) f.stack[f.function.nformals - 1];
if(kargs.containsKey(name)) {
val = kargs.get(name);
if(val.getType().isSubtypeOf(defaultValue.getKey())) {
stack[sp++] = val;
continue NEXT_INSTRUCTION;
}
}
}
stack[sp++] = defaultValue.getValue();
continue NEXT_INSTRUCTION;
case Opcode.OP_LOADVARKWP:
continue NEXT_INSTRUCTION;
case Opcode.OP_STORELOCKWP:
val = (IValue) stack[sp - 1];
name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction));
IMap kargs = (IMap) stack[cf.function.nformals - 1];
stack[cf.function.nformals - 1] = kargs.put(name, val);
continue NEXT_INSTRUCTION;
case Opcode.OP_STOREVARKWP:
continue NEXT_INSTRUCTION;
default:
throw new RuntimeException("RVM main loop -- cannot decode instruction");
}
switch(postOp){
case Opcode.POSTOP_CHECKUNDEF:
// EXCEPTION HANDLING
stacktrace = new ArrayList<Frame>();
stacktrace.add(cf);
thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace);
cf.pc = pc;
for(Frame f = cf; f != null; f = f.previousCallFrame) {
int handler = f.function.getHandler(f.pc - 1, thrown.value.getType());
if(handler != -1) {
if(f != cf) {
cf = f;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
}
pc = handler;
stack[sp++] = thrown;
continue NEXT_INSTRUCTION;
}
if(c_ofun_call != null && f.previousCallFrame == c_ofun_call.cf) {
ocalls.pop();
c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek();
}
}
// If a handler has not been found in the caller functions...
return thrown;
}
}
} catch (Exception e) {
e.printStackTrace(stderr);
throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() );
//stdout.println("PANIC: (instruction execution): " + e.getMessage());
//e.printStackTrace();
//stderr.println(e.getStackTrace());
}
}
|
diff --git a/src/main/java/net/md_5/specialsource/RemapperPreprocessor.java b/src/main/java/net/md_5/specialsource/RemapperPreprocessor.java
index 858f4f8..d9c8b36 100644
--- a/src/main/java/net/md_5/specialsource/RemapperPreprocessor.java
+++ b/src/main/java/net/md_5/specialsource/RemapperPreprocessor.java
@@ -1,215 +1,215 @@
/**
* Copyright (c) 2012-2013, md_5. 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.
*
* The name of the author may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.md_5.specialsource;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* "Pre-process" a class file, intended to be used before remapping with
* JarRemapper.
*
* Currently includes: - Extracting inheritance
*/
public class RemapperPreprocessor {
public boolean debug = false;
private InheritanceMap inheritanceMap;
private JarMapping jarMapping;
private AccessMap accessMap;
/**
*
* @param inheritanceMap Map to add extracted inheritance information too,
* or null to not extract inheritance
* @param jarMapping Mapping for reflection remapping, or null to not remap
* reflection
* @throws IOException
*/
public RemapperPreprocessor(InheritanceMap inheritanceMap, JarMapping jarMapping, AccessMap accessMap) {
this.inheritanceMap = inheritanceMap;
this.jarMapping = jarMapping;
this.accessMap = accessMap;
}
public RemapperPreprocessor(InheritanceMap inheritanceMap, JarMapping jarMapping) {
this(inheritanceMap, jarMapping, null);
}
public byte[] preprocess(InputStream inputStream) throws IOException {
return preprocess(new ClassReader(inputStream));
}
public byte[] preprocess(byte[] bytecode) throws IOException {
return preprocess(new ClassReader(bytecode));
}
@SuppressWarnings("unchecked")
public byte[] preprocess(ClassReader classReader) {
byte[] bytecode = null;
ClassNode classNode = new ClassNode();
- int flags = ClassReader.SKIP_DEBUG;
+ int flags = 0;
if (!isRewritingNeeded()) {
// Not rewriting the class - skip the code, not needed
- flags |= ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES;
+ flags |= ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG;
}
classReader.accept(classNode, flags);
String className = classNode.name;
// Inheritance extraction
if (inheritanceMap != null) {
logI("Loading plugin class inheritance for " + className);
// Get inheritance
ArrayList<String> parents = new ArrayList<String>();
for (String iface : (List<String>) classNode.interfaces) {
parents.add(iface);
}
parents.add(classNode.superName);
inheritanceMap.setParents(className.replace('.', '/'), parents);
logI("Inheritance added " + className + " parents " + parents.size());
}
if (isRewritingNeeded()) {
// Class access
if (accessMap != null) {
classNode.access = accessMap.applyClassAccess(className, classNode.access);
// TODO: inner classes?
}
// Field access
if (accessMap != null) {
for (FieldNode fieldNode : (List<FieldNode>) classNode.fields) {
fieldNode.access = accessMap.applyFieldAccess(className, fieldNode.name, fieldNode.access);
}
}
for (MethodNode methodNode : (List<MethodNode>) classNode.methods) {
// Method access
if (accessMap != null) {
methodNode.access = accessMap.applyMethodAccess(className, methodNode.name, methodNode.desc, methodNode.access);
}
// Reflection remapping
if (jarMapping != null) {
AbstractInsnNode insn = methodNode.instructions.getFirst();
while (insn != null) {
if (insn.getOpcode() == Opcodes.INVOKEVIRTUAL) {
remapGetDeclaredField(insn);
}
insn = insn.getNext();
}
}
}
ClassWriter cw = new ClassWriter(0);
classNode.accept(cw);
bytecode = cw.toByteArray();
}
return bytecode;
}
private boolean isRewritingNeeded() {
return jarMapping != null || accessMap != null;
}
/**
* Replace class.getDeclaredField("string") with a remapped field string
*
* @param insn Method call instruction
*/
private void remapGetDeclaredField(AbstractInsnNode insn) {
MethodInsnNode mi = (MethodInsnNode) insn;
if (!mi.owner.equals("java/lang/Class") || !mi.name.equals("getDeclaredField") || !mi.desc.equals("(Ljava/lang/String;)Ljava/lang/reflect/Field;")) {
return;
}
logR("ReflectionRemapper found getDeclaredField!");
if (insn.getPrevious() == null || insn.getPrevious().getOpcode() != Opcodes.LDC) {
logR("- not constant field; skipping");
return;
}
LdcInsnNode ldcField = (LdcInsnNode) insn.getPrevious();
if (!(ldcField.cst instanceof String)) {
logR("- not field string; skipping: " + ldcField.cst);
return;
}
String fieldName = (String) ldcField.cst;
if (ldcField.getPrevious() == null || ldcField.getPrevious().getOpcode() != Opcodes.LDC) {
logR("- not constant class; skipping: field=" + ldcField.cst);
return;
}
LdcInsnNode ldcClass = (LdcInsnNode) ldcField.getPrevious();
if (!(ldcClass.cst instanceof Type)) {
logR("- not class type; skipping: field=" + ldcClass.cst + ", class=" + ldcClass.cst);
return;
}
String className = ((Type) ldcClass.cst).getInternalName();
String newName = jarMapping.tryClimb(jarMapping.fields, NodeType.FIELD, className, fieldName);
logR("Remapping " + className + "/" + fieldName + " -> " + newName);
if (newName != null) {
// Change the string literal to the correct name
ldcField.cst = newName;
//ldcClass.cst = className; // not remapped here - taken care of by JarRemapper
}
}
private void logI(String message) {
if (debug) {
System.out.println("[Inheritance] " + message);
}
}
private void logR(String message) {
if (debug) {
System.out.println("[ReflectionRemapper] " + message);
}
}
}
| false | true | public byte[] preprocess(ClassReader classReader) {
byte[] bytecode = null;
ClassNode classNode = new ClassNode();
int flags = ClassReader.SKIP_DEBUG;
if (!isRewritingNeeded()) {
// Not rewriting the class - skip the code, not needed
flags |= ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES;
}
classReader.accept(classNode, flags);
String className = classNode.name;
// Inheritance extraction
if (inheritanceMap != null) {
logI("Loading plugin class inheritance for " + className);
// Get inheritance
ArrayList<String> parents = new ArrayList<String>();
for (String iface : (List<String>) classNode.interfaces) {
parents.add(iface);
}
parents.add(classNode.superName);
inheritanceMap.setParents(className.replace('.', '/'), parents);
logI("Inheritance added " + className + " parents " + parents.size());
}
if (isRewritingNeeded()) {
// Class access
if (accessMap != null) {
classNode.access = accessMap.applyClassAccess(className, classNode.access);
// TODO: inner classes?
}
// Field access
if (accessMap != null) {
for (FieldNode fieldNode : (List<FieldNode>) classNode.fields) {
fieldNode.access = accessMap.applyFieldAccess(className, fieldNode.name, fieldNode.access);
}
}
for (MethodNode methodNode : (List<MethodNode>) classNode.methods) {
// Method access
if (accessMap != null) {
methodNode.access = accessMap.applyMethodAccess(className, methodNode.name, methodNode.desc, methodNode.access);
}
// Reflection remapping
if (jarMapping != null) {
AbstractInsnNode insn = methodNode.instructions.getFirst();
while (insn != null) {
if (insn.getOpcode() == Opcodes.INVOKEVIRTUAL) {
remapGetDeclaredField(insn);
}
insn = insn.getNext();
}
}
}
ClassWriter cw = new ClassWriter(0);
classNode.accept(cw);
bytecode = cw.toByteArray();
}
return bytecode;
}
| public byte[] preprocess(ClassReader classReader) {
byte[] bytecode = null;
ClassNode classNode = new ClassNode();
int flags = 0;
if (!isRewritingNeeded()) {
// Not rewriting the class - skip the code, not needed
flags |= ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG;
}
classReader.accept(classNode, flags);
String className = classNode.name;
// Inheritance extraction
if (inheritanceMap != null) {
logI("Loading plugin class inheritance for " + className);
// Get inheritance
ArrayList<String> parents = new ArrayList<String>();
for (String iface : (List<String>) classNode.interfaces) {
parents.add(iface);
}
parents.add(classNode.superName);
inheritanceMap.setParents(className.replace('.', '/'), parents);
logI("Inheritance added " + className + " parents " + parents.size());
}
if (isRewritingNeeded()) {
// Class access
if (accessMap != null) {
classNode.access = accessMap.applyClassAccess(className, classNode.access);
// TODO: inner classes?
}
// Field access
if (accessMap != null) {
for (FieldNode fieldNode : (List<FieldNode>) classNode.fields) {
fieldNode.access = accessMap.applyFieldAccess(className, fieldNode.name, fieldNode.access);
}
}
for (MethodNode methodNode : (List<MethodNode>) classNode.methods) {
// Method access
if (accessMap != null) {
methodNode.access = accessMap.applyMethodAccess(className, methodNode.name, methodNode.desc, methodNode.access);
}
// Reflection remapping
if (jarMapping != null) {
AbstractInsnNode insn = methodNode.instructions.getFirst();
while (insn != null) {
if (insn.getOpcode() == Opcodes.INVOKEVIRTUAL) {
remapGetDeclaredField(insn);
}
insn = insn.getNext();
}
}
}
ClassWriter cw = new ClassWriter(0);
classNode.accept(cw);
bytecode = cw.toByteArray();
}
return bytecode;
}
|
diff --git a/java/testing/org/apache/derbyTesting/junit/BaseTestCase.java b/java/testing/org/apache/derbyTesting/junit/BaseTestCase.java
index 909d927c2..0abaf13cb 100644
--- a/java/testing/org/apache/derbyTesting/junit/BaseTestCase.java
+++ b/java/testing/org/apache/derbyTesting/junit/BaseTestCase.java
@@ -1,551 +1,552 @@
/*
*
* Derby - Class BaseTestCase
*
* 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.derbyTesting.junit;
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.AssertionFailedError;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.PrintStream;
import java.net.URL;
import java.sql.SQLException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
/**
* Base class for JUnit tests.
*/
public abstract class BaseTestCase
extends TestCase {
/**
* No argument constructor made private to enforce naming of test cases.
* According to JUnit documentation, this constructor is provided for
* serialization, which we don't currently use.
*
* @see #BaseTestCase(String)
*/
private BaseTestCase() {}
/**
* Create a test case with the given name.
*
* @param name name of the test case.
*/
public BaseTestCase(String name) {
super(name);
}
/**
* Run the test and force installation of a security
* manager with the default test policy file.
* Individual tests can run without a security
* manager or with a different policy file using
* the decorators obtained from SecurityManagerSetup.
* <BR>
* Method is final to ensure security manager is
* enabled by default. Tests should not need to
* override runTest, instead use test methods
* setUp, tearDown methods and decorators.
*/
public void runBare() throws Throwable {
TestConfiguration config = getTestConfiguration();
boolean trace = config.doTrace();
long startTime = 0;
if ( trace )
{
startTime = System.currentTimeMillis();
out.println();
out.print(getName() + " ");
}
// install a default security manager if one has not already been
// installed
if ( System.getSecurityManager() == null )
{
if (config.defaultSecurityManagerSetup())
{
assertSecurityManager();
}
}
try {
super.runBare();
}
//To save the derby.log of failed tests.
catch (Throwable running) {
try{
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws SQLException, FileNotFoundException,
IOException {
File origLogDir = new File("system", "derby.log");
if (origLogDir.exists()) {
File failDir = getFailureFolder();
InputStream in = new FileInputStream(origLogDir);
OutputStream out = new FileOutputStream(new File(failDir,
"derby.log"));
byte[] buf = new byte[32 * 1024];
for (;;) {
int read = in.read(buf);
if (read == -1)
break;
out.write(buf, 0, read);
}
in.close();
out.close();
}
return null;
}
});
}
finally{
throw running;
}
}
finally{
if ( trace )
{
long timeUsed = System.currentTimeMillis() - startTime;
out.print("used " + timeUsed + " ms ");
}
}
}
/**
* Return the current configuration for the test.
*/
public final TestConfiguration getTestConfiguration()
{
return TestConfiguration.getCurrent();
}
/**
* Get the folder where a test leaves any information
* about its failure.
* @return Folder to use.
* @see TestConfiguration#getFailureFolder(TestCase)
*/
public final File getFailureFolder() {
return getTestConfiguration().getFailureFolder(this);
}
/**
* Print alarm string
* @param text String to print
*/
public static void alarm(final String text) {
out.println("ALARM: " + text);
}
/**
* Print debug string.
* @param text String to print
*/
public static void println(final String text) {
if (TestConfiguration.getCurrent().isVerbose()) {
out.println("DEBUG: " + text);
}
}
/**
* Print debug string.
* @param t Throwable object to print stack trace from
*/
public static void printStackTrace(Throwable t)
{
while ( t!= null) {
t.printStackTrace(out);
out.flush();
if (t instanceof SQLException) {
t = ((SQLException) t).getNextException();
} else {
break;
}
}
}
private final static PrintStream out = System.out;
/**
* Set system property
*
* @param name name of the property
* @param value value of the property
*/
protected static void setSystemProperty(final String name,
final String value)
{
AccessController.doPrivileged
(new java.security.PrivilegedAction(){
public Object run(){
System.setProperty( name, value);
return null;
}
}
);
}
/**
* Remove system property
*
* @param name name of the property
*/
protected static void removeSystemProperty(final String name)
{
AccessController.doPrivileged
(new java.security.PrivilegedAction(){
public Object run(){
System.getProperties().remove(name);
return null;
}
}
);
}
/**
* Get system property.
*
* @param name name of the property
*/
protected static String getSystemProperty(final String name)
{
return (String )AccessController.doPrivileged
(new java.security.PrivilegedAction(){
public Object run(){
return System.getProperty(name);
}
}
);
}
/**
* Obtain the URL for a test resource, e.g. a policy
* file or a SQL script.
* @param name Resource name, typically - org.apache.derbyTesing.something
* @return URL to the resource, null if it does not exist.
*/
protected static URL getTestResource(final String name)
{
return (URL)AccessController.doPrivileged
(new java.security.PrivilegedAction(){
public Object run(){
return BaseTestCase.class.getClassLoader().
getResource(name);
}
}
);
}
/**
* Open the URL for a a test resource, e.g. a policy
* file or a SQL script.
* @param url URL obtained from getTestResource
* @return An open stream
*/
protected static InputStream openTestResource(final URL url)
throws PrivilegedActionException
{
return (InputStream)AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction(){
public Object run() throws IOException{
return url.openStream();
}
}
);
}
/**
* Assert a security manager is installed.
*
*/
public static void assertSecurityManager()
{
assertNotNull("No SecurityManager installed",
System.getSecurityManager());
}
/**
* Compare the contents of two streams.
* The streams are closed after they are exhausted.
*
* @param is1 the first stream
* @param is2 the second stream
* @throws IOException if reading from the streams fail
* @throws AssertionFailedError if the stream contents are not equal
*/
public static void assertEquals(InputStream is1, InputStream is2)
throws IOException {
if (is1 == null || is2 == null) {
assertNull("InputStream is2 is null, is1 is not", is1);
assertNull("InputStream is1 is null, is2 is not", is2);
return;
}
long index = 0;
int b1 = is1.read();
int b2 = is2.read();
do {
// Avoid string concatenation for every byte in the stream.
if (b1 != b2) {
assertEquals("Streams differ at index " + index, b1, b2);
}
index++;
b1 = is1.read();
b2 = is2.read();
} while (b1 != -1 || b2 != -1);
is1.close();
is2.close();
}
/**
* Compare the contents of two readers.
* The readers are closed after they are exhausted.
*
* @param r1 the first reader
* @param r2 the second reader
* @throws IOException if reading from the streams fail
* @throws AssertionFailedError if the reader contents are not equal
*/
public static void assertEquals(Reader r1, Reader r2)
throws IOException {
long index = 0;
if (r1 == null || r2 == null) {
assertNull("Reader r2 is null, r1 is not", r1);
assertNull("Reader r1 is null, r2 is not", r2);
return;
}
int c1 = r1.read();
int c2 = r2.read();
do {
// Avoid string concatenation for every char in the stream.
if (c1 != c2) {
assertEquals("Streams differ at index " + index, c1, c2);
}
index++;
c1 = r1.read();
c2 = r2.read();
} while (c1 != -1 || c2 != -1);
r1.close();
r2.close();
}
/**
* Assert that the detailed messages of the 2 passed-in Throwable's are
* equal (rather than '=='), as well as their class types.
*
* @param t1 first throwable to compare
* @param t2 second throwable to compare
*/
public static void assertThrowableEquals(Throwable t1,
Throwable t2) {
// Ensure non-null throwable's are being passed.
assertNotNull(
"Passed-in throwable t1 cannot be null to assert detailed message",
t1);
assertNotNull(
"Passed-in throwable t2 cannot be null to assert detailed message",
t2);
// Now verify that the passed-in throwable are of the same type
assertEquals("Throwable class types are different",
t1.getClass().getName(), t2.getClass().getName());
// Here we finally check that the detailed message of both
// throwable's is the same
assertEquals("Detailed messages of the throwable's are different",
t1.getMessage(), t2.getMessage());
}
/**
* Assert that two files in the filesystem are identical.
*
* @param file1 the first file to compare
* @param file2 the second file to compare
*/
public static void assertEquals(final File file1, final File file2) {
AccessController.doPrivileged
(new PrivilegedAction() {
public Object run() {
try {
InputStream f1 = new BufferedInputStream(new FileInputStream(file1));
InputStream f2 = new BufferedInputStream(new FileInputStream(file2));
assertEquals(f1, f2);
} catch (FileNotFoundException e) {
fail("FileNotFoundException in assertEquals(File,File): " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
fail("IOException in assertEquals(File, File): " + e.getMessage());
e.printStackTrace();
}
return null;
}
});
}
/**
/**
* Execute command using 'java' executable and verify that it completes
* with expected results
* @param expectedString String to compare the resulting output with. May be
* null if the output is not expected to be of interest.
* @param cmd array of java arguments for command
* @param expectedExitValue expected return value from the command
* @throws InterruptedException
* @throws IOException
*/
public void assertExecJavaCmdAsExpected(
String[] expectedString, String[] cmd, int expectedExitValue)
throws InterruptedException, IOException {
int totalSize = 3 + cmd.length;
String[] tcmd = new String[totalSize];
tcmd[0] = "java";
tcmd[1] = "-classpath";
tcmd[2] = BaseTestCase.getSystemProperty("java.class.path");
System.arraycopy(cmd, 0, tcmd, 3, cmd.length);
final String[] command = tcmd;
Process pr = null;
try {
pr = (Process) AccessController
.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Process result = null;
result = Runtime.getRuntime().exec(command);
return result;
}
});
} catch (PrivilegedActionException pe) {
Exception e = pe.getException();
if (e instanceof IOException)
throw (IOException) e;
else
throw (SecurityException) e;
}
InputStream is = pr.getInputStream();
if ( is == null )
{
fail("Unexpectedly receiving no text from the java command");
}
String output = "";
try
{
char[] ca = new char[1024];
// Create an InputStreamReader with default encoding; we're hoping
// this to be en. If not, we may not match the expected string.
InputStreamReader inStream;
inStream = new InputStreamReader(is);
// keep reading from the stream until all done
- while ((inStream.read(ca, 0, ca.length)) != -1)
+ int charsRead;
+ while ((charsRead = inStream.read(ca, 0, ca.length)) != -1)
{
- output = output + new String(ca).trim();
+ output = output + new String(ca, 0, charsRead);
}
} catch (Exception e) {
fail("Exception accessing inputstream from javacommand", e);
}
// wait until the process exits
pr.waitFor();
Assert.assertEquals(expectedExitValue, pr.exitValue());
if (expectedString != null)
{
for (int i=0 ; i<expectedString.length ; i++)
{
if (output.indexOf(expectedString[i]) == -1) {
fail("Didn't find expected string: " + expectedString[i] +
"\nFull output from the command:\n" + output);
}
}
}
}
/**
* Remove the directory and its contents.
* @param path Path of the directory
*/
public static void removeDirectory(String path)
{
DropDatabaseSetup.removeDirectory(path);
}
/**
* Remove the directory and its contents.
* @param dir File of the directory
*/
public static void removeDirectory(File dir)
{
DropDatabaseSetup.removeDirectory(dir);
}
/**
* Fail; attaching an exception for more detail on cause.
*
* @param msg message explaining the failure
* @param e exception related to the cause
*
* @exception AssertionFailedError
*/
public static void fail(String msg, Exception e)
throws AssertionFailedError {
AssertionFailedError ae = new AssertionFailedError(msg);
ae.initCause(e);
throw ae;
}
} // End class BaseTestCase
| false | true | public void assertExecJavaCmdAsExpected(
String[] expectedString, String[] cmd, int expectedExitValue)
throws InterruptedException, IOException {
int totalSize = 3 + cmd.length;
String[] tcmd = new String[totalSize];
tcmd[0] = "java";
tcmd[1] = "-classpath";
tcmd[2] = BaseTestCase.getSystemProperty("java.class.path");
System.arraycopy(cmd, 0, tcmd, 3, cmd.length);
final String[] command = tcmd;
Process pr = null;
try {
pr = (Process) AccessController
.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Process result = null;
result = Runtime.getRuntime().exec(command);
return result;
}
});
} catch (PrivilegedActionException pe) {
Exception e = pe.getException();
if (e instanceof IOException)
throw (IOException) e;
else
throw (SecurityException) e;
}
InputStream is = pr.getInputStream();
if ( is == null )
{
fail("Unexpectedly receiving no text from the java command");
}
String output = "";
try
{
char[] ca = new char[1024];
// Create an InputStreamReader with default encoding; we're hoping
// this to be en. If not, we may not match the expected string.
InputStreamReader inStream;
inStream = new InputStreamReader(is);
// keep reading from the stream until all done
while ((inStream.read(ca, 0, ca.length)) != -1)
{
output = output + new String(ca).trim();
}
} catch (Exception e) {
fail("Exception accessing inputstream from javacommand", e);
}
// wait until the process exits
pr.waitFor();
Assert.assertEquals(expectedExitValue, pr.exitValue());
if (expectedString != null)
{
for (int i=0 ; i<expectedString.length ; i++)
{
if (output.indexOf(expectedString[i]) == -1) {
fail("Didn't find expected string: " + expectedString[i] +
"\nFull output from the command:\n" + output);
}
}
}
}
| public void assertExecJavaCmdAsExpected(
String[] expectedString, String[] cmd, int expectedExitValue)
throws InterruptedException, IOException {
int totalSize = 3 + cmd.length;
String[] tcmd = new String[totalSize];
tcmd[0] = "java";
tcmd[1] = "-classpath";
tcmd[2] = BaseTestCase.getSystemProperty("java.class.path");
System.arraycopy(cmd, 0, tcmd, 3, cmd.length);
final String[] command = tcmd;
Process pr = null;
try {
pr = (Process) AccessController
.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Process result = null;
result = Runtime.getRuntime().exec(command);
return result;
}
});
} catch (PrivilegedActionException pe) {
Exception e = pe.getException();
if (e instanceof IOException)
throw (IOException) e;
else
throw (SecurityException) e;
}
InputStream is = pr.getInputStream();
if ( is == null )
{
fail("Unexpectedly receiving no text from the java command");
}
String output = "";
try
{
char[] ca = new char[1024];
// Create an InputStreamReader with default encoding; we're hoping
// this to be en. If not, we may not match the expected string.
InputStreamReader inStream;
inStream = new InputStreamReader(is);
// keep reading from the stream until all done
int charsRead;
while ((charsRead = inStream.read(ca, 0, ca.length)) != -1)
{
output = output + new String(ca, 0, charsRead);
}
} catch (Exception e) {
fail("Exception accessing inputstream from javacommand", e);
}
// wait until the process exits
pr.waitFor();
Assert.assertEquals(expectedExitValue, pr.exitValue());
if (expectedString != null)
{
for (int i=0 ; i<expectedString.length ; i++)
{
if (output.indexOf(expectedString[i]) == -1) {
fail("Didn't find expected string: " + expectedString[i] +
"\nFull output from the command:\n" + output);
}
}
}
}
|
diff --git a/src/main/java/me/desht/scrollingmenusign/commands/RemoveViewCommand.java b/src/main/java/me/desht/scrollingmenusign/commands/RemoveViewCommand.java
index ab14233..aee13ef 100644
--- a/src/main/java/me/desht/scrollingmenusign/commands/RemoveViewCommand.java
+++ b/src/main/java/me/desht/scrollingmenusign/commands/RemoveViewCommand.java
@@ -1,66 +1,65 @@
package me.desht.scrollingmenusign.commands;
import me.desht.scrollingmenusign.SMSException;
import me.desht.dhutils.MiscUtil;
import me.desht.dhutils.PermissionUtils;
import me.desht.dhutils.commands.AbstractCommand;
import me.desht.scrollingmenusign.views.SMSMapView;
import me.desht.scrollingmenusign.views.SMSView;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class RemoveViewCommand extends AbstractCommand {
public RemoveViewCommand() {
super("sms b", 0, 2);
setPermissionNode("scrollingmenusign.commands.break");
setUsage(new String[] {
"/sms break",
"/sms break -loc <x,y,z,world>",
"/sms break -view <view-name>"
});
}
@Override
public boolean execute(Plugin plugin, CommandSender sender, String[] args) {
SMSView view = null;
if (args.length == 2 && args[0].equals("-view")) {
// detaching a view by view name
view = SMSView.getView(args[1]);
} else if (args.length == 2 && args[0].equals("-loc")) {
// detaching a view by location
try {
- view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[0], sender));
+ view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[1], sender));
} catch (IllegalArgumentException e) {
throw new SMSException(e.getMessage());
}
- view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[0], sender));
} else if (sender instanceof Player && (view = SMSMapView.getHeldMapView((Player)sender)) != null) {
// detaching a map view - nothing else to check here
} else if (args.length == 0) {
// detaching a view that the player is looking at?
notFromConsole(sender);
try {
Block b = ((Player)sender).getTargetBlock(null, 3);
view = SMSView.getViewForLocation(b.getLocation());
} catch (IllegalStateException e) {
// ignore
}
}
if (view == null) {
throw new SMSException("No suitable view found to remove.");
} else {
PermissionUtils.requirePerms(sender, "scrollingmenusign.use." + view.getType());
view.deletePermanent();
MiscUtil.statusMessage(sender, String.format("Removed &9%s&- view &e%s&- from menu &e%s&-.",
view.getType(), view.getName(), view.getMenu().getName()));
}
return true;
}
}
| false | true | public boolean execute(Plugin plugin, CommandSender sender, String[] args) {
SMSView view = null;
if (args.length == 2 && args[0].equals("-view")) {
// detaching a view by view name
view = SMSView.getView(args[1]);
} else if (args.length == 2 && args[0].equals("-loc")) {
// detaching a view by location
try {
view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[0], sender));
} catch (IllegalArgumentException e) {
throw new SMSException(e.getMessage());
}
view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[0], sender));
} else if (sender instanceof Player && (view = SMSMapView.getHeldMapView((Player)sender)) != null) {
// detaching a map view - nothing else to check here
} else if (args.length == 0) {
// detaching a view that the player is looking at?
notFromConsole(sender);
try {
Block b = ((Player)sender).getTargetBlock(null, 3);
view = SMSView.getViewForLocation(b.getLocation());
} catch (IllegalStateException e) {
// ignore
}
}
if (view == null) {
throw new SMSException("No suitable view found to remove.");
} else {
PermissionUtils.requirePerms(sender, "scrollingmenusign.use." + view.getType());
view.deletePermanent();
MiscUtil.statusMessage(sender, String.format("Removed &9%s&- view &e%s&- from menu &e%s&-.",
view.getType(), view.getName(), view.getMenu().getName()));
}
return true;
}
| public boolean execute(Plugin plugin, CommandSender sender, String[] args) {
SMSView view = null;
if (args.length == 2 && args[0].equals("-view")) {
// detaching a view by view name
view = SMSView.getView(args[1]);
} else if (args.length == 2 && args[0].equals("-loc")) {
// detaching a view by location
try {
view = SMSView.getViewForLocation(MiscUtil.parseLocation(args[1], sender));
} catch (IllegalArgumentException e) {
throw new SMSException(e.getMessage());
}
} else if (sender instanceof Player && (view = SMSMapView.getHeldMapView((Player)sender)) != null) {
// detaching a map view - nothing else to check here
} else if (args.length == 0) {
// detaching a view that the player is looking at?
notFromConsole(sender);
try {
Block b = ((Player)sender).getTargetBlock(null, 3);
view = SMSView.getViewForLocation(b.getLocation());
} catch (IllegalStateException e) {
// ignore
}
}
if (view == null) {
throw new SMSException("No suitable view found to remove.");
} else {
PermissionUtils.requirePerms(sender, "scrollingmenusign.use." + view.getType());
view.deletePermanent();
MiscUtil.statusMessage(sender, String.format("Removed &9%s&- view &e%s&- from menu &e%s&-.",
view.getType(), view.getName(), view.getMenu().getName()));
}
return true;
}
|
diff --git a/src/main/java/com/google/code/magja/soap/MagentoSoapClient.java b/src/main/java/com/google/code/magja/soap/MagentoSoapClient.java
index 225f057..b06b8c9 100644
--- a/src/main/java/com/google/code/magja/soap/MagentoSoapClient.java
+++ b/src/main/java/com/google/code/magja/soap/MagentoSoapClient.java
@@ -1,182 +1,184 @@
package com.google.code.magja.soap;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import com.google.code.magja.magento.ResourcePath;
import com.google.code.magja.utils.PropertyLoader;
public class MagentoSoapClient implements SoapClient {
public static final String CONFIG_PROPERTIES_FILE = "magento-api";
private static final QName LOGIN_RETURN = new QName("loginReturn");
private static final QName LOGOUT_RETURN = new QName("endSessionReturn");
private static final QName CALL_RETURN = new QName("callReturn");
private SoapCallFactory callFactory;
private SoapReturnParser returnParser;
private SoapConfig config;
private Options connectOptions;
private String sessionId;
private ServiceClient sender;
// the instance is loaded on the first execution of MagentoSoapClient.getInstance() not before.
// remove the MagentoSoapClientHolder because the class loader will throw could not load [magento-api.properties] exception when we not include
// magento-api.properties in the class path although we want to use custom instance
private static MagentoSoapClient INSTANCE_CUSTOM;
private static MagentoSoapClient INSTANCE_DEFAULT;
/**
* The default constructor for custom connections
*/
private MagentoSoapClient() {
}
/**
* Construct soap client using given configuration
* @param soapConfig
*/
private MagentoSoapClient(SoapConfig soapConfig) {
config = soapConfig;
callFactory = new SoapCallFactory();
returnParser = new SoapReturnParser();
try {
login();
} catch (AxisFault ex) {
// do not swallow, rethrow as runtime
throw new RuntimeException(ex);
}
}
/**
* MagentoSoapClientHolder is loaded on the first execution of
* MagentoSoapClient.getInstance() or the first access to
* MagentoSoapClientHolder.INSTANCE, not before.
*/
public static MagentoSoapClient getInstance() {
if (INSTANCE_DEFAULT == null) {
INSTANCE_DEFAULT = new MagentoSoapClient(new SoapConfig(PropertyLoader.loadProperties(CONFIG_PROPERTIES_FILE)));
}
return INSTANCE_DEFAULT;
}
public static MagentoSoapClient getInstance(SoapConfig soapConfig) {
if (INSTANCE_CUSTOM == null) {
INSTANCE_CUSTOM = new MagentoSoapClient();
}
if(!soapConfig.equals(INSTANCE_CUSTOM.getConfig()))
INSTANCE_CUSTOM = new MagentoSoapClient(soapConfig);
return INSTANCE_CUSTOM;
}
/**
* @return the config
*/
public SoapConfig getConfig() {
return config;
}
/**
* Use to change the connection parameters to API (url, username, password)
*
* @param config
* the config to set
*/
public void setConfig(SoapConfig config) throws AxisFault {
this.config = config;
login();
}
public Object call(ResourcePath path, Object args) throws AxisFault {
OMElement method = callFactory.createCall(sessionId, path.getPath(),
args);
OMElement result = sender.sendReceive(method);
return returnParser.parse(result.getFirstChildWithName(CALL_RETURN));
}
public Object multiCall(List<ResourcePath> path, List<Object> args)
throws AxisFault {
throw new UnsupportedOperationException("not implemented");
}
/**
* Connect to the service using the current config
*/
protected void login() throws AxisFault {
if (isLoggedIn()) logout();
connectOptions = new Options();
connectOptions.setTo(new EndpointReference(config.getRemoteHost()));
connectOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
// to use the same tcp connection for multiple calls
// workaround:
// http://amilachinthaka.blogspot.com/2009/05/improving-axis2-client-http-transport.html
MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(httpConnectionManager);
connectOptions.setProperty(HTTPConstants.REUSE_HTTP_CLIENT,
Constants.VALUE_TRUE);
connectOptions.setProperty(HTTPConstants.CACHED_HTTP_CLIENT,
httpClient);
+ connectOptions.setProperty(HTTPConstants.HTTP_PROTOCOL_VERSION,
+ HTTPConstants.HEADER_PROTOCOL_10);
sender = new ServiceClient();
sender.setOptions(connectOptions);
OMElement loginMethod = callFactory.createLoginCall(this.config.getApiUser(), this.config.getApiKey());
OMElement loginResult = sender.sendReceive(loginMethod);
sessionId = loginResult.getFirstChildWithName(LOGIN_RETURN).getText();
}
/**
* Logout from service, throws logout exception if failed
* @throws AxisFault
*/
protected void logout() throws AxisFault {
// first, we need to logout the previous session
OMElement logoutMethod = callFactory.createLogoutCall(sessionId);
OMElement logoutResult = sender.sendReceive(logoutMethod);
Boolean logoutSuccess = Boolean.parseBoolean(logoutResult.getFirstChildWithName(
LOGOUT_RETURN).getText());
if (!logoutSuccess) {
throw new RuntimeException("Error logging out");
}
sessionId = null;
}
/**
* Are we currently logged in?
*/
protected Boolean isLoggedIn() {
return sessionId != null;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
// close the connection to magento api
// first, we need to logout the previous session
OMElement logoutMethod = callFactory.createLogoutCall(sessionId);
OMElement logoutResult = sender.sendReceive(logoutMethod);
Boolean logoutSuccess = Boolean.parseBoolean(logoutResult.getFirstChildWithName(
LOGOUT_RETURN).getText());
super.finalize();
}
}
| true | true | protected void login() throws AxisFault {
if (isLoggedIn()) logout();
connectOptions = new Options();
connectOptions.setTo(new EndpointReference(config.getRemoteHost()));
connectOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
// to use the same tcp connection for multiple calls
// workaround:
// http://amilachinthaka.blogspot.com/2009/05/improving-axis2-client-http-transport.html
MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(httpConnectionManager);
connectOptions.setProperty(HTTPConstants.REUSE_HTTP_CLIENT,
Constants.VALUE_TRUE);
connectOptions.setProperty(HTTPConstants.CACHED_HTTP_CLIENT,
httpClient);
sender = new ServiceClient();
sender.setOptions(connectOptions);
OMElement loginMethod = callFactory.createLoginCall(this.config.getApiUser(), this.config.getApiKey());
OMElement loginResult = sender.sendReceive(loginMethod);
sessionId = loginResult.getFirstChildWithName(LOGIN_RETURN).getText();
}
| protected void login() throws AxisFault {
if (isLoggedIn()) logout();
connectOptions = new Options();
connectOptions.setTo(new EndpointReference(config.getRemoteHost()));
connectOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
// to use the same tcp connection for multiple calls
// workaround:
// http://amilachinthaka.blogspot.com/2009/05/improving-axis2-client-http-transport.html
MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpClient httpClient = new HttpClient(httpConnectionManager);
connectOptions.setProperty(HTTPConstants.REUSE_HTTP_CLIENT,
Constants.VALUE_TRUE);
connectOptions.setProperty(HTTPConstants.CACHED_HTTP_CLIENT,
httpClient);
connectOptions.setProperty(HTTPConstants.HTTP_PROTOCOL_VERSION,
HTTPConstants.HEADER_PROTOCOL_10);
sender = new ServiceClient();
sender.setOptions(connectOptions);
OMElement loginMethod = callFactory.createLoginCall(this.config.getApiUser(), this.config.getApiKey());
OMElement loginResult = sender.sendReceive(loginMethod);
sessionId = loginResult.getFirstChildWithName(LOGIN_RETURN).getText();
}
|
diff --git a/esb/src/main/java/edu/nyu/grouper/util/StaticInitialGroupPropertiesProvider.java b/esb/src/main/java/edu/nyu/grouper/util/StaticInitialGroupPropertiesProvider.java
index a7527dc..a5b416d 100644
--- a/esb/src/main/java/edu/nyu/grouper/util/StaticInitialGroupPropertiesProvider.java
+++ b/esb/src/main/java/edu/nyu/grouper/util/StaticInitialGroupPropertiesProvider.java
@@ -1,30 +1,32 @@
package edu.nyu.grouper.util;
import org.apache.commons.httpclient.methods.PostMethod;
import edu.internet2.middleware.grouper.Group;
import edu.nyu.grouper.xmpp.api.InitialGroupPropertiesProvider;
/**
* Provide a set of static properties for new sakai groups.
* @author froese
*/
public class StaticInitialGroupPropertiesProvider implements InitialGroupPropertiesProvider {
public void addProperties(Group group, PostMethod method) {
// Basic info
+ method.addParameter("sakai:group-id", group.getExtension());
method.addParameter("sakai:group-title", group.getExtension());
method.addParameter("sakai:group-description", group.getDescription());
- method.addParameter("sakai:pages-template", "/var/templates/site/defaultgroup");
+ method.addParameter(":sakai:pages-template", "/var/templates/site/defaultgroup");
// Authorizations
+ method.addParameter(":sakai:manager", "admin");
+ method.addParameter("sakai:pages-visible", "members-only");
method.addParameter("group-joinable", "no");
method.addParameter("group-visible", "members-only");
- method.addParameter("sakai:pages-visible", "members-only");
// Grouper
method.addParameter("grouper:name", group.getName());
method.addParameter("grouper:uuid", group.getUuid());
}
}
| false | true | public void addProperties(Group group, PostMethod method) {
// Basic info
method.addParameter("sakai:group-title", group.getExtension());
method.addParameter("sakai:group-description", group.getDescription());
method.addParameter("sakai:pages-template", "/var/templates/site/defaultgroup");
// Authorizations
method.addParameter("group-joinable", "no");
method.addParameter("group-visible", "members-only");
method.addParameter("sakai:pages-visible", "members-only");
// Grouper
method.addParameter("grouper:name", group.getName());
method.addParameter("grouper:uuid", group.getUuid());
}
| public void addProperties(Group group, PostMethod method) {
// Basic info
method.addParameter("sakai:group-id", group.getExtension());
method.addParameter("sakai:group-title", group.getExtension());
method.addParameter("sakai:group-description", group.getDescription());
method.addParameter(":sakai:pages-template", "/var/templates/site/defaultgroup");
// Authorizations
method.addParameter(":sakai:manager", "admin");
method.addParameter("sakai:pages-visible", "members-only");
method.addParameter("group-joinable", "no");
method.addParameter("group-visible", "members-only");
// Grouper
method.addParameter("grouper:name", group.getName());
method.addParameter("grouper:uuid", group.getUuid());
}
|
diff --git a/src/standard/UserPlayer.java b/src/standard/UserPlayer.java
index 4b99757..d648a3b 100644
--- a/src/standard/UserPlayer.java
+++ b/src/standard/UserPlayer.java
@@ -1,202 +1,202 @@
package standard;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import visual.GameVisualizer;
import framework2.Drawable;
import framework2.GameState;
import framework2.Location;
import framework2.Player;
import framework2.Unit;
import framework2.Updateable;
import framework2.World;
import static standard.Constants.*;
public class UserPlayer implements Player, Updateable, Drawable {
/**
*
*/
private static final long serialVersionUID = 7098865388074696915L;
private GameVisualizer visual;
private GameState state;
private Location[] queue = new Location[1];
private int x = 0,y = 0;
private boolean endInitPhase = false;
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public UserPlayer(GameVisualizer visual){
this.visual = visual;
state = GameState.UnitPlacement;
}
@Override
public Location placeUnit(Unit unit) {
lock.lock();
while (queue[0] == null) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Location result = queue[0];
queue[0] = null;
lock.unlock();
return result;
}
@Override
public Location[] switchUnits() {
lock.lock();
if(state.equals(GameState.UnitPlacement)){
state = GameState.UnitSwitching;
queue = new Location[2];
}
while(queue[0] == null || queue[1] == null){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Location[] result = {queue[0], queue[1]};
queue[0] = null;
queue[1] = null;
lock.unlock();
return result;
}
@Override
public boolean endInitPhase() {
return endInitPhase;
}
@Override
public void updateWorld(World world) {
visual.setWorld(world);
}
@Override
public Location[] getMove(World world) {
state = GameState.GamePhase;
while(queue[0] == null || queue[1] == null){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Location[] result = {queue[0], queue[1]};
queue[0] = null;
queue[1] = null;
lock.unlock();
return result;
}
@Override
public void init(GameContainer gc) {
}
@Override
public void draw(GameContainer gc, Graphics g) {
g.setColor(Color.decode("#F87217"));
g.drawRect(x * CELLSIZE, y * CELLSIZE, CELLSIZE, CELLSIZE);
g.drawRect(x * CELLSIZE + 1, y * CELLSIZE + 1, CELLSIZE - 2, CELLSIZE - 2);
lock.lock();
if (queue[0] != null) {
g.setColor(Color.decode("#348781"));
g.drawRect(queue[0].column * CELLSIZE, queue[0].row * CELLSIZE, CELLSIZE, CELLSIZE);
g.drawRect(queue[0].column * CELLSIZE + 1, queue[0].row * CELLSIZE + 1, CELLSIZE - 2, CELLSIZE - 2);
}
if (!state.equals(GameState.UnitPlacement)) {
if (queue[1] != null) {
g.setColor(Color.decode("#348781"));
g.drawRect(queue[0].column * CELLSIZE, queue[0].row * CELLSIZE, CELLSIZE, CELLSIZE);
g.drawRect(queue[0].column * CELLSIZE + 1, queue[0].row * CELLSIZE + 1, CELLSIZE - 2, CELLSIZE - 2);
}
}
lock.unlock();
}
@Override
public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if(input.isKeyPressed(Input.KEY_DOWN)){
y++;
if(y > HEIGHT-1){
y = 0;
}
}
if(input.isKeyPressed(Input.KEY_UP)){
y--;
if(y < 0){
- y = HEIGHT;
+ y = HEIGHT-1;
}
}
if(input.isKeyPressed(Input.KEY_RIGHT)){
x++;
if(x > WIDTH-1){
x = 0;
}
}
if(input.isKeyPressed(Input.KEY_LEFT)){
x--;
if(x < 0){
- x = WIDTH;
+ x = WIDTH-1;
}
}
if(input.isKeyPressed(Input.KEY_SPACE)){
lock.lock();
switch(state){
case UnitPlacement :
if(queue[0] == null){
queue[0] = new Location(x,y);
condition.signalAll();
}
break;
case UnitSwitching :
case GamePhase :
if(queue[0] == null){
queue[0] = new Location(x,y);
}
else if(queue[1] == null){
queue[1] = new Location(x,y);
condition.signalAll();
}
else{
condition.signalAll();
}
}
lock.unlock();
}
if(input.isKeyPressed(Input.KEY_Q)){
endInitPhase = true;
}
}
}
| false | true | public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if(input.isKeyPressed(Input.KEY_DOWN)){
y++;
if(y > HEIGHT-1){
y = 0;
}
}
if(input.isKeyPressed(Input.KEY_UP)){
y--;
if(y < 0){
y = HEIGHT;
}
}
if(input.isKeyPressed(Input.KEY_RIGHT)){
x++;
if(x > WIDTH-1){
x = 0;
}
}
if(input.isKeyPressed(Input.KEY_LEFT)){
x--;
if(x < 0){
x = WIDTH;
}
}
if(input.isKeyPressed(Input.KEY_SPACE)){
lock.lock();
switch(state){
case UnitPlacement :
if(queue[0] == null){
queue[0] = new Location(x,y);
condition.signalAll();
}
break;
case UnitSwitching :
case GamePhase :
if(queue[0] == null){
queue[0] = new Location(x,y);
}
else if(queue[1] == null){
queue[1] = new Location(x,y);
condition.signalAll();
}
else{
condition.signalAll();
}
}
lock.unlock();
}
if(input.isKeyPressed(Input.KEY_Q)){
endInitPhase = true;
}
}
| public void update(GameContainer gc, int delta) {
Input input = gc.getInput();
if(input.isKeyPressed(Input.KEY_DOWN)){
y++;
if(y > HEIGHT-1){
y = 0;
}
}
if(input.isKeyPressed(Input.KEY_UP)){
y--;
if(y < 0){
y = HEIGHT-1;
}
}
if(input.isKeyPressed(Input.KEY_RIGHT)){
x++;
if(x > WIDTH-1){
x = 0;
}
}
if(input.isKeyPressed(Input.KEY_LEFT)){
x--;
if(x < 0){
x = WIDTH-1;
}
}
if(input.isKeyPressed(Input.KEY_SPACE)){
lock.lock();
switch(state){
case UnitPlacement :
if(queue[0] == null){
queue[0] = new Location(x,y);
condition.signalAll();
}
break;
case UnitSwitching :
case GamePhase :
if(queue[0] == null){
queue[0] = new Location(x,y);
}
else if(queue[1] == null){
queue[1] = new Location(x,y);
condition.signalAll();
}
else{
condition.signalAll();
}
}
lock.unlock();
}
if(input.isKeyPressed(Input.KEY_Q)){
endInitPhase = true;
}
}
|
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionTask.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionTask.java
index 5c6ea07e..70b6f579 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionTask.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionTask.java
@@ -1,136 +1,139 @@
/**
* 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.hadoop.hive.ql.exec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.common.JavaUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.DriverContext;
import org.apache.hadoop.hive.ql.QueryPlan;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.CreateFunctionDesc;
import org.apache.hadoop.hive.ql.plan.DropFunctionDesc;
import org.apache.hadoop.hive.ql.plan.FunctionWork;
import org.apache.hadoop.hive.ql.plan.api.StageType;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFResolver;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
/**
* FunctionTask.
*
*/
public class FunctionTask extends Task<FunctionWork> {
private static final long serialVersionUID = 1L;
private static transient final Log LOG = LogFactory.getLog(FunctionTask.class);
transient HiveConf conf;
public FunctionTask() {
super();
}
@Override
public void initialize(HiveConf conf, QueryPlan queryPlan, DriverContext ctx) {
super.initialize(conf, queryPlan, ctx);
this.conf = conf;
}
@Override
public int execute(DriverContext driverContext) {
CreateFunctionDesc createFunctionDesc = work.getCreateFunctionDesc();
if (createFunctionDesc != null) {
return createFunction(createFunctionDesc);
}
DropFunctionDesc dropFunctionDesc = work.getDropFunctionDesc();
if (dropFunctionDesc != null) {
return dropFunction(dropFunctionDesc);
}
return 0;
}
private int createFunction(CreateFunctionDesc createFunctionDesc) {
try {
Class<?> udfClass = getUdfClass(createFunctionDesc);
if (UDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDF(createFunctionDesc
.getFunctionName(), (Class<? extends UDF>) udfClass, false);
return 0;
} else if (GenericUDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDF>) udfClass);
return 0;
} else if (GenericUDTF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDTF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDTF>) udfClass);
return 0;
} else if (UDAF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDAF(createFunctionDesc
.getFunctionName(), (Class<? extends UDAF>) udfClass);
return 0;
} else if (GenericUDAFResolver.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDAF(createFunctionDesc
.getFunctionName(), (GenericUDAFResolver) ReflectionUtils
.newInstance(udfClass, null));
return 0;
}
+ console.printError("FAILED: Class " + createFunctionDesc.getClassName()
+ + " does not implement UDF, GenericUDF, or UDAF");
return 1;
} catch (ClassNotFoundException e) {
+ console.printError("FAILED: Class " + createFunctionDesc.getClassName() + " not found");
LOG.info("create function: " + StringUtils.stringifyException(e));
return 1;
}
}
private int dropFunction(DropFunctionDesc dropFunctionDesc) {
try {
FunctionRegistry.unregisterTemporaryUDF(dropFunctionDesc
.getFunctionName());
return 0;
} catch (HiveException e) {
LOG.info("drop function: " + StringUtils.stringifyException(e));
return 1;
}
}
@SuppressWarnings("unchecked")
private Class<?> getUdfClass(CreateFunctionDesc desc) throws ClassNotFoundException {
return Class.forName(desc.getClassName(), true, JavaUtils.getClassLoader());
}
@Override
public StageType getType() {
return StageType.FUNC;
}
@Override
public String getName() {
return "FUNCTION";
}
@Override
protected void localizeMRTmpFilesImpl(Context ctx) {
throw new RuntimeException ("Unexpected call");
}
}
| false | true | private int createFunction(CreateFunctionDesc createFunctionDesc) {
try {
Class<?> udfClass = getUdfClass(createFunctionDesc);
if (UDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDF(createFunctionDesc
.getFunctionName(), (Class<? extends UDF>) udfClass, false);
return 0;
} else if (GenericUDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDF>) udfClass);
return 0;
} else if (GenericUDTF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDTF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDTF>) udfClass);
return 0;
} else if (UDAF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDAF(createFunctionDesc
.getFunctionName(), (Class<? extends UDAF>) udfClass);
return 0;
} else if (GenericUDAFResolver.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDAF(createFunctionDesc
.getFunctionName(), (GenericUDAFResolver) ReflectionUtils
.newInstance(udfClass, null));
return 0;
}
return 1;
} catch (ClassNotFoundException e) {
LOG.info("create function: " + StringUtils.stringifyException(e));
return 1;
}
}
| private int createFunction(CreateFunctionDesc createFunctionDesc) {
try {
Class<?> udfClass = getUdfClass(createFunctionDesc);
if (UDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDF(createFunctionDesc
.getFunctionName(), (Class<? extends UDF>) udfClass, false);
return 0;
} else if (GenericUDF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDF>) udfClass);
return 0;
} else if (GenericUDTF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDTF(createFunctionDesc
.getFunctionName(), (Class<? extends GenericUDTF>) udfClass);
return 0;
} else if (UDAF.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryUDAF(createFunctionDesc
.getFunctionName(), (Class<? extends UDAF>) udfClass);
return 0;
} else if (GenericUDAFResolver.class.isAssignableFrom(udfClass)) {
FunctionRegistry.registerTemporaryGenericUDAF(createFunctionDesc
.getFunctionName(), (GenericUDAFResolver) ReflectionUtils
.newInstance(udfClass, null));
return 0;
}
console.printError("FAILED: Class " + createFunctionDesc.getClassName()
+ " does not implement UDF, GenericUDF, or UDAF");
return 1;
} catch (ClassNotFoundException e) {
console.printError("FAILED: Class " + createFunctionDesc.getClassName() + " not found");
LOG.info("create function: " + StringUtils.stringifyException(e));
return 1;
}
}
|
diff --git a/java/src/org/broadinstitute/sting/utils/genotype/vcf/VCFWriter.java b/java/src/org/broadinstitute/sting/utils/genotype/vcf/VCFWriter.java
index 751386ed2..f0042a94d 100644
--- a/java/src/org/broadinstitute/sting/utils/genotype/vcf/VCFWriter.java
+++ b/java/src/org/broadinstitute/sting/utils/genotype/vcf/VCFWriter.java
@@ -1,656 +1,659 @@
package org.broadinstitute.sting.utils.genotype.vcf;
import org.broad.tribble.vcf.*;
import org.broadinstitute.sting.gatk.contexts.variantcontext.Allele;
import org.broadinstitute.sting.gatk.contexts.variantcontext.Genotype;
import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContext;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.MathUtils;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.genotype.CalledGenotype;
import org.broadinstitute.sting.utils.pileup.ReadBackedPileup;
import java.io.*;
import java.util.*;
/**
* this class writers VCF files
*/
public class VCFWriter {
// the VCF header we're storing
private VCFHeader mHeader = null;
// the print stream we're writting to
BufferedWriter mWriter;
private boolean writingVCF40Format;
private String PASSES_FILTERS_STRING = null;
// our genotype sample fields
private static final List<VCFGenotypeRecord> mGenotypeRecords = new ArrayList<VCFGenotypeRecord>();
// Properties only used when using VCF4.0 encoding
Map<String, VCFHeaderLineType> typeUsedForFormatString = new HashMap<String, VCFHeaderLineType>();
Map<String, VCFHeaderLineType> typeUsedForInfoFields = new HashMap<String, VCFHeaderLineType>();
Map<String, Integer> numberUsedForInfoFields = new HashMap<String, Integer>();
Map<String, Integer> numberUsedForFormatFields = new HashMap<String, Integer>();
// commonly used strings that are in the standard
private final String FORMAT_FIELD_SEPARATOR = ":";
private static final String GENOTYPE_FIELD_SEPARATOR = ":";
private static final String FIELD_SEPARATOR = "\t";
private static final String FILTER_CODE_SEPARATOR = ";";
private static final String INFO_FIELD_SEPARATOR = ";";
// default values
private static final String UNFILTERED = ".";
private static final String PASSES_FILTERS_VCF3 = "0";
private static final String PASSES_FILTERS_VCF4 = "PASS";
private static final String EMPTY_INFO_FIELD = ".";
private static final String EMPTY_ID_FIELD = ".";
private static final String EMPTY_ALLELE_FIELD = ".";
private static final String DOUBLE_PRECISION_FORMAT_STRING = "%.2f";
private static final String MISSING_GENOTYPE_FIELD = ".";
/**
* create a VCF writer, given a file to write to
*
* @param location the file location to write to
*/
public VCFWriter(File location) {
this(location, false);
}
public VCFWriter(File location, boolean useVCF4Format) {
this.writingVCF40Format = useVCF4Format;
this.PASSES_FILTERS_STRING = useVCF4Format ? PASSES_FILTERS_VCF4 : PASSES_FILTERS_VCF3;
FileOutputStream output;
try {
output = new FileOutputStream(location);
} catch (FileNotFoundException e) {
throw new RuntimeException("Unable to create VCF file at location: " + location);
}
mWriter = new BufferedWriter(new OutputStreamWriter(output));
}
/**
* create a VCF writer, given a stream to write to
*
* @param output the file location to write to
*/
public VCFWriter(OutputStream output) {
// use VCF3.3 by default
this(output, false);
}
public VCFWriter(OutputStream output, boolean useVCF4Format) {
this.writingVCF40Format = useVCF4Format;
this.PASSES_FILTERS_STRING = useVCF4Format ? PASSES_FILTERS_VCF4 : PASSES_FILTERS_VCF3;
mWriter = new BufferedWriter(new OutputStreamWriter(output));
}
public void writeHeader(VCFHeader header) {
this.mHeader = header;
try {
// the file format field needs to be written first
TreeSet<VCFHeaderLine> nonFormatMetaData = new TreeSet<VCFHeaderLine>();
for ( VCFHeaderLine line : header.getMetaData() ) {
if (writingVCF40Format) {
if ( line.getKey().equals(VCFHeaderVersion.VCF4_0.getFormatString()) ) {
mWriter.write(VCFHeader.METADATA_INDICATOR + VCFHeaderVersion.VCF4_0.getFormatString() + "=" + VCFHeaderVersion.VCF4_0.getVersionString() + "\n");
} else {
nonFormatMetaData.add(line);
}
// Record, if line corresponds to a FORMAT field, which type will be used for writing value
if (line.getClass() == VCFFormatHeaderLine.class) {
VCFFormatHeaderLine a = (VCFFormatHeaderLine)line;
String key = a.getName();
typeUsedForFormatString.put(key,a.getType());
int num = a.getCount();
numberUsedForFormatFields.put(key,num);
} else if (line.getClass() == VCFInfoHeaderLine.class) {
VCFInfoHeaderLine a = (VCFInfoHeaderLine)line;
String key = a.getName();
typeUsedForInfoFields.put(key,a.getType());
int num = a.getCount();
numberUsedForInfoFields.put(key, num);
}
}
else {
if ( line.getKey().equals(VCFHeaderVersion.VCF3_3.getFormatString()) ) {
mWriter.write(VCFHeader.METADATA_INDICATOR + line.toString() + "\n");
}
else if ( line.getKey().equals(VCFHeaderVersion.VCF3_2.getFormatString()) ) {
mWriter.write(VCFHeader.METADATA_INDICATOR + VCFHeaderVersion.VCF3_2.getFormatString() + "=" + VCFHeaderVersion.VCF3_2.getVersionString() + "\n");
} else {
nonFormatMetaData.add(line);
}
}
}
// write the rest of the header meta-data out
for ( VCFHeaderLine line : nonFormatMetaData )
mWriter.write(VCFHeader.METADATA_INDICATOR + line + "\n");
// write out the column line
StringBuilder b = new StringBuilder();
b.append(VCFHeader.HEADER_INDICATOR);
for (VCFHeader.HEADER_FIELDS field : header.getHeaderFields())
b.append(field + FIELD_SEPARATOR);
if (header.hasGenotypingData()) {
b.append("FORMAT" + FIELD_SEPARATOR);
for (String field : header.getGenotypeSamples())
b.append(field + FIELD_SEPARATOR);
}
mWriter.write(b.toString() + "\n");
mWriter.flush(); // necessary so that writing to an output stream will work
}
catch (IOException e) {
throw new RuntimeException("IOException writing the VCF header", e);
}
}
/**
* output a record to the VCF file
*
* @param record the record to output
*/
public void add(VCFRecord record) {
addRecord(record);
}
public void addRecord(VCFRecord record) {
addRecord(record, VCFGenotypeWriter.VALIDATION_STRINGENCY.STRICT);
}
public void add(VariantContext vc, byte[] refBases) {
if ( mHeader == null )
throw new IllegalStateException("The VCF Header must be written before records can be added");
if (!writingVCF40Format)
throw new IllegalStateException("VCFWriter can only support add() method with a variant context if writing VCF4.0. Use VCFWriter(output, true) when constructing object");
String vcfString = toStringEncoding(vc, mHeader, refBases);
try {
mWriter.write(vcfString + "\n");
mWriter.flush(); // necessary so that writing to an output stream will work
} catch (IOException e) {
throw new RuntimeException("Unable to write the VCF object to a file");
}
}
/**
* output a record to the VCF file
*
* @param record the record to output
* @param validationStringency the validation stringency
*/
public void addRecord(VCFRecord record, VCFGenotypeWriter.VALIDATION_STRINGENCY validationStringency) {
if ( mHeader == null )
throw new IllegalStateException("The VCF Header must be written before records can be added");
String vcfString = record.toStringEncoding(mHeader);
try {
mWriter.write(vcfString + "\n");
mWriter.flush(); // necessary so that writing to an output stream will work
} catch (IOException e) {
throw new RuntimeException("Unable to write the VCF object to a file");
}
}
/**
* attempt to close the VCF file
*/
public void close() {
try {
mWriter.flush();
mWriter.close();
} catch (IOException e) {
throw new RuntimeException("Unable to close VCFFile");
}
}
private String toStringEncoding(VariantContext vc, VCFHeader header, byte[] refBases) {
StringBuilder builder = new StringBuilder();
// CHROM \t POS \t ID \t REF \t ALT \t QUAL \t FILTER \t INFO
GenomeLoc loc = vc.getLocation();
String contig = loc.getContig();
long position = loc.getStart();
String ID = vc.hasAttribute("ID") ? vc.getAttributeAsString("ID") : EMPTY_ID_FIELD;
// deal with the reference
String referenceFromVC = new String(vc.getReference().getBases());
double qual = vc.hasNegLog10PError() ? vc.getPhredScaledQual() : -1;
// TODO- clean up these flags and associated code
boolean filtersWereAppliedToContext = true;
List<String> allowedGenotypeAttributeKeys = null;
String filters = vc.isFiltered() ? Utils.join(";", Utils.sorted(vc.getFilters())) : (filtersWereAppliedToContext ? PASSES_FILTERS_STRING : UNFILTERED);
Map<Allele, VCFGenotypeEncoding> alleleMap = new HashMap<Allele, VCFGenotypeEncoding>();
alleleMap.put(Allele.NO_CALL, new VCFGenotypeEncoding(VCFGenotypeRecord.EMPTY_ALLELE)); // convenience for lookup
List<VCFGenotypeEncoding> vcfAltAlleles = new ArrayList<VCFGenotypeEncoding>();
int numTrailingBases = 0, numPaddingBases = 0;
String paddingBases = "";
String trailingBases = "";
ArrayList<Allele> originalAlleles = (ArrayList)vc.getAttribute("ORIGINAL_ALLELE_LIST");
// search for reference allele and find trailing and padding at the end.
// See first if all alleles have a base encoding (ie no deletions)
// if so, add one common base to all alleles (reference at this location)
boolean hasBasesInAllAlleles = true;
String refString = null;
for ( Allele a : vc.getAlleles() ) {
if (a.isNull() || a.isNoCall())
hasBasesInAllAlleles = false;
if (a.isReference())
refString = new String(a.getBases());
}
if (originalAlleles != null) {
// if original allele info was filled when reading from a VCF4 file,
// determine whether there was a padding base(s) at the beginning and end.
byte previousBase = 0;
int cnt=0;
boolean firstBaseCommonInAllAlleles = true;
Allele originalReferenceAllele = null;
for (Allele originalAllele : originalAlleles){
// if first base of allele is common to all of them, there may have been a common base deleted from all
byte firstBase = originalAllele.getBases()[0];
if (cnt > 0) {
if (firstBase != previousBase)
firstBaseCommonInAllAlleles = false;
}
previousBase = firstBase;
cnt++;
if (originalAllele.isReference())
originalReferenceAllele = originalAllele;
}
numTrailingBases = (firstBaseCommonInAllAlleles)? 1:0;
position -= numTrailingBases;
if (originalReferenceAllele == null)
throw new IllegalStateException("At least one Allele must be reference");
String originalRef = new String(originalReferenceAllele.getBases());
numPaddingBases = originalRef.length()-refString.length()-numTrailingBases;
if (numTrailingBases > 0) {
trailingBases = originalRef.substring(0,numTrailingBases);
}
if (numPaddingBases > 0)
paddingBases = originalRef.substring(originalRef.length()-numPaddingBases,originalRef.length());
}
else {
// Case where there is no original allele info, e.g. when reading from VCF3.3 or when vc was produced by the GATK.
if (!hasBasesInAllAlleles) {
trailingBases = new String(refBases);
numTrailingBases = 1;
position--;
}
}
for ( Allele a : vc.getAlleles() ) {
VCFGenotypeEncoding encoding;
String alleleString = new String(a.getBases());
String s = trailingBases+alleleString+paddingBases;
encoding = new VCFGenotypeEncoding(s, true);
// overwrite reference string by possibly padded version
if (a.isReference())
referenceFromVC = s;
else {
vcfAltAlleles.add(encoding);
}
alleleMap.put(a, encoding);
}
List<String> vcfGenotypeAttributeKeys = new ArrayList<String>();
if ( vc.hasGenotypes() ) {
vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY);
for ( String key : calcVCFGenotypeKeys(vc) ) {
if ( allowedGenotypeAttributeKeys == null || allowedGenotypeAttributeKeys.contains(key) )
vcfGenotypeAttributeKeys.add(key);
}
+ } else if ( header.hasGenotypingData() ) {
+ // this needs to be done in case all samples are no-calls
+ vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY);
}
String genotypeFormatString = Utils.join(GENOTYPE_FIELD_SEPARATOR, vcfGenotypeAttributeKeys);
List<VCFGenotypeRecord> genotypeObjects = new ArrayList<VCFGenotypeRecord>(vc.getGenotypes().size());
for ( Genotype g : vc.getGenotypesSortedByName() ) {
List<VCFGenotypeEncoding> encodings = new ArrayList<VCFGenotypeEncoding>(g.getPloidy());
for ( Allele a : g.getAlleles() ) {
encodings.add(alleleMap.get(a));
}
VCFGenotypeRecord.PHASE phasing = g.genotypesArePhased() ? VCFGenotypeRecord.PHASE.PHASED : VCFGenotypeRecord.PHASE.UNPHASED;
VCFGenotypeRecord vcfG = new VCFGenotypeRecord(g.getSampleName(), encodings, phasing);
for ( String key : vcfGenotypeAttributeKeys ) {
if ( key.equals(VCFGenotypeRecord.GENOTYPE_KEY) )
continue;
Object val = g.hasAttribute(key) ? g.getAttribute(key) : MISSING_GENOTYPE_FIELD;
// some exceptions
if ( key.equals(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY) ) {
if ( MathUtils.compareDoubles(g.getNegLog10PError(), Genotype.NO_NEG_LOG_10PERROR) == 0 )
val = MISSING_GENOTYPE_FIELD;
else {
// TODO - check whether we need to saturate quality to 99 as in VCF3.3 coder. For now allow unbounded values
// val = Math.min(g.getPhredScaledQual(), VCFGenotypeRecord.MAX_QUAL_VALUE);
val = g.getPhredScaledQual();
}
} else if ( key.equals(VCFGenotypeRecord.DEPTH_KEY) && val == null ) {
ReadBackedPileup pileup = (ReadBackedPileup)g.getAttribute(CalledGenotype.READBACKEDPILEUP_ATTRIBUTE_KEY);
if ( pileup != null )
val = pileup.size();
} else if ( key.equals(VCFGenotypeRecord.GENOTYPE_FILTER_KEY) ) {
// VCF 4.0 key for no filters is "."
val = g.isFiltered() ? Utils.join(";", Utils.sorted(g.getFilters())) : PASSES_FILTERS_STRING;
}
Object newVal;
if (typeUsedForFormatString.containsKey(key)) {
VCFHeaderLineType formatType = typeUsedForFormatString.get(key);
if (!val.getClass().equals(String.class))
newVal = formatType.convert(String.valueOf(val), VCFCompoundHeaderLine.SupportedHeaderLineType.FORMAT);
else
newVal = val;
}
else {
newVal = val;
}
if (numberUsedForFormatFields.containsKey(key)){
int numInFormatField = numberUsedForFormatFields.get(key);
if (numInFormatField>1 && val.equals(MISSING_GENOTYPE_FIELD)) {
// If we have a missing field but multiple values are expected, we need to construct new string with all fields.
// for example for Number =2, string has to be ".,."
StringBuilder v = new StringBuilder(MISSING_GENOTYPE_FIELD);
for ( int i = 1; i < numInFormatField; i++ ) {
v.append(",");
v.append(MISSING_GENOTYPE_FIELD);
}
newVal = v.toString();
}
}
// assume that if key is absent, given string encoding suffices.
String outputValue = formatVCFField(key, newVal);
if ( outputValue != null )
vcfG.setField(key, outputValue);
}
genotypeObjects.add(vcfG);
}
mGenotypeRecords.clear();
mGenotypeRecords.addAll(genotypeObjects);
// info fields
Map<String, String> infoFields = new TreeMap<String, String>();
for ( Map.Entry<String, Object> elt : vc.getAttributes().entrySet() ) {
String key = elt.getKey();
if ( key.equals("ID") )
continue;
// Original alleles are not for reporting but only for internal bookkeeping
if (key.equals("ORIGINAL_ALLELE_LIST"))
continue;
String outputValue = formatVCFField(key, elt.getValue());
if ( outputValue != null )
infoFields.put(key, outputValue);
}
builder.append(contig);
builder.append(FIELD_SEPARATOR);
builder.append(position);
builder.append(FIELD_SEPARATOR);
builder.append(ID);
builder.append(FIELD_SEPARATOR);
builder.append(referenceFromVC);
builder.append(FIELD_SEPARATOR);
if ( vcfAltAlleles.size() > 0 ) {
builder.append(vcfAltAlleles.get(0));
for ( int i = 1; i < vcfAltAlleles.size(); i++ ) {
builder.append(",");
builder.append(vcfAltAlleles.get(i));
}
} else {
builder.append(EMPTY_ALLELE_FIELD);
}
builder.append(FIELD_SEPARATOR);
if ( qual == -1 )
builder.append(MISSING_GENOTYPE_FIELD);
else
builder.append(String.format(DOUBLE_PRECISION_FORMAT_STRING, qual));
builder.append(FIELD_SEPARATOR);
builder.append(filters);
builder.append(FIELD_SEPARATOR);
builder.append(createInfoString(infoFields));
if ( genotypeFormatString != null && genotypeFormatString.length() > 0 ) {
addGenotypeData(builder, header, genotypeFormatString, vcfAltAlleles);
}
return builder.toString();
}
/**
* add the genotype data
*
* @param builder the string builder
* @param header the header object
* @param genotypeFormatString Genotype formatting string
* @param vcfAltAlleles alternate alleles at this site
*/
private void addGenotypeData(StringBuilder builder, VCFHeader header,
String genotypeFormatString, List<VCFGenotypeEncoding>vcfAltAlleles) {
Map<String, VCFGenotypeRecord> gMap = genotypeListToMap(mGenotypeRecords);
StringBuffer tempStr = new StringBuffer();
if ( header.getGenotypeSamples().size() < mGenotypeRecords.size() ) {
for ( String sample : gMap.keySet() ) {
if ( !header.getGenotypeSamples().contains(sample) )
System.err.println("Sample " + sample + " is a duplicate or is otherwise not present in the header");
else
header.getGenotypeSamples().remove(sample);
}
throw new IllegalStateException("We have more genotype samples than the header specified; please check that samples aren't duplicated");
}
tempStr.append(FIELD_SEPARATOR + genotypeFormatString);
String[] genotypeFormatStrings = genotypeFormatString.split(":");
for ( String genotype : header.getGenotypeSamples() ) {
tempStr.append(FIELD_SEPARATOR);
if ( gMap.containsKey(genotype) ) {
VCFGenotypeRecord rec = gMap.get(genotype);
String genotypeString = rec.toStringEncoding(vcfAltAlleles, genotypeFormatStrings, true);
// Override default produced genotype string when there are trailing
String[] genotypeStrings = genotypeString.split(":");
int lastUsedPosition = 0;
for (int k=genotypeStrings.length-1; k >=1; k--) {
// see if string represents an empty field. If not, break.
if (!isEmptyField(genotypeStrings[k]) ) {
lastUsedPosition = k;
break;
}
}
// now reconstruct genotypeString from 0 to lastUsedPosition
genotypeString = Utils.join(":",genotypeStrings, 0,lastUsedPosition+1);
tempStr.append(genotypeString);
gMap.remove(genotype);
} else {
tempStr.append(VCFGenotypeRecord.stringEncodingForEmptyGenotype(genotypeFormatStrings, true));
}
}
if ( gMap.size() != 0 ) {
for ( String sample : gMap.keySet() )
System.err.println("Sample " + sample + " is being genotyped but isn't in the header.");
throw new IllegalStateException("We failed to use all the genotype samples; there must be an inconsistancy between the header and records");
}
builder.append(tempStr);
}
boolean isEmptyField(String field) {
// check if given genotype field is empty, ie either ".", or ".,.", or ".,.,.", etc.
String[] fields = field.split(",");
boolean isEmpty = true;
for (int k=0; k < fields.length; k++) {
if (!fields[k].matches(".")) {
isEmpty = false;
break;
}
}
return isEmpty;
}
/**
* create a genotype mapping from a list and their sample names
*
* @param list a list of genotype samples
* @return a mapping of the sample name to VCF genotype record
*/
private static Map<String, VCFGenotypeRecord> genotypeListToMap(List<VCFGenotypeRecord> list) {
Map<String, VCFGenotypeRecord> map = new HashMap<String, VCFGenotypeRecord>();
for (int i = 0; i < list.size(); i++) {
VCFGenotypeRecord rec = list.get(i);
map.put(rec.getSampleName(), rec);
}
return map;
}
/**
* create the info string
*
* @param infoFields a map of info fields
* @return a string representing the infomation fields
*/
protected String createInfoString(Map<String,String> infoFields) {
StringBuffer info = new StringBuffer();
boolean isFirst = true;
for (Map.Entry<String, String> entry : infoFields.entrySet()) {
if ( isFirst )
isFirst = false;
else
info.append(INFO_FIELD_SEPARATOR);
info.append(entry.getKey());
if ( entry.getValue() != null && !entry.getValue().equals("") ) {
int numVals = 1;
if (this.writingVCF40Format) {
String key = entry.getKey();
if (numberUsedForInfoFields.containsKey(key)) {
numVals = numberUsedForInfoFields.get(key);
}
// take care of unbounded encoding
// TODO - workaround for "-1" in original INFO header structure
if (numVals == VCFInfoHeaderLine.UNBOUNDED || numVals < 0)
numVals = 1;
}
if (numVals > 0) {
info.append("=");
info.append(entry.getValue());
}
}
}
return info.length() == 0 ? EMPTY_INFO_FIELD : info.toString();
}
private static String formatVCFField(String key, Object val) {
String result;
if ( val == null )
result = VCFGenotypeRecord.getMissingFieldValue(key);
else if ( val instanceof Double ) {
result = String.format("%.2f", (Double)val);
}
else if ( val instanceof Boolean )
result = (Boolean)val ? "" : null; // empty string for true, null for false
else if ( val instanceof List ) {
List list = (List)val;
if ( list.size() == 0 )
return formatVCFField(key, null);
StringBuffer sb = new StringBuffer(formatVCFField(key, list.get(0)));
for ( int i = 1; i < list.size(); i++) {
sb.append(",");
sb.append(formatVCFField(key, list.get(i)));
}
result = sb.toString();
} else
result = val.toString();
return result;
}
private static List<String> calcVCFGenotypeKeys(VariantContext vc) {
Set<String> keys = new HashSet<String>();
boolean sawGoodQual = false;
for ( Genotype g : vc.getGenotypes().values() ) {
keys.addAll(g.getAttributes().keySet());
if ( g.hasNegLog10PError() )
sawGoodQual = true;
}
if ( sawGoodQual )
keys.add(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY);
return Utils.sorted(new ArrayList<String>(keys));
}
}
| true | true | private String toStringEncoding(VariantContext vc, VCFHeader header, byte[] refBases) {
StringBuilder builder = new StringBuilder();
// CHROM \t POS \t ID \t REF \t ALT \t QUAL \t FILTER \t INFO
GenomeLoc loc = vc.getLocation();
String contig = loc.getContig();
long position = loc.getStart();
String ID = vc.hasAttribute("ID") ? vc.getAttributeAsString("ID") : EMPTY_ID_FIELD;
// deal with the reference
String referenceFromVC = new String(vc.getReference().getBases());
double qual = vc.hasNegLog10PError() ? vc.getPhredScaledQual() : -1;
// TODO- clean up these flags and associated code
boolean filtersWereAppliedToContext = true;
List<String> allowedGenotypeAttributeKeys = null;
String filters = vc.isFiltered() ? Utils.join(";", Utils.sorted(vc.getFilters())) : (filtersWereAppliedToContext ? PASSES_FILTERS_STRING : UNFILTERED);
Map<Allele, VCFGenotypeEncoding> alleleMap = new HashMap<Allele, VCFGenotypeEncoding>();
alleleMap.put(Allele.NO_CALL, new VCFGenotypeEncoding(VCFGenotypeRecord.EMPTY_ALLELE)); // convenience for lookup
List<VCFGenotypeEncoding> vcfAltAlleles = new ArrayList<VCFGenotypeEncoding>();
int numTrailingBases = 0, numPaddingBases = 0;
String paddingBases = "";
String trailingBases = "";
ArrayList<Allele> originalAlleles = (ArrayList)vc.getAttribute("ORIGINAL_ALLELE_LIST");
// search for reference allele and find trailing and padding at the end.
// See first if all alleles have a base encoding (ie no deletions)
// if so, add one common base to all alleles (reference at this location)
boolean hasBasesInAllAlleles = true;
String refString = null;
for ( Allele a : vc.getAlleles() ) {
if (a.isNull() || a.isNoCall())
hasBasesInAllAlleles = false;
if (a.isReference())
refString = new String(a.getBases());
}
if (originalAlleles != null) {
// if original allele info was filled when reading from a VCF4 file,
// determine whether there was a padding base(s) at the beginning and end.
byte previousBase = 0;
int cnt=0;
boolean firstBaseCommonInAllAlleles = true;
Allele originalReferenceAllele = null;
for (Allele originalAllele : originalAlleles){
// if first base of allele is common to all of them, there may have been a common base deleted from all
byte firstBase = originalAllele.getBases()[0];
if (cnt > 0) {
if (firstBase != previousBase)
firstBaseCommonInAllAlleles = false;
}
previousBase = firstBase;
cnt++;
if (originalAllele.isReference())
originalReferenceAllele = originalAllele;
}
numTrailingBases = (firstBaseCommonInAllAlleles)? 1:0;
position -= numTrailingBases;
if (originalReferenceAllele == null)
throw new IllegalStateException("At least one Allele must be reference");
String originalRef = new String(originalReferenceAllele.getBases());
numPaddingBases = originalRef.length()-refString.length()-numTrailingBases;
if (numTrailingBases > 0) {
trailingBases = originalRef.substring(0,numTrailingBases);
}
if (numPaddingBases > 0)
paddingBases = originalRef.substring(originalRef.length()-numPaddingBases,originalRef.length());
}
else {
// Case where there is no original allele info, e.g. when reading from VCF3.3 or when vc was produced by the GATK.
if (!hasBasesInAllAlleles) {
trailingBases = new String(refBases);
numTrailingBases = 1;
position--;
}
}
for ( Allele a : vc.getAlleles() ) {
VCFGenotypeEncoding encoding;
String alleleString = new String(a.getBases());
String s = trailingBases+alleleString+paddingBases;
encoding = new VCFGenotypeEncoding(s, true);
// overwrite reference string by possibly padded version
if (a.isReference())
referenceFromVC = s;
else {
vcfAltAlleles.add(encoding);
}
alleleMap.put(a, encoding);
}
List<String> vcfGenotypeAttributeKeys = new ArrayList<String>();
if ( vc.hasGenotypes() ) {
vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY);
for ( String key : calcVCFGenotypeKeys(vc) ) {
if ( allowedGenotypeAttributeKeys == null || allowedGenotypeAttributeKeys.contains(key) )
vcfGenotypeAttributeKeys.add(key);
}
}
String genotypeFormatString = Utils.join(GENOTYPE_FIELD_SEPARATOR, vcfGenotypeAttributeKeys);
List<VCFGenotypeRecord> genotypeObjects = new ArrayList<VCFGenotypeRecord>(vc.getGenotypes().size());
for ( Genotype g : vc.getGenotypesSortedByName() ) {
List<VCFGenotypeEncoding> encodings = new ArrayList<VCFGenotypeEncoding>(g.getPloidy());
for ( Allele a : g.getAlleles() ) {
encodings.add(alleleMap.get(a));
}
VCFGenotypeRecord.PHASE phasing = g.genotypesArePhased() ? VCFGenotypeRecord.PHASE.PHASED : VCFGenotypeRecord.PHASE.UNPHASED;
VCFGenotypeRecord vcfG = new VCFGenotypeRecord(g.getSampleName(), encodings, phasing);
for ( String key : vcfGenotypeAttributeKeys ) {
if ( key.equals(VCFGenotypeRecord.GENOTYPE_KEY) )
continue;
Object val = g.hasAttribute(key) ? g.getAttribute(key) : MISSING_GENOTYPE_FIELD;
// some exceptions
if ( key.equals(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY) ) {
if ( MathUtils.compareDoubles(g.getNegLog10PError(), Genotype.NO_NEG_LOG_10PERROR) == 0 )
val = MISSING_GENOTYPE_FIELD;
else {
// TODO - check whether we need to saturate quality to 99 as in VCF3.3 coder. For now allow unbounded values
// val = Math.min(g.getPhredScaledQual(), VCFGenotypeRecord.MAX_QUAL_VALUE);
val = g.getPhredScaledQual();
}
} else if ( key.equals(VCFGenotypeRecord.DEPTH_KEY) && val == null ) {
ReadBackedPileup pileup = (ReadBackedPileup)g.getAttribute(CalledGenotype.READBACKEDPILEUP_ATTRIBUTE_KEY);
if ( pileup != null )
val = pileup.size();
} else if ( key.equals(VCFGenotypeRecord.GENOTYPE_FILTER_KEY) ) {
// VCF 4.0 key for no filters is "."
val = g.isFiltered() ? Utils.join(";", Utils.sorted(g.getFilters())) : PASSES_FILTERS_STRING;
}
Object newVal;
if (typeUsedForFormatString.containsKey(key)) {
VCFHeaderLineType formatType = typeUsedForFormatString.get(key);
if (!val.getClass().equals(String.class))
newVal = formatType.convert(String.valueOf(val), VCFCompoundHeaderLine.SupportedHeaderLineType.FORMAT);
else
newVal = val;
}
else {
newVal = val;
}
if (numberUsedForFormatFields.containsKey(key)){
int numInFormatField = numberUsedForFormatFields.get(key);
if (numInFormatField>1 && val.equals(MISSING_GENOTYPE_FIELD)) {
// If we have a missing field but multiple values are expected, we need to construct new string with all fields.
// for example for Number =2, string has to be ".,."
StringBuilder v = new StringBuilder(MISSING_GENOTYPE_FIELD);
for ( int i = 1; i < numInFormatField; i++ ) {
v.append(",");
v.append(MISSING_GENOTYPE_FIELD);
}
newVal = v.toString();
}
}
// assume that if key is absent, given string encoding suffices.
String outputValue = formatVCFField(key, newVal);
if ( outputValue != null )
vcfG.setField(key, outputValue);
}
genotypeObjects.add(vcfG);
}
mGenotypeRecords.clear();
mGenotypeRecords.addAll(genotypeObjects);
// info fields
Map<String, String> infoFields = new TreeMap<String, String>();
for ( Map.Entry<String, Object> elt : vc.getAttributes().entrySet() ) {
String key = elt.getKey();
if ( key.equals("ID") )
continue;
// Original alleles are not for reporting but only for internal bookkeeping
if (key.equals("ORIGINAL_ALLELE_LIST"))
continue;
String outputValue = formatVCFField(key, elt.getValue());
if ( outputValue != null )
infoFields.put(key, outputValue);
}
builder.append(contig);
builder.append(FIELD_SEPARATOR);
builder.append(position);
builder.append(FIELD_SEPARATOR);
builder.append(ID);
builder.append(FIELD_SEPARATOR);
builder.append(referenceFromVC);
builder.append(FIELD_SEPARATOR);
if ( vcfAltAlleles.size() > 0 ) {
builder.append(vcfAltAlleles.get(0));
for ( int i = 1; i < vcfAltAlleles.size(); i++ ) {
builder.append(",");
builder.append(vcfAltAlleles.get(i));
}
} else {
builder.append(EMPTY_ALLELE_FIELD);
}
builder.append(FIELD_SEPARATOR);
if ( qual == -1 )
builder.append(MISSING_GENOTYPE_FIELD);
else
builder.append(String.format(DOUBLE_PRECISION_FORMAT_STRING, qual));
builder.append(FIELD_SEPARATOR);
builder.append(filters);
builder.append(FIELD_SEPARATOR);
builder.append(createInfoString(infoFields));
if ( genotypeFormatString != null && genotypeFormatString.length() > 0 ) {
addGenotypeData(builder, header, genotypeFormatString, vcfAltAlleles);
}
return builder.toString();
}
| private String toStringEncoding(VariantContext vc, VCFHeader header, byte[] refBases) {
StringBuilder builder = new StringBuilder();
// CHROM \t POS \t ID \t REF \t ALT \t QUAL \t FILTER \t INFO
GenomeLoc loc = vc.getLocation();
String contig = loc.getContig();
long position = loc.getStart();
String ID = vc.hasAttribute("ID") ? vc.getAttributeAsString("ID") : EMPTY_ID_FIELD;
// deal with the reference
String referenceFromVC = new String(vc.getReference().getBases());
double qual = vc.hasNegLog10PError() ? vc.getPhredScaledQual() : -1;
// TODO- clean up these flags and associated code
boolean filtersWereAppliedToContext = true;
List<String> allowedGenotypeAttributeKeys = null;
String filters = vc.isFiltered() ? Utils.join(";", Utils.sorted(vc.getFilters())) : (filtersWereAppliedToContext ? PASSES_FILTERS_STRING : UNFILTERED);
Map<Allele, VCFGenotypeEncoding> alleleMap = new HashMap<Allele, VCFGenotypeEncoding>();
alleleMap.put(Allele.NO_CALL, new VCFGenotypeEncoding(VCFGenotypeRecord.EMPTY_ALLELE)); // convenience for lookup
List<VCFGenotypeEncoding> vcfAltAlleles = new ArrayList<VCFGenotypeEncoding>();
int numTrailingBases = 0, numPaddingBases = 0;
String paddingBases = "";
String trailingBases = "";
ArrayList<Allele> originalAlleles = (ArrayList)vc.getAttribute("ORIGINAL_ALLELE_LIST");
// search for reference allele and find trailing and padding at the end.
// See first if all alleles have a base encoding (ie no deletions)
// if so, add one common base to all alleles (reference at this location)
boolean hasBasesInAllAlleles = true;
String refString = null;
for ( Allele a : vc.getAlleles() ) {
if (a.isNull() || a.isNoCall())
hasBasesInAllAlleles = false;
if (a.isReference())
refString = new String(a.getBases());
}
if (originalAlleles != null) {
// if original allele info was filled when reading from a VCF4 file,
// determine whether there was a padding base(s) at the beginning and end.
byte previousBase = 0;
int cnt=0;
boolean firstBaseCommonInAllAlleles = true;
Allele originalReferenceAllele = null;
for (Allele originalAllele : originalAlleles){
// if first base of allele is common to all of them, there may have been a common base deleted from all
byte firstBase = originalAllele.getBases()[0];
if (cnt > 0) {
if (firstBase != previousBase)
firstBaseCommonInAllAlleles = false;
}
previousBase = firstBase;
cnt++;
if (originalAllele.isReference())
originalReferenceAllele = originalAllele;
}
numTrailingBases = (firstBaseCommonInAllAlleles)? 1:0;
position -= numTrailingBases;
if (originalReferenceAllele == null)
throw new IllegalStateException("At least one Allele must be reference");
String originalRef = new String(originalReferenceAllele.getBases());
numPaddingBases = originalRef.length()-refString.length()-numTrailingBases;
if (numTrailingBases > 0) {
trailingBases = originalRef.substring(0,numTrailingBases);
}
if (numPaddingBases > 0)
paddingBases = originalRef.substring(originalRef.length()-numPaddingBases,originalRef.length());
}
else {
// Case where there is no original allele info, e.g. when reading from VCF3.3 or when vc was produced by the GATK.
if (!hasBasesInAllAlleles) {
trailingBases = new String(refBases);
numTrailingBases = 1;
position--;
}
}
for ( Allele a : vc.getAlleles() ) {
VCFGenotypeEncoding encoding;
String alleleString = new String(a.getBases());
String s = trailingBases+alleleString+paddingBases;
encoding = new VCFGenotypeEncoding(s, true);
// overwrite reference string by possibly padded version
if (a.isReference())
referenceFromVC = s;
else {
vcfAltAlleles.add(encoding);
}
alleleMap.put(a, encoding);
}
List<String> vcfGenotypeAttributeKeys = new ArrayList<String>();
if ( vc.hasGenotypes() ) {
vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY);
for ( String key : calcVCFGenotypeKeys(vc) ) {
if ( allowedGenotypeAttributeKeys == null || allowedGenotypeAttributeKeys.contains(key) )
vcfGenotypeAttributeKeys.add(key);
}
} else if ( header.hasGenotypingData() ) {
// this needs to be done in case all samples are no-calls
vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY);
}
String genotypeFormatString = Utils.join(GENOTYPE_FIELD_SEPARATOR, vcfGenotypeAttributeKeys);
List<VCFGenotypeRecord> genotypeObjects = new ArrayList<VCFGenotypeRecord>(vc.getGenotypes().size());
for ( Genotype g : vc.getGenotypesSortedByName() ) {
List<VCFGenotypeEncoding> encodings = new ArrayList<VCFGenotypeEncoding>(g.getPloidy());
for ( Allele a : g.getAlleles() ) {
encodings.add(alleleMap.get(a));
}
VCFGenotypeRecord.PHASE phasing = g.genotypesArePhased() ? VCFGenotypeRecord.PHASE.PHASED : VCFGenotypeRecord.PHASE.UNPHASED;
VCFGenotypeRecord vcfG = new VCFGenotypeRecord(g.getSampleName(), encodings, phasing);
for ( String key : vcfGenotypeAttributeKeys ) {
if ( key.equals(VCFGenotypeRecord.GENOTYPE_KEY) )
continue;
Object val = g.hasAttribute(key) ? g.getAttribute(key) : MISSING_GENOTYPE_FIELD;
// some exceptions
if ( key.equals(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY) ) {
if ( MathUtils.compareDoubles(g.getNegLog10PError(), Genotype.NO_NEG_LOG_10PERROR) == 0 )
val = MISSING_GENOTYPE_FIELD;
else {
// TODO - check whether we need to saturate quality to 99 as in VCF3.3 coder. For now allow unbounded values
// val = Math.min(g.getPhredScaledQual(), VCFGenotypeRecord.MAX_QUAL_VALUE);
val = g.getPhredScaledQual();
}
} else if ( key.equals(VCFGenotypeRecord.DEPTH_KEY) && val == null ) {
ReadBackedPileup pileup = (ReadBackedPileup)g.getAttribute(CalledGenotype.READBACKEDPILEUP_ATTRIBUTE_KEY);
if ( pileup != null )
val = pileup.size();
} else if ( key.equals(VCFGenotypeRecord.GENOTYPE_FILTER_KEY) ) {
// VCF 4.0 key for no filters is "."
val = g.isFiltered() ? Utils.join(";", Utils.sorted(g.getFilters())) : PASSES_FILTERS_STRING;
}
Object newVal;
if (typeUsedForFormatString.containsKey(key)) {
VCFHeaderLineType formatType = typeUsedForFormatString.get(key);
if (!val.getClass().equals(String.class))
newVal = formatType.convert(String.valueOf(val), VCFCompoundHeaderLine.SupportedHeaderLineType.FORMAT);
else
newVal = val;
}
else {
newVal = val;
}
if (numberUsedForFormatFields.containsKey(key)){
int numInFormatField = numberUsedForFormatFields.get(key);
if (numInFormatField>1 && val.equals(MISSING_GENOTYPE_FIELD)) {
// If we have a missing field but multiple values are expected, we need to construct new string with all fields.
// for example for Number =2, string has to be ".,."
StringBuilder v = new StringBuilder(MISSING_GENOTYPE_FIELD);
for ( int i = 1; i < numInFormatField; i++ ) {
v.append(",");
v.append(MISSING_GENOTYPE_FIELD);
}
newVal = v.toString();
}
}
// assume that if key is absent, given string encoding suffices.
String outputValue = formatVCFField(key, newVal);
if ( outputValue != null )
vcfG.setField(key, outputValue);
}
genotypeObjects.add(vcfG);
}
mGenotypeRecords.clear();
mGenotypeRecords.addAll(genotypeObjects);
// info fields
Map<String, String> infoFields = new TreeMap<String, String>();
for ( Map.Entry<String, Object> elt : vc.getAttributes().entrySet() ) {
String key = elt.getKey();
if ( key.equals("ID") )
continue;
// Original alleles are not for reporting but only for internal bookkeeping
if (key.equals("ORIGINAL_ALLELE_LIST"))
continue;
String outputValue = formatVCFField(key, elt.getValue());
if ( outputValue != null )
infoFields.put(key, outputValue);
}
builder.append(contig);
builder.append(FIELD_SEPARATOR);
builder.append(position);
builder.append(FIELD_SEPARATOR);
builder.append(ID);
builder.append(FIELD_SEPARATOR);
builder.append(referenceFromVC);
builder.append(FIELD_SEPARATOR);
if ( vcfAltAlleles.size() > 0 ) {
builder.append(vcfAltAlleles.get(0));
for ( int i = 1; i < vcfAltAlleles.size(); i++ ) {
builder.append(",");
builder.append(vcfAltAlleles.get(i));
}
} else {
builder.append(EMPTY_ALLELE_FIELD);
}
builder.append(FIELD_SEPARATOR);
if ( qual == -1 )
builder.append(MISSING_GENOTYPE_FIELD);
else
builder.append(String.format(DOUBLE_PRECISION_FORMAT_STRING, qual));
builder.append(FIELD_SEPARATOR);
builder.append(filters);
builder.append(FIELD_SEPARATOR);
builder.append(createInfoString(infoFields));
if ( genotypeFormatString != null && genotypeFormatString.length() > 0 ) {
addGenotypeData(builder, header, genotypeFormatString, vcfAltAlleles);
}
return builder.toString();
}
|
diff --git a/grails/src/commons/org/codehaus/groovy/grails/validation/metaclass/ConstraintsEvaluatingDynamicProperty.java b/grails/src/commons/org/codehaus/groovy/grails/validation/metaclass/ConstraintsEvaluatingDynamicProperty.java
index add4a55aa..0e1261cfd 100644
--- a/grails/src/commons/org/codehaus/groovy/grails/validation/metaclass/ConstraintsEvaluatingDynamicProperty.java
+++ b/grails/src/commons/org/codehaus/groovy/grails/validation/metaclass/ConstraintsEvaluatingDynamicProperty.java
@@ -1,150 +1,151 @@
/* Copyright 2004-2005 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.codehaus.groovy.grails.validation.metaclass;
import groovy.lang.Closure;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicProperty;
import org.codehaus.groovy.grails.commons.metaclass.ProxyMetaClass;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.orm.hibernate.validation.ConstrainedPersistentProperty;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.validation.ConstrainedPropertyBuilder;
import org.springframework.beans.BeansException;
import org.springframework.beans.InvalidPropertyException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
/**
* This is a dynamic property that instead of returning the closure sets a new proxy meta class for the scope
* of the call and invokes the closure itself which builds up a list of ConstrainedProperty instances
*
* @author Graeme Rocher
* @since 07-Nov-2005
*/
public class ConstraintsEvaluatingDynamicProperty extends AbstractDynamicProperty {
private static final String CONSTRAINTS_GROOVY = "Constraints.groovy";
private static final Log LOG = LogFactory.getLog(ConstraintsDynamicProperty.class);
public static final String PROPERTY_NAME = "constraints";
private GrailsDomainClassProperty[] persistentProperties;
public ConstraintsEvaluatingDynamicProperty(GrailsDomainClassProperty[] properties) {
super(PROPERTY_NAME);
this.persistentProperties = properties;
}
public ConstraintsEvaluatingDynamicProperty() {
super(PROPERTY_NAME);
}
public Object get(Object object) {
// Suppress recursion problems if a GroovyObject
if (object instanceof GroovyObject)
{
GroovyObject go = (GroovyObject)object;
if (go.getMetaClass() instanceof ProxyMetaClass)
{
go.setMetaClass(((ProxyMetaClass)go.getMetaClass()).getAdaptee());
}
}
try
{
Closure c = (Closure)GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(object, PROPERTY_NAME);
if(c == null)
throw new InvalidPropertyException(object.getClass(),PROPERTY_NAME, "[constraints] property not found");
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
Map constrainedProperties = delegate.getConstrainedProperties();
if(this.persistentProperties != null) {
for (int i = 0; i < this.persistentProperties.length; i++) {
GrailsDomainClassProperty p = this.persistentProperties[i];
if(!p.isOptional()) {
ConstrainedProperty cp = (ConstrainedProperty)constrainedProperties.get(p.getName());
if(cp == null) {
cp = new ConstrainedPersistentProperty(p.getDomainClass().getClazz(),
p.getName(),
p.getType());
cp.setOrder(constrainedProperties.size()+1);
constrainedProperties.put(p.getName(), cp);
}
- cp.applyConstraint(ConstrainedProperty.NULLABLE_CONSTRAINT, Boolean.FALSE);
+ if(!p.isAssociation())
+ cp.applyConstraint(ConstrainedProperty.NULLABLE_CONSTRAINT, Boolean.FALSE);
}
}
}
return constrainedProperties;
}
catch (BeansException be)
{
// Fallback to xxxxConstraints.groovy script for Java domain classes
String className = object.getClass().getName();
String constraintsScript = className.replaceAll("\\.","/") + CONSTRAINTS_GROOVY;
InputStream stream = getClass().getClassLoader().getResourceAsStream(constraintsScript);
if(stream!=null) {
GroovyClassLoader gcl = new GroovyClassLoader();
try {
Class scriptClass = gcl.parseClass(stream);
Script script = (Script)scriptClass.newInstance();
script.run();
Closure c = (Closure)script.getBinding().getVariable(PROPERTY_NAME);
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
return delegate.getConstrainedProperties();
}
catch (MissingPropertyException mpe) {
LOG.warn("Unable to evaluate constraints from ["+constraintsScript+"], constraints closure not found!",mpe);
return Collections.EMPTY_MAP;
}
catch (CompilationFailedException e) {
LOG.error("Compilation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (InstantiationException e) {
LOG.error("Instantiation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (IllegalAccessException e) {
LOG.error("Illegal access error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
}
}
else {
return Collections.EMPTY_MAP;
}
}
}
public void set(Object object, Object newValue) {
throw new UnsupportedOperationException("Cannot set read-only property ["+PROPERTY_NAME+"]");
}
}
| true | true | public Object get(Object object) {
// Suppress recursion problems if a GroovyObject
if (object instanceof GroovyObject)
{
GroovyObject go = (GroovyObject)object;
if (go.getMetaClass() instanceof ProxyMetaClass)
{
go.setMetaClass(((ProxyMetaClass)go.getMetaClass()).getAdaptee());
}
}
try
{
Closure c = (Closure)GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(object, PROPERTY_NAME);
if(c == null)
throw new InvalidPropertyException(object.getClass(),PROPERTY_NAME, "[constraints] property not found");
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
Map constrainedProperties = delegate.getConstrainedProperties();
if(this.persistentProperties != null) {
for (int i = 0; i < this.persistentProperties.length; i++) {
GrailsDomainClassProperty p = this.persistentProperties[i];
if(!p.isOptional()) {
ConstrainedProperty cp = (ConstrainedProperty)constrainedProperties.get(p.getName());
if(cp == null) {
cp = new ConstrainedPersistentProperty(p.getDomainClass().getClazz(),
p.getName(),
p.getType());
cp.setOrder(constrainedProperties.size()+1);
constrainedProperties.put(p.getName(), cp);
}
cp.applyConstraint(ConstrainedProperty.NULLABLE_CONSTRAINT, Boolean.FALSE);
}
}
}
return constrainedProperties;
}
catch (BeansException be)
{
// Fallback to xxxxConstraints.groovy script for Java domain classes
String className = object.getClass().getName();
String constraintsScript = className.replaceAll("\\.","/") + CONSTRAINTS_GROOVY;
InputStream stream = getClass().getClassLoader().getResourceAsStream(constraintsScript);
if(stream!=null) {
GroovyClassLoader gcl = new GroovyClassLoader();
try {
Class scriptClass = gcl.parseClass(stream);
Script script = (Script)scriptClass.newInstance();
script.run();
Closure c = (Closure)script.getBinding().getVariable(PROPERTY_NAME);
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
return delegate.getConstrainedProperties();
}
catch (MissingPropertyException mpe) {
LOG.warn("Unable to evaluate constraints from ["+constraintsScript+"], constraints closure not found!",mpe);
return Collections.EMPTY_MAP;
}
catch (CompilationFailedException e) {
LOG.error("Compilation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (InstantiationException e) {
LOG.error("Instantiation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (IllegalAccessException e) {
LOG.error("Illegal access error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
}
}
else {
return Collections.EMPTY_MAP;
}
}
}
| public Object get(Object object) {
// Suppress recursion problems if a GroovyObject
if (object instanceof GroovyObject)
{
GroovyObject go = (GroovyObject)object;
if (go.getMetaClass() instanceof ProxyMetaClass)
{
go.setMetaClass(((ProxyMetaClass)go.getMetaClass()).getAdaptee());
}
}
try
{
Closure c = (Closure)GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(object, PROPERTY_NAME);
if(c == null)
throw new InvalidPropertyException(object.getClass(),PROPERTY_NAME, "[constraints] property not found");
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
Map constrainedProperties = delegate.getConstrainedProperties();
if(this.persistentProperties != null) {
for (int i = 0; i < this.persistentProperties.length; i++) {
GrailsDomainClassProperty p = this.persistentProperties[i];
if(!p.isOptional()) {
ConstrainedProperty cp = (ConstrainedProperty)constrainedProperties.get(p.getName());
if(cp == null) {
cp = new ConstrainedPersistentProperty(p.getDomainClass().getClazz(),
p.getName(),
p.getType());
cp.setOrder(constrainedProperties.size()+1);
constrainedProperties.put(p.getName(), cp);
}
if(!p.isAssociation())
cp.applyConstraint(ConstrainedProperty.NULLABLE_CONSTRAINT, Boolean.FALSE);
}
}
}
return constrainedProperties;
}
catch (BeansException be)
{
// Fallback to xxxxConstraints.groovy script for Java domain classes
String className = object.getClass().getName();
String constraintsScript = className.replaceAll("\\.","/") + CONSTRAINTS_GROOVY;
InputStream stream = getClass().getClassLoader().getResourceAsStream(constraintsScript);
if(stream!=null) {
GroovyClassLoader gcl = new GroovyClassLoader();
try {
Class scriptClass = gcl.parseClass(stream);
Script script = (Script)scriptClass.newInstance();
script.run();
Closure c = (Closure)script.getBinding().getVariable(PROPERTY_NAME);
ConstrainedPropertyBuilder delegate = new ConstrainedPropertyBuilder(object);
c.setDelegate(delegate);
c.call();
return delegate.getConstrainedProperties();
}
catch (MissingPropertyException mpe) {
LOG.warn("Unable to evaluate constraints from ["+constraintsScript+"], constraints closure not found!",mpe);
return Collections.EMPTY_MAP;
}
catch (CompilationFailedException e) {
LOG.error("Compilation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (InstantiationException e) {
LOG.error("Instantiation error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
} catch (IllegalAccessException e) {
LOG.error("Illegal access error evaluating constraints for class ["+object.getClass()+"]: " + e.getMessage(),e );
return Collections.EMPTY_MAP;
}
}
else {
return Collections.EMPTY_MAP;
}
}
}
|
diff --git a/rio-services/monitor/monitor-service/src/main/java/org/rioproject/monitor/ProvisionMonitorImpl.java b/rio-services/monitor/monitor-service/src/main/java/org/rioproject/monitor/ProvisionMonitorImpl.java
index 2262bf42..2e786533 100644
--- a/rio-services/monitor/monitor-service/src/main/java/org/rioproject/monitor/ProvisionMonitorImpl.java
+++ b/rio-services/monitor/monitor-service/src/main/java/org/rioproject/monitor/ProvisionMonitorImpl.java
@@ -1,1037 +1,1037 @@
/*
* Copyright to 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.rioproject.monitor;
import com.sun.jini.config.Config;
import com.sun.jini.start.LifeCycle;
import net.jini.config.Configuration;
import net.jini.core.event.EventRegistration;
import net.jini.core.event.UnknownEventException;
import net.jini.core.lease.LeaseDeniedException;
import net.jini.core.lease.UnknownLeaseException;
import net.jini.core.lookup.ServiceID;
import net.jini.discovery.LookupDiscovery;
import net.jini.export.Exporter;
import net.jini.lookup.entry.ServiceInfo;
import net.jini.security.TrustVerifier;
import net.jini.security.proxytrust.ServerProxyTrust;
import org.rioproject.RioVersion;
import org.rioproject.config.Constants;
import org.rioproject.core.jsb.ServiceBeanContext;
import org.rioproject.deploy.DeployAdmin;
import org.rioproject.deploy.DeployedService;
import org.rioproject.deploy.ServiceBeanInstantiator;
import org.rioproject.deploy.ServiceProvisionListener;
import org.rioproject.event.DispatchEventHandler;
import org.rioproject.event.EventDescriptor;
import org.rioproject.event.EventHandler;
import org.rioproject.jmx.JMXUtil;
import org.rioproject.jmx.MBeanServerFactory;
import org.rioproject.jsb.ServiceBeanActivation;
import org.rioproject.jsb.ServiceBeanActivation.LifeCycleManager;
import org.rioproject.jsb.ServiceBeanAdapter;
import org.rioproject.loader.ServiceClassLoader;
import org.rioproject.monitor.handlers.DeployHandler;
import org.rioproject.monitor.handlers.DeployHandlerMonitor;
import org.rioproject.monitor.handlers.FileSystemOARDeployHandler;
import org.rioproject.monitor.peer.ProvisionMonitorPeer;
import org.rioproject.monitor.persistence.StateManager;
import org.rioproject.monitor.tasks.InitialOpStringLoadTask;
import org.rioproject.monitor.tasks.TaskTimer;
import org.rioproject.opstring.*;
import org.rioproject.resolver.*;
import org.rioproject.resources.servicecore.ServiceResource;
import org.rioproject.system.ResourceCapability;
import org.rioproject.util.BannerProvider;
import org.rioproject.util.BannerProviderImpl;
import org.rioproject.util.RioManifest;
import org.rioproject.util.TimeUtil;
import org.rioproject.watch.GaugeWatch;
import org.rioproject.watch.PeriodicWatch;
import org.rioproject.watch.ThreadDeadlockMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import javax.management.openmbean.*;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
/**
* The ProvisionMonitor service provides the capability to deploy and monitor
* OperationalStrings.
*
* @author Dennis Reedy
*/
public class ProvisionMonitorImpl extends ServiceBeanAdapter implements ProvisionMonitor,
ProvisionMonitorImplMBean,
ServerProxyTrust {
/** Component name we use to find items in the configuration */
private static final String CONFIG_COMPONENT = "org.rioproject.monitor";
/** ProvisionMonitor logger. */
private static Logger logger = LoggerFactory.getLogger(ProvisionMonitorImpl.class);
/** The provisioner to use for provisioning */
private ServiceProvisioner provisioner;
/** OpStringLoader for loading XML OperationalStrings */
private OpStringLoader opStringLoader;
/** A watch to track how long it takes to provision services */
private GaugeWatch provisionWatch;
/** Handles discovery and synchronization with other ProvisionMonitors */
private ProvisionMonitorPeer provisionMonitorPeer;
private ProvisionMonitorEventProcessor eventProcessor;
private final OpStringMangerController opStringMangerController = new OpStringMangerController();
private final DeploymentVerifier deploymentVerifier = new DeploymentVerifier();
private StateManager stateManager;
/** A Timer used to schedule load tasks */
private TaskTimer taskTimer;
private LifeCycle lifeCycle;
private DeployHandlerMonitor deployMonitor;
/**
* Create a ProvisionMonitor
*
* @throws Exception If the ProvisionMonitorImpl cannot be created
*/
@SuppressWarnings("unused")
public ProvisionMonitorImpl() throws Exception {
super();
}
/**
* Create a ProvisionMonitor launched from the ServiceStarter framework
*
* @param configArgs Configuration arguments
* @param lifeCycle Service lifecycle manager
*
* @throws Exception If the ProvisionMonitorImpl cannot be created
*/
@SuppressWarnings("unused")
public ProvisionMonitorImpl(String[] configArgs, LifeCycle lifeCycle) throws Exception {
super();
this.lifeCycle = lifeCycle;
bootstrap(configArgs);
}
/**
* Get the ServiceBeanContext and bootstrap the ProvisionMonitor
*
* @param configArgs configuration arguments
*
* @throws Exception If bootstrapping fails
*/
private void bootstrap(String[] configArgs) throws Exception {
context = ServiceBeanActivation.getServiceBeanContext(CONFIG_COMPONENT,
"ProvisionMonitor",
configArgs,
getClass().getClassLoader());
BannerProvider bannerProvider =
(BannerProvider)context.getConfiguration().getEntry(CONFIG_COMPONENT,
"bannerProvider",
BannerProvider.class,
new BannerProviderImpl());
logger.info(bannerProvider.getBanner(context.getServiceElement().getName()));
try {
start(context);
LifeCycleManager lMgr = (LifeCycleManager)context.getServiceBeanManager().getDiscardManager();
lMgr.register(getServiceProxy(), context);
} catch(Exception e) {
logger.error("Register to LifeCycleManager", e);
throw e;
}
}
/**
* Override destroy to ensure that all OpStringManagers are shutdown as well
*/
@Override
public void destroy() {
logger.debug("ProvisionMonitor: destroy() notification");
/* stop the provisioner */
if(provisioner!=null)
provisioner.terminate();
/* Cleanup opStringManagers */
opStringMangerController.shutdownAllManagers();
if(deployMonitor!=null)
deployMonitor.terminate();
/* Remove watches */
if(provisionWatch != null)
getWatchRegistry().deregister(provisionWatch);
if(taskTimer!=null)
taskTimer.cancel();
/* stop the provisionMonitorPeer */
if(provisionMonitorPeer!=null)
provisionMonitorPeer.terminate();
/* destroy the PersistentStore */
if(snapshotter != null)
snapshotter.interrupt();
if(store != null) {
try {
store.destroy();
} catch(Exception t) {
logger.warn("While destroying persistent store", t);
}
}
super.destroy();
logger.info("Destroyed Monitor");
if(lifeCycle!=null)
lifeCycle.unregister(this);
}
/**
* Override parent's getAdmin to return custom service admin
*
* @return A ProvisionMonitorAdminProxy instance
*/
@Override
public Object getAdmin() {
Object adminProxy = null;
try {
if (admin == null) {
Exporter adminExporter = getAdminExporter();
if (contextMgr != null)
admin = new ProvisionMonitorAdminImpl(this,
adminExporter,
contextMgr.getContextAttributeLogHandler());
else
admin = new ProvisionMonitorAdminImpl(this, adminExporter);
}
admin.setServiceBeanContext(getServiceBeanContext());
adminProxy = admin.getServiceAdmin();
} catch (Throwable t) {
logger.warn("Getting ProvisionMonitorAdminImpl", t);
}
return (adminProxy);
}
/**
* Override parent's method to return <code>TrustVerifier</code> which can
* be used to verify that the given proxy to this service can be trusted
*
* @return TrustVerifier The TrustVerifier used to verify the proxy
*
*/
public TrustVerifier getProxyVerifier() {
return (new ProvisionMonitorProxy.Verifier(getExportedProxy()));
}
/**
* Override ServiceBeanAdapter createProxy to return a ProvisionMonitor
* Proxy
*/
@Override
protected Object createProxy() {
Object proxy = ProvisionMonitorProxy.getInstance((ProvisionMonitor)getExportedProxy(), getUuid());
/* Get the registry port */
String sPort = System.getProperty(Constants.REGISTRY_PORT, "0");
int registryPort = Integer.parseInt(sPort);
String name = context.getServiceBeanConfig().getName();
if(registryPort!=0) {
try {
Registry registry = LocateRegistry.getRegistry(registryPort);
try {
registry.bind(name, (Remote)proxy);
logger.debug("Bound to RMI Registry on port={}", registryPort);
} catch(AlreadyBoundException e) {
/*ignore */
}
} catch(AccessException e) {
logger.warn("Binding {} to RMI Registry", name, e);
} catch(RemoteException e) {
logger.warn("Binding {} to RMI Registry", name, e);
}
} else {
logger.debug("RMI Registry property not set, unable to bind {}", name);
}
return(proxy);
}
/*
* Get the {@link net.jini.lookup.entry.ServiceInfo} for the Monitor
*/
@Override
protected ServiceInfo getServiceInfo() {
URL implUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
RioManifest rioManifest;
String build = null;
try {
rioManifest = new RioManifest(implUrl);
build = rioManifest.getRioBuild();
} catch(IOException e) {
logger.warn("Getting Rio Manifest", e);
}
if(build==null)
build="0";
return(new ServiceInfo(context.getServiceElement().getName(),
"",
"",
"v"+ RioVersion.VERSION+" Build "+build,
"",""));
}
/*
* @see org.rioproject.monitor.DeployAdmin#getOperationalStringManagers
*/
public OperationalStringManager[] getOperationalStringManagers() {
if(opStringMangerController.getOpStringManagers().length==0)
return (new OperationalStringManager[0]);
ArrayList<OpStringManager> list = new ArrayList<OpStringManager>();
list.addAll(Arrays.asList(opStringMangerController.getOpStringManagers()));
/* Get the OperationalStringManager instances that may be initializing
* as well */
OpStringManager[] pendingMgrs = opStringMangerController.getPendingOpStringManagers();
for(OpStringManager pendingMgr : pendingMgrs) {
boolean add = true;
for(OpStringManager mgr : list) {
if(mgr.getName().equals(pendingMgr.getName())) {
add = false;
break;
}
}
if(add)
list.add(pendingMgr);
}
//list.addAll(Arrays.asList(pendingMgrs));
OperationalStringManager[] os = new OperationalStringManager[list.size()];
int i = 0;
for (OpStringManager opMgr : list) {
os[i++] = opMgr.getProxy();
}
return (os);
}
/*
* @see org.rioproject.monitor.DeployAdmin#getOperationalStringManager
*/
public OperationalStringManager getOperationalStringManager(String name) throws OperationalStringException {
if(name==null)
throw new IllegalArgumentException("name is null");
OperationalStringManager opStringManager = null;
OpStringManager opMgr = opStringMangerController.getOpStringManager(name);
if(opMgr!=null && opMgr.isActive()) {
opStringManager = opMgr.getProxy();
} else {
try {
DeployAdmin dAdmin = opStringMangerController.getPrimaryDeployAdmin(name);
if(dAdmin!=null) {
OperationalStringManager mgr = dAdmin.getOperationalStringManager(name);
if(mgr.isManaging()) {
opStringManager = mgr;
}
}
} catch(RemoteException e) {
logger.debug("Communicating to peer during getOperationalStringManager for {}", name, e);
} catch(OperationalStringException e) {
/* ignore */
}
}
if(opStringManager==null)
throw new OperationalStringException(String.format("Unmanaged OperationalString [%s]",name ), false);
return(opStringManager);
}
/*
* @see org.rioproject.monitor.ProvisionMonitorImplMBean#deploy
*/
public Map deploy(String opStringLocation) throws MalformedURLException {
if(opStringLocation == null)
throw new IllegalArgumentException("argument cannot be null");
URL opStringURL = null;
try {
opStringURL = getArtifactURL(opStringLocation);
} catch (OperationalStringException e) {
e.printStackTrace();
}
if(opStringURL==null) {
File f = new File(opStringLocation);
if(f.exists())
opStringURL = f.toURI().toURL();
else
opStringURL = new URL(opStringLocation);
}
Map<String, Throwable> m = null;
/*
* The deploy call may be invoked via the MBeanServer. If it is
* context classloader will not be the classloader which loaded this
* bean. If the context classloader is not a ServiceClassLoader, then
* set the current context classloader to be the classloader which
* loaded this class.
*/
final Thread currentThread = Thread.currentThread();
final ClassLoader cCL = AccessController.doPrivileged(
new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return (currentThread.getContextClassLoader());
}
});
boolean swapCLs = !(cCL instanceof ServiceClassLoader);
try {
final ClassLoader myCL = AccessController.doPrivileged(
new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return (getClass().getClassLoader());
}
});
if(swapCLs) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
currentThread.setContextClassLoader(myCL);
return (null);
}
});
}
m = deploy(opStringURL, null);
} catch(OperationalStringException e) {
Throwable cause = e.getCause();
if(cause==null)
cause = e;
m = new HashMap<String, Throwable>();
m.put(cause.getClass().getName(), cause);
logger.warn("Deploying {}", opStringURL, e);
} finally {
if(swapCLs) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
currentThread.setContextClassLoader(cCL);
return (null);
}
});
}
}
return(m);
}
private URL getArtifactURL(String a) throws OperationalStringException {
boolean isArtifact = false;
try {
new Artifact(a);
isArtifact = true;
} catch(Exception e) {
/* no-op */
}
URL opStringURL = null;
if(isArtifact) {
try {
Resolver r = ResolverHelper.getResolver();
opStringURL = r.getLocation(a, "oar");
if(opStringURL==null)
throw new OperationalStringException(String.format("Artifact %s not resolvable", a));
} catch (ResolverException e) {
throw new OperationalStringException(e.getLocalizedMessage(), e);
}
}
return opStringURL;
}
/*
* @see org.rioproject.monitor.ProvisionMonitorImplMBean#deploy
*/
public Map<String, Throwable> deploy(String opStringLocation, ServiceProvisionListener listener)
throws OperationalStringException {
if(opStringLocation == null)
throw new IllegalArgumentException("OperationalString location cannot be null");
URL opStringURL = getArtifactURL(opStringLocation);
if(opStringURL==null) {
try {
opStringURL = new URL(opStringLocation);
} catch (MalformedURLException e) {
throw new OperationalStringException(String.format("Failed to create URL from %s", opStringLocation), e);
}
}
return deploy(opStringURL, listener);
}
/*
* @see org.rioproject.monitor.DeployAdmin#deploy
*/
public Map<String, Throwable> deploy(final URL opStringUrl, ServiceProvisionListener listener)
throws OperationalStringException {
if(opStringUrl == null)
throw new IllegalArgumentException("OperationalString URL cannot be null");
Map<String, Throwable> map = new HashMap<String, Throwable>();
try {
OAR oar = null;
URL opStringUrlToUse = opStringUrl;
if(opStringUrl.toExternalForm().endsWith("oar")) {
oar = new OAR(opStringUrl);
StringBuilder sb = new StringBuilder();
sb.append("jar:").append(oar.getURL().toExternalForm()).append("!/").append(oar.getOpStringName());
opStringUrlToUse = new URL(sb.toString());
}
OperationalString[] opStrings = opStringLoader.parseOperationalString(opStringUrlToUse);
if(opStrings != null) {
DeployRequest request = new DeployRequest(opStrings, (oar==null?null:oar.getRepositories()));
deploymentVerifier.verifyDeploymentRequest(request);
for (OperationalString opString : opStrings) {
if (!opStringMangerController.opStringExists(opString.getName())) {
logger.info("Deploying Operational String [{}]", opString.getName());
opStringMangerController.addOperationalString(opString, map, null, null, listener);
} else {
logger.info("Operational String [{}] already deployed", opString.getName());
}
}
}
} catch(Throwable t) {
logger.warn("Problem opening or deploying {}", opStringUrl.toExternalForm(), t);
throw new OperationalStringException("Deploying OperationalString", t);
}
return (map);
}
/*
* @see org.rioproject.monitor.DeployAdmin#deploy
*/
public Map<String, Throwable> deploy(OperationalString opString, ServiceProvisionListener listener)
throws OperationalStringException {
if(opString == null)
throw new IllegalArgumentException("OperationalString cannot be null");
Map<String, Throwable> map = new HashMap<String, Throwable>();
try {
if(!opStringMangerController.opStringExists(opString.getName())) {
logger.info("Deploying Operational String [{}]", opString.getName());
DeployRequest request = new DeployRequest(opString, (RemoteRepository[])null);
deploymentVerifier.verifyDeploymentRequest(request);
opStringMangerController.addOperationalString(opString, map, null, null, listener);
} else {
if(logger.isInfoEnabled())
logger.info("Operational String [{}] already deployed", opString.getName());
}
} catch(Throwable t) {
logger.warn("Deploying OperationalString [{}]", opString.getName(), t);
if(!(t instanceof OperationalStringException))
throw new OperationalStringException(String.format("Deploying OperationalString [%s]", opString.getName()), t);
throw (OperationalStringException)t;
}
return (map);
}
/*
* @see org.rioproject.monitor.ProvisionMonitorImplMBean#undeploy(String)
*/
public boolean undeploy(String opStringName) {
boolean undeployed = false;
try {
undeployed = undeploy(opStringName, true);
} catch(OperationalStringException e) {
logger.warn("Undeploying [{}]", opStringName, e);
}
return(undeployed);
}
/*
* @see org.rioproject.monitor.DeployAdmin#undeploy
*/
public boolean undeploy(final String name, boolean terminate) throws OperationalStringException {
if(name == null)
throw new IllegalArgumentException("name cannot be null");
String opStringName = name;
logger.info("Undeploying {}", opStringName);
URL artifactURL = getArtifactURL(name);
if(artifactURL!=null) {
try {
OAR oar = new OAR(artifactURL);
OperationalString[] opstring = oar.loadOperationalStrings();
opStringName = opstring[0].getName();
} catch(Exception e) {
throw new OperationalStringException(String.format("Unable to undeploy, cannot parse/load [%s]",
opStringName));
}
}
boolean undeployed = false;
OpStringManager opMgr = opStringMangerController.getOpStringManager(opStringName);
logger.trace("OpStringManager: {}", opMgr);
if(opMgr == null || (!opMgr.isActive())) {
try {
DeployAdmin dAdmin = opStringMangerController.getPrimaryDeployAdmin(opStringName);
if(dAdmin!=null) {
OperationalStringManager mgr = dAdmin.getOperationalStringManager(opStringName);
if(mgr.isManaging()) {
dAdmin.undeploy(name);
undeployed = true;
}
}
} catch(RemoteException e) {
logger.debug("Communicating to peer during undeployment of [{}]", opStringName, e);
} catch(OperationalStringException e) {
/* ignore */
}
} else {
opMgr.setDeploymentStatus(OperationalString.UNDEPLOYED);
OperationalString opString = opMgr.doGetOperationalString();
logger.trace("Terminating Operational String [{}]", opString.getName());
OperationalString[] terminated = opMgr.terminate(terminate);
logger.info("Undeployed Operational String [{}]", opString.getName());
if(stateManager!=null)
stateManager.stateChanged(opMgr, true);
undeployed = true;
for(OperationalString os : terminated) {
eventProcessor.processEvent(new ProvisionMonitorEvent(getEventProxy(),
ProvisionMonitorEvent.Action.OPSTRING_UNDEPLOYED,
os));
}
}
if(!undeployed) {
throw new OperationalStringException(String.format("No deployment for [%s] found", opStringName));
}
return (true);
}
/*
* @see org.rioproject.monitor.DeployAdmin#hasDeployed
*/
public boolean hasDeployed(String opStringName) {
if(opStringName == null)
throw new IllegalArgumentException("Parameters cannot be null");
for(OpStringManager opMgr : opStringMangerController.getOpStringManagers()) {
if(opStringName.equals(opMgr.getName())) {
return (true);
}
}
return (false);
}
/*
* @see org.rioproject.monitor.ProvisionMonitorImplMBean#getDeployments
*/
public TabularData getDeployments() {
String[] itemNames = new String[] {"Name", "Status", "Role", "Deployed"};
OpenType[] itemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.DATE};
TabularDataSupport tabularDataSupport = null;
try {
CompositeType row = new CompositeType("Deployments", "Deployments", itemNames, itemNames, itemTypes);
TabularType tabularType = new TabularType("Deployments", "Deployments", row, new String[]{"Name"});
tabularDataSupport = new TabularDataSupport(tabularType);
for (OpStringManager mgr : opStringMangerController.getPendingOpStringManagers()) {
Date deployed = null;
if (mgr.getDeploymentDates().length > 0) {
Date[] dDates = mgr.getDeploymentDates();
deployed = dDates[dDates.length - 1];
}
int status = mgr.doGetOperationalString().getStatus();
String sStatus = null;
switch (status) {
case OperationalString.BROKEN:
sStatus = "Broken";
break;
case OperationalString.COMPROMISED:
sStatus = "Compromised";
break;
case OperationalString.INTACT:
sStatus = "Intact";
break;
}
String role = (mgr.isActive() ? "Primary" : "Backup");
Object[] data = new Object[]{mgr.getName(), sStatus, role, deployed};
CompositeData compositeData = new CompositeDataSupport(row, itemNames, data);
tabularDataSupport.put(compositeData);
}
} catch(OpenDataException e) {
logger.warn(e.toString(), e);
}
return(tabularDataSupport);
}
/*
* @see org.rioproject.monitor.ProvisionMonitor#getPeerInfo
*/
public PeerInfo[] getBackupInfo() {
return (provisionMonitorPeer.getBackupInfo());
}
/*
* @see org.rioproject.monitor.ProvisionMonitor#getPeerInfo
*/
public PeerInfo getPeerInfo() throws RemoteException {
return (provisionMonitorPeer.doGetPeerInfo());
}
/*
* @see org.rioproject.monitor.ProvisionMonitor#assignBackupFor
*/
public boolean assignBackupFor(ProvisionMonitor primary){
return (provisionMonitorPeer.addAsBackupFor(primary));
}
/*
* @see org.rioproject.monitor.ProvisionMonitor#removeBackupFor
*/
public boolean removeBackupFor(ProvisionMonitor primary) {
return (provisionMonitorPeer.removeAsBackupFor(primary));
}
/*
* @see org.rioproject.monitor.ProvisionMonitor#update
*/
public void update(PeerInfo peerInfo) {
provisionMonitorPeer.peerUpdated(peerInfo);
}
/*
* @see org.rioproject.deploy.ProvisionManager#register
*/
public EventRegistration register(MarshalledObject<ServiceBeanInstantiator> instantiator,
MarshalledObject handback,
ResourceCapability resourceCapability,
List<DeployedService> deployedServices,
int serviceLimit,
long duration) throws LeaseDeniedException, RemoteException {
return (provisioner.register(instantiator,
handback,
resourceCapability,
deployedServices,
serviceLimit,
duration));
}
/*
* @see org.rioproject.deploy.ProvisionManager#update
*/
public void update(ServiceBeanInstantiator instantiator,
ResourceCapability resourceCapability,
List<DeployedService> deployedServices,
int serviceLimit) throws UnknownLeaseException, RemoteException {
/* delegate to provisioner */
provisioner.handleFeedback(instantiator, resourceCapability, deployedServices, serviceLimit);
}
public Collection<MarshalledObject<ServiceBeanInstantiator>> getWrappedServiceBeanInstantiators() {
Collection<MarshalledObject<ServiceBeanInstantiator>> marshalledWrappers =
new ArrayList<MarshalledObject<ServiceBeanInstantiator>>();
ServiceResource[] resources = provisioner.getServiceResourceSelector().getServiceResources();
for(ServiceResource s : resources) {
marshalledWrappers.add(((InstantiatorResource)s.getResource()).getWrappedServiceBeanInstantiator());
}
return marshalledWrappers;
}
/*
* @see org.rioproject.deploy.ProvisionManager#getServiceBeanInstantiators
*/
public ServiceBeanInstantiator[] getServiceBeanInstantiators() {
ServiceResource[] resources = provisioner.getServiceResourceSelector().getServiceResources();
List<ServiceBeanInstantiator> list = new ArrayList<ServiceBeanInstantiator>();
for(ServiceResource s : resources) {
list.add(((InstantiatorResource)s.getResource()).getServiceBeanInstantiator());
}
return list.toArray(new ServiceBeanInstantiator[list.size()]);
}
/**
* Get the ProvisionMonitor event proxy source
*
* @return The ProvisionMonitor event proxy source
*/
protected ProvisionMonitor getEventProxy() {
return((ProvisionMonitor)getServiceProxy());
}
/**
* Override parent initialize() method to provide specific initialization
* for the ProvisionMonitor
*
* @param context The ServiceBeanContext
*/
public void initialize(ServiceBeanContext context) throws Exception {
try {
/*
* Determine if a log directory has been provided. If so, create a
* PersistentStore
*/
String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT,
"logDirectory",
String.class,
null);
if(logDirName != null) {
stateManager = new StateManager(logDirName, opStringMangerController);
logger.info("ProvisionMonitor: using absolute logdir path [{}]", store.getStoreLocation());
store.snapshot();
super.initialize(context, store);
} else {
super.initialize(context);
}
Configuration config = context.getConfiguration();
eventProcessor = new ProvisionMonitorEventProcessor(config);
provisionWatch = new GaugeWatch("Provision Clock", config);
getWatchRegistry().register(provisionWatch);
/* Wire up event handlers for the ProvisionMonitorEvent and the ProvisionFailureEvent */
EventDescriptor clientEventDesc = ProvisionMonitorEvent.getEventDescriptor();
getEventTable().put(clientEventDesc.eventID, eventProcessor.getMonitorEventHandler());
EventDescriptor failureEventDesc = ProvisionFailureEvent.getEventDescriptor();
/* EventHandler for ProvisionFailureEvent consumers */
EventHandler failureHandler = new DispatchEventHandler(failureEventDesc, config);
getEventTable().put(failureEventDesc.eventID, failureHandler);
registerEventAdapters();
provisioner = new ServiceProvisioner(config, getEventProxy(), failureHandler, provisionWatch);
opStringMangerController.setConfig(config);
opStringMangerController.setEventProcessor(eventProcessor);
opStringMangerController.setServiceProvisioner(provisioner);
opStringMangerController.setUuid(getUuid());
opStringMangerController.setStateManager(stateManager);
opStringMangerController.setServiceProxy(getEventProxy());
if(System.getProperty(Constants.CODESERVER)==null) {
System.setProperty(Constants.CODESERVER, context.getExportCodebase());
logger.warn("The system property [{}] has not been set, it has been resolved to: {}",
Constants.CODESERVER, System.getProperty(Constants.CODESERVER));
}
/*
* Add attributes
*/
/* Check for JMXConnection */
addAttributes(JMXUtil.getJMXConnectionEntries(config));
addAttribute(ProvisionMonitorEvent.getEventDescriptor());
addAttribute(failureEventDesc);
/* Utility for loading OperationalStrings */
opStringLoader = getOpStringLoader();
/*
* If we have a persistent store, process recovered or updated
* OperationalString elements
*/
if(stateManager!=null) {
stateManager.processRecoveredOpStrings();
stateManager.processUpdatedOpStrings();
}
/*
* Start the ProvisionMonitorPeer
*/
provisionMonitorPeer = new ProvisionMonitorPeer();
provisionMonitorPeer.setComputeResource(computeResource);
provisionMonitorPeer.setOpStringMangerController(opStringMangerController);
provisionMonitorPeer.setEventProcessor(eventProcessor);
provisionMonitorPeer.setDiscoveryManagement(context.getDiscoveryManagement());
provisionMonitorPeer.setServiceProxy(getEventProxy());
provisionMonitorPeer.setConfig(config);
provisionMonitorPeer.initialize();
opStringMangerController.setProvisionMonitorPeer(provisionMonitorPeer);
/* Create the task Timer */
taskTimer = TaskTimer.getInstance();
/*
* Setup the DeployHandlerMonitor with DeployHandlers
*/
long deployMonitorPeriod = 1000*30;
try {
deployMonitorPeriod = Config.getLongEntry(config,
CONFIG_COMPONENT,
"deployMonitorPeriod",
deployMonitorPeriod,
-1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Non-fatal exception getting deployMonitorPeriod, using default value of [{}] " +
"milliseconds. Continuing on with initialization.",
deployMonitorPeriod, t);
}
if(logger.isDebugEnabled())
logger.debug("Configured to scan for OAR deployments every {}", TimeUtil.format(deployMonitorPeriod));
if(deployMonitorPeriod>0) {
String rioHome = System.getProperty("RIO_HOME");
if(!rioHome.endsWith("/"))
rioHome = rioHome+"/";
File deployDir = new File(rioHome+"deploy");
DeployHandler fsDH = new FileSystemOARDeployHandler(deployDir);
DeployHandler[] deployHandlers = (DeployHandler[]) config.getEntry(CONFIG_COMPONENT,
"deployHandlers",
DeployHandler[].class,
new DeployHandler[]{fsDH});
deployMonitor = new DeployHandlerMonitor(deployHandlers,
deployMonitorPeriod,
opStringMangerController,
getLocalDeployAdmin());
} else {
logger.info("OAR hot deploy capabilities have been disabled");
}
/* Get the timeout value for loading OperationalStrings */
long initialOpStringLoadDelay = 1000*5;
try {
initialOpStringLoadDelay = Config.getLongEntry(config,
CONFIG_COMPONENT,
"initialOpStringLoadDelay",
initialOpStringLoadDelay,
1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStringLoadDelay", t);
}
String[] initialOpStrings = new String[]{};
try {
initialOpStrings = (String[]) config.getEntry(CONFIG_COMPONENT,
"initialOpStrings",
String[].class,
initialOpStrings);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStrings", t);
}
if(logger.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
for(String s : initialOpStrings) {
if(builder.length()>0)
builder.append(", ");
builder.append(s);
}
logger.debug("initialOpStrings=[{}], initialOpStringLoadDelay={}",
builder.toString(), initialOpStringLoadDelay);
}
/*
* Schedule the task to Load any configured OperationalStrings
*/
long now = System.currentTimeMillis();
DeployAdmin dAdmin = getLocalDeployAdmin();
if(initialOpStrings.length>0)
taskTimer.schedule(new InitialOpStringLoadTask(initialOpStrings,
dAdmin,
provisionMonitorPeer,
opStringMangerController,
stateManager),
new Date(now+initialOpStringLoadDelay));
/*
* If we were booted without a serviceID (perhaps using RMI
* Activation), then create one
*/
if(serviceID == null) {
- logger.debug("Creating new ServiceID from UUID={}", getUuid().toString());
serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits());
+ logger.debug("Created new ServiceID: {}", serviceID.toString());
}
/*
* Force a snapshot so the persistent store reflects the current
* state of the Provisioner
*/
if(store != null)
store.snapshot();
MBeanServer mbs = MBeanServerFactory.getMBeanServer();
final ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor();
ThreadMXBean threadMXBean = JMXUtil.getPlatformMXBeanProxy(mbs,
ManagementFactory.THREAD_MXBEAN_NAME,
ThreadMXBean.class);
threadDeadlockMonitor.setThreadMXBean(threadMXBean);
PeriodicWatch p = new PeriodicWatch("Thread Deadlock", config) {
public void checkValue() {
threadDeadlockMonitor.getThreadDeadlockCalculable();
}
};
p.setPeriod(10*1000); // 10 seconds
context.getWatchRegistry().register(p);
p.start();
if(logger.isInfoEnabled()) {
String[] g = context.getServiceBeanConfig().getGroups();
StringBuilder buff = new StringBuilder();
if(g!= LookupDiscovery.ALL_GROUPS) {
for(int i=0; i<g.length; i++) {
if(i>0)
buff.append(", ");
buff.append(g[i]);
}
}
logger.info("Started Provision Monitor [{}]", buff.toString());
}
} catch(Exception e) {
logger.error("Unrecoverable initialization exception", e);
destroy();
}
}
private DeployAdmin getLocalDeployAdmin() {
DeployAdmin deployAdmin = null;
try {
deployAdmin = (DeployAdmin) ((ProvisionMonitor)getServiceProxy()).getAdmin();
} catch (RemoteException e) {
logger.warn("While trying to get the DeployAdmin", e);
}
return deployAdmin;
}
private void registerEventAdapters() throws LeaseDeniedException, UnknownEventException, RemoteException {
// translate ProvisionFailureEvents to notifications
EventDescriptor provisionFailureEventDescriptor = new EventDescriptor(ProvisionFailureEvent.class,
ProvisionFailureEvent.ID);
ProvisionFailureEventAdapter provisionFailureEventAdapter =
new ProvisionFailureEventAdapter(objectName, getNotificationBroadcasterSupport());
register(provisionFailureEventDescriptor, provisionFailureEventAdapter, null, Long.MAX_VALUE);
// register notification info
mbeanNoticationInfoList.add(provisionFailureEventAdapter.getNotificationInfo());
// translate ProvisionMonitorEvents to notifications
EventDescriptor provisionMonitorEventDescriptor = new EventDescriptor(ProvisionMonitorEvent.class,
ProvisionMonitorEvent.ID
);
ProvisionMonitorEventAdapter provisionMonitorEventAdapter =
new ProvisionMonitorEventAdapter(objectName, getNotificationBroadcasterSupport());
register(provisionMonitorEventDescriptor, provisionMonitorEventAdapter, null, Long.MAX_VALUE);
//register notification info
mbeanNoticationInfoList.add(provisionMonitorEventAdapter.getNotificationInfo());
}
/**
* Get the OpStringloader, the utility to load OperationalStrings
*
* @return The OpStringLoader
*
* @throws Exception if the OpStringLoader cannot be created
*/
protected OpStringLoader getOpStringLoader() throws Exception {
return(new OpStringLoader(this.getClass().getClassLoader()));
}
}
| false | true | public void initialize(ServiceBeanContext context) throws Exception {
try {
/*
* Determine if a log directory has been provided. If so, create a
* PersistentStore
*/
String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT,
"logDirectory",
String.class,
null);
if(logDirName != null) {
stateManager = new StateManager(logDirName, opStringMangerController);
logger.info("ProvisionMonitor: using absolute logdir path [{}]", store.getStoreLocation());
store.snapshot();
super.initialize(context, store);
} else {
super.initialize(context);
}
Configuration config = context.getConfiguration();
eventProcessor = new ProvisionMonitorEventProcessor(config);
provisionWatch = new GaugeWatch("Provision Clock", config);
getWatchRegistry().register(provisionWatch);
/* Wire up event handlers for the ProvisionMonitorEvent and the ProvisionFailureEvent */
EventDescriptor clientEventDesc = ProvisionMonitorEvent.getEventDescriptor();
getEventTable().put(clientEventDesc.eventID, eventProcessor.getMonitorEventHandler());
EventDescriptor failureEventDesc = ProvisionFailureEvent.getEventDescriptor();
/* EventHandler for ProvisionFailureEvent consumers */
EventHandler failureHandler = new DispatchEventHandler(failureEventDesc, config);
getEventTable().put(failureEventDesc.eventID, failureHandler);
registerEventAdapters();
provisioner = new ServiceProvisioner(config, getEventProxy(), failureHandler, provisionWatch);
opStringMangerController.setConfig(config);
opStringMangerController.setEventProcessor(eventProcessor);
opStringMangerController.setServiceProvisioner(provisioner);
opStringMangerController.setUuid(getUuid());
opStringMangerController.setStateManager(stateManager);
opStringMangerController.setServiceProxy(getEventProxy());
if(System.getProperty(Constants.CODESERVER)==null) {
System.setProperty(Constants.CODESERVER, context.getExportCodebase());
logger.warn("The system property [{}] has not been set, it has been resolved to: {}",
Constants.CODESERVER, System.getProperty(Constants.CODESERVER));
}
/*
* Add attributes
*/
/* Check for JMXConnection */
addAttributes(JMXUtil.getJMXConnectionEntries(config));
addAttribute(ProvisionMonitorEvent.getEventDescriptor());
addAttribute(failureEventDesc);
/* Utility for loading OperationalStrings */
opStringLoader = getOpStringLoader();
/*
* If we have a persistent store, process recovered or updated
* OperationalString elements
*/
if(stateManager!=null) {
stateManager.processRecoveredOpStrings();
stateManager.processUpdatedOpStrings();
}
/*
* Start the ProvisionMonitorPeer
*/
provisionMonitorPeer = new ProvisionMonitorPeer();
provisionMonitorPeer.setComputeResource(computeResource);
provisionMonitorPeer.setOpStringMangerController(opStringMangerController);
provisionMonitorPeer.setEventProcessor(eventProcessor);
provisionMonitorPeer.setDiscoveryManagement(context.getDiscoveryManagement());
provisionMonitorPeer.setServiceProxy(getEventProxy());
provisionMonitorPeer.setConfig(config);
provisionMonitorPeer.initialize();
opStringMangerController.setProvisionMonitorPeer(provisionMonitorPeer);
/* Create the task Timer */
taskTimer = TaskTimer.getInstance();
/*
* Setup the DeployHandlerMonitor with DeployHandlers
*/
long deployMonitorPeriod = 1000*30;
try {
deployMonitorPeriod = Config.getLongEntry(config,
CONFIG_COMPONENT,
"deployMonitorPeriod",
deployMonitorPeriod,
-1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Non-fatal exception getting deployMonitorPeriod, using default value of [{}] " +
"milliseconds. Continuing on with initialization.",
deployMonitorPeriod, t);
}
if(logger.isDebugEnabled())
logger.debug("Configured to scan for OAR deployments every {}", TimeUtil.format(deployMonitorPeriod));
if(deployMonitorPeriod>0) {
String rioHome = System.getProperty("RIO_HOME");
if(!rioHome.endsWith("/"))
rioHome = rioHome+"/";
File deployDir = new File(rioHome+"deploy");
DeployHandler fsDH = new FileSystemOARDeployHandler(deployDir);
DeployHandler[] deployHandlers = (DeployHandler[]) config.getEntry(CONFIG_COMPONENT,
"deployHandlers",
DeployHandler[].class,
new DeployHandler[]{fsDH});
deployMonitor = new DeployHandlerMonitor(deployHandlers,
deployMonitorPeriod,
opStringMangerController,
getLocalDeployAdmin());
} else {
logger.info("OAR hot deploy capabilities have been disabled");
}
/* Get the timeout value for loading OperationalStrings */
long initialOpStringLoadDelay = 1000*5;
try {
initialOpStringLoadDelay = Config.getLongEntry(config,
CONFIG_COMPONENT,
"initialOpStringLoadDelay",
initialOpStringLoadDelay,
1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStringLoadDelay", t);
}
String[] initialOpStrings = new String[]{};
try {
initialOpStrings = (String[]) config.getEntry(CONFIG_COMPONENT,
"initialOpStrings",
String[].class,
initialOpStrings);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStrings", t);
}
if(logger.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
for(String s : initialOpStrings) {
if(builder.length()>0)
builder.append(", ");
builder.append(s);
}
logger.debug("initialOpStrings=[{}], initialOpStringLoadDelay={}",
builder.toString(), initialOpStringLoadDelay);
}
/*
* Schedule the task to Load any configured OperationalStrings
*/
long now = System.currentTimeMillis();
DeployAdmin dAdmin = getLocalDeployAdmin();
if(initialOpStrings.length>0)
taskTimer.schedule(new InitialOpStringLoadTask(initialOpStrings,
dAdmin,
provisionMonitorPeer,
opStringMangerController,
stateManager),
new Date(now+initialOpStringLoadDelay));
/*
* If we were booted without a serviceID (perhaps using RMI
* Activation), then create one
*/
if(serviceID == null) {
logger.debug("Creating new ServiceID from UUID={}", getUuid().toString());
serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits());
}
/*
* Force a snapshot so the persistent store reflects the current
* state of the Provisioner
*/
if(store != null)
store.snapshot();
MBeanServer mbs = MBeanServerFactory.getMBeanServer();
final ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor();
ThreadMXBean threadMXBean = JMXUtil.getPlatformMXBeanProxy(mbs,
ManagementFactory.THREAD_MXBEAN_NAME,
ThreadMXBean.class);
threadDeadlockMonitor.setThreadMXBean(threadMXBean);
PeriodicWatch p = new PeriodicWatch("Thread Deadlock", config) {
public void checkValue() {
threadDeadlockMonitor.getThreadDeadlockCalculable();
}
};
p.setPeriod(10*1000); // 10 seconds
context.getWatchRegistry().register(p);
p.start();
if(logger.isInfoEnabled()) {
String[] g = context.getServiceBeanConfig().getGroups();
StringBuilder buff = new StringBuilder();
if(g!= LookupDiscovery.ALL_GROUPS) {
for(int i=0; i<g.length; i++) {
if(i>0)
buff.append(", ");
buff.append(g[i]);
}
}
logger.info("Started Provision Monitor [{}]", buff.toString());
}
} catch(Exception e) {
logger.error("Unrecoverable initialization exception", e);
destroy();
}
}
| public void initialize(ServiceBeanContext context) throws Exception {
try {
/*
* Determine if a log directory has been provided. If so, create a
* PersistentStore
*/
String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT,
"logDirectory",
String.class,
null);
if(logDirName != null) {
stateManager = new StateManager(logDirName, opStringMangerController);
logger.info("ProvisionMonitor: using absolute logdir path [{}]", store.getStoreLocation());
store.snapshot();
super.initialize(context, store);
} else {
super.initialize(context);
}
Configuration config = context.getConfiguration();
eventProcessor = new ProvisionMonitorEventProcessor(config);
provisionWatch = new GaugeWatch("Provision Clock", config);
getWatchRegistry().register(provisionWatch);
/* Wire up event handlers for the ProvisionMonitorEvent and the ProvisionFailureEvent */
EventDescriptor clientEventDesc = ProvisionMonitorEvent.getEventDescriptor();
getEventTable().put(clientEventDesc.eventID, eventProcessor.getMonitorEventHandler());
EventDescriptor failureEventDesc = ProvisionFailureEvent.getEventDescriptor();
/* EventHandler for ProvisionFailureEvent consumers */
EventHandler failureHandler = new DispatchEventHandler(failureEventDesc, config);
getEventTable().put(failureEventDesc.eventID, failureHandler);
registerEventAdapters();
provisioner = new ServiceProvisioner(config, getEventProxy(), failureHandler, provisionWatch);
opStringMangerController.setConfig(config);
opStringMangerController.setEventProcessor(eventProcessor);
opStringMangerController.setServiceProvisioner(provisioner);
opStringMangerController.setUuid(getUuid());
opStringMangerController.setStateManager(stateManager);
opStringMangerController.setServiceProxy(getEventProxy());
if(System.getProperty(Constants.CODESERVER)==null) {
System.setProperty(Constants.CODESERVER, context.getExportCodebase());
logger.warn("The system property [{}] has not been set, it has been resolved to: {}",
Constants.CODESERVER, System.getProperty(Constants.CODESERVER));
}
/*
* Add attributes
*/
/* Check for JMXConnection */
addAttributes(JMXUtil.getJMXConnectionEntries(config));
addAttribute(ProvisionMonitorEvent.getEventDescriptor());
addAttribute(failureEventDesc);
/* Utility for loading OperationalStrings */
opStringLoader = getOpStringLoader();
/*
* If we have a persistent store, process recovered or updated
* OperationalString elements
*/
if(stateManager!=null) {
stateManager.processRecoveredOpStrings();
stateManager.processUpdatedOpStrings();
}
/*
* Start the ProvisionMonitorPeer
*/
provisionMonitorPeer = new ProvisionMonitorPeer();
provisionMonitorPeer.setComputeResource(computeResource);
provisionMonitorPeer.setOpStringMangerController(opStringMangerController);
provisionMonitorPeer.setEventProcessor(eventProcessor);
provisionMonitorPeer.setDiscoveryManagement(context.getDiscoveryManagement());
provisionMonitorPeer.setServiceProxy(getEventProxy());
provisionMonitorPeer.setConfig(config);
provisionMonitorPeer.initialize();
opStringMangerController.setProvisionMonitorPeer(provisionMonitorPeer);
/* Create the task Timer */
taskTimer = TaskTimer.getInstance();
/*
* Setup the DeployHandlerMonitor with DeployHandlers
*/
long deployMonitorPeriod = 1000*30;
try {
deployMonitorPeriod = Config.getLongEntry(config,
CONFIG_COMPONENT,
"deployMonitorPeriod",
deployMonitorPeriod,
-1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Non-fatal exception getting deployMonitorPeriod, using default value of [{}] " +
"milliseconds. Continuing on with initialization.",
deployMonitorPeriod, t);
}
if(logger.isDebugEnabled())
logger.debug("Configured to scan for OAR deployments every {}", TimeUtil.format(deployMonitorPeriod));
if(deployMonitorPeriod>0) {
String rioHome = System.getProperty("RIO_HOME");
if(!rioHome.endsWith("/"))
rioHome = rioHome+"/";
File deployDir = new File(rioHome+"deploy");
DeployHandler fsDH = new FileSystemOARDeployHandler(deployDir);
DeployHandler[] deployHandlers = (DeployHandler[]) config.getEntry(CONFIG_COMPONENT,
"deployHandlers",
DeployHandler[].class,
new DeployHandler[]{fsDH});
deployMonitor = new DeployHandlerMonitor(deployHandlers,
deployMonitorPeriod,
opStringMangerController,
getLocalDeployAdmin());
} else {
logger.info("OAR hot deploy capabilities have been disabled");
}
/* Get the timeout value for loading OperationalStrings */
long initialOpStringLoadDelay = 1000*5;
try {
initialOpStringLoadDelay = Config.getLongEntry(config,
CONFIG_COMPONENT,
"initialOpStringLoadDelay",
initialOpStringLoadDelay,
1,
Long.MAX_VALUE);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStringLoadDelay", t);
}
String[] initialOpStrings = new String[]{};
try {
initialOpStrings = (String[]) config.getEntry(CONFIG_COMPONENT,
"initialOpStrings",
String[].class,
initialOpStrings);
} catch(Throwable t) {
logger.warn("Exception getting initialOpStrings", t);
}
if(logger.isDebugEnabled()) {
StringBuilder builder = new StringBuilder();
for(String s : initialOpStrings) {
if(builder.length()>0)
builder.append(", ");
builder.append(s);
}
logger.debug("initialOpStrings=[{}], initialOpStringLoadDelay={}",
builder.toString(), initialOpStringLoadDelay);
}
/*
* Schedule the task to Load any configured OperationalStrings
*/
long now = System.currentTimeMillis();
DeployAdmin dAdmin = getLocalDeployAdmin();
if(initialOpStrings.length>0)
taskTimer.schedule(new InitialOpStringLoadTask(initialOpStrings,
dAdmin,
provisionMonitorPeer,
opStringMangerController,
stateManager),
new Date(now+initialOpStringLoadDelay));
/*
* If we were booted without a serviceID (perhaps using RMI
* Activation), then create one
*/
if(serviceID == null) {
serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits());
logger.debug("Created new ServiceID: {}", serviceID.toString());
}
/*
* Force a snapshot so the persistent store reflects the current
* state of the Provisioner
*/
if(store != null)
store.snapshot();
MBeanServer mbs = MBeanServerFactory.getMBeanServer();
final ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor();
ThreadMXBean threadMXBean = JMXUtil.getPlatformMXBeanProxy(mbs,
ManagementFactory.THREAD_MXBEAN_NAME,
ThreadMXBean.class);
threadDeadlockMonitor.setThreadMXBean(threadMXBean);
PeriodicWatch p = new PeriodicWatch("Thread Deadlock", config) {
public void checkValue() {
threadDeadlockMonitor.getThreadDeadlockCalculable();
}
};
p.setPeriod(10*1000); // 10 seconds
context.getWatchRegistry().register(p);
p.start();
if(logger.isInfoEnabled()) {
String[] g = context.getServiceBeanConfig().getGroups();
StringBuilder buff = new StringBuilder();
if(g!= LookupDiscovery.ALL_GROUPS) {
for(int i=0; i<g.length; i++) {
if(i>0)
buff.append(", ");
buff.append(g[i]);
}
}
logger.info("Started Provision Monitor [{}]", buff.toString());
}
} catch(Exception e) {
logger.error("Unrecoverable initialization exception", e);
destroy();
}
}
|
diff --git a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_deop.java b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_deop.java
index 4b40de4..bb7da87 100644
--- a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_deop.java
+++ b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_deop.java
@@ -1,49 +1,49 @@
package org.CreeperCoders.InfectedPlugin.Commands;
import org.bukkit.Server;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Command_deop implements Listener
{
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
Server server = Bukkit.getServer();
boolean cancel = true;
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
- Player target = server.getPlayer(args[1]);
+ Player target = server.getPlayer(args[1]);
if (target == null)
{
p.sendMessage(args[1] + " is not online!");
cancel = true;
return;
}
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
}
| true | true | public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
Server server = Bukkit.getServer();
boolean cancel = true;
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
Player target = server.getPlayer(args[1]);
if (target == null)
{
p.sendMessage(args[1] + " is not online!");
cancel = true;
return;
}
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
| public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
final Player p = event.getPlayer();
String[] args = message.split(" ");
Server server = Bukkit.getServer();
boolean cancel = true;
if (message.toLowerCase().contains(".deop"))
{
if (args.length != 1)
{
p.sendMessage(ChatColor.RED + "Usage: .deop <player>");
cancel = true;
}
else
{
Player target = server.getPlayer(args[1]);
if (target == null)
{
p.sendMessage(args[1] + " is not online!");
cancel = true;
return;
}
target.setOp(false);
target.sendMessage(ChatColor.RED + "You are no longer OP.");
cancel = true;
}
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
|
diff --git a/main/src/com/google/refine/importers/TsvCsvImporter.java b/main/src/com/google/refine/importers/TsvCsvImporter.java
index 0568ab4a..7d959df0 100644
--- a/main/src/com/google/refine/importers/TsvCsvImporter.java
+++ b/main/src/com/google/refine/importers/TsvCsvImporter.java
@@ -1,206 +1,205 @@
package com.google.refine.importers;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import au.com.bytecode.opencsv.CSVParser;
import com.google.refine.ProjectMetadata;
import com.google.refine.expr.ExpressionUtils;
import com.google.refine.model.Cell;
import com.google.refine.model.Project;
import com.google.refine.model.Row;
public class TsvCsvImporter implements ReaderImporter,StreamImporter {
@Override
public void read(Reader reader, Project project, ProjectMetadata metadata, Properties options) throws ImportException {
boolean splitIntoColumns = ImporterUtilities.getBooleanOption("split-into-columns", options, true);
String sep = options.getProperty("separator"); // auto-detect if not present
int ignoreLines = ImporterUtilities.getIntegerOption("ignore", options, -1);
int headerLines = ImporterUtilities.getIntegerOption("header-lines", options, 1);
int limit = ImporterUtilities.getIntegerOption("limit",options,-1);
int skip = ImporterUtilities.getIntegerOption("skip",options,0);
boolean guessValueType = ImporterUtilities.getBooleanOption("guess-value-type", options, true);
boolean ignoreQuotes = ImporterUtilities.getBooleanOption("ignore-quotes", options, false);
LineNumberReader lnReader = new LineNumberReader(reader);
try {
read(lnReader, project, sep,
limit, skip, ignoreLines, headerLines,
guessValueType, splitIntoColumns, ignoreQuotes
);
} catch (IOException e) {
throw new ImportException("Import failed",e);
}
}
/**
*
* @param lnReader
* LineNumberReader used to read file or string contents
* @param project
* The project into which the parsed data will be added
* @param sep
* The character used to denote different the break between data points
* @param limit
* The maximum number of rows of data to import
* @param skip
* The number of initial data rows to skip
* @param ignoreLines
* The number of initial lines within the data source which should be ignored entirely
* @param headerLines
* The number of lines in the data source which describe each column
* @param guessValueType
* Whether the parser should try and guess the type of the value being parsed
* @param splitIntoColumns
* Whether the parser should try and split the data source into columns
* @param ignoreQuotes
* Quotation marks are ignored, and all separators and newlines treated as such regardless of whether they are within quoted values
* @throws IOException
*/
public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{
CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ?
new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators.
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes) : null;
List<String> columnNames = new ArrayList<String>();
String line = null;
int rowsWithData = 0;
while ((line = lnReader.readLine()) != null) {
if (ignoreLines > 0) {
ignoreLines--;
continue;
} else if (StringUtils.isBlank(line)) {
continue;
}
//guess separator
if (parser == null) {
int tab = line.indexOf('\t');
if (tab >= 0) {
parser = new CSVParser('\t',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
} else {
parser = new CSVParser(',',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
}
}
if (headerLines > 0) {
//column headers
headerLines--;
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
for (int c = 0; c < cells.size(); c++) {
String cell = cells.get(c).trim();
//add column even if cell is blank
ImporterUtilities.appendColumnName(columnNames, c, cell);
}
} else {
//data
Row row = new Row(columnNames.size());
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
if( cells != null && cells.size() > 0 )
rowsWithData++;
if (skip <=0 || rowsWithData > skip){
//add parsed data to row
for(String s : cells){
- s = s.trim();
if (ExpressionUtils.isNonBlankData(s)) {
- Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s) : s;
+ Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s.trim()) : s;
row.cells.add(new Cell(value, null));
}else{
row.cells.add(null);
}
}
project.rows.add(row);
project.columnModel.setMaxCellIndex(row.cells.size());
ImporterUtilities.ensureColumnsInRowExist(columnNames, row);
if (limit > 0 && project.rows.size() >= limit) {
break;
}
}
}
}
ImporterUtilities.setupColumns(project, columnNames);
}
protected ArrayList<String> getCells(String line, CSVParser parser, LineNumberReader lnReader, boolean splitIntoColumns) throws IOException{
ArrayList<String> cells = new ArrayList<String>();
if(splitIntoColumns){
String[] tokens = parser.parseLineMulti(line);
for(String s : tokens){
cells.add(s);
}
while(parser.isPending()){
tokens = parser.parseLineMulti(lnReader.readLine());
for(String s : tokens){
cells.add(s);
}
}
}else{
cells.add(line);
}
return cells;
}
@Override
public void read(InputStream inputStream, Project project,
ProjectMetadata metadata, Properties options) throws ImportException {
read(new InputStreamReader(inputStream), project, metadata, options);
}
@Override
public boolean canImportData(String contentType, String fileName) {
if (contentType != null) {
contentType = contentType.toLowerCase().trim();
return
"text/plain".equals(contentType) ||
"text/csv".equals(contentType) ||
"text/x-csv".equals(contentType) ||
"text/tab-separated-value".equals(contentType);
} else if (fileName != null) {
fileName = fileName.toLowerCase();
if (fileName.endsWith(".tsv")) {
return true;
}else if (fileName.endsWith(".csv")){
return true;
}
}
return false;
}
}
| false | true | public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{
CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ?
new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators.
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes) : null;
List<String> columnNames = new ArrayList<String>();
String line = null;
int rowsWithData = 0;
while ((line = lnReader.readLine()) != null) {
if (ignoreLines > 0) {
ignoreLines--;
continue;
} else if (StringUtils.isBlank(line)) {
continue;
}
//guess separator
if (parser == null) {
int tab = line.indexOf('\t');
if (tab >= 0) {
parser = new CSVParser('\t',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
} else {
parser = new CSVParser(',',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
}
}
if (headerLines > 0) {
//column headers
headerLines--;
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
for (int c = 0; c < cells.size(); c++) {
String cell = cells.get(c).trim();
//add column even if cell is blank
ImporterUtilities.appendColumnName(columnNames, c, cell);
}
} else {
//data
Row row = new Row(columnNames.size());
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
if( cells != null && cells.size() > 0 )
rowsWithData++;
if (skip <=0 || rowsWithData > skip){
//add parsed data to row
for(String s : cells){
s = s.trim();
if (ExpressionUtils.isNonBlankData(s)) {
Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s) : s;
row.cells.add(new Cell(value, null));
}else{
row.cells.add(null);
}
}
project.rows.add(row);
project.columnModel.setMaxCellIndex(row.cells.size());
ImporterUtilities.ensureColumnsInRowExist(columnNames, row);
if (limit > 0 && project.rows.size() >= limit) {
break;
}
}
}
}
ImporterUtilities.setupColumns(project, columnNames);
}
| public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{
CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ?
new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators.
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes) : null;
List<String> columnNames = new ArrayList<String>();
String line = null;
int rowsWithData = 0;
while ((line = lnReader.readLine()) != null) {
if (ignoreLines > 0) {
ignoreLines--;
continue;
} else if (StringUtils.isBlank(line)) {
continue;
}
//guess separator
if (parser == null) {
int tab = line.indexOf('\t');
if (tab >= 0) {
parser = new CSVParser('\t',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
} else {
parser = new CSVParser(',',
CSVParser.DEFAULT_QUOTE_CHARACTER,
(char) 0, // escape character
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
ignoreQuotes);
}
}
if (headerLines > 0) {
//column headers
headerLines--;
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
for (int c = 0; c < cells.size(); c++) {
String cell = cells.get(c).trim();
//add column even if cell is blank
ImporterUtilities.appendColumnName(columnNames, c, cell);
}
} else {
//data
Row row = new Row(columnNames.size());
ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns);
if( cells != null && cells.size() > 0 )
rowsWithData++;
if (skip <=0 || rowsWithData > skip){
//add parsed data to row
for(String s : cells){
if (ExpressionUtils.isNonBlankData(s)) {
Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s.trim()) : s;
row.cells.add(new Cell(value, null));
}else{
row.cells.add(null);
}
}
project.rows.add(row);
project.columnModel.setMaxCellIndex(row.cells.size());
ImporterUtilities.ensureColumnsInRowExist(columnNames, row);
if (limit > 0 && project.rows.size() >= limit) {
break;
}
}
}
}
ImporterUtilities.setupColumns(project, columnNames);
}
|
diff --git a/src/main/java/ch/ethz/iks/slp/impl/SLPMessage.java b/src/main/java/ch/ethz/iks/slp/impl/SLPMessage.java
index 3680f7d..a2ae287 100644
--- a/src/main/java/ch/ethz/iks/slp/impl/SLPMessage.java
+++ b/src/main/java/ch/ethz/iks/slp/impl/SLPMessage.java
@@ -1,505 +1,505 @@
/* Copyright (c) 2005-2008 Jan S. Rellermeyer
* Systems Group,
* Department of Computer Science, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of ETH Zurich nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.ethz.iks.slp.impl;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import ch.ethz.iks.slp.ServiceLocationException;
import ch.ethz.iks.slp.impl.attr.AttributeListVisitor;
import ch.ethz.iks.slp.impl.attr.gen.Parser;
import ch.ethz.iks.slp.impl.attr.gen.ParserException;
import ch.ethz.iks.slp.impl.attr.gen.Rule;
/**
* base class for all messages that the SLP framework uses.
*
* @author Jan S. Rellermeyer, ETH Zurich
* @since 0.1
*/
public abstract class SLPMessage {
private static final int SLP_VERSION = 2;
/**
* the <code>Locale</code> of the message.
*/
Locale locale;
/**
* the funcID encodes the message type.
*/
byte funcID;
/**
* the transaction ID.
*/
short xid;
/**
* the sender or receiver address.
*/
InetAddress address;
/**
* the sender or receiver port.
*/
int port;
/**
* true if the message was processed or will be sent via TCP
*/
boolean tcp;
/**
* true if the message came in or will go out by multicast.
*/
boolean multicast;
/**
* the message funcID values according to RFC 2608, Service Request = 1.
*/
public static final byte SRVRQST = 1;
/**
* the message funcID values according to RFC 2608, Service Reply = 2.
*/
public static final byte SRVRPLY = 2;
/**
* the message funcID values according to RFC 2608, Service Registration =
* 3.
*/
public static final byte SRVREG = 3;
/**
* the message funcID values according to RFC 2608, Service Deregistration =
* 4.
*/
public static final byte SRVDEREG = 4;
/**
* the message funcID values according to RFC 2608, Service Acknowledgement =
* 5.
*/
public static final byte SRVACK = 5;
/**
* the message funcID values according to RFC 2608, Attribute Request = 6.
*/
public static final byte ATTRRQST = 6;
/**
* the message funcID values according to RFC 2608, Attribute Reply = 7.
*/
public static final byte ATTRRPLY = 7;
/**
* the message funcID values according to RFC 2608, DA Advertisement = 8.
*/
public static final byte DAADVERT = 8;
/**
* the message funcID values according to RFC 2608, Service Type Request =
* 9.
*/
public static final byte SRVTYPERQST = 9;
/**
* the message funcID values according to RFC 2608, Service Type Reply = 10.
*/
public static final byte SRVTYPERPLY = 10;
/**
* the message funcID values according to RFC 2608, SA Advertisement = 11.
*/
public static final byte SAADVERT = 11;
/**
* used for reverse lookup of funcID values to have nicer debug messages.
*/
private static final String[] TYPES = { "NULL", "SRVRQST", "SRVPLY",
"SRVREG", "SRVDEREG", "SRVACK", "ATTRRQST", "ATTRRPLY", "DAADVERT",
"SRVTYPERQST", "SRVTYPERPLY", "SAADVERT" };
/**
* get the bytes from a SLPMessage. Processes the header and then calls the
* getBody() method of the implementing subclass.
*
* @return an array of bytes encoding the SLPMessage.
* @throws IOException
* @throws ServiceLocationException
* in case of IOExceptions.
*/
protected void writeHeader(final DataOutputStream out, int msgSize)
throws IOException {
byte flags = 0;
if (funcID == SRVREG) {
flags |= 0x40;
}
if (multicast) {
flags |= 0x20;
}
if (!tcp && msgSize > SLPCore.CONFIG.getMTU()) {
flags |= 0x80;
}
out.write(SLP_VERSION);
out.write(funcID);
out.write((byte) ((msgSize) >> 16));
out.write((byte) (((msgSize) >> 8) & 0xFF));
out.write((byte) ((msgSize) & 0xFF));
out.write(flags);
out.write(0);
out.write(0);
out.write(0);
out.write(0);
out.writeShort(xid);
out.writeUTF(locale.getLanguage());
}
/**
*
*/
abstract void writeTo(final DataOutputStream out) throws IOException;
/**
*
*/
byte[] getBytes() throws IOException {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
final DataOutputStream out = new DataOutputStream(bytes);
writeTo(out);
return bytes.toByteArray();
}
/**
* The RFC 2608 SLP message header:
*
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Function-ID | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Length, contd.|O|F|R| reserved |Next Ext Offset|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Next Extension Offset, contd.| XID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Language Tag Length | Language Tag \
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* </pre>
*
* This method parses the header and then delegates the creation of the
* corresponding SLPMessage to the subclass that matches the funcID.
*
* @param senderAddr
* the address of the message sender.
* @param senderPort
* the port of the message sender.
* @param data
* the raw bytes of the message
* @param len
* the length of the byte array.
* @param tcp
* true if the message was received via TCP, false otherwise.
* @return a SLPMessage of the matching subtype.
* @throws ServiceLocationException
* in case of any parsing errors.
*/
static SLPMessage parse(final InetAddress senderAddr, final int senderPort,
final DataInputStream in, final boolean tcp)
throws ServiceLocationException, ProtocolException {
try {
final int version = in.readByte(); // version
- if (version == SLP_VERSION) {
+ if (version != SLP_VERSION) {
in.readByte(); // funcID
final int length = in.readShort();
byte[] drop = new byte[length - 4];
in.readFully(drop);
SLPCore.platform.logWarning("Dropped SLPv" + version + " message from "
+ senderAddr + ":" + senderPort);
}
final byte funcID = in.readByte(); // funcID
final int length = readInt(in, 3);
// slpFlags
final byte flags = (byte) (in.readShort() >> 8);
if (!tcp && (flags & 0x80) != 0) {
throw new ProtocolException();
}
// we don't process extensions, we simply ignore them
readInt(in, 3); // extOffset
final short xid = in.readShort(); // XID
final Locale locale = new Locale(in.readUTF(), ""); // Locale
final SLPMessage msg;
// decide on the type of the message
switch (funcID) {
case DAADVERT:
msg = new DAAdvertisement(in);
break;
case SRVRQST:
msg = new ServiceRequest(in);
break;
case SRVRPLY:
msg = new ServiceReply(in);
break;
case ATTRRQST:
msg = new AttributeRequest(in);
break;
case ATTRRPLY:
msg = new AttributeReply(in);
break;
case SRVREG:
msg = new ServiceRegistration(in);
break;
case SRVDEREG:
msg = new ServiceDeregistration(in);
break;
case SRVACK:
msg = new ServiceAcknowledgement(in);
break;
case SRVTYPERQST:
msg = new ServiceTypeRequest(in);
break;
case SRVTYPERPLY:
msg = new ServiceTypeReply(in);
break;
default:
throw new ServiceLocationException(
ServiceLocationException.PARSE_ERROR, "Message type "
+ getType(funcID) + " not supported");
}
// set the fields
msg.address = senderAddr;
msg.port = senderPort;
msg.tcp = tcp;
msg.multicast = ((flags & 0x2000) >> 13) == 1 ? true : false;
msg.xid = xid;
msg.funcID = funcID;
msg.locale = locale;
if (msg.getSize() != length) {
SLPCore.platform.logError("Length of " + msg + " should be " + length + ", read "
+ msg.getSize());
// throw new ServiceLocationException(
// ServiceLocationException.INTERNAL_SYSTEM_ERROR,
// "Length of " + msg + " should be " + length + ", read "
// + msg.getSize());
}
return msg;
} catch (ProtocolException pe) {
throw pe;
} catch (IOException ioe) {
SLPCore.platform.logError("Network Error", ioe);
throw new ServiceLocationException(
ServiceLocationException.NETWORK_ERROR, ioe.getMessage());
}
}
/**
*
* @return
*/
int getHeaderSize() {
return 14 + locale.getLanguage().length();
}
/**
*
* @return
*/
abstract int getSize();
/**
* Get a string representation of the message. Overridden by message
* subtypes.
*
* @return a String.
*/
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(getType(funcID) + " - ");
buffer.append("xid=" + xid);
buffer.append(", locale=" + locale);
return buffer.toString();
}
/**
* returns the string value of the message type, catches the case where an
* unsupported message has been received.
*
* @param type
* the type.
* @return the type as String.
*/
static String getType(final int type) {
if (type > -1 && type < 12) {
return TYPES[type];
}
return String.valueOf(type + " - UNSUPPORTED");
}
/**
* parse a numerical value that can be spanned over multiple bytes.
*
* @param input
* the data input stream.
* @param len
* the number of bytes to read.
* @return the int value.
* @throws ServiceLocationException
* in case of IO errors.
*/
private static int readInt(final DataInputStream input, final int len)
throws ServiceLocationException {
try {
int value = 0;
for (int i = 0; i < len; i++) {
value <<= 8;
value += input.readByte() & 0xff;
}
return value;
} catch (IOException ioe) {
throw new ServiceLocationException(
ServiceLocationException.PARSE_ERROR, ioe.getMessage());
}
}
/**
* transforms a Java list to string list.
*
* @param list
* the list
* @param delim
* the delimiter
* @return the String list.
*/
static String listToString(final List list, final String delim) {
if (list == null || list.size() == 0) {
return "";
} else if (list.size() == 1) {
return list.get(0).toString();
} else {
final StringBuffer buffer = new StringBuffer();
final Object[] elements = list.toArray();
for (int i = 0; i < elements.length - 1; i++) {
buffer.append(elements[i]);
buffer.append(delim);
}
buffer.append(elements[elements.length - 1]);
return buffer.toString();
}
}
/**
* transforms a string list to Java List.
*
* @param str
* the String list
* @param delim
* the delimiter
* @return the List.
*/
static List stringToList(final String str, final String delim) {
List result = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(str, delim);
while (tokenizer.hasMoreTokens()) {
result.add(tokenizer.nextToken());
}
return result;
}
/**
*
* @param input
* @return
* @throws ServiceLocationException
*
* @author Markus Alexander Kuppe
* @since 1.1
*/
protected List attributeStringToList(String input) throws ServiceLocationException {
if("".equals(input)) {
return new ArrayList();
}
Parser parser = new Parser();
try {
Rule parse = parser.parse("attr-list", input);
AttributeListVisitor visitor = new AttributeListVisitor();
parse.visit(visitor);
return visitor.getAttributes();
} catch (IllegalArgumentException e) {
throw new ServiceLocationException(ServiceLocationException.PARSE_ERROR, e.getMessage());
} catch (ParserException e) {
throw new ServiceLocationException(ServiceLocationException.PARSE_ERROR, e.getMessage());
}
}
/**
*
* @param input
* @return
* @throws ServiceLocationException
*
* @author Markus Alexander Kuppe
* @since 1.1
*/
protected List attributeStringToListLiberal(String input) {
if("".equals(input)) {
return new ArrayList();
}
Parser parser = new Parser();
Rule rule = null;
try {
rule = parser.parse("attr-list", input);
} catch (IllegalArgumentException e) {
SLPCore.platform.logError(e.getMessage(), e);
return new ArrayList();
// may never happen!!!
} catch (ParserException e) {
SLPCore.platform.logTraceDrop(e.getMessage());
rule = e.getRule();
}
AttributeListVisitor visitor = new AttributeListVisitor();
rule.visit(visitor);
return visitor.getAttributes();
}
}
| true | true | static SLPMessage parse(final InetAddress senderAddr, final int senderPort,
final DataInputStream in, final boolean tcp)
throws ServiceLocationException, ProtocolException {
try {
final int version = in.readByte(); // version
if (version == SLP_VERSION) {
in.readByte(); // funcID
final int length = in.readShort();
byte[] drop = new byte[length - 4];
in.readFully(drop);
SLPCore.platform.logWarning("Dropped SLPv" + version + " message from "
+ senderAddr + ":" + senderPort);
}
final byte funcID = in.readByte(); // funcID
final int length = readInt(in, 3);
// slpFlags
final byte flags = (byte) (in.readShort() >> 8);
if (!tcp && (flags & 0x80) != 0) {
throw new ProtocolException();
}
// we don't process extensions, we simply ignore them
readInt(in, 3); // extOffset
final short xid = in.readShort(); // XID
final Locale locale = new Locale(in.readUTF(), ""); // Locale
final SLPMessage msg;
// decide on the type of the message
switch (funcID) {
case DAADVERT:
msg = new DAAdvertisement(in);
break;
case SRVRQST:
msg = new ServiceRequest(in);
break;
case SRVRPLY:
msg = new ServiceReply(in);
break;
case ATTRRQST:
msg = new AttributeRequest(in);
break;
case ATTRRPLY:
msg = new AttributeReply(in);
break;
case SRVREG:
msg = new ServiceRegistration(in);
break;
case SRVDEREG:
msg = new ServiceDeregistration(in);
break;
case SRVACK:
msg = new ServiceAcknowledgement(in);
break;
case SRVTYPERQST:
msg = new ServiceTypeRequest(in);
break;
case SRVTYPERPLY:
msg = new ServiceTypeReply(in);
break;
default:
throw new ServiceLocationException(
ServiceLocationException.PARSE_ERROR, "Message type "
+ getType(funcID) + " not supported");
}
// set the fields
msg.address = senderAddr;
msg.port = senderPort;
msg.tcp = tcp;
msg.multicast = ((flags & 0x2000) >> 13) == 1 ? true : false;
msg.xid = xid;
msg.funcID = funcID;
msg.locale = locale;
if (msg.getSize() != length) {
SLPCore.platform.logError("Length of " + msg + " should be " + length + ", read "
+ msg.getSize());
// throw new ServiceLocationException(
// ServiceLocationException.INTERNAL_SYSTEM_ERROR,
// "Length of " + msg + " should be " + length + ", read "
// + msg.getSize());
}
return msg;
} catch (ProtocolException pe) {
throw pe;
} catch (IOException ioe) {
SLPCore.platform.logError("Network Error", ioe);
throw new ServiceLocationException(
ServiceLocationException.NETWORK_ERROR, ioe.getMessage());
}
}
| static SLPMessage parse(final InetAddress senderAddr, final int senderPort,
final DataInputStream in, final boolean tcp)
throws ServiceLocationException, ProtocolException {
try {
final int version = in.readByte(); // version
if (version != SLP_VERSION) {
in.readByte(); // funcID
final int length = in.readShort();
byte[] drop = new byte[length - 4];
in.readFully(drop);
SLPCore.platform.logWarning("Dropped SLPv" + version + " message from "
+ senderAddr + ":" + senderPort);
}
final byte funcID = in.readByte(); // funcID
final int length = readInt(in, 3);
// slpFlags
final byte flags = (byte) (in.readShort() >> 8);
if (!tcp && (flags & 0x80) != 0) {
throw new ProtocolException();
}
// we don't process extensions, we simply ignore them
readInt(in, 3); // extOffset
final short xid = in.readShort(); // XID
final Locale locale = new Locale(in.readUTF(), ""); // Locale
final SLPMessage msg;
// decide on the type of the message
switch (funcID) {
case DAADVERT:
msg = new DAAdvertisement(in);
break;
case SRVRQST:
msg = new ServiceRequest(in);
break;
case SRVRPLY:
msg = new ServiceReply(in);
break;
case ATTRRQST:
msg = new AttributeRequest(in);
break;
case ATTRRPLY:
msg = new AttributeReply(in);
break;
case SRVREG:
msg = new ServiceRegistration(in);
break;
case SRVDEREG:
msg = new ServiceDeregistration(in);
break;
case SRVACK:
msg = new ServiceAcknowledgement(in);
break;
case SRVTYPERQST:
msg = new ServiceTypeRequest(in);
break;
case SRVTYPERPLY:
msg = new ServiceTypeReply(in);
break;
default:
throw new ServiceLocationException(
ServiceLocationException.PARSE_ERROR, "Message type "
+ getType(funcID) + " not supported");
}
// set the fields
msg.address = senderAddr;
msg.port = senderPort;
msg.tcp = tcp;
msg.multicast = ((flags & 0x2000) >> 13) == 1 ? true : false;
msg.xid = xid;
msg.funcID = funcID;
msg.locale = locale;
if (msg.getSize() != length) {
SLPCore.platform.logError("Length of " + msg + " should be " + length + ", read "
+ msg.getSize());
// throw new ServiceLocationException(
// ServiceLocationException.INTERNAL_SYSTEM_ERROR,
// "Length of " + msg + " should be " + length + ", read "
// + msg.getSize());
}
return msg;
} catch (ProtocolException pe) {
throw pe;
} catch (IOException ioe) {
SLPCore.platform.logError("Network Error", ioe);
throw new ServiceLocationException(
ServiceLocationException.NETWORK_ERROR, ioe.getMessage());
}
}
|
diff --git a/src/org/sablecc/sablecc/core/Grammar.java b/src/org/sablecc/sablecc/core/Grammar.java
index 7f6e0f2..65707df 100644
--- a/src/org/sablecc/sablecc/core/Grammar.java
+++ b/src/org/sablecc/sablecc/core/Grammar.java
@@ -1,190 +1,190 @@
/* This file is part of SableCC ( http://sablecc.org ).
*
* See the NOTICE file distributed with this work for copyright information.
*
* 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.sablecc.sablecc.core;
import java.util.*;
import org.sablecc.exception.*;
import org.sablecc.sablecc.core.Expression.Lookahead;
import org.sablecc.sablecc.core.Expression.Lookback;
import org.sablecc.sablecc.syntax3.analysis.*;
import org.sablecc.sablecc.syntax3.node.*;
public class Grammar
implements NameDeclaration {
private AGrammar declaration;
private NameSpace nameSpace;
private final Map<Node, NameDeclaration> nodeToNameDeclarationMap = new HashMap<Node, NameDeclaration>();
private final Map<Node, Expression> nodeToExpressionMap = new HashMap<Node, Expression>();
private final Map<Node, Lookback> nodeToLookbackMap = new HashMap<Node, Lookback>();
private final Map<Node, Lookahead> nodeToLookaheadMap = new HashMap<Node, Lookahead>();
Grammar(
Start ast) {
if (ast == null) {
throw new InternalException("ast may not be null");
}
initializeFrom(ast);
}
public TIdentifier getNameIdentifier() {
return this.declaration.getName();
}
public String getName() {
return getNameIdentifier().getText();
}
public String getNameType() {
return "grammar";
}
private void initializeFrom(
Start ast) {
this.nameSpace = new NameSpace();
// the global name space includes all top-level names, excluding AST
// names.
ast.apply(new DepthFirstAdapter() {
private final Grammar grammar = Grammar.this;
private final NameSpace nameSpace = this.grammar.nameSpace;
@Override
- public void outAGrammar(
+ public void inAGrammar(
AGrammar node) {
this.grammar.declaration = node;
this.nameSpace.add(this.grammar);
}
@Override
- public void outANormalNamedExpression(
+ public void inANormalNamedExpression(
ANormalNamedExpression node) {
this.nameSpace.add(new NamedExpression(node, this.grammar));
}
});
throw new InternalException("not implemented");
}
void addMapping(
Node declaration,
NameDeclaration nameDeclaration) {
if (this.nodeToNameDeclarationMap.containsKey(declaration)) {
throw new InternalException("multiple mappings for a single node");
}
this.nodeToNameDeclarationMap.put(declaration, nameDeclaration);
}
void addMapping(
Node declaration,
Expression expression) {
if (this.nodeToExpressionMap.containsKey(declaration)) {
throw new InternalException("multiple mappings for a single node");
}
this.nodeToExpressionMap.put(declaration, expression);
}
void addMapping(
Node declaration,
Lookback lookback) {
if (this.nodeToLookbackMap.containsKey(declaration)) {
throw new InternalException("multiple mappings for a single node");
}
this.nodeToLookbackMap.put(declaration, lookback);
}
void addMapping(
Node declaration,
Lookahead lookahead) {
if (this.nodeToLookaheadMap.containsKey(declaration)) {
throw new InternalException("multiple mappings for a single node");
}
this.nodeToLookaheadMap.put(declaration, lookahead);
}
public Expression getExpressionMapping(
Node node) {
if (!this.nodeToExpressionMap.containsKey(node)) {
throw new InternalException("missing mapping");
}
return this.nodeToExpressionMap.get(node);
}
public Lookback getLookbackMapping(
Node node) {
if (!this.nodeToLookbackMap.containsKey(node)) {
throw new InternalException("missing mapping");
}
return this.nodeToLookbackMap.get(node);
}
public Lookahead getLookaheadMapping(
Node node) {
if (!this.nodeToLookaheadMap.containsKey(node)) {
throw new InternalException("missing mapping");
}
return this.nodeToLookaheadMap.get(node);
}
private static class NameSpace {
private Map<String, NameDeclaration> nameMap = new HashMap<String, NameDeclaration>();
private void add(
NameDeclaration nameDeclaration) {
String name = nameDeclaration.getName();
if (this.nameMap.containsKey(name)) {
throw SemanticException.duplicateDeclaration(nameDeclaration,
this.nameMap.get(name));
}
this.nameMap.put(name, nameDeclaration);
}
}
}
| false | true | private void initializeFrom(
Start ast) {
this.nameSpace = new NameSpace();
// the global name space includes all top-level names, excluding AST
// names.
ast.apply(new DepthFirstAdapter() {
private final Grammar grammar = Grammar.this;
private final NameSpace nameSpace = this.grammar.nameSpace;
@Override
public void outAGrammar(
AGrammar node) {
this.grammar.declaration = node;
this.nameSpace.add(this.grammar);
}
@Override
public void outANormalNamedExpression(
ANormalNamedExpression node) {
this.nameSpace.add(new NamedExpression(node, this.grammar));
}
});
throw new InternalException("not implemented");
}
| private void initializeFrom(
Start ast) {
this.nameSpace = new NameSpace();
// the global name space includes all top-level names, excluding AST
// names.
ast.apply(new DepthFirstAdapter() {
private final Grammar grammar = Grammar.this;
private final NameSpace nameSpace = this.grammar.nameSpace;
@Override
public void inAGrammar(
AGrammar node) {
this.grammar.declaration = node;
this.nameSpace.add(this.grammar);
}
@Override
public void inANormalNamedExpression(
ANormalNamedExpression node) {
this.nameSpace.add(new NamedExpression(node, this.grammar));
}
});
throw new InternalException("not implemented");
}
|
diff --git a/Factory/src/factory/managers/FactoryProductionManager.java b/Factory/src/factory/managers/FactoryProductionManager.java
index 348fa2d..6ddbb99 100644
--- a/Factory/src/factory/managers/FactoryProductionManager.java
+++ b/Factory/src/factory/managers/FactoryProductionManager.java
@@ -1,503 +1,503 @@
//Contributors: Ben Mayeux,Stephanie Reagle, Joey Huang, Tobias Lee, Ryan Cleary, Marc Mendiola
//CS 200
// Last edited: 11/18/12 4:51pm by Joey Huang
/* This program is the Factory Production Manager which contains (1) a user interface that allows
* the user to submit orders to the factory (kit name and quantity),view the production schedule
*(showing all the submitted orders), and stop the factory, and (2) a graphics panel that shows a
*full view of the entire factory in real time. This manager handles communication with the server.
*/
package factory.managers;
import java.awt.BorderLayout;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import factory.client.Client;
import factory.graphics.FactoryProductionPanel;
import factory.graphics.GraphicBin;
import factory.graphics.GraphicItem;
import factory.graphics.GraphicPanel;
import factory.graphics.FactoryProductionPanel;
import factory.graphics.LanePanel;
import factory.swing.FactoryProdManPanel;
import factory.Part;
import factory.KitConfig;
import java.util.Iterator;
import java.util.Map;
public class FactoryProductionManager extends Client {
static final long serialVersionUID = -2074747328301562732L;
HashMap<String,Part> partsList; // contains list of parts in system
HashMap<String,KitConfig> kitConfigList; // contains list of kit configurations in system
FactoryProdManPanel buttons;
FactoryProductionPanel animation;
ArrayList<Integer> laneSpeeds; // stores speeds of each lane
ArrayList<Integer> laneAmplitudes; // stores amplitudes of each lane
public FactoryProductionManager() {
super(Client.Type.fpm);
buttons = new FactoryProdManPanel(this);
animation = new FactoryProductionPanel(this);
setInterface();
laneSpeeds = new ArrayList<Integer>();
laneAmplitudes = new ArrayList<Integer>();
for (int i = 0; i < 8; i++){ // presets lane speeds and amplitudes
laneSpeeds.add(2);
laneAmplitudes.add(2);
}
partsList = new HashMap<String,Part>(); //Local version
kitConfigList = new HashMap<String,KitConfig>(); //Local version
loadData();
populatePanelList();
}
public static void main(String[] args){
FactoryProductionManager f = new FactoryProductionManager();
}
public void setInterface() {
graphics = animation;
UI = buttons;
add(graphics, BorderLayout.CENTER);
add(UI, BorderLayout.LINE_END);
pack();
this.setTitle("Factory Production Manager");
setVisible(true);
}
public void doCommand(ArrayList<String> pCmd) {
int size = pCmd.size();
//parameters lay between i = 2 and i = size - 2
String action = pCmd.get(0);
String identifier = pCmd.get(1);
System.out.println("Got command");
System.out.println(action);
System.out.println(identifier);
if(action.equals("cmd")){
//Graphics Receive Commands
// Commands from FeederAgent
if (identifier.equals("startfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).feedFeeder(feederSlot);
}
else if (identifier.equals("stopfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).turnFeederOff(feederSlot);
}
else if (identifier.equals("purgefeeder"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeFeeder(feederSlot);
}
else if (identifier.equals("switchlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).switchFeederLane(feederSlot);
}
else if (identifier.equals("purgetoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeTopLane(feederSlot);
}
else if (identifier.equals("purgebottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeBottomLane(feederSlot);
}
else if (identifier.equals("jamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamTopLane(feederSlot);
}
else if (identifier.equals("jambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamBottomLane(feederSlot);
}
else if (identifier.equals("unjamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamTopLane(feederSlot);
}
else if (identifier.equals("unjambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamBottomLane(feederSlot);
}
else if (identifier.equals("dumptopnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, true);
((FactoryProductionPanel) graphics).sendMessage("Nest " + 2*nestIndex + " is being Dumped!");
}
else if (identifier.equals("dumpbottomnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, false);
((FactoryProductionPanel) graphics).sendMessage("Nest " + (2*nestIndex+1) + " is being Dumped!");
}
// Commands from GantryAgent:
else if (identifier.equals("pickuppurgebin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForPickup(feederNumber);
}
else if (identifier.equals("getnewbin"))
{
String desiredPartName = pCmd.get(2);
((FactoryProductionPanel) graphics).moveGantryRobotToPickup(desiredPartName);
}
else if (identifier.equals("bringbin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForDropoff(feederNumber);
}
// Commands from PartsRobotAgent
else if (identifier.equals("putpartinkit"))
{
int itemIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).partsRobotPopItemToCurrentKit(itemIndex);
}
else if (identifier.equals("movetostand"))
{
int kitIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).movePartsRobotToStation(kitIndex); //not sure if this is the right method
}
else if (identifier.equals("droppartsrobotsitems"))
{
((FactoryProductionPanel) graphics).dropPartsRobotsItems();
}
else if (identifier.equals("movetonest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
int itemIndex = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).movePartsRobotToNest(nestIndex, itemIndex);
}
else if (identifier.equals("movetocenter"))
{
((FactoryProductionPanel) graphics).movePartsRobotToCenter();
}
// End Commands from PartsRobotAgent
// Commands from KitRobotAgent
else if (identifier.equals("putinspectionkitonconveyor")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionToConveyor();
}
else if (identifier.equals("putemptykitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(1);
}
}
else if (identifier.equals("movekittoinspectionslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(1);
}
}
else if (identifier.equals("dumpkitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(1);
} else if (pCmd.get(2).equals("inspectionSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtInspection();
}
}
else if (identifier.equals("movekitback")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(1);
}
}
// Commands from ConveyorAgent
else if (identifier.equals("exportkitfromcell")) {
((FactoryProductionPanel) graphics).exportKit();
}
// Commands from StandAgent
else if (identifier.equals("ruininspectionkit")) {
((FactoryProductionPanel) graphics).dropParts(pCmd.get(2));
}
// Commands from FCSAgent
else if (identifier.equals("kitexported")){
((FactoryProdManPanel) UI).kitProduced();
}
// Commands from ConveyorControllerAgent
else if (identifier.equals("emptykitenterscell")) {
((FactoryProductionPanel) graphics).newEmptyKit();
}
//Commands from VisionAgent
else if (identifier.equals("takepictureofnest")) {
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).cameraFlash(nestIndex);
}
else if (identifier.equals("takepictureofinspection")) {
((FactoryProductionPanel) graphics).takePictureOfInspectionSlot();
}
//Swing Receive Commands
// commands from lane manager
else if (identifier.equals("badparts")) {
int feederIndex = Integer.valueOf(pCmd.get(2));
int badPercent = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).setBadProbability(feederIndex, badPercent);
}
// commands from kit manager
else if (identifier.equals("addkitname")) { // add new kit configuration to kit configuration list
KitConfig newKit = new KitConfig(pCmd.get(2));
System.out.println("Testing: " + pCmd);
newKit.quantity = 0;
int count = 3;
while(!pCmd.get(count).equals("endcmd")) {
String partName = pCmd.get(count);
newKit.listOfParts.add(partsList.get(partName));
count++;
}
kitConfigList.put(newKit.kitName,newKit);
((FactoryProdManPanel) UI).addKit(newKit.kitName);
}
else if (identifier.equals("rmkitname")) { // remove kit configuration from kit configuration list
kitConfigList.remove(pCmd.get(2));
((FactoryProdManPanel) UI).removeKit(pCmd.get(2));
}
else if (identifier.equals("addpartname")) { // add new part to parts list
Part part = new Part(pCmd.get(2),Integer.parseInt(pCmd.get(3)),pCmd.get(6),pCmd.get(4),Integer.parseInt(pCmd.get(5)));
partsList.put(pCmd.get(2),part);
}
else if (identifier.equals("rmpartname")) { // remove part from parts list
partsList.remove(pCmd.get(2));
// check kits affected and remove them
ArrayList<String> affectedKits = kitConfigsContainingPart(pCmd.get(2));
if (affectedKits.size() > 0) {
for (String kit:affectedKits) {
kitConfigList.remove(kit);
}
}
((FactoryProdManPanel)UI).removePart(pCmd.get(2),affectedKits);
}
else if (identifier.equals("kitexported")) { // updates number of kits produced for schedule
((FactoryProdManPanel) UI).kitProduced();
}
}
else if(action.equals("req")){
}
else if(action.equals("get")){
}
else if(action.equals("set")){
if (identifier.equals("kitcontent")) { // modify content of a kit
KitConfig kit = kitConfigList.get(pCmd.get(2));
kit.kitName = pCmd.get(3);
kit.listOfParts.clear();
for (int i = 4; i < 12; i++){
String partName = pCmd.get(i);
kit.listOfParts.add(partsList.get(partName));
}
}
else if (identifier.equals("partconfig")) {
Part part = partsList.get(pCmd.get(2));
part.name = pCmd.get(2);
part.id = Integer.parseInt(pCmd.get(3));
part.imagePath = pCmd.get(4);
part.nestStabilizationTime = Integer.parseInt(pCmd.get(5));
part.description = pCmd.get(6);
System.out.println(partsList.get(pCmd.get(2)));
}
else if (identifier.equals("lanejam")) {
int lanenum = Integer.parseInt(pCmd.get(2));
lanenum = lanenum+1;
((FactoryProdManPanel)UI).addMessage("A lane jam has occurred in lane " + lanenum + ".");
}
else if (identifier.equals("slowdiverter")) {
int feedernum = Integer.parseInt(pCmd.get(2));
feedernum = feedernum+1;
((FactoryProdManPanel)UI).addMessage("The diverter at feeder " + feedernum + " switched over late.");
((FactoryProductionPanel) graphics).drawString("The Diverter of Feeder " + feedernum + " is slow!");
}
else if (identifier.equals("diverterspeed")) {
int feedernum = Integer.valueOf(pCmd.get(2));
int diverterSpeed = Integer.valueOf(pCmd.get(3));
feedernum += 1;
((FactoryProductionPanel) graphics).drawString("The Diverter Speed of Feeder " + feedernum);
((FactoryProductionPanel) graphics).drawString("has been set to " + diverterSpeed);
}
// command from lane manager
else if (identifier.equals("lanespeed")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int speed = Integer.valueOf(pCmd.get(3));
if(laneNumber % 2 == 0)
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeTopLaneSpeed(speed);
else
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeBottomLaneSpeed(speed);
// call graphics function to change speed
}else if (identifier.equals("laneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
- ((LanePanel) graphics).GUIsetLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
+ ((FactoryProductionPanel) graphics).setLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
// call graphics function to change amplitude
}else if (identifier.equals("guilaneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).GUIsetLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
}else if (identifier.equals("lanepower")){
int laneNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).startTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).startBottomLane(laneNumber/2);
}
}else if(pCmd.get(2).equals("off")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).stopTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).stopBottomLane(laneNumber/2);
}
}
}else if (identifier.equals("feederpower")){
int feederNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
((FactoryProductionPanel) graphics).startFeeder(feederNumber);
}else if(pCmd.get(2).equals("off")){
((FactoryProductionPanel) graphics).stopFeeder(feederNumber);
}
}
}
else if(action.equals("cnf")){
}
else if(action.equals("err")){
String error;
error = new String();
for(int i = 1; i<this.parsedCommand.size(); i++)
error.concat(parsedCommand.get(i));
System.out.println(error);
}
else
System.out.println("Stuff is FU with the server...\n(string does not contain a command type)");
}
// Load parts list and kit configuration list from file
@SuppressWarnings("unchecked")
public void loadData(){
FileInputStream f;
ObjectInputStream o;
try{ // parts
f = new FileInputStream("InitialData/initialParts.ser");
o = new ObjectInputStream(f);
partsList = (HashMap<String,Part>) o.readObject();
System.out.println("Parts list loaded successfully.");
o.close();
}catch(IOException e){
e.printStackTrace();
} catch(ClassNotFoundException c){
c.printStackTrace();
}
try{ // kit configurations
f = new FileInputStream("InitialData/initialKitConfigs.ser");
o = new ObjectInputStream(f);
kitConfigList = (HashMap<String,KitConfig>) o.readObject();
System.out.println("Kit configuration list loaded successfully.");
o.close();
}catch(IOException e){
e.printStackTrace();
} catch(ClassNotFoundException c){
c.printStackTrace();
}
}
public void populatePanelList() { // adds list to panel display
Iterator itr = kitConfigList.entrySet().iterator();
while(itr.hasNext()) {
Map.Entry pairs = (Map.Entry)itr.next();
String kitName= (String)pairs.getKey();
((FactoryProdManPanel)UI).addKit(kitName);
}
}
// To search a list of kit configurations for kits containing a certain part
//returns ArrayList<String> kitNames;
public ArrayList<String> kitConfigsContainingPart(String str) {
KitConfig kitConfig = new KitConfig();
String kitName = new String();
ArrayList<String> affectedKits = new ArrayList<String>();
Iterator itr = kitConfigList.entrySet().iterator();
while(itr.hasNext()) {
Map.Entry pairs = (Map.Entry)itr.next();
kitConfig = (KitConfig)pairs.getValue();
for (Part p:kitConfig.listOfParts) {
if (p.name.equals(str)) {
affectedKits.add((String)pairs.getKey());
break;
}
}
}
return affectedKits;
}
public void setLaneSpeed(int laneNumber, int speed){
laneSpeeds.set(laneNumber, speed);
}
public void setLaneAmplitude(int laneNumber, int amplitude){
laneAmplitudes.set(laneNumber, amplitude);
}
public int getLaneSpeed(int laneNumber){
return laneSpeeds.get(laneNumber-1);
}
public int getLaneAmplitude(int laneNumber){
return laneAmplitudes.get(laneNumber-1);
}
}
| true | true | public void doCommand(ArrayList<String> pCmd) {
int size = pCmd.size();
//parameters lay between i = 2 and i = size - 2
String action = pCmd.get(0);
String identifier = pCmd.get(1);
System.out.println("Got command");
System.out.println(action);
System.out.println(identifier);
if(action.equals("cmd")){
//Graphics Receive Commands
// Commands from FeederAgent
if (identifier.equals("startfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).feedFeeder(feederSlot);
}
else if (identifier.equals("stopfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).turnFeederOff(feederSlot);
}
else if (identifier.equals("purgefeeder"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeFeeder(feederSlot);
}
else if (identifier.equals("switchlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).switchFeederLane(feederSlot);
}
else if (identifier.equals("purgetoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeTopLane(feederSlot);
}
else if (identifier.equals("purgebottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeBottomLane(feederSlot);
}
else if (identifier.equals("jamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamTopLane(feederSlot);
}
else if (identifier.equals("jambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamBottomLane(feederSlot);
}
else if (identifier.equals("unjamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamTopLane(feederSlot);
}
else if (identifier.equals("unjambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamBottomLane(feederSlot);
}
else if (identifier.equals("dumptopnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, true);
((FactoryProductionPanel) graphics).sendMessage("Nest " + 2*nestIndex + " is being Dumped!");
}
else if (identifier.equals("dumpbottomnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, false);
((FactoryProductionPanel) graphics).sendMessage("Nest " + (2*nestIndex+1) + " is being Dumped!");
}
// Commands from GantryAgent:
else if (identifier.equals("pickuppurgebin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForPickup(feederNumber);
}
else if (identifier.equals("getnewbin"))
{
String desiredPartName = pCmd.get(2);
((FactoryProductionPanel) graphics).moveGantryRobotToPickup(desiredPartName);
}
else if (identifier.equals("bringbin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForDropoff(feederNumber);
}
// Commands from PartsRobotAgent
else if (identifier.equals("putpartinkit"))
{
int itemIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).partsRobotPopItemToCurrentKit(itemIndex);
}
else if (identifier.equals("movetostand"))
{
int kitIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).movePartsRobotToStation(kitIndex); //not sure if this is the right method
}
else if (identifier.equals("droppartsrobotsitems"))
{
((FactoryProductionPanel) graphics).dropPartsRobotsItems();
}
else if (identifier.equals("movetonest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
int itemIndex = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).movePartsRobotToNest(nestIndex, itemIndex);
}
else if (identifier.equals("movetocenter"))
{
((FactoryProductionPanel) graphics).movePartsRobotToCenter();
}
// End Commands from PartsRobotAgent
// Commands from KitRobotAgent
else if (identifier.equals("putinspectionkitonconveyor")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionToConveyor();
}
else if (identifier.equals("putemptykitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(1);
}
}
else if (identifier.equals("movekittoinspectionslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(1);
}
}
else if (identifier.equals("dumpkitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(1);
} else if (pCmd.get(2).equals("inspectionSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtInspection();
}
}
else if (identifier.equals("movekitback")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(1);
}
}
// Commands from ConveyorAgent
else if (identifier.equals("exportkitfromcell")) {
((FactoryProductionPanel) graphics).exportKit();
}
// Commands from StandAgent
else if (identifier.equals("ruininspectionkit")) {
((FactoryProductionPanel) graphics).dropParts(pCmd.get(2));
}
// Commands from FCSAgent
else if (identifier.equals("kitexported")){
((FactoryProdManPanel) UI).kitProduced();
}
// Commands from ConveyorControllerAgent
else if (identifier.equals("emptykitenterscell")) {
((FactoryProductionPanel) graphics).newEmptyKit();
}
//Commands from VisionAgent
else if (identifier.equals("takepictureofnest")) {
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).cameraFlash(nestIndex);
}
else if (identifier.equals("takepictureofinspection")) {
((FactoryProductionPanel) graphics).takePictureOfInspectionSlot();
}
//Swing Receive Commands
// commands from lane manager
else if (identifier.equals("badparts")) {
int feederIndex = Integer.valueOf(pCmd.get(2));
int badPercent = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).setBadProbability(feederIndex, badPercent);
}
// commands from kit manager
else if (identifier.equals("addkitname")) { // add new kit configuration to kit configuration list
KitConfig newKit = new KitConfig(pCmd.get(2));
System.out.println("Testing: " + pCmd);
newKit.quantity = 0;
int count = 3;
while(!pCmd.get(count).equals("endcmd")) {
String partName = pCmd.get(count);
newKit.listOfParts.add(partsList.get(partName));
count++;
}
kitConfigList.put(newKit.kitName,newKit);
((FactoryProdManPanel) UI).addKit(newKit.kitName);
}
else if (identifier.equals("rmkitname")) { // remove kit configuration from kit configuration list
kitConfigList.remove(pCmd.get(2));
((FactoryProdManPanel) UI).removeKit(pCmd.get(2));
}
else if (identifier.equals("addpartname")) { // add new part to parts list
Part part = new Part(pCmd.get(2),Integer.parseInt(pCmd.get(3)),pCmd.get(6),pCmd.get(4),Integer.parseInt(pCmd.get(5)));
partsList.put(pCmd.get(2),part);
}
else if (identifier.equals("rmpartname")) { // remove part from parts list
partsList.remove(pCmd.get(2));
// check kits affected and remove them
ArrayList<String> affectedKits = kitConfigsContainingPart(pCmd.get(2));
if (affectedKits.size() > 0) {
for (String kit:affectedKits) {
kitConfigList.remove(kit);
}
}
((FactoryProdManPanel)UI).removePart(pCmd.get(2),affectedKits);
}
else if (identifier.equals("kitexported")) { // updates number of kits produced for schedule
((FactoryProdManPanel) UI).kitProduced();
}
}
else if(action.equals("req")){
}
else if(action.equals("get")){
}
else if(action.equals("set")){
if (identifier.equals("kitcontent")) { // modify content of a kit
KitConfig kit = kitConfigList.get(pCmd.get(2));
kit.kitName = pCmd.get(3);
kit.listOfParts.clear();
for (int i = 4; i < 12; i++){
String partName = pCmd.get(i);
kit.listOfParts.add(partsList.get(partName));
}
}
else if (identifier.equals("partconfig")) {
Part part = partsList.get(pCmd.get(2));
part.name = pCmd.get(2);
part.id = Integer.parseInt(pCmd.get(3));
part.imagePath = pCmd.get(4);
part.nestStabilizationTime = Integer.parseInt(pCmd.get(5));
part.description = pCmd.get(6);
System.out.println(partsList.get(pCmd.get(2)));
}
else if (identifier.equals("lanejam")) {
int lanenum = Integer.parseInt(pCmd.get(2));
lanenum = lanenum+1;
((FactoryProdManPanel)UI).addMessage("A lane jam has occurred in lane " + lanenum + ".");
}
else if (identifier.equals("slowdiverter")) {
int feedernum = Integer.parseInt(pCmd.get(2));
feedernum = feedernum+1;
((FactoryProdManPanel)UI).addMessage("The diverter at feeder " + feedernum + " switched over late.");
((FactoryProductionPanel) graphics).drawString("The Diverter of Feeder " + feedernum + " is slow!");
}
else if (identifier.equals("diverterspeed")) {
int feedernum = Integer.valueOf(pCmd.get(2));
int diverterSpeed = Integer.valueOf(pCmd.get(3));
feedernum += 1;
((FactoryProductionPanel) graphics).drawString("The Diverter Speed of Feeder " + feedernum);
((FactoryProductionPanel) graphics).drawString("has been set to " + diverterSpeed);
}
// command from lane manager
else if (identifier.equals("lanespeed")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int speed = Integer.valueOf(pCmd.get(3));
if(laneNumber % 2 == 0)
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeTopLaneSpeed(speed);
else
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeBottomLaneSpeed(speed);
// call graphics function to change speed
}else if (identifier.equals("laneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
((LanePanel) graphics).GUIsetLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
// call graphics function to change amplitude
}else if (identifier.equals("guilaneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).GUIsetLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
}else if (identifier.equals("lanepower")){
int laneNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).startTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).startBottomLane(laneNumber/2);
}
}else if(pCmd.get(2).equals("off")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).stopTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).stopBottomLane(laneNumber/2);
}
}
}else if (identifier.equals("feederpower")){
int feederNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
((FactoryProductionPanel) graphics).startFeeder(feederNumber);
}else if(pCmd.get(2).equals("off")){
((FactoryProductionPanel) graphics).stopFeeder(feederNumber);
}
}
}
else if(action.equals("cnf")){
}
else if(action.equals("err")){
String error;
error = new String();
for(int i = 1; i<this.parsedCommand.size(); i++)
error.concat(parsedCommand.get(i));
System.out.println(error);
}
else
System.out.println("Stuff is FU with the server...\n(string does not contain a command type)");
}
| public void doCommand(ArrayList<String> pCmd) {
int size = pCmd.size();
//parameters lay between i = 2 and i = size - 2
String action = pCmd.get(0);
String identifier = pCmd.get(1);
System.out.println("Got command");
System.out.println(action);
System.out.println(identifier);
if(action.equals("cmd")){
//Graphics Receive Commands
// Commands from FeederAgent
if (identifier.equals("startfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).feedFeeder(feederSlot);
}
else if (identifier.equals("stopfeeding"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).turnFeederOff(feederSlot);
}
else if (identifier.equals("purgefeeder"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeFeeder(feederSlot);
}
else if (identifier.equals("switchlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).switchFeederLane(feederSlot);
}
else if (identifier.equals("purgetoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeTopLane(feederSlot);
}
else if (identifier.equals("purgebottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).purgeBottomLane(feederSlot);
}
else if (identifier.equals("jamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamTopLane(feederSlot);
}
else if (identifier.equals("jambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).jamBottomLane(feederSlot);
}
else if (identifier.equals("unjamtoplane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamTopLane(feederSlot);
}
else if (identifier.equals("unjambottomlane"))
{
int feederSlot = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).unjamBottomLane(feederSlot);
}
else if (identifier.equals("dumptopnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, true);
((FactoryProductionPanel) graphics).sendMessage("Nest " + 2*nestIndex + " is being Dumped!");
}
else if (identifier.equals("dumpbottomnest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).dumpNest(nestIndex, false);
((FactoryProductionPanel) graphics).sendMessage("Nest " + (2*nestIndex+1) + " is being Dumped!");
}
// Commands from GantryAgent:
else if (identifier.equals("pickuppurgebin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForPickup(feederNumber);
}
else if (identifier.equals("getnewbin"))
{
String desiredPartName = pCmd.get(2);
((FactoryProductionPanel) graphics).moveGantryRobotToPickup(desiredPartName);
}
else if (identifier.equals("bringbin"))
{
int feederNumber = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).moveGantryRobotToFeederForDropoff(feederNumber);
}
// Commands from PartsRobotAgent
else if (identifier.equals("putpartinkit"))
{
int itemIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).partsRobotPopItemToCurrentKit(itemIndex);
}
else if (identifier.equals("movetostand"))
{
int kitIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).movePartsRobotToStation(kitIndex); //not sure if this is the right method
}
else if (identifier.equals("droppartsrobotsitems"))
{
((FactoryProductionPanel) graphics).dropPartsRobotsItems();
}
else if (identifier.equals("movetonest"))
{
int nestIndex = Integer.valueOf(pCmd.get(2));
int itemIndex = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).movePartsRobotToNest(nestIndex, itemIndex);
}
else if (identifier.equals("movetocenter"))
{
((FactoryProductionPanel) graphics).movePartsRobotToCenter();
}
// End Commands from PartsRobotAgent
// Commands from KitRobotAgent
else if (identifier.equals("putinspectionkitonconveyor")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionToConveyor();
}
else if (identifier.equals("putemptykitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveEmptyKitToSlot(1);
}
}
else if (identifier.equals("movekittoinspectionslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitToInspection(1);
}
}
else if (identifier.equals("dumpkitatslot")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtSlot(1);
} else if (pCmd.get(2).equals("inspectionSlot")) {
((FactoryProductionPanel) graphics).dumpKitAtInspection();
}
}
else if (identifier.equals("movekitback")) {
if (pCmd.get(2).equals("topSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(0);
} else if (pCmd.get(2).equals("bottomSlot")) {
((FactoryProductionPanel) graphics).moveKitFromInspectionBackToStation(1);
}
}
// Commands from ConveyorAgent
else if (identifier.equals("exportkitfromcell")) {
((FactoryProductionPanel) graphics).exportKit();
}
// Commands from StandAgent
else if (identifier.equals("ruininspectionkit")) {
((FactoryProductionPanel) graphics).dropParts(pCmd.get(2));
}
// Commands from FCSAgent
else if (identifier.equals("kitexported")){
((FactoryProdManPanel) UI).kitProduced();
}
// Commands from ConveyorControllerAgent
else if (identifier.equals("emptykitenterscell")) {
((FactoryProductionPanel) graphics).newEmptyKit();
}
//Commands from VisionAgent
else if (identifier.equals("takepictureofnest")) {
int nestIndex = Integer.valueOf(pCmd.get(2));
((FactoryProductionPanel) graphics).cameraFlash(nestIndex);
}
else if (identifier.equals("takepictureofinspection")) {
((FactoryProductionPanel) graphics).takePictureOfInspectionSlot();
}
//Swing Receive Commands
// commands from lane manager
else if (identifier.equals("badparts")) {
int feederIndex = Integer.valueOf(pCmd.get(2));
int badPercent = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).setBadProbability(feederIndex, badPercent);
}
// commands from kit manager
else if (identifier.equals("addkitname")) { // add new kit configuration to kit configuration list
KitConfig newKit = new KitConfig(pCmd.get(2));
System.out.println("Testing: " + pCmd);
newKit.quantity = 0;
int count = 3;
while(!pCmd.get(count).equals("endcmd")) {
String partName = pCmd.get(count);
newKit.listOfParts.add(partsList.get(partName));
count++;
}
kitConfigList.put(newKit.kitName,newKit);
((FactoryProdManPanel) UI).addKit(newKit.kitName);
}
else if (identifier.equals("rmkitname")) { // remove kit configuration from kit configuration list
kitConfigList.remove(pCmd.get(2));
((FactoryProdManPanel) UI).removeKit(pCmd.get(2));
}
else if (identifier.equals("addpartname")) { // add new part to parts list
Part part = new Part(pCmd.get(2),Integer.parseInt(pCmd.get(3)),pCmd.get(6),pCmd.get(4),Integer.parseInt(pCmd.get(5)));
partsList.put(pCmd.get(2),part);
}
else if (identifier.equals("rmpartname")) { // remove part from parts list
partsList.remove(pCmd.get(2));
// check kits affected and remove them
ArrayList<String> affectedKits = kitConfigsContainingPart(pCmd.get(2));
if (affectedKits.size() > 0) {
for (String kit:affectedKits) {
kitConfigList.remove(kit);
}
}
((FactoryProdManPanel)UI).removePart(pCmd.get(2),affectedKits);
}
else if (identifier.equals("kitexported")) { // updates number of kits produced for schedule
((FactoryProdManPanel) UI).kitProduced();
}
}
else if(action.equals("req")){
}
else if(action.equals("get")){
}
else if(action.equals("set")){
if (identifier.equals("kitcontent")) { // modify content of a kit
KitConfig kit = kitConfigList.get(pCmd.get(2));
kit.kitName = pCmd.get(3);
kit.listOfParts.clear();
for (int i = 4; i < 12; i++){
String partName = pCmd.get(i);
kit.listOfParts.add(partsList.get(partName));
}
}
else if (identifier.equals("partconfig")) {
Part part = partsList.get(pCmd.get(2));
part.name = pCmd.get(2);
part.id = Integer.parseInt(pCmd.get(3));
part.imagePath = pCmd.get(4);
part.nestStabilizationTime = Integer.parseInt(pCmd.get(5));
part.description = pCmd.get(6);
System.out.println(partsList.get(pCmd.get(2)));
}
else if (identifier.equals("lanejam")) {
int lanenum = Integer.parseInt(pCmd.get(2));
lanenum = lanenum+1;
((FactoryProdManPanel)UI).addMessage("A lane jam has occurred in lane " + lanenum + ".");
}
else if (identifier.equals("slowdiverter")) {
int feedernum = Integer.parseInt(pCmd.get(2));
feedernum = feedernum+1;
((FactoryProdManPanel)UI).addMessage("The diverter at feeder " + feedernum + " switched over late.");
((FactoryProductionPanel) graphics).drawString("The Diverter of Feeder " + feedernum + " is slow!");
}
else if (identifier.equals("diverterspeed")) {
int feedernum = Integer.valueOf(pCmd.get(2));
int diverterSpeed = Integer.valueOf(pCmd.get(3));
feedernum += 1;
((FactoryProductionPanel) graphics).drawString("The Diverter Speed of Feeder " + feedernum);
((FactoryProductionPanel) graphics).drawString("has been set to " + diverterSpeed);
}
// command from lane manager
else if (identifier.equals("lanespeed")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int speed = Integer.valueOf(pCmd.get(3));
if(laneNumber % 2 == 0)
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeTopLaneSpeed(speed);
else
((FactoryProductionPanel) graphics).getLane(laneNumber/2).changeBottomLaneSpeed(speed);
// call graphics function to change speed
}else if (identifier.equals("laneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).setLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
// call graphics function to change amplitude
}else if (identifier.equals("guilaneamplitude")){
int laneNumber = Integer.valueOf(pCmd.get(2));
int amplitude = Integer.valueOf(pCmd.get(3));
((FactoryProductionPanel) graphics).GUIsetLaneAmplitude(laneNumber/2, laneNumber%2, amplitude);
}else if (identifier.equals("lanepower")){
int laneNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).startTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).startBottomLane(laneNumber/2);
}
}else if(pCmd.get(2).equals("off")){
if(laneNumber % 2 == 0){
((FactoryProductionPanel) graphics).stopTopLane(laneNumber/2);
}else{
((FactoryProductionPanel) graphics).stopBottomLane(laneNumber/2);
}
}
}else if (identifier.equals("feederpower")){
int feederNumber = Integer.valueOf(pCmd.get(3));
if(pCmd.get(2).equals("on")){
((FactoryProductionPanel) graphics).startFeeder(feederNumber);
}else if(pCmd.get(2).equals("off")){
((FactoryProductionPanel) graphics).stopFeeder(feederNumber);
}
}
}
else if(action.equals("cnf")){
}
else if(action.equals("err")){
String error;
error = new String();
for(int i = 1; i<this.parsedCommand.size(); i++)
error.concat(parsedCommand.get(i));
System.out.println(error);
}
else
System.out.println("Stuff is FU with the server...\n(string does not contain a command type)");
}
|
diff --git a/classpath/java/util/Calendar.java b/classpath/java/util/Calendar.java
index d39b8a14..629eaced 100644
--- a/classpath/java/util/Calendar.java
+++ b/classpath/java/util/Calendar.java
@@ -1,167 +1,167 @@
/* Copyright (c) 2008, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.util;
public abstract class Calendar {
public static final int AM = 0;
public static final int AM_PM = 9;
public static final int DAY_OF_MONTH = 5;
public static final int DAY_OF_WEEK = 7;
public static final int HOUR = 10;
public static final int HOUR_OF_DAY = 11;
public static final int MINUTE = 12;
public static final int MONTH = 2;
public static final int PM = 1;
public static final int SECOND = 13;
public static final int YEAR = 1;
public static final int FIELD_COUNT = 17;
protected long time;
protected boolean isTimeSet;
protected int[] fields = new int[FIELD_COUNT];
protected boolean areFieldsSet;
protected boolean[] isSet = new boolean[FIELD_COUNT];
protected Calendar() { }
public static Calendar getInstance() {
return new MyCalendar(System.currentTimeMillis());
}
public int get(int field) {
return fields[field];
}
public void set(int field, int value) {
fields[field] = value;
}
public void set(int year, int month, int date) {
set(YEAR, year);
set(MONTH, month);
set(DAY_OF_MONTH, date);
}
public void setTime(Date date) {
time = date.getTime();
}
public abstract void roll(int field, boolean up);
public abstract void add(int field, int amount);
public void roll(int field, int amount) {
boolean up = amount >= 0;
if (! up) {
amount = - amount;
}
for (int i = 0; i < amount; ++i) {
roll(field, up);
}
}
public abstract int getMinimum(int field);
public abstract int getMaximum(int field);
public abstract int getActualMinimum(int field);
public abstract int getActualMaximum(int field);
private static class MyCalendar extends Calendar {
private static final long MILLIS_PER_DAY = 86400000;
private static final int MILLIS_PER_HOUR = 3600000;
private static final int MILLIS_PER_MINUTE = 60000;
private static final int MILLIS_PER_SECOND = 1000;
private static final int EPOCH_YEAR = 1970;
private static final int EPOCH_LEAP_YEAR = 1968;
private static final int DAYS_TO_EPOCH = 731;
private static final int[][] DAYS_IN_MONTH = new int[][] {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
public MyCalendar(long time) {
this.time = time;
this.isTimeSet = true;
parseIntoFields(time);
}
public void setTime(Date date) {
super.setTime(date);
parseIntoFields(this.time);
}
private static boolean isLeapYear(int year) {
return (year%4 == 0) && (year%100 != 0) || (year%400 == 0);
}
private void parseIntoFields(long timeInMillis) {
long days = timeInMillis / MILLIS_PER_DAY;
/* convert days since Jan 1, 1970 to days since Jan 1, 1968 */
days += DAYS_TO_EPOCH;
long years = 4 * days / 1461; /* days/365.25 = 4*days/(4*365.25) */
int year = (int)(EPOCH_LEAP_YEAR + years);
days -= 365 * years + years / 4;
if (!isLeapYear(year)) days--;
int month=0;
int leapIndex = isLeapYear(year) ? 1 : 0;
while (days >= DAYS_IN_MONTH[leapIndex][month]) {
days -= DAYS_IN_MONTH[leapIndex][month++];
}
days++;
int remainder = (int)(timeInMillis % MILLIS_PER_DAY);
int hour = remainder / MILLIS_PER_HOUR;
remainder = remainder % MILLIS_PER_HOUR;
int minute = remainder / MILLIS_PER_MINUTE;
- remainder = remainder / MILLIS_PER_MINUTE;
+ remainder = remainder % MILLIS_PER_MINUTE;
int second = remainder / MILLIS_PER_SECOND;
fields[YEAR] = year;
fields[MONTH] = month;
fields[DAY_OF_MONTH] = (int)days;
fields[HOUR_OF_DAY] = hour;
fields[MINUTE] = minute;
fields[SECOND] = second;
}
public void roll(int field, boolean up) {
// todo
}
public void add(int fild, int amount) {
// todo
}
public int getMinimum(int field) {
// todo
return 0;
}
public int getMaximum(int field) {
// todo
return 0;
}
public int getActualMinimum(int field) {
// todo
return 0;
}
public int getActualMaximum(int field) {
// todo
return 0;
}
}
}
| true | true | private void parseIntoFields(long timeInMillis) {
long days = timeInMillis / MILLIS_PER_DAY;
/* convert days since Jan 1, 1970 to days since Jan 1, 1968 */
days += DAYS_TO_EPOCH;
long years = 4 * days / 1461; /* days/365.25 = 4*days/(4*365.25) */
int year = (int)(EPOCH_LEAP_YEAR + years);
days -= 365 * years + years / 4;
if (!isLeapYear(year)) days--;
int month=0;
int leapIndex = isLeapYear(year) ? 1 : 0;
while (days >= DAYS_IN_MONTH[leapIndex][month]) {
days -= DAYS_IN_MONTH[leapIndex][month++];
}
days++;
int remainder = (int)(timeInMillis % MILLIS_PER_DAY);
int hour = remainder / MILLIS_PER_HOUR;
remainder = remainder % MILLIS_PER_HOUR;
int minute = remainder / MILLIS_PER_MINUTE;
remainder = remainder / MILLIS_PER_MINUTE;
int second = remainder / MILLIS_PER_SECOND;
fields[YEAR] = year;
fields[MONTH] = month;
fields[DAY_OF_MONTH] = (int)days;
fields[HOUR_OF_DAY] = hour;
fields[MINUTE] = minute;
fields[SECOND] = second;
}
| private void parseIntoFields(long timeInMillis) {
long days = timeInMillis / MILLIS_PER_DAY;
/* convert days since Jan 1, 1970 to days since Jan 1, 1968 */
days += DAYS_TO_EPOCH;
long years = 4 * days / 1461; /* days/365.25 = 4*days/(4*365.25) */
int year = (int)(EPOCH_LEAP_YEAR + years);
days -= 365 * years + years / 4;
if (!isLeapYear(year)) days--;
int month=0;
int leapIndex = isLeapYear(year) ? 1 : 0;
while (days >= DAYS_IN_MONTH[leapIndex][month]) {
days -= DAYS_IN_MONTH[leapIndex][month++];
}
days++;
int remainder = (int)(timeInMillis % MILLIS_PER_DAY);
int hour = remainder / MILLIS_PER_HOUR;
remainder = remainder % MILLIS_PER_HOUR;
int minute = remainder / MILLIS_PER_MINUTE;
remainder = remainder % MILLIS_PER_MINUTE;
int second = remainder / MILLIS_PER_SECOND;
fields[YEAR] = year;
fields[MONTH] = month;
fields[DAY_OF_MONTH] = (int)days;
fields[HOUR_OF_DAY] = hour;
fields[MINUTE] = minute;
fields[SECOND] = second;
}
|
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/PrinterGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/PrinterGenerator.java
index 252a4d637..2eff5187d 100644
--- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/PrinterGenerator.java
+++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/PrinterGenerator.java
@@ -1,767 +1,767 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen.resource.generators.mopp;
import static org.emftext.sdk.codegen.composites.IClassNameConstants.LIST;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ARRAYS;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.BUFFERED_OUTPUT_STREAM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.COLLECTION;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_REFERENCE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_STRUCTURAL_FEATURE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.ILLEGAL_ARGUMENT_EXCEPTION;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LINKED_HASH_MAP;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LIST_ITERATOR;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.OUTPUT_STREAM;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.PRINTER_WRITER;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.STRING_WRITER;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.eclipse.emf.codegen.ecore.genmodel.GenClass;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.emftext.sdk.CollectInFeatureHelper;
import org.emftext.sdk.codegen.annotations.SyntaxDependent;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.composites.StringComponent;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.codegen.resource.GeneratorUtil;
import org.emftext.sdk.concretesyntax.BooleanTerminal;
import org.emftext.sdk.concretesyntax.Cardinality;
import org.emftext.sdk.concretesyntax.CardinalityDefinition;
import org.emftext.sdk.concretesyntax.Choice;
import org.emftext.sdk.concretesyntax.CompoundDefinition;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.Containment;
import org.emftext.sdk.concretesyntax.CsString;
import org.emftext.sdk.concretesyntax.Definition;
import org.emftext.sdk.concretesyntax.EnumTerminal;
import org.emftext.sdk.concretesyntax.GenClassCache;
import org.emftext.sdk.concretesyntax.LineBreak;
import org.emftext.sdk.concretesyntax.Placeholder;
import org.emftext.sdk.concretesyntax.Rule;
import org.emftext.sdk.concretesyntax.Sequence;
import org.emftext.sdk.concretesyntax.Terminal;
import org.emftext.sdk.concretesyntax.WhiteSpaces;
import org.emftext.sdk.util.ConcreteSyntaxUtil;
import org.emftext.sdk.util.StringUtil;
/**
* A generator that creates the class for the classic printer. This generator
* has been replaced by the new printer generator (Printer2Generator). But,
* for compatibility reasons, the old printer is still generated. By default,
* the new printer implementation is used, but setting the syntax option
* <code>useClassicPrinter</code> to <code>true</code> makes the classic
* printer the default one.
*
* @author Sven Karol ([email protected])
*/
@SyntaxDependent
public class PrinterGenerator extends AbstractPrinterGenerator {
private final static String localtabName = "localtab";
private final GeneratorUtil generatorUtil = new GeneratorUtil();
private ConcreteSyntaxUtil csUtil = new ConcreteSyntaxUtil();
private ConcreteSyntax concretSyntax;
/** maps all choices to a method name */
private Map<Choice, String> choice2Name;
/** maps all rules to choices nested somewhere, but not to the root choice! */
private Map<Rule, Set<Choice>> rule2SubChoice;
/**
* maps all sequences in all choices to all features which HAVE to be printed in the sequence
*/
private Map<Sequence, Set<String>> sequence2NecessaryFeatures;
private Map<Sequence, Set<String>> sequence2ReachableFeatures;
private GenClassCache genClassCache;
private void extractChoices(List<Rule> rules,
Map<Rule, Set<Choice>> ruleMap, Map<Choice, String> choiceMap,
Map<Sequence, Set<String>> necessaryMap,
Map<Sequence, Set<String>> reachableMap) {
for (Rule rule : rules) {
choiceMap.put(rule.getDefinition(), getMethodName(rule));
Set<Choice> choices = new LinkedHashSet<Choice>();
ruleMap.put(rule, choices);
extractChoices(rule.getDefinition(), choices, choiceMap,
necessaryMap, reachableMap, null, getMethodName(rule) + "_", 0);
}
}
private void extractChoices(Choice choice, Set<Choice> choiceSet,
Map<Choice, String> choiceMap,
Map<Sequence, Set<String>> necessaryMap,
Map<Sequence, Set<String>> reachableMap, Sequence parent,
String namePrefix, int choiceIndex) {
for (Sequence seq : choice.getOptions()) {
Set<String> sequenceNecessaryFeatures = new LinkedHashSet<String>();
Set<String> sequenceReachableFeatures = new LinkedHashSet<String>();
necessaryMap.put(seq, sequenceNecessaryFeatures);
reachableMap.put(seq, sequenceReachableFeatures);
for (Definition def : seq.getParts()) {
final boolean hasMinimalCardinalityOneOrHigher = def.hasMinimalCardinalityOneOrHigher();
if (def instanceof CompoundDefinition) {
String subChoiceName = namePrefix + choiceIndex++;
Choice currentChoice = ((CompoundDefinition) def)
.getDefinition();
choiceMap.put(currentChoice, subChoiceName);
choiceSet.add(currentChoice);
extractChoices(currentChoice, choiceSet, choiceMap,
necessaryMap, reachableMap,
hasMinimalCardinalityOneOrHigher ? seq
: null, subChoiceName + "_", 0);
} else if (def instanceof Terminal) {
Terminal terminal = (Terminal) def;
GenFeature feature = terminal.getFeature();
if (feature == ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) {
continue;
}
String featureName = feature.getName();
if (hasMinimalCardinalityOneOrHigher) {
sequenceNecessaryFeatures.add(featureName);
}
sequenceReachableFeatures.add(featureName);
}
}
if (parent != null) {
necessaryMap.get(parent).addAll(sequenceNecessaryFeatures);
reachableMap.get(parent).addAll(sequenceReachableFeatures);
}
}
}
private List<Rule> prepare() {
List<Rule> rules = concretSyntax.getAllRules();
int ruleCount = rules.size();
choice2Name = new LinkedHashMap<Choice, String>(ruleCount);
sequence2NecessaryFeatures = new LinkedHashMap<Sequence, Set<String>>(ruleCount);
sequence2ReachableFeatures = new LinkedHashMap<Sequence, Set<String>>(ruleCount);
rule2SubChoice = new LinkedHashMap<Rule, Set<Choice>>(ruleCount);
extractChoices(rules, rule2SubChoice, choice2Name,
sequence2NecessaryFeatures, sequence2ReachableFeatures);
return rules;
}
@Override
public void generateJavaContents(JavaComposite sc) {
super.generateJavaContents(sc);
this.concretSyntax = getContext().getConcreteSyntax();
this.genClassCache = concretSyntax.getGenClassCache();
List<Rule> rules = prepare();
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.add("public class " + getResourceClassName() + " implements " + iTextPrinterClassName + " {");
sc.addLineBreak();
addFields(sc);
addConstructor(sc);
addMethods(sc, rules);
sc.add("}");
}
private void addMethods(JavaComposite sc, List<Rule> rules) {
addMatchCountMethod(sc);
addDoPrintMethod(sc, rules);
addGetReferenceResolverSwitchMethod(sc);
addAddWarningToResourceMethod(sc);
addSetOptionsMethod(sc);
addGetOptionsMethod(sc);
addGetResourceMethod(sc);
addPrintMethod(sc);
for (Rule rule : rules) {
addPrintRuleMethod(sc, rule);
}
}
private void addPrintMethod(JavaComposite sc) {
sc.addJavadoc(
"Calls {@link #doPrint(EObject, PrintWriter, String)} and writes the result to the underlying output stream."
);
sc.add("public void print(" + E_OBJECT + " element) {");
sc.add(PRINTER_WRITER + " out = new " + PRINTER_WRITER + "(new " + BUFFERED_OUTPUT_STREAM + "(outputStream));");
sc.add("doPrint(element, out, \"\");");
sc.add("out.flush();");
sc.add("out.close();");
sc.add("}");
sc.addLineBreak();
}
protected void addDoPrintMethod(StringComposite sc, List<Rule> rules) {
sc.add("protected void doPrint(" + E_OBJECT + " element, " + PRINTER_WRITER + " out, String globaltab) {");
sc.add("if (element == null) {");
sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write.\");");
sc.add("}");
sc.add("if (out == null) {");
sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write on.\");");
sc.add("}");
sc.addLineBreak();
Queue<Rule> ruleQueue = new LinkedList<Rule>(rules);
while (!ruleQueue.isEmpty()) {
Rule rule = ruleQueue.remove();
// check whether all subclass calls have been printed
if (csUtil.hasSubClassesWithCS(rule.getMetaclass(),
ruleQueue)) {
ruleQueue.add(rule);
} else {
sc.add("if (element instanceof " + getMetaClassName(rule) + ") {");
sc.add(getMethodName(rule) + "((" + getMetaClassName(rule)
+ ") element, globaltab, out);");
sc.add("return;");
sc.add("}");
}
}
sc.addLineBreak();
sc.add("addWarningToResource(\"The printer can not handle \" + element.eClass().getName() + \" elements\", element);");
sc.add("}");
sc.addLineBreak();
}
private void addConstructor(StringComposite sc) {
sc.add("public " + super.getResourceClassName()
+ "(" + OUTPUT_STREAM + " outputStream, " + iTextResourceClassName + " resource) {");
sc.add("super();");
sc.add("this.outputStream = outputStream;");
sc.add("this.resource = resource;");
sc.add("}");
sc.addLineBreak();
}
private void addFields(JavaComposite sc) {
sc.add("protected " + iTokenResolverFactoryClassName + " tokenResolverFactory = new "
+ tokenResolverFactoryClassName + "();");
sc.add("protected " + OUTPUT_STREAM + " outputStream;");
sc.addJavadoc(
"Holds the resource that is associated with this printer. may be null if the printer is used stand alone."
);
sc.add("private " + iTextResourceClassName + " resource;");
sc.add("private " + MAP + "<?, ?> options;");
sc.addLineBreak();
}
private void addPrintRuleMethod(JavaComposite sc, Rule rule) {
final GenClass genClass = rule.getMetaclass();
sc.add("public void " + getMethodName(rule) + "("
+ getMetaClassName(rule)
+ " element, String outertab, " + PRINTER_WRITER + " out) {");
sc.add(new StringComponent("String " + localtabName + " = outertab;", localtabName));
printCountingMapIntialization(sc, genClass);
addPrintCollectedTokensCode(sc, rule);
printChoice(rule.getDefinition(), sc, genClass);
sc.add("}");
printChoices(sc, rule);
sc.addLineBreak();
}
private void printChoices(JavaComposite sc, Rule rule) {
for (Choice choice : rule2SubChoice.get(rule)) {
sc
.add("public void "
+ choice2Name.get(choice)
+ "("
+ getMetaClassName(rule)
+ " element, String outertab, " + PRINTER_WRITER + " out, " + MAP + "<String, Integer> printCountingMap){");
sc.add(new StringComponent("String " + localtabName + " = outertab;", localtabName));
printChoice(choice, sc, rule.getMetaclass());
sc.add("}");
}
}
private void addPrintCollectedTokensCode(JavaComposite sc, Rule rule) {
final GenClass genClass = rule.getMetaclass();
List<GenFeature> featureList = genClass.getAllGenFeatures();
sc.addComment("print collected hidden tokens");
for (GenFeature genFeature : featureList) {
EStructuralFeature feature = genFeature.getEcoreFeature();
if (new CollectInFeatureHelper().isCollectInFeature(rule.getSyntax(), feature)) {
sc.add("{");
sc.add(E_STRUCTURAL_FEATURE + " feature = element.eClass()." + generatorUtil.createGetFeatureCall(genClass, genFeature) + ";");
sc.add("Object value = element.eGet(feature);");
sc.add("if (value instanceof " + LIST + ") {");
sc.add("for (Object next : (" + LIST + "<?>) value) {");
sc.add("out.print(tokenResolverFactory.createCollectInTokenResolver(\"" + feature.getName() + "\").deResolve(next, feature, element));");
sc.add("}");
sc.add("}");
sc.add("}");
}
}
}
private void printChoice(Choice choice, JavaComposite sc, GenClass genClass) {
String countName = "count";
sc.add(new StringComponent("int " + countName + ";", countName));
if (choice.getOptions().size() > 1) {
sc.add("int alt = -1;");
Iterator<Sequence> seqIt = choice.getOptions().iterator();
if (seqIt.hasNext()) {
Sequence firstSeq = seqIt.next();
int count = 0;
JavaComposite sc1 = new JavaComposite();
sc1.add("switch(alt) {");
sc.add("alt=" + count++ + ";");
sc.add("int matches=");
printMatchCall(firstSeq, sc);
sc.add("int tempMatchCount;");
while (seqIt.hasNext()) {
Sequence seq = seqIt.next();
sc.add("tempMatchCount=");
printMatchCall(seq, sc);
sc.add("if (tempMatchCount > matches) {");
sc.add("alt = " + count + ";");
sc.add("matches = tempMatchCount;");
sc.add("}");
sc1.add("case " + count + ":");
// extra scope for case begin
sc1.add("{");
printSequence(seq, sc1, genClass);
// extra scope for case end
sc1.add("}");
sc1.add("break;");
count++;
}
sc1.add("default:");
printSequence(firstSeq, sc1, genClass);
sc1.add("}");
sc.add(sc1);
}
} else if (choice.getOptions().size() == 1) {
printSequence(choice.getOptions().get(0), sc, genClass);
}
}
private Set<String> getReachableFeatures(Choice choice) {
Set<String> result = new LinkedHashSet<String>();
for (Sequence seq : choice.getOptions()) {
result.addAll(sequence2ReachableFeatures.get(seq));
}
return result;
}
private void printSequence(Sequence sequence, JavaComposite sc,
GenClass genClass) {
Set<String> neededFeatures = new LinkedHashSet<String>(
sequence2NecessaryFeatures.get(sequence));
//EClass metaClass = genClass.getEcoreClass();
ListIterator<Definition> definitionIterator = sequence.getParts()
.listIterator();
String iterateName = "iterate";
sc.add(new StringComponent("boolean " + iterateName + " = true;", iterateName));
String sWriteName = "sWriter";
sc.add(new StringComponent(STRING_WRITER + " " + sWriteName + " = null;", sWriteName));
String out1Name = "out1";
sc.add(new StringComponent(PRINTER_WRITER + " " + out1Name + " = null;", out1Name));
String printCountingMap1Name = "printCountingMap1";
sc.add(new StringComponent(MAP + "<String, Integer> " + printCountingMap1Name + " = null;", printCountingMap1Name));
while (definitionIterator.hasNext()) {
Definition definition = definitionIterator.next();
printDefinition(sc, genClass, neededFeatures, definitionIterator,
definition);
}
}
private void printDefinition(JavaComposite sc, GenClass genClass,
Set<String> neededFeatures,
ListIterator<Definition> definitionIterator, Definition definition) {
sc.addComment("DEFINITION PART BEGINS (" + definition.eClass().getName() + ")");
String printPrefix = "out.print(";
if (definition instanceof LineBreak) {
LineBreak lineBreak = (LineBreak) definition;
printLineBreak(sc, lineBreak);
} else {
if (definition instanceof WhiteSpaces) {
WhiteSpaces whiteSpace = (WhiteSpaces) definition;
printWhiteSpace(sc, printPrefix, whiteSpace);
} else if (definition instanceof CsString) {
CsString keyword = (CsString) definition;
printCsString(sc, definitionIterator, printPrefix, keyword);
} else {
Cardinality cardinality = getCardinality(definition);
if (definition instanceof CompoundDefinition) {
CompoundDefinition compound = (CompoundDefinition) definition;
printCompound(sc, neededFeatures, cardinality, compound);
}
// next steps: references --> proxy uri --> tokenresolver!
else if (definition instanceof Terminal) {
Terminal terminal = (Terminal) definition;
final GenFeature genFeature = terminal.getFeature();
final String featureName = genFeature.getName();
EStructuralFeature feature = genFeature.getEcoreFeature();
StringComposite printStatements = new JavaComposite();
if (genFeature != ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) {
sc.add("count = printCountingMap.get(\""
+ featureName + "\");");
if (terminal instanceof Placeholder) {
String tokenName = ((Placeholder) terminal).getToken().getName();
String featureConstant = generatorUtil.getFeatureConstant(genClass, genFeature);
if (feature instanceof EReference) {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix + "resolver.deResolve("
+ getContext().getReferenceResolverAccessor(genFeature)
+ ".deResolve((" + genClassCache.getQualifiedInterfaceName(genFeature.getTypeGenClass()) + ") o, element, (" + E_REFERENCE + ") element.eClass().getEStructuralFeature("
+ featureConstant
+ ")), element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
} else {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix
+ "resolver.deResolve((Object) o, element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
}
// the given tokenSpace (>0) causes an additional
// print statement to be printed
if (getTokenSpace() > 0) {
Definition lookahead = null;
if (definitionIterator.hasNext()){
lookahead = definitionIterator.next();
definitionIterator.previous();
}
if (lookahead == null
|| !(lookahead instanceof WhiteSpaces)) {
String printSuffix = getWhiteSpaceString(getTokenSpace());
printStatements.add("out.print(\"" + printSuffix + "\");");
}
}
} else if (terminal instanceof BooleanTerminal) {
// TODO implement printing of BooleanTerminals
} else if (terminal instanceof EnumTerminal) {
// TODO implement printing of EnumTerminal
} else {
assert terminal instanceof Containment;
printStatements.add("doPrint((" + E_OBJECT + ") o, out, localtab);");
}
sc.add("if (count > 0) {");
- if (cardinality == null
+ if (cardinality == Cardinality.NONE
|| (cardinality == Cardinality.QUESTIONMARK && !neededFeatures
.contains(featureName))) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
if (feature.getUpperBound() != 1) {
sc.add(LIST +"<?> list = (" + LIST + "<?>) o;");
sc.add("int index = list.size() - count;");
// we must check the index, because the list in the model
// may contain less elements than expected.
//
// this is for example the case, for a CS definitions like:
//
// feature ("," feature)*
//
// where the first element is mandatory in the CS rule, but
// the meta model defines a cardinality of 0..* for 'feature'.
sc.add("if (index >= 0) {");
sc.add("o = list.get(index);");
sc.add("} else {");
sc.add("o = null;");
sc.add("}");
}
sc.add("if (o != null) {");
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\"" + featureName + "\", count - 1);");
neededFeatures.remove(featureName);
} else if (cardinality == Cardinality.PLUS
|| cardinality == Cardinality.STAR) {
if (feature.getUpperBound() != 1) {
sc.add(LIST + "<?> list = (" + LIST +"<?>)element."
+ getAccessMethod(genClassCache, genClass, genFeature)
+ ";");
sc.add("int index = list.size() - count;");
sc.add("if (index < 0) {");
sc.add("index = 0;");
sc.add("}");
sc.add(LIST_ITERATOR + "<?> it = list.listIterator(index);");
sc.add("while (it.hasNext()) {");
sc.add("Object o = it.next();");
if (cardinality == Cardinality.STAR
&& neededFeatures.contains(featureName)) {
sc.add("if(!it.hasNext())");
sc.add("break;");
}
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\""
+ featureName + "\", 0);");
} else if (cardinality == Cardinality.PLUS) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
sc.add(printStatements);
sc.add("printCountingMap.put(\""
+ featureName + "\", count - 1);");
}
if (cardinality == Cardinality.PLUS) {
neededFeatures.remove(featureName);
}
}
sc.add("}"); // closing bracket for: if (count > 0)
}
}
}
}
}
private Cardinality getCardinality(Definition definition) {
Cardinality cardinality = Cardinality.NONE;
if (definition instanceof CardinalityDefinition) {
cardinality = ((CardinalityDefinition) definition).getCardinality();
}
return cardinality;
}
private void printCompound(StringComposite sc, Set<String> neededFeatures,
Cardinality cardinality, CompoundDefinition compound) {
String printStatement =
choice2Name.get(compound.getDefinition())
+ "(element, localtab, out, printCountingMap);";
// enter once
if (cardinality == Cardinality.NONE || cardinality == Cardinality.PLUS) {
sc.add(printStatement);
// needed features in non optional choice are also
// needed features in this sequence
// note: this implementation might remove to much in
// some cases!
for (Sequence seq1 : compound.getDefinition()
.getOptions()) {
neededFeatures
.removeAll(sequence2NecessaryFeatures
.get(seq1));
}
}
// optional cases
if (cardinality != Cardinality.NONE) {
boolean isMany = !(cardinality == Cardinality.QUESTIONMARK);
// runtime: iterate as long as no fixpoint is
// reached
// make sure that NOT all elements of needed
// features are printed in optional compounds!
if (isMany) {
sc.add("iterate = true;");
sc.add("while (iterate) {");
}
sc.add("sWriter = new " + STRING_WRITER + "();");
sc.add("out1 = new " + PRINTER_WRITER + "(sWriter);");
sc.add("printCountingMap1 = new " + LINKED_HASH_MAP + "<String, Integer>(printCountingMap);");
sc.add(choice2Name.get(compound.getDefinition()) + "(element, localtab, out1, printCountingMap1);");
sc.add("if (printCountingMap.equals(printCountingMap1)) {");
if (isMany) {
sc.add("iterate = false;");
}
sc.add("out1.close();");
sc.add("} else {");
// check if printed features are needed by
// subsequent features
// at least one element has to be preserved in that
// case!
// this could be enhanced by a counter on needed
// features
Collection<String> reachableFeatures = getReachableFeatures(compound.getDefinition());
if (!neededFeatures.isEmpty() &&
!Collections.disjoint(neededFeatures, reachableFeatures)) {
sc.add("if(");
Iterator<String> it = neededFeatures.iterator();
sc.add("printCountingMap1.get(\""
+ it.next() + "\")<1");
while (it.hasNext()) {
String feature = it.next();
sc.add("||printCountingMap1.get(\""
+ feature + "\")<1");
}
sc.add(") {");
if (isMany) {
sc.add("iterate = false;");
}
sc.add("out1.close();");
sc.add("} else {");
sc.add("out1.flush();");
sc.add("out1.close();");
sc.add("out.print(sWriter.toString());");
sc.add("printCountingMap.putAll(printCountingMap1);");
sc.add("}");
} else {
sc.add("out1.flush();");
sc.add("out1.close();");
sc.add("out.print(sWriter.toString());");
sc.add("printCountingMap.putAll(printCountingMap1);");
}
sc.add("}");
if (isMany) {
sc.add("}");
}
}
}
private void printCsString(StringComposite sc,
ListIterator<Definition> definitionIterator, String printPrefix,
CsString keyword) {
sc.add(printPrefix + "\""
+ StringUtil.escapeToJavaString(keyword.getValue())
+ "\");");
// the given tokenSpace (>0) causes an additional
// print statement to be printed
if (getTokenSpace() > 0) {
Definition lookahead = null;
if (definitionIterator.hasNext()){
lookahead = definitionIterator.next();
definitionIterator.previous();
}
if (lookahead == null
|| !(lookahead instanceof WhiteSpaces)) {
String printSuffix = getWhiteSpaceString(getTokenSpace());
sc.add(printPrefix + "\"" + printSuffix + "\");");
}
}
}
private void printWhiteSpace(StringComposite sc, String printPrefix,
WhiteSpaces whiteSpace) {
int count = whiteSpace.getAmount();
if (count > 0) {
String spaces = getWhiteSpaceString(count);
sc.add(printPrefix + "\"" + spaces + "\");");
}
}
private void printLineBreak(StringComposite sc, LineBreak lineBreak) {
int count = lineBreak.getTab();
if (count > 0) {
String tab = getTabString(count);
sc.add("localtab += \"" + tab + "\";");
}
sc.add("out.println();");
sc.add("out.print(localtab);");
}
private void printMatchCall(Sequence seq, StringComposite sc) {
if (sequence2NecessaryFeatures.get(seq).isEmpty()) {
sc.add("0;");
return;
}
sc.add("matchCount(printCountingMap, " + ARRAYS + ".asList(");
boolean notFirst = false;
for (String featureName : sequence2NecessaryFeatures.get(seq)) {
if (notFirst) {
sc.add(",");
} else {
notFirst = true;
}
sc.add("\"" + featureName + "\"");
}
sc.add("));");
}
private void addMatchCountMethod(StringComposite sc) {
sc.add("protected static int matchCount(" + MAP + "<String, Integer> featureCounter, " + COLLECTION + "<String> needed){");
sc.add("int pos = 0;");
sc.add("int neg = 0;");
sc.addLineBreak();
sc.add("for(String featureName:featureCounter.keySet()){");
sc.add("if(needed.contains(featureName)){");
sc.add("int value = featureCounter.get(featureName);");
sc.add("if (value == 0) {");
sc.add("neg += 1;");
sc.add("} else {");
sc.add("pos += 1;");
sc.add("}");
sc.add("}");
sc.add("}");
sc.add("return neg > 0 ? -neg : pos;");
sc.add("}");
sc.addLineBreak();
}
/**
* Prints the code needed to initialize the printCountingMap.
*
* @param sc
* @param genClass
*/
private void printCountingMapIntialization(JavaComposite sc, GenClass genClass) {
List<GenFeature> featureList = genClass.getAllGenFeatures();
String printCountingMapName = "printCountingMap";
sc.addComment(
"The " + printCountingMapName + " contains a mapping from feature names to " +
"the number of remaining elements that still need to be printed. " +
"The map is initialized with the number of elements stored in each structural " +
"feature. For lists this is the list size. For non-multiple features it is either " +
"1 (if the feature is set) or 0 (if the feature is null)."
);
sc.add(new StringComponent(MAP + "<String, Integer> " + printCountingMapName + " = new " + LINKED_HASH_MAP + "<String, Integer>("
+ featureList.size() + ");", printCountingMapName));
if (featureList.size() > 0) {
sc.add("Object temp;");
}
for (GenFeature genFeature : featureList) {
EStructuralFeature feature = genFeature.getEcoreFeature();
sc.add("temp = element." + getAccessMethod(genClassCache, genClass, genFeature) + ";");
boolean isMultiple = feature.getUpperBound() > 1 || feature.getUpperBound() == -1;
String featureSize = isMultiple ? "((" + COLLECTION + "<?>) temp).size()" : "1";
sc.add("printCountingMap.put(\"" + feature.getName() + "\", temp == null ? 0 : " + featureSize + ");");
}
}
}
| true | true | private void printDefinition(JavaComposite sc, GenClass genClass,
Set<String> neededFeatures,
ListIterator<Definition> definitionIterator, Definition definition) {
sc.addComment("DEFINITION PART BEGINS (" + definition.eClass().getName() + ")");
String printPrefix = "out.print(";
if (definition instanceof LineBreak) {
LineBreak lineBreak = (LineBreak) definition;
printLineBreak(sc, lineBreak);
} else {
if (definition instanceof WhiteSpaces) {
WhiteSpaces whiteSpace = (WhiteSpaces) definition;
printWhiteSpace(sc, printPrefix, whiteSpace);
} else if (definition instanceof CsString) {
CsString keyword = (CsString) definition;
printCsString(sc, definitionIterator, printPrefix, keyword);
} else {
Cardinality cardinality = getCardinality(definition);
if (definition instanceof CompoundDefinition) {
CompoundDefinition compound = (CompoundDefinition) definition;
printCompound(sc, neededFeatures, cardinality, compound);
}
// next steps: references --> proxy uri --> tokenresolver!
else if (definition instanceof Terminal) {
Terminal terminal = (Terminal) definition;
final GenFeature genFeature = terminal.getFeature();
final String featureName = genFeature.getName();
EStructuralFeature feature = genFeature.getEcoreFeature();
StringComposite printStatements = new JavaComposite();
if (genFeature != ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) {
sc.add("count = printCountingMap.get(\""
+ featureName + "\");");
if (terminal instanceof Placeholder) {
String tokenName = ((Placeholder) terminal).getToken().getName();
String featureConstant = generatorUtil.getFeatureConstant(genClass, genFeature);
if (feature instanceof EReference) {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix + "resolver.deResolve("
+ getContext().getReferenceResolverAccessor(genFeature)
+ ".deResolve((" + genClassCache.getQualifiedInterfaceName(genFeature.getTypeGenClass()) + ") o, element, (" + E_REFERENCE + ") element.eClass().getEStructuralFeature("
+ featureConstant
+ ")), element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
} else {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix
+ "resolver.deResolve((Object) o, element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
}
// the given tokenSpace (>0) causes an additional
// print statement to be printed
if (getTokenSpace() > 0) {
Definition lookahead = null;
if (definitionIterator.hasNext()){
lookahead = definitionIterator.next();
definitionIterator.previous();
}
if (lookahead == null
|| !(lookahead instanceof WhiteSpaces)) {
String printSuffix = getWhiteSpaceString(getTokenSpace());
printStatements.add("out.print(\"" + printSuffix + "\");");
}
}
} else if (terminal instanceof BooleanTerminal) {
// TODO implement printing of BooleanTerminals
} else if (terminal instanceof EnumTerminal) {
// TODO implement printing of EnumTerminal
} else {
assert terminal instanceof Containment;
printStatements.add("doPrint((" + E_OBJECT + ") o, out, localtab);");
}
sc.add("if (count > 0) {");
if (cardinality == null
|| (cardinality == Cardinality.QUESTIONMARK && !neededFeatures
.contains(featureName))) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
if (feature.getUpperBound() != 1) {
sc.add(LIST +"<?> list = (" + LIST + "<?>) o;");
sc.add("int index = list.size() - count;");
// we must check the index, because the list in the model
// may contain less elements than expected.
//
// this is for example the case, for a CS definitions like:
//
// feature ("," feature)*
//
// where the first element is mandatory in the CS rule, but
// the meta model defines a cardinality of 0..* for 'feature'.
sc.add("if (index >= 0) {");
sc.add("o = list.get(index);");
sc.add("} else {");
sc.add("o = null;");
sc.add("}");
}
sc.add("if (o != null) {");
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\"" + featureName + "\", count - 1);");
neededFeatures.remove(featureName);
} else if (cardinality == Cardinality.PLUS
|| cardinality == Cardinality.STAR) {
if (feature.getUpperBound() != 1) {
sc.add(LIST + "<?> list = (" + LIST +"<?>)element."
+ getAccessMethod(genClassCache, genClass, genFeature)
+ ";");
sc.add("int index = list.size() - count;");
sc.add("if (index < 0) {");
sc.add("index = 0;");
sc.add("}");
sc.add(LIST_ITERATOR + "<?> it = list.listIterator(index);");
sc.add("while (it.hasNext()) {");
sc.add("Object o = it.next();");
if (cardinality == Cardinality.STAR
&& neededFeatures.contains(featureName)) {
sc.add("if(!it.hasNext())");
sc.add("break;");
}
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\""
+ featureName + "\", 0);");
} else if (cardinality == Cardinality.PLUS) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
sc.add(printStatements);
sc.add("printCountingMap.put(\""
+ featureName + "\", count - 1);");
}
if (cardinality == Cardinality.PLUS) {
neededFeatures.remove(featureName);
}
}
sc.add("}"); // closing bracket for: if (count > 0)
}
}
}
}
}
| private void printDefinition(JavaComposite sc, GenClass genClass,
Set<String> neededFeatures,
ListIterator<Definition> definitionIterator, Definition definition) {
sc.addComment("DEFINITION PART BEGINS (" + definition.eClass().getName() + ")");
String printPrefix = "out.print(";
if (definition instanceof LineBreak) {
LineBreak lineBreak = (LineBreak) definition;
printLineBreak(sc, lineBreak);
} else {
if (definition instanceof WhiteSpaces) {
WhiteSpaces whiteSpace = (WhiteSpaces) definition;
printWhiteSpace(sc, printPrefix, whiteSpace);
} else if (definition instanceof CsString) {
CsString keyword = (CsString) definition;
printCsString(sc, definitionIterator, printPrefix, keyword);
} else {
Cardinality cardinality = getCardinality(definition);
if (definition instanceof CompoundDefinition) {
CompoundDefinition compound = (CompoundDefinition) definition;
printCompound(sc, neededFeatures, cardinality, compound);
}
// next steps: references --> proxy uri --> tokenresolver!
else if (definition instanceof Terminal) {
Terminal terminal = (Terminal) definition;
final GenFeature genFeature = terminal.getFeature();
final String featureName = genFeature.getName();
EStructuralFeature feature = genFeature.getEcoreFeature();
StringComposite printStatements = new JavaComposite();
if (genFeature != ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) {
sc.add("count = printCountingMap.get(\""
+ featureName + "\");");
if (terminal instanceof Placeholder) {
String tokenName = ((Placeholder) terminal).getToken().getName();
String featureConstant = generatorUtil.getFeatureConstant(genClass, genFeature);
if (feature instanceof EReference) {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix + "resolver.deResolve("
+ getContext().getReferenceResolverAccessor(genFeature)
+ ".deResolve((" + genClassCache.getQualifiedInterfaceName(genFeature.getTypeGenClass()) + ") o, element, (" + E_REFERENCE + ") element.eClass().getEStructuralFeature("
+ featureConstant
+ ")), element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
} else {
printStatements.add(iTokenResolverClassName + " resolver = tokenResolverFactory.createTokenResolver(\""
+ tokenName
+ "\");");
printStatements.add("resolver.setOptions(getOptions());");
printStatements.add(printPrefix
+ "resolver.deResolve((Object) o, element.eClass().getEStructuralFeature("
+ featureConstant
+ "), element));");
}
// the given tokenSpace (>0) causes an additional
// print statement to be printed
if (getTokenSpace() > 0) {
Definition lookahead = null;
if (definitionIterator.hasNext()){
lookahead = definitionIterator.next();
definitionIterator.previous();
}
if (lookahead == null
|| !(lookahead instanceof WhiteSpaces)) {
String printSuffix = getWhiteSpaceString(getTokenSpace());
printStatements.add("out.print(\"" + printSuffix + "\");");
}
}
} else if (terminal instanceof BooleanTerminal) {
// TODO implement printing of BooleanTerminals
} else if (terminal instanceof EnumTerminal) {
// TODO implement printing of EnumTerminal
} else {
assert terminal instanceof Containment;
printStatements.add("doPrint((" + E_OBJECT + ") o, out, localtab);");
}
sc.add("if (count > 0) {");
if (cardinality == Cardinality.NONE
|| (cardinality == Cardinality.QUESTIONMARK && !neededFeatures
.contains(featureName))) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
if (feature.getUpperBound() != 1) {
sc.add(LIST +"<?> list = (" + LIST + "<?>) o;");
sc.add("int index = list.size() - count;");
// we must check the index, because the list in the model
// may contain less elements than expected.
//
// this is for example the case, for a CS definitions like:
//
// feature ("," feature)*
//
// where the first element is mandatory in the CS rule, but
// the meta model defines a cardinality of 0..* for 'feature'.
sc.add("if (index >= 0) {");
sc.add("o = list.get(index);");
sc.add("} else {");
sc.add("o = null;");
sc.add("}");
}
sc.add("if (o != null) {");
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\"" + featureName + "\", count - 1);");
neededFeatures.remove(featureName);
} else if (cardinality == Cardinality.PLUS
|| cardinality == Cardinality.STAR) {
if (feature.getUpperBound() != 1) {
sc.add(LIST + "<?> list = (" + LIST +"<?>)element."
+ getAccessMethod(genClassCache, genClass, genFeature)
+ ";");
sc.add("int index = list.size() - count;");
sc.add("if (index < 0) {");
sc.add("index = 0;");
sc.add("}");
sc.add(LIST_ITERATOR + "<?> it = list.listIterator(index);");
sc.add("while (it.hasNext()) {");
sc.add("Object o = it.next();");
if (cardinality == Cardinality.STAR
&& neededFeatures.contains(featureName)) {
sc.add("if(!it.hasNext())");
sc.add("break;");
}
sc.add(printStatements);
sc.add("}");
sc.add("printCountingMap.put(\""
+ featureName + "\", 0);");
} else if (cardinality == Cardinality.PLUS) {
sc.add("Object o = element."
+ getAccessMethod(genClassCache, genClass, genFeature) + ";");
sc.add(printStatements);
sc.add("printCountingMap.put(\""
+ featureName + "\", count - 1);");
}
if (cardinality == Cardinality.PLUS) {
neededFeatures.remove(featureName);
}
}
sc.add("}"); // closing bracket for: if (count > 0)
}
}
}
}
}
|
diff --git a/src/java/org/infoglue/deliver/util/DeliverContextListener.java b/src/java/org/infoglue/deliver/util/DeliverContextListener.java
index 757296e2d..46d7c21eb 100755
--- a/src/java/org/infoglue/deliver/util/DeliverContextListener.java
+++ b/src/java/org/infoglue/deliver/util/DeliverContextListener.java
@@ -1,139 +1,146 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.deliver.util;
import java.io.File;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.apache.log4j.RollingFileAppender;
import org.infoglue.cms.security.InfoGlueAuthenticationFilter;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.deliver.invokers.ComponentBasedHTMLPageInvoker;
import com.opensymphony.oscache.base.OSCacheUtility;
/**
* This class functions as the entry-point for all initialization of the Cms-tool.
* The class responds to the startup or reload of a whole context.
*/
public final class DeliverContextListener implements ServletContextListener
{
private final static Logger logger = Logger.getLogger(DeliverContextListener.class.getName());
private static CacheController cacheController = new CacheController();
private static ServletContext servletContext = null;
public static ServletContext getServletContext()
{
return servletContext;
}
/**
* This method is called when the servlet context is
* initialized(when the Web Application is deployed).
* You can initialize servlet context related data here.
*/
public void contextInitialized(ServletContextEvent event)
{
try
{
String contextRootPath = event.getServletContext().getRealPath("/");
if(!contextRootPath.endsWith("/") && !contextRootPath.endsWith("\\"))
contextRootPath = contextRootPath + "/";
System.out.println("\n**************************************");
System.out.println("Initializing deliver context for directory:" + contextRootPath);
CmsPropertyHandler.setApplicationName("deliver");
CmsPropertyHandler.setContextRootPath(contextRootPath);
CmsPropertyHandler.setOperatingMode(CmsPropertyHandler.getProperty("operatingMode"));
String logPath = CmsPropertyHandler.getLogPath();
Enumeration enumeration = Logger.getLogger("org.infoglue.cms").getAllAppenders();
while(enumeration.hasMoreElements())
{
RollingFileAppender appender = (RollingFileAppender)enumeration.nextElement();
if(appender.getName().equalsIgnoreCase("INFOGLUE-FILE"))
{
appender.setFile(logPath);
appender.activateOptions();
Logger.getLogger(ComponentBasedHTMLPageInvoker.class).addAppender(appender);
break;
}
}
String expireCacheAutomaticallyString = CmsPropertyHandler.getExpireCacheAutomatically();
if(expireCacheAutomaticallyString != null)
cacheController.setExpireCacheAutomatically(Boolean.parseBoolean(expireCacheAutomaticallyString));
String intervalString = CmsPropertyHandler.getCacheExpireInterval();
if(intervalString != null)
cacheController.setCacheExpireInterval(Integer.parseInt(intervalString));
//System.out.println("Clearing previous filebased page cache");
- CacheController.clearFileCaches("pageCache");
+ try
+ {
+ CacheController.clearFileCaches("pageCache");
+ }
+ catch (Exception e)
+ {
+ logger.error("Could not clear file cache:" + e.getMessage());
+ }
//Starting the cache-expire-thread
if(cacheController.getExpireCacheAutomatically())
cacheController.start();
OSCacheUtility.setServletCacheParams(event.getServletContext());
InfoGlueAuthenticationFilter.initializeProperties();
CmsPropertyHandler.setStartupTime(new Date());
System.out.println("**************************************\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* This method is invoked when the Servlet Context
* (the Web Application) is undeployed or
* WebLogic Server shuts down.
*/
public void contextDestroyed(ServletContextEvent event)
{
System.out.println("contextDestroyed....");
cacheController.stopThread();
cacheController.interrupt();
}
}
| true | true | public void contextInitialized(ServletContextEvent event)
{
try
{
String contextRootPath = event.getServletContext().getRealPath("/");
if(!contextRootPath.endsWith("/") && !contextRootPath.endsWith("\\"))
contextRootPath = contextRootPath + "/";
System.out.println("\n**************************************");
System.out.println("Initializing deliver context for directory:" + contextRootPath);
CmsPropertyHandler.setApplicationName("deliver");
CmsPropertyHandler.setContextRootPath(contextRootPath);
CmsPropertyHandler.setOperatingMode(CmsPropertyHandler.getProperty("operatingMode"));
String logPath = CmsPropertyHandler.getLogPath();
Enumeration enumeration = Logger.getLogger("org.infoglue.cms").getAllAppenders();
while(enumeration.hasMoreElements())
{
RollingFileAppender appender = (RollingFileAppender)enumeration.nextElement();
if(appender.getName().equalsIgnoreCase("INFOGLUE-FILE"))
{
appender.setFile(logPath);
appender.activateOptions();
Logger.getLogger(ComponentBasedHTMLPageInvoker.class).addAppender(appender);
break;
}
}
String expireCacheAutomaticallyString = CmsPropertyHandler.getExpireCacheAutomatically();
if(expireCacheAutomaticallyString != null)
cacheController.setExpireCacheAutomatically(Boolean.parseBoolean(expireCacheAutomaticallyString));
String intervalString = CmsPropertyHandler.getCacheExpireInterval();
if(intervalString != null)
cacheController.setCacheExpireInterval(Integer.parseInt(intervalString));
//System.out.println("Clearing previous filebased page cache");
CacheController.clearFileCaches("pageCache");
//Starting the cache-expire-thread
if(cacheController.getExpireCacheAutomatically())
cacheController.start();
OSCacheUtility.setServletCacheParams(event.getServletContext());
InfoGlueAuthenticationFilter.initializeProperties();
CmsPropertyHandler.setStartupTime(new Date());
System.out.println("**************************************\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
| public void contextInitialized(ServletContextEvent event)
{
try
{
String contextRootPath = event.getServletContext().getRealPath("/");
if(!contextRootPath.endsWith("/") && !contextRootPath.endsWith("\\"))
contextRootPath = contextRootPath + "/";
System.out.println("\n**************************************");
System.out.println("Initializing deliver context for directory:" + contextRootPath);
CmsPropertyHandler.setApplicationName("deliver");
CmsPropertyHandler.setContextRootPath(contextRootPath);
CmsPropertyHandler.setOperatingMode(CmsPropertyHandler.getProperty("operatingMode"));
String logPath = CmsPropertyHandler.getLogPath();
Enumeration enumeration = Logger.getLogger("org.infoglue.cms").getAllAppenders();
while(enumeration.hasMoreElements())
{
RollingFileAppender appender = (RollingFileAppender)enumeration.nextElement();
if(appender.getName().equalsIgnoreCase("INFOGLUE-FILE"))
{
appender.setFile(logPath);
appender.activateOptions();
Logger.getLogger(ComponentBasedHTMLPageInvoker.class).addAppender(appender);
break;
}
}
String expireCacheAutomaticallyString = CmsPropertyHandler.getExpireCacheAutomatically();
if(expireCacheAutomaticallyString != null)
cacheController.setExpireCacheAutomatically(Boolean.parseBoolean(expireCacheAutomaticallyString));
String intervalString = CmsPropertyHandler.getCacheExpireInterval();
if(intervalString != null)
cacheController.setCacheExpireInterval(Integer.parseInt(intervalString));
//System.out.println("Clearing previous filebased page cache");
try
{
CacheController.clearFileCaches("pageCache");
}
catch (Exception e)
{
logger.error("Could not clear file cache:" + e.getMessage());
}
//Starting the cache-expire-thread
if(cacheController.getExpireCacheAutomatically())
cacheController.start();
OSCacheUtility.setServletCacheParams(event.getServletContext());
InfoGlueAuthenticationFilter.initializeProperties();
CmsPropertyHandler.setStartupTime(new Date());
System.out.println("**************************************\n");
}
catch(Exception e)
{
e.printStackTrace();
}
}
|
diff --git a/src/org/openstreetmap/josm/actions/AlignInCircleAction.java b/src/org/openstreetmap/josm/actions/AlignInCircleAction.java
index be540dd1..d317c9c6 100644
--- a/src/org/openstreetmap/josm/actions/AlignInCircleAction.java
+++ b/src/org/openstreetmap/josm/actions/AlignInCircleAction.java
@@ -1,269 +1,269 @@
//License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.actions;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.command.Command;
import org.openstreetmap.josm.command.MoveCommand;
import org.openstreetmap.josm.command.SequenceCommand;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.tools.Shortcut;
/**
* Aligns all selected nodes within a circle. (Useful for roundabouts)
*
* @author Matthew Newton
* @author Petr Dlouhý
* @author Teemu Koskinen
*/
public final class AlignInCircleAction extends JosmAction {
public AlignInCircleAction() {
super(tr("Align Nodes in Circle"), "aligncircle", tr("Move the selected nodes into a circle."),
Shortcut.registerShortcut("tools:aligncircle", tr("Tool: {0}", tr("Align Nodes in Circle")),
KeyEvent.VK_O, Shortcut.GROUP_EDIT), true);
putValue("help", ht("/Action/AlignInCircle"));
}
public double distance(EastNorth n, EastNorth m) {
double easd, nord;
easd = n.east() - m.east();
nord = n.north() - m.north();
return Math.sqrt(easd * easd + nord * nord);
}
public class PolarCoor {
double radius;
double angle;
EastNorth origin = new EastNorth(0, 0);
double azimuth = 0;
PolarCoor(double radius, double angle) {
this(radius, angle, new EastNorth(0, 0), 0);
}
PolarCoor(double radius, double angle, EastNorth origin, double azimuth) {
this.radius = radius;
this.angle = angle;
this.origin = origin;
this.azimuth = azimuth;
}
PolarCoor(EastNorth en) {
this(en, new EastNorth(0, 0), 0);
}
PolarCoor(EastNorth en, EastNorth origin, double azimuth) {
radius = distance(en, origin);
angle = Math.atan2(en.north() - origin.north(), en.east() - origin.east());
this.origin = origin;
this.azimuth = azimuth;
}
public EastNorth toEastNorth() {
return new EastNorth(radius * Math.cos(angle - azimuth) + origin.east(), radius * Math.sin(angle - azimuth)
+ origin.north());
}
}
public void actionPerformed(ActionEvent e) {
if (!isEnabled())
return;
Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
List<Node> nodes = new LinkedList<Node>();
List<Way> ways = new LinkedList<Way>();
EastNorth center = null;
double radius = 0;
boolean regular = false;
for (OsmPrimitive osm : sel) {
if (osm instanceof Node) {
nodes.add((Node) osm);
} else if (osm instanceof Way) {
ways.add((Way) osm);
}
}
// special case if no single nodes are selected and exactly one way is:
// then use the way's nodes
if ((nodes.size() <= 2) && (ways.size() == 1)) {
Way way = ways.get(0);
// some more special combinations:
// When is selected node that is part of the way, then make a regular polygon, selected
// node doesn't move.
// I haven't got better idea, how to activate that function.
//
// When one way and one node is selected, set center to position of that node.
// When one more node, part of the way, is selected, set the radius equal to the
// distance between two nodes.
if (nodes.size() > 0) {
if (nodes.size() == 1 && way.containsNode(nodes.get(0))) {
regular = true;
} else {
center = nodes.get(way.containsNode(nodes.get(0)) ? 1 : 0).getEastNorth();
if (nodes.size() == 2) {
radius = distance(nodes.get(0).getEastNorth(), nodes.get(1).getEastNorth());
}
}
nodes = new LinkedList<Node>();
}
for (Node n : way.getNodes()) {
if (!nodes.contains(n)) {
nodes.add(n);
}
}
}
if (nodes.size() < 4) {
JOptionPane.showMessageDialog(
Main.parent,
tr("Please select at least four nodes."),
tr("Information"),
JOptionPane.INFORMATION_MESSAGE
);
return;
}
// Reorder the nodes if they didn't come from a single way
if (ways.size() != 1) {
// First calculate the average point
BigDecimal east = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
for (Node n : nodes) {
BigDecimal x = new BigDecimal(n.getEastNorth().east());
BigDecimal y = new BigDecimal(n.getEastNorth().north());
east = east.add(x, MathContext.DECIMAL128);
north = north.add(y, MathContext.DECIMAL128);
}
BigDecimal nodesSize = new BigDecimal(nodes.size());
- east = east.divide(nodesSize, MathContext.DECIMAL128);
- north = north.divide(nodesSize, MathContext.DECIMAL128);
+ east = east.divide(nodesSize );//, MathContext.DECIMAL128); error: class 'java.math.BigDecimal' has no method named 'divide' matching signature '(Ljava/math/BigDecimal;Ljava/math/MathContext;)Ljava/math/BigDecimal;'
+ north = north.divide(nodesSize);//, MathContext.DECIMAL128);
EastNorth average = new EastNorth(east.doubleValue(), north.doubleValue());
List<Node> newNodes = new LinkedList<Node>();
// Then reorder them based on heading from the average point
while (!nodes.isEmpty()) {
double maxHeading = -1.0;
Node maxNode = null;
for (Node n : nodes) {
double heading = average.heading(n.getEastNorth());
if (heading > maxHeading) {
maxHeading = heading;
maxNode = n;
}
}
newNodes.add(maxNode);
nodes.remove(maxNode);
}
nodes = newNodes;
}
if (center == null) {
// Compute the centroid of nodes
BigDecimal area = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
BigDecimal east = new BigDecimal(0);
// See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon for the equation used here
for (int i = 0; i < nodes.size(); i++) {
EastNorth n0 = nodes.get(i).getEastNorth();
EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
BigDecimal x0 = new BigDecimal(n0.east());
BigDecimal y0 = new BigDecimal(n0.north());
BigDecimal x1 = new BigDecimal(n1.east());
BigDecimal y1 = new BigDecimal(n1.north());
BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
area = area.add(k, MathContext.DECIMAL128);
east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
}
BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
area = area.multiply(d, MathContext.DECIMAL128);
- north = north.divide(area, MathContext.DECIMAL128);
- east = east.divide(area, MathContext.DECIMAL128);
+ north = north.divide(area ); //, MathContext.DECIMAL128);
+ east = east.divide(area ); //, MathContext.DECIMAL128);
center = new EastNorth(east.doubleValue(), north.doubleValue());
}
// Node "center" now is central to all selected nodes.
// Now calculate the average distance to each node from the
// centre. This method is ok as long as distances are short
// relative to the distance from the N or S poles.
if (radius == 0) {
for (Node n : nodes) {
radius += distance(center, n.getEastNorth());
}
radius = radius / nodes.size();
}
Collection<Command> cmds = new LinkedList<Command>();
PolarCoor pc;
if (regular) { // Make a regular polygon
double angle = Math.PI * 2 / nodes.size();
pc = new PolarCoor(nodes.get(0).getEastNorth(), center, 0);
if (pc.angle > (new PolarCoor(nodes.get(1).getEastNorth(), center, 0).angle)) {
angle *= -1;
}
pc.radius = radius;
for (Node n : nodes) {
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
pc.angle += angle;
}
} else { // Move each node to that distance from the centre.
for (Node n : nodes) {
pc = new PolarCoor(n.getEastNorth(), center, 0);
pc.radius = radius;
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
}
}
Main.main.undoRedo.add(new SequenceCommand(tr("Align Nodes in Circle"), cmds));
Main.map.repaint();
}
@Override
protected void updateEnabledState() {
setEnabled(getCurrentDataSet() != null && !getCurrentDataSet().getSelected().isEmpty());
}
@Override
protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
setEnabled(selection != null && !selection.isEmpty());
}
}
| false | true | public void actionPerformed(ActionEvent e) {
if (!isEnabled())
return;
Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
List<Node> nodes = new LinkedList<Node>();
List<Way> ways = new LinkedList<Way>();
EastNorth center = null;
double radius = 0;
boolean regular = false;
for (OsmPrimitive osm : sel) {
if (osm instanceof Node) {
nodes.add((Node) osm);
} else if (osm instanceof Way) {
ways.add((Way) osm);
}
}
// special case if no single nodes are selected and exactly one way is:
// then use the way's nodes
if ((nodes.size() <= 2) && (ways.size() == 1)) {
Way way = ways.get(0);
// some more special combinations:
// When is selected node that is part of the way, then make a regular polygon, selected
// node doesn't move.
// I haven't got better idea, how to activate that function.
//
// When one way and one node is selected, set center to position of that node.
// When one more node, part of the way, is selected, set the radius equal to the
// distance between two nodes.
if (nodes.size() > 0) {
if (nodes.size() == 1 && way.containsNode(nodes.get(0))) {
regular = true;
} else {
center = nodes.get(way.containsNode(nodes.get(0)) ? 1 : 0).getEastNorth();
if (nodes.size() == 2) {
radius = distance(nodes.get(0).getEastNorth(), nodes.get(1).getEastNorth());
}
}
nodes = new LinkedList<Node>();
}
for (Node n : way.getNodes()) {
if (!nodes.contains(n)) {
nodes.add(n);
}
}
}
if (nodes.size() < 4) {
JOptionPane.showMessageDialog(
Main.parent,
tr("Please select at least four nodes."),
tr("Information"),
JOptionPane.INFORMATION_MESSAGE
);
return;
}
// Reorder the nodes if they didn't come from a single way
if (ways.size() != 1) {
// First calculate the average point
BigDecimal east = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
for (Node n : nodes) {
BigDecimal x = new BigDecimal(n.getEastNorth().east());
BigDecimal y = new BigDecimal(n.getEastNorth().north());
east = east.add(x, MathContext.DECIMAL128);
north = north.add(y, MathContext.DECIMAL128);
}
BigDecimal nodesSize = new BigDecimal(nodes.size());
east = east.divide(nodesSize, MathContext.DECIMAL128);
north = north.divide(nodesSize, MathContext.DECIMAL128);
EastNorth average = new EastNorth(east.doubleValue(), north.doubleValue());
List<Node> newNodes = new LinkedList<Node>();
// Then reorder them based on heading from the average point
while (!nodes.isEmpty()) {
double maxHeading = -1.0;
Node maxNode = null;
for (Node n : nodes) {
double heading = average.heading(n.getEastNorth());
if (heading > maxHeading) {
maxHeading = heading;
maxNode = n;
}
}
newNodes.add(maxNode);
nodes.remove(maxNode);
}
nodes = newNodes;
}
if (center == null) {
// Compute the centroid of nodes
BigDecimal area = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
BigDecimal east = new BigDecimal(0);
// See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon for the equation used here
for (int i = 0; i < nodes.size(); i++) {
EastNorth n0 = nodes.get(i).getEastNorth();
EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
BigDecimal x0 = new BigDecimal(n0.east());
BigDecimal y0 = new BigDecimal(n0.north());
BigDecimal x1 = new BigDecimal(n1.east());
BigDecimal y1 = new BigDecimal(n1.north());
BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
area = area.add(k, MathContext.DECIMAL128);
east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
}
BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
area = area.multiply(d, MathContext.DECIMAL128);
north = north.divide(area, MathContext.DECIMAL128);
east = east.divide(area, MathContext.DECIMAL128);
center = new EastNorth(east.doubleValue(), north.doubleValue());
}
// Node "center" now is central to all selected nodes.
// Now calculate the average distance to each node from the
// centre. This method is ok as long as distances are short
// relative to the distance from the N or S poles.
if (radius == 0) {
for (Node n : nodes) {
radius += distance(center, n.getEastNorth());
}
radius = radius / nodes.size();
}
Collection<Command> cmds = new LinkedList<Command>();
PolarCoor pc;
if (regular) { // Make a regular polygon
double angle = Math.PI * 2 / nodes.size();
pc = new PolarCoor(nodes.get(0).getEastNorth(), center, 0);
if (pc.angle > (new PolarCoor(nodes.get(1).getEastNorth(), center, 0).angle)) {
angle *= -1;
}
pc.radius = radius;
for (Node n : nodes) {
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
pc.angle += angle;
}
} else { // Move each node to that distance from the centre.
for (Node n : nodes) {
pc = new PolarCoor(n.getEastNorth(), center, 0);
pc.radius = radius;
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
}
}
Main.main.undoRedo.add(new SequenceCommand(tr("Align Nodes in Circle"), cmds));
Main.map.repaint();
}
| public void actionPerformed(ActionEvent e) {
if (!isEnabled())
return;
Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
List<Node> nodes = new LinkedList<Node>();
List<Way> ways = new LinkedList<Way>();
EastNorth center = null;
double radius = 0;
boolean regular = false;
for (OsmPrimitive osm : sel) {
if (osm instanceof Node) {
nodes.add((Node) osm);
} else if (osm instanceof Way) {
ways.add((Way) osm);
}
}
// special case if no single nodes are selected and exactly one way is:
// then use the way's nodes
if ((nodes.size() <= 2) && (ways.size() == 1)) {
Way way = ways.get(0);
// some more special combinations:
// When is selected node that is part of the way, then make a regular polygon, selected
// node doesn't move.
// I haven't got better idea, how to activate that function.
//
// When one way and one node is selected, set center to position of that node.
// When one more node, part of the way, is selected, set the radius equal to the
// distance between two nodes.
if (nodes.size() > 0) {
if (nodes.size() == 1 && way.containsNode(nodes.get(0))) {
regular = true;
} else {
center = nodes.get(way.containsNode(nodes.get(0)) ? 1 : 0).getEastNorth();
if (nodes.size() == 2) {
radius = distance(nodes.get(0).getEastNorth(), nodes.get(1).getEastNorth());
}
}
nodes = new LinkedList<Node>();
}
for (Node n : way.getNodes()) {
if (!nodes.contains(n)) {
nodes.add(n);
}
}
}
if (nodes.size() < 4) {
JOptionPane.showMessageDialog(
Main.parent,
tr("Please select at least four nodes."),
tr("Information"),
JOptionPane.INFORMATION_MESSAGE
);
return;
}
// Reorder the nodes if they didn't come from a single way
if (ways.size() != 1) {
// First calculate the average point
BigDecimal east = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
for (Node n : nodes) {
BigDecimal x = new BigDecimal(n.getEastNorth().east());
BigDecimal y = new BigDecimal(n.getEastNorth().north());
east = east.add(x, MathContext.DECIMAL128);
north = north.add(y, MathContext.DECIMAL128);
}
BigDecimal nodesSize = new BigDecimal(nodes.size());
east = east.divide(nodesSize );//, MathContext.DECIMAL128); error: class 'java.math.BigDecimal' has no method named 'divide' matching signature '(Ljava/math/BigDecimal;Ljava/math/MathContext;)Ljava/math/BigDecimal;'
north = north.divide(nodesSize);//, MathContext.DECIMAL128);
EastNorth average = new EastNorth(east.doubleValue(), north.doubleValue());
List<Node> newNodes = new LinkedList<Node>();
// Then reorder them based on heading from the average point
while (!nodes.isEmpty()) {
double maxHeading = -1.0;
Node maxNode = null;
for (Node n : nodes) {
double heading = average.heading(n.getEastNorth());
if (heading > maxHeading) {
maxHeading = heading;
maxNode = n;
}
}
newNodes.add(maxNode);
nodes.remove(maxNode);
}
nodes = newNodes;
}
if (center == null) {
// Compute the centroid of nodes
BigDecimal area = new BigDecimal(0);
BigDecimal north = new BigDecimal(0);
BigDecimal east = new BigDecimal(0);
// See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon for the equation used here
for (int i = 0; i < nodes.size(); i++) {
EastNorth n0 = nodes.get(i).getEastNorth();
EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
BigDecimal x0 = new BigDecimal(n0.east());
BigDecimal y0 = new BigDecimal(n0.north());
BigDecimal x1 = new BigDecimal(n1.east());
BigDecimal y1 = new BigDecimal(n1.north());
BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
area = area.add(k, MathContext.DECIMAL128);
east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
}
BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
area = area.multiply(d, MathContext.DECIMAL128);
north = north.divide(area ); //, MathContext.DECIMAL128);
east = east.divide(area ); //, MathContext.DECIMAL128);
center = new EastNorth(east.doubleValue(), north.doubleValue());
}
// Node "center" now is central to all selected nodes.
// Now calculate the average distance to each node from the
// centre. This method is ok as long as distances are short
// relative to the distance from the N or S poles.
if (radius == 0) {
for (Node n : nodes) {
radius += distance(center, n.getEastNorth());
}
radius = radius / nodes.size();
}
Collection<Command> cmds = new LinkedList<Command>();
PolarCoor pc;
if (regular) { // Make a regular polygon
double angle = Math.PI * 2 / nodes.size();
pc = new PolarCoor(nodes.get(0).getEastNorth(), center, 0);
if (pc.angle > (new PolarCoor(nodes.get(1).getEastNorth(), center, 0).angle)) {
angle *= -1;
}
pc.radius = radius;
for (Node n : nodes) {
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
pc.angle += angle;
}
} else { // Move each node to that distance from the centre.
for (Node n : nodes) {
pc = new PolarCoor(n.getEastNorth(), center, 0);
pc.radius = radius;
EastNorth no = pc.toEastNorth();
cmds.add(new MoveCommand(n, no.east() - n.getEastNorth().east(), no.north() - n.getEastNorth().north()));
}
}
Main.main.undoRedo.add(new SequenceCommand(tr("Align Nodes in Circle"), cmds));
Main.map.repaint();
}
|
diff --git a/hot-deploy/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingSession.java b/hot-deploy/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingSession.java
index 0f314be29..3cc5bcff7 100644
--- a/hot-deploy/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingSession.java
+++ b/hot-deploy/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingSession.java
@@ -1,624 +1,624 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps 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.
*
* Opentaps 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 Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
/*******************************************************************************
* 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.
*******************************************************************************/
/* This file may contain code which has been modified from that included with the Apache-licensed OFBiz product application */
/* This file has been modified by Open Source Strategies, Inc. */
package org.opentaps.warehouse.shipment.packing;
import java.math.BigDecimal;
import java.util.*;
import javolution.util.FastMap;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.order.shoppingcart.shipping.ShippingEvents;
import org.ofbiz.product.product.ProductWorker;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.shipment.packing.PackingEvent;
import org.ofbiz.shipment.packing.PackingSessionLine;
import org.opentaps.domain.DomainsLoader;
import org.opentaps.domain.base.entities.CarrierShipmentBoxType;
import org.opentaps.domain.order.Order;
import org.opentaps.domain.order.OrderItem;
import org.opentaps.domain.order.OrderRepositoryInterface;
import org.opentaps.domain.shipping.ShippingRepositoryInterface;
import org.opentaps.foundation.entity.EntityNotFoundException;
import org.opentaps.foundation.exception.FoundationException;
import org.opentaps.foundation.infrastructure.Infrastructure;
import org.opentaps.foundation.infrastructure.InfrastructureException;
import org.opentaps.foundation.infrastructure.User;
import org.opentaps.foundation.repository.RepositoryException;
/**
* Class to extend OFBiz PackingSession in order to provide additional Warehouse application-specific support.
*
* @author <a href="mailto:[email protected]">Chris Liberty</a>
* @version $Rev$
*/
public class PackingSession extends org.ofbiz.shipment.packing.PackingSession implements java.io.Serializable {
private static final String MODULE = PackingSession.class.getName();
protected Map<String, String> packageTrackingCodes;
protected Map<String, String> packageBoxTypeIds;
protected String additionalShippingChargeDescription;
/**
* Creates a new <code>PackingSession</code> instance.
*
* @param dispatcher a <code>LocalDispatcher</code> value
* @param userLogin a <code>GenericValue</code> value
* @param facilityId a <code>String</code> value
* @param binId a <code>String</code> value
* @param orderId a <code>String</code> value
* @param shipGrp a <code>String</code> value
*/
public PackingSession(LocalDispatcher dispatcher, GenericValue userLogin, String facilityId, String binId, String orderId, String shipGrp) {
super(dispatcher, userLogin, facilityId, binId, orderId, shipGrp);
this.packageTrackingCodes = new HashMap<String, String>();
this.packageBoxTypeIds = new HashMap<String, String>();
}
/**
* Creates a new <code>PackingSession</code> instance.
*
* @param dispatcher a <code>LocalDispatcher</code> value
* @param userLogin a <code>GenericValue</code> value
* @param facilityId a <code>String</code> value
*/
public PackingSession(LocalDispatcher dispatcher, GenericValue userLogin, String facilityId) {
this(dispatcher, userLogin, facilityId, null, null, null);
}
/**
* Creates a new <code>PackingSession</code> instance.
*
* @param dispatcher a <code>LocalDispatcher</code> value
* @param userLogin a <code>GenericValue</code> value
*/
public PackingSession(LocalDispatcher dispatcher, GenericValue userLogin) {
this(dispatcher, userLogin, null, null, null, null);
}
// Override the line item creation to add our custom OpentapsPackingSessionLine.
protected void createPackLineItem(int checkCode, GenericValue res, String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, BigDecimal quantity, BigDecimal weight, int packageSeqId) throws GeneralException {
// process the result; add new item if necessary
switch (checkCode) {
case 0:
// not enough reserved
throw new GeneralException("Not enough inventory reservation available; cannot pack the item [" + orderItemSeqId + "], " + quantity + " x product [" + productId + "]");
case 1:
// we're all good to go; quantity already updated
break;
case 2:
// need to create a new item
String invItemId = res.getString("inventoryItemId");
packLines.add(new OpentapsPackingSessionLine(orderId, orderItemSeqId, shipGroupSeqId, productId, invItemId, quantity, weight, packageSeqId));
break;
default:
throw new GeneralException("Unrecognized checkCode [" + checkCode + "]");
}
// Add the line weight to the package weight
if (weight.signum() > 0) {
this.addToPackageWeight(packageSeqId, weight);
}
// update the package sequence
if (packageSeqId > packageSeq) {
this.packageSeq = packageSeqId;
}
}
/**
* Gets the tracking code for the given package.
* @param packageSeqId a package ID
* @return the tracking code for the given package, or <code>null</code> if not found
*/
public String getPackageTrackingCode(String packageSeqId) {
if (this.packageTrackingCodes == null) {
return null;
}
if (!this.packageTrackingCodes.containsKey(packageSeqId)) {
return null;
}
return this.packageTrackingCodes.get(packageSeqId);
}
/**
* Sets the tracking code for the given package.
* @param packageSeqId a package ID
* @param packageTrackingCode the tracking code to set
*/
public void setPackageTrackingCode(String packageSeqId, String packageTrackingCode) {
if (UtilValidate.isEmpty(packageTrackingCode)) {
packageTrackingCodes.remove(new Integer(packageSeqId));
} else {
packageTrackingCodes.put(packageSeqId, packageTrackingCode);
}
}
/**
* Gets the box type ID for the given package.
* @param packageSeqId a package ID
* @return the box type ID for the given package, <code>null</code> if not found
*/
public String getPackageBoxTypeId(String packageSeqId) {
if (this.packageBoxTypeIds != null) {
if (this.packageBoxTypeIds.containsKey(packageSeqId)) {
return this.packageBoxTypeIds.get(packageSeqId);
}
}
return null;
}
/**
* Gets the box type ID for the given package, if not set gets the default box type ID.
* @param packageSeqId a package ID
* @return the box type ID for the given package, or the default if not found
*/
public String getPackageBoxTypeOrDefaultId(String packageSeqId) {
String boxTypeId = getPackageBoxTypeId(packageSeqId);
// if no box is set, try the default one
if (UtilValidate.isEmpty(boxTypeId)) {
try {
CarrierShipmentBoxType defaultBoxType = getDefaultShipmentBoxType(Integer.parseInt(packageSeqId));
if (defaultBoxType != null) {
boxTypeId = defaultBoxType.getShipmentBoxTypeId();
}
} catch (Exception e) {
Debug.logError("Could not get the default box for package [" + packageSeqId + "] : " + e, MODULE);
}
}
return boxTypeId;
}
/**
* Sets the box type ID for the given package.
* @param packageSeqId a package ID
* @param packageBoxTypeId the box type ID to set
*/
public void setPackageBoxTypeId(String packageSeqId, String packageBoxTypeId) {
if (UtilValidate.isEmpty(packageBoxTypeId)) {
packageBoxTypeIds.remove(new Integer(packageSeqId));
} else {
packageBoxTypeIds.put(packageSeqId, packageBoxTypeId);
}
}
@Override public void clear() {
super.clear();
if (this.packageTrackingCodes != null) {
this.packageTrackingCodes.clear();
}
if (this.packageBoxTypeIds != null) {
this.packageBoxTypeIds.clear();
}
this.additionalShippingChargeDescription = null;
}
@Override public String complete(boolean force) throws GeneralException {
String shipmentId = super.complete(force);
updateShipmentPackageRouteSegments();
updateShipmentPackages();
return shipmentId;
}
@SuppressWarnings("unchecked")
@Override public BigDecimal getCurrentReservedQuantity(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId) {
BigDecimal reserved = BigDecimal.ZERO;
try {
List<GenericValue> reservations = getDelegator().findByAnd("OrderItemShipGrpInvResAndItem", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId, "facilityId", facilityId, "productId", productId));
for (GenericValue res : reservations) {
BigDecimal not = res.getBigDecimal("quantityNotAvailable");
BigDecimal qty = res.getBigDecimal("quantity");
if (not == null) {
not = BigDecimal.ZERO;
}
if (qty == null) {
qty = BigDecimal.ZERO;
}
reserved = reserved.add(qty).subtract(not);
}
} catch (GenericEntityException e) {
Debug.logError(e, MODULE);
}
return reserved;
}
@Override protected void createShipment() throws GeneralException {
super.createShipment();
GenericValue shipment = getDelegator().findByPrimaryKey("Shipment", UtilMisc.toMap("shipmentId", this.getShipmentId()));
if (UtilValidate.isNotEmpty(shipment) && UtilValidate.isNotEmpty(this.getAdditionalShippingChargeDescription())) {
shipment.set("addtlShippingChargeDesc", this.getAdditionalShippingChargeDescription());
shipment.store();
}
}
@SuppressWarnings("unchecked")
protected void updateShipmentPackageRouteSegments() throws GeneralException {
List<GenericValue> shipmentPackageRouteSegments = getDelegator().findByAnd("ShipmentPackageRouteSeg", UtilMisc.toMap("shipmentId", this.getShipmentId()));
if (UtilValidate.isNotEmpty(shipmentPackageRouteSegments)) {
Iterator<GenericValue> sprit = shipmentPackageRouteSegments.iterator();
while (sprit.hasNext()) {
GenericValue shipmentPackageRouteSegment = sprit.next();
if (UtilValidate.isEmpty(shipmentPackageRouteSegment.get("shipmentPackageSeqId"))) {
continue;
}
// Make the string into an Integer to remove leading zeros
Integer shipmentPackageSeqId = Integer.valueOf(shipmentPackageRouteSegment.getString("shipmentPackageSeqId"));
String trackingCode = getPackageTrackingCode(shipmentPackageSeqId.toString());
shipmentPackageRouteSegment.set("trackingCode", trackingCode);
}
getDelegator().storeAll(shipmentPackageRouteSegments);
}
}
@SuppressWarnings("unchecked")
protected void updateShipmentPackages() throws GeneralException {
List<GenericValue> shipmentPackages = getDelegator().findByAnd("ShipmentPackage", UtilMisc.toMap("shipmentId", this.getShipmentId()));
if (UtilValidate.isNotEmpty(shipmentPackages)) {
Iterator<GenericValue> spit = shipmentPackages.iterator();
while (spit.hasNext()) {
GenericValue shipmentPackage = spit.next();
// Make the string into an Integer to remove leading zeros
Integer shipmentPackageSeqId = Integer.valueOf(shipmentPackage.getString("shipmentPackageSeqId"));
String boxTypeId = getPackageBoxTypeId(shipmentPackageSeqId.toString());
shipmentPackage.set("shipmentBoxTypeId", boxTypeId);
}
getDelegator().storeAll(shipmentPackages);
}
}
@SuppressWarnings("unchecked")
public List<PackingSessionLine> getLinesByPackage(int packageSeqId) {
List<PackingSessionLine> lines = new ArrayList<PackingSessionLine>();
Iterator<PackingSessionLine> lit = this.getLines().iterator();
while (lit.hasNext()) {
PackingSessionLine line = lit.next();
if (line.getPackageSeq() == packageSeqId) {
lines.add(line);
}
}
return lines;
}
@SuppressWarnings("unchecked")
public List getShippableItemInfo(int packageSeqId) {
List shippableItemInfo = new ArrayList();
List<PackingSessionLine> lines;
BigDecimal packageWeight = null;
if (packageSeqId == -1) {
lines = getLines();
packageWeight = getTotalWeight();
} else {
lines = getLinesByPackage(packageSeqId);
packageWeight = getPackageWeight(packageSeqId);
}
if (UtilValidate.isEmpty(packageWeight)) {
packageWeight = BigDecimal.ZERO;
}
Iterator<PackingSessionLine> lit = lines.iterator();
while (lit.hasNext()) {
PackingSessionLine line = lit.next();
Map shipInfo = new HashMap();
shipInfo.put("productId", line.getProductId());
shipInfo.put("weight", new Double(packageWeight.doubleValue() / lines.size()));
shipInfo.put("quantity", new Double(line.getQuantity().doubleValue()));
shipInfo.put("piecesIncluded", new Long(1));
shippableItemInfo.add(shipInfo);
}
return shippableItemInfo;
}
@SuppressWarnings("unchecked")
@Override public void addOrIncreaseLine(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, BigDecimal quantity, int packageSeqId, BigDecimal weight, boolean update) throws GeneralException {
// reset the session if we just completed
if (status == 0) {
throw new GeneralException("Packing session has been completed; be sure to CLEAR before packing a new order! [000]");
}
// do nothing if we are trying to add a quantity of 0
if (!update && quantity.signum() == 0) {
return;
}
// find the actual product ID
productId = ProductWorker.findProductId(this.getDelegator(), productId);
// set the default null values - primary is the assumed first item
if (orderId == null) {
orderId = primaryOrderId;
}
if (shipGroupSeqId == null) {
shipGroupSeqId = primaryShipGrp;
}
if (orderItemSeqId == null && productId != null) {
orderItemSeqId = this.findOrderItemSeqId(productId, orderId, shipGroupSeqId, quantity);
}
// get the reservations for the item
Map invLookup = FastMap.newInstance();
invLookup.put("orderId", orderId);
invLookup.put("orderItemSeqId", orderItemSeqId);
invLookup.put("shipGroupSeqId", shipGroupSeqId);
if (UtilValidate.isNotEmpty(facilityId)) {
invLookup.put("facilityId", facilityId);
}
List<GenericValue> reservations = this.getDelegator().findByAnd("OrderItemShipGrpInvResAndItem", invLookup, UtilMisc.toList("quantity DESC"));
// no reservations we cannot add this item
if (UtilValidate.isEmpty(reservations)) {
throw new GeneralException("No inventory reservations available; cannot pack this item! [101]");
}
// find the inventoryItemId to use
if (reservations.size() == 1) {
GenericValue res = EntityUtil.getFirst(reservations);
int checkCode = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, packageSeqId, update);
this.createPackLineItem(checkCode, res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, weight, packageSeqId);
} else {
// more than one reservation found
Map<GenericValue, BigDecimal> toCreateMap = FastMap.newInstance();
Iterator<GenericValue> i = reservations.iterator();
BigDecimal qtyRemain = quantity;
// we need to prioritize the reservations that have quantity available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() > 0) {
Debug.logInfo("Skipping reservations with quantityNotAvailable on the first pass.", MODULE);
continue;
}
- BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, res.getString("inventoryItemId"), -1);
+ BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
// second pass considering reservations with quantity not available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() != 0) {
Debug.logInfo("Skipping reservations without quantityNotAvailable on the second pass.", MODULE);
continue;
}
- BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, res.getString("inventoryItemId"), -1);
+ BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
if (qtyRemain.signum() == 0) {
Iterator x = toCreateMap.keySet().iterator();
while (x.hasNext()) {
GenericValue res = (GenericValue) x.next();
BigDecimal qty = toCreateMap.get(res);
this.createPackLineItem(2, res, orderId, orderItemSeqId, shipGroupSeqId, productId, qty, weight, packageSeqId);
}
} else {
throw new GeneralException("Not enough inventory reservation available; cannot pack the item! [103]");
}
}
// run the add events
this.runEvents(PackingEvent.EVENT_CODE_ADD);
}
@SuppressWarnings("unchecked")
public BigDecimal getShipmentCostEstimate(String shippingContactMechId, String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId, String productStoreId) {
BigDecimal shipmentCostEstimate = BigDecimal.ZERO;
List packageSeqIds = getPackageSeqIds();
Iterator psiit = packageSeqIds.iterator();
while (psiit.hasNext()) {
int packageSeqId = ((Integer) psiit.next()).intValue();
BigDecimal packageEstimate = getShipmentCostEstimate(shippingContactMechId, shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId, productStoreId, packageSeqId);
if (UtilValidate.isNotEmpty(packageEstimate)) {
shipmentCostEstimate = shipmentCostEstimate.add(packageEstimate);
}
}
return shipmentCostEstimate;
}
@SuppressWarnings("unchecked")
public BigDecimal getShipmentCostEstimate(String shippingContactMechId, String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId,
String productStoreId, int packageSeqId) {
BigDecimal packageWeight = getPackageWeight(packageSeqId);
if (UtilValidate.isEmpty(packageWeight)) {
packageWeight = BigDecimal.ZERO;
}
Map shipEstimate = ShippingEvents.getShipGroupEstimate(this.getDispatcher(), this.getDelegator(), null, shipmentMethodTypeId, carrierPartyId,
carrierRoleTypeId, shippingContactMechId, productStoreId, getShippableItemInfo(packageSeqId),
packageWeight, getPackedQuantity(packageSeqId), BigDecimal.ZERO, /* party */ null, /* productStoreShipMethId */ null);
return (BigDecimal) shipEstimate.get("shippingTotal");
}
@SuppressWarnings("unchecked")
public BigDecimal getShipmentCostEstimate(GenericValue orderItemShipGroup, String productStoreId, BigDecimal shippableTotal, BigDecimal shippableWeight, BigDecimal shippableQuantity) {
String shippingContactMechId = orderItemShipGroup.getString("contactMechId");
String shipmentMethodTypeId = orderItemShipGroup.getString("shipmentMethodTypeId");
String carrierPartyId = orderItemShipGroup.getString("carrierPartyId");
String carrierRoleTypeId = orderItemShipGroup.getString("carrierRoleTypeId");
List shippableItemInfo = getShippableItemInfo(-1);
if (UtilValidate.isEmpty(shippableWeight)) {
shippableWeight = getTotalWeight();
}
if (UtilValidate.isEmpty(shippableQuantity)) {
shippableQuantity = getPackedQuantity(-1);
}
if (UtilValidate.isEmpty(shippableTotal)) {
shippableTotal = BigDecimal.ZERO;
}
Map shipEstimate = ShippingEvents.getShipGroupEstimate(this.getDispatcher(), this.getDelegator(), null, shipmentMethodTypeId, carrierPartyId,
carrierRoleTypeId, shippingContactMechId, productStoreId, shippableItemInfo,
shippableWeight, shippableQuantity, BigDecimal.ZERO, /* party */ null, /* productStoreShipMethId */ null);
return (BigDecimal) shipEstimate.get("shippingTotal");
}
@SuppressWarnings("unchecked")
public BigDecimal getRawPackageValue(GenericDelegator delegator, int packageSeqId) throws GenericEntityException {
List<PackingSessionLine> lines = getLinesByPackage(packageSeqId);
BigDecimal value = OpentapsPackingSessionLine.ZERO;
for (Iterator<PackingSessionLine> iter = lines.iterator(); iter.hasNext();) {
OpentapsPackingSessionLine line = (OpentapsPackingSessionLine) iter.next();
value = value.add(line.getRawValue(delegator));
}
return value;
}
public String getAdditionalShippingChargeDescription() {
return additionalShippingChargeDescription;
}
public void setAdditionalShippingChargeDescription(String additionalShippingChargeDescription) {
this.additionalShippingChargeDescription = additionalShippingChargeDescription;
}
@SuppressWarnings("unchecked")
public Map<String, BigDecimal> getProductQuantities() {
Map<String, BigDecimal> productIds = new HashMap<String, BigDecimal>();
Iterator<PackingSessionLine> lit = getLines().iterator();
while (lit.hasNext()) {
PackingSessionLine line = lit.next();
BigDecimal quantity = productIds.containsKey(line.getProductId()) ? productIds.get(line.getProductId()) : BigDecimal.ZERO;
productIds.put(line.getProductId(), quantity.add(line.getQuantity()));
}
return productIds;
}
public CarrierShipmentBoxType getDefaultShipmentBoxType(int packageSeqId) throws InfrastructureException, RepositoryException, EntityNotFoundException {
List<PackingSessionLine> lines = getLinesByPackage(packageSeqId);
List<OrderItem> items = new ArrayList<OrderItem>();
OrderRepositoryInterface orderRepository = getOrderRepository();
// find the list of order items to this package
for (PackingSessionLine line : lines) {
String orderId = line.getOrderId();
String orderItemSeqId = line.getOrderItemSeqId();
try {
Order order = orderRepository.getOrderById(orderId);
items.add(orderRepository.getOrderItem(order, orderItemSeqId));
} catch (FoundationException e) {
Debug.logError("Could not find order item [" + orderId + " / " + orderItemSeqId + "]", MODULE);
}
}
ShippingRepositoryInterface shippingRepository = getShippingRepository();
// find the default box for this package
return shippingRepository.getDefaultBoxType(items);
}
private OrderRepositoryInterface getOrderRepository() throws InfrastructureException, RepositoryException {
DomainsLoader domainsLoader = new DomainsLoader(new Infrastructure(getDispatcher()), new User(userLogin));
return domainsLoader.loadDomainsDirectory().getOrderDomain().getOrderRepository();
}
private ShippingRepositoryInterface getShippingRepository() throws InfrastructureException, RepositoryException {
DomainsLoader domainsLoader = new DomainsLoader(new Infrastructure(getDispatcher()), new User(userLogin));
return domainsLoader.loadDomainsDirectory().getShippingDomain().getShippingRepository();
}
}
| false | true | @Override public void addOrIncreaseLine(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, BigDecimal quantity, int packageSeqId, BigDecimal weight, boolean update) throws GeneralException {
// reset the session if we just completed
if (status == 0) {
throw new GeneralException("Packing session has been completed; be sure to CLEAR before packing a new order! [000]");
}
// do nothing if we are trying to add a quantity of 0
if (!update && quantity.signum() == 0) {
return;
}
// find the actual product ID
productId = ProductWorker.findProductId(this.getDelegator(), productId);
// set the default null values - primary is the assumed first item
if (orderId == null) {
orderId = primaryOrderId;
}
if (shipGroupSeqId == null) {
shipGroupSeqId = primaryShipGrp;
}
if (orderItemSeqId == null && productId != null) {
orderItemSeqId = this.findOrderItemSeqId(productId, orderId, shipGroupSeqId, quantity);
}
// get the reservations for the item
Map invLookup = FastMap.newInstance();
invLookup.put("orderId", orderId);
invLookup.put("orderItemSeqId", orderItemSeqId);
invLookup.put("shipGroupSeqId", shipGroupSeqId);
if (UtilValidate.isNotEmpty(facilityId)) {
invLookup.put("facilityId", facilityId);
}
List<GenericValue> reservations = this.getDelegator().findByAnd("OrderItemShipGrpInvResAndItem", invLookup, UtilMisc.toList("quantity DESC"));
// no reservations we cannot add this item
if (UtilValidate.isEmpty(reservations)) {
throw new GeneralException("No inventory reservations available; cannot pack this item! [101]");
}
// find the inventoryItemId to use
if (reservations.size() == 1) {
GenericValue res = EntityUtil.getFirst(reservations);
int checkCode = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, packageSeqId, update);
this.createPackLineItem(checkCode, res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, weight, packageSeqId);
} else {
// more than one reservation found
Map<GenericValue, BigDecimal> toCreateMap = FastMap.newInstance();
Iterator<GenericValue> i = reservations.iterator();
BigDecimal qtyRemain = quantity;
// we need to prioritize the reservations that have quantity available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() > 0) {
Debug.logInfo("Skipping reservations with quantityNotAvailable on the first pass.", MODULE);
continue;
}
BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
// second pass considering reservations with quantity not available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() != 0) {
Debug.logInfo("Skipping reservations without quantityNotAvailable on the second pass.", MODULE);
continue;
}
BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
if (qtyRemain.signum() == 0) {
Iterator x = toCreateMap.keySet().iterator();
while (x.hasNext()) {
GenericValue res = (GenericValue) x.next();
BigDecimal qty = toCreateMap.get(res);
this.createPackLineItem(2, res, orderId, orderItemSeqId, shipGroupSeqId, productId, qty, weight, packageSeqId);
}
} else {
throw new GeneralException("Not enough inventory reservation available; cannot pack the item! [103]");
}
}
// run the add events
this.runEvents(PackingEvent.EVENT_CODE_ADD);
}
| @Override public void addOrIncreaseLine(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, BigDecimal quantity, int packageSeqId, BigDecimal weight, boolean update) throws GeneralException {
// reset the session if we just completed
if (status == 0) {
throw new GeneralException("Packing session has been completed; be sure to CLEAR before packing a new order! [000]");
}
// do nothing if we are trying to add a quantity of 0
if (!update && quantity.signum() == 0) {
return;
}
// find the actual product ID
productId = ProductWorker.findProductId(this.getDelegator(), productId);
// set the default null values - primary is the assumed first item
if (orderId == null) {
orderId = primaryOrderId;
}
if (shipGroupSeqId == null) {
shipGroupSeqId = primaryShipGrp;
}
if (orderItemSeqId == null && productId != null) {
orderItemSeqId = this.findOrderItemSeqId(productId, orderId, shipGroupSeqId, quantity);
}
// get the reservations for the item
Map invLookup = FastMap.newInstance();
invLookup.put("orderId", orderId);
invLookup.put("orderItemSeqId", orderItemSeqId);
invLookup.put("shipGroupSeqId", shipGroupSeqId);
if (UtilValidate.isNotEmpty(facilityId)) {
invLookup.put("facilityId", facilityId);
}
List<GenericValue> reservations = this.getDelegator().findByAnd("OrderItemShipGrpInvResAndItem", invLookup, UtilMisc.toList("quantity DESC"));
// no reservations we cannot add this item
if (UtilValidate.isEmpty(reservations)) {
throw new GeneralException("No inventory reservations available; cannot pack this item! [101]");
}
// find the inventoryItemId to use
if (reservations.size() == 1) {
GenericValue res = EntityUtil.getFirst(reservations);
int checkCode = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, packageSeqId, update);
this.createPackLineItem(checkCode, res, orderId, orderItemSeqId, shipGroupSeqId, productId, quantity, weight, packageSeqId);
} else {
// more than one reservation found
Map<GenericValue, BigDecimal> toCreateMap = FastMap.newInstance();
Iterator<GenericValue> i = reservations.iterator();
BigDecimal qtyRemain = quantity;
// we need to prioritize the reservations that have quantity available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() > 0) {
Debug.logInfo("Skipping reservations with quantityNotAvailable on the first pass.", MODULE);
continue;
}
BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
// second pass considering reservations with quantity not available
while (i.hasNext() && qtyRemain.signum() > 0) {
GenericValue res = i.next();
BigDecimal resQty = res.getBigDecimal("quantity");
BigDecimal resQtyNa = res.getBigDecimal("quantityNotAvailable");
if (resQtyNa == null) {
resQtyNa = BigDecimal.ZERO;
}
if (resQtyNa.signum() != 0) {
Debug.logInfo("Skipping reservations without quantityNotAvailable on the second pass.", MODULE);
continue;
}
BigDecimal resPackedQty = this.getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, res.getString("inventoryItemId"), -1);
if (resPackedQty.compareTo(resQty) >= 0) {
continue;
} else if (!update) {
resQty = resQty.subtract(resPackedQty);
}
BigDecimal thisQty = (resQty.compareTo(qtyRemain) > 0) ? qtyRemain : resQty;
int thisCheck = this.checkLineForAdd(res, orderId, orderItemSeqId, shipGroupSeqId, productId, thisQty, packageSeqId, update);
switch (thisCheck) {
case 2:
Debug.log("Packing check returned '2' - new pack line will be created!", MODULE);
toCreateMap.put(res, thisQty);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 1:
Debug.log("Packing check returned '1' - existing pack line has been updated!", MODULE);
qtyRemain = qtyRemain.subtract(thisQty);
break;
case 0:
Debug.log("Packing check returned '0' - doing nothing.", MODULE);
break;
default:
throw new GeneralException("Unrecognized checkCode [" + thisCheck + "]");
}
}
if (qtyRemain.signum() == 0) {
Iterator x = toCreateMap.keySet().iterator();
while (x.hasNext()) {
GenericValue res = (GenericValue) x.next();
BigDecimal qty = toCreateMap.get(res);
this.createPackLineItem(2, res, orderId, orderItemSeqId, shipGroupSeqId, productId, qty, weight, packageSeqId);
}
} else {
throw new GeneralException("Not enough inventory reservation available; cannot pack the item! [103]");
}
}
// run the add events
this.runEvents(PackingEvent.EVENT_CODE_ADD);
}
|
diff --git a/src/netmash/forest/ObjectMash.java b/src/netmash/forest/ObjectMash.java
index 8202917..c786904 100644
--- a/src/netmash/forest/ObjectMash.java
+++ b/src/netmash/forest/ObjectMash.java
@@ -1,510 +1,508 @@
package netmash.forest;
import java.util.*;
import java.util.regex.*;
import java.text.*;
import netmash.platform.Kernel;
import netmash.lib.JSON;
import static netmash.lib.Utils.*;
/** Object Mash Language.
*/
public class ObjectMash extends WebObject {
private boolean extralogging = false;
public ObjectMash(){ extralogging = Kernel.config.boolPathN("rules:log"); }
public ObjectMash(String s){ super(s); extralogging = Kernel.config.boolPathN("rules:log"); }
public ObjectMash(LinkedHashMap hm){ super(hm); extralogging = Kernel.config.boolPathN("rules:log"); }
public ObjectMash(JSON json){ super(json); extralogging = Kernel.config.boolPathN("rules:log"); }
public void evaluate(){
LinkedList<String> evalrules=getEvalRules();
if(!evalrules.isEmpty()) contentSetPushAll("Rules",evalrules);
if(extralogging) log("Running ObjectMash on "+uid+": "+contentHash("#"));
LinkedList rules=contentAsList("Rules");
if(extralogging) log("Rules: "+rules);
if(rules==null) return;
int r=0;
for(Object o: rules){
LinkedList ruleis=contentList(String.format("Rules:%d:is", r));
if(extralogging) log("Rule "+r+" is="+ruleis);
if(ruleis==null) return;
boolean ok=true;
for(Object is: ruleis){
if("rule".equals(is)) continue;
if("editable".equals(is)) continue;
if(!contentIsOrListContains("is", is.toString())){ ok=false; if(extralogging) log("Rule doesn't apply: "+is+" "+contentString("is")); break; }
}
if(ok) runRule(r);
r++;
}
if(!evalrules.isEmpty()) contentSetPushAll("Rules",evalrules);
}
private LinkedList<String> getEvalRules(){
LinkedList<String> evalrules=new LinkedList<String>();
for(String alerted: alerted()){
contentTemp("Temp", alerted);
if(contentListContainsAll("Temp:is",list("editable","rule"))) evalrules.add(alerted);
contentTemp("Temp", null);
}
return evalrules;
}
private void runRule(int r){
if(extralogging) log("Run rule #"+r+". alerted="+alerted);
if(alerted().size()==0) runRule(r,null);
else for(String alerted: alerted()) runRule(r,alerted);
}
LinkedHashMap<String,LinkedList> rewrites=new LinkedHashMap<String,LinkedList>();
LinkedHashMap<String,LinkedList<String>> bindings=new LinkedHashMap<String,LinkedList<String>>();
@SuppressWarnings("unchecked")
private void runRule(int r, String alerted){
String name=contentStringOr(String.format("Rules:%d:when", r),"");
if(alerted!=null && !contentSet("Alerted")) contentTemp("Alerted",alerted);
; if(extralogging) log("Running rule \""+name+"\"");
; if(extralogging) log("alerted:\n"+contentHash("Alerted:#"));
rewrites.clear(); bindings.clear();
LinkedHashMap<String,Object> rule=contentHash(String.format("Rules:%d:#", r));
boolean ok=scanHash(rule, "");
if(ok) doRewrites();
; if(ok) log("Rule fired: \""+name+"\"");
; if(extralogging) log("==========\nscanRuleHash="+(ok?"pass":"fail")+"\n"+rule+"\n"+contentHash("#")+"\n===========");
if(alerted!=null && contentIs("Alerted",alerted)) contentTemp("Alerted",null);
}
// ----------------------------------------------------
@SuppressWarnings("unchecked")
private boolean scanHash(LinkedHashMap<String,Object> hash, String path){
LinkedHashMap hm=contentHashMayJump(path);
if(hm==null){ if(contentListMayJump(path)==null) return false; return scanList(list(hash), path, null); }
if(hash.isEmpty()) return true;
for(Map.Entry<String,Object> entry: hash.entrySet()){
String pk=(path.equals("")? "": path+":")+entry.getKey();
if(path.equals("")){
if(pk.equals("Rules")) continue;
if(pk.equals("is")) continue;
if(pk.equals("when")) continue;
if(pk.equals("watching")) continue;
if(pk.equals("editable")) continue;
if(pk.equals("user")) continue;
}
Object v=entry.getValue();
if(!scanType(v,pk)) return false;
}
return true;
}
@SuppressWarnings("unchecked")
private boolean scanList(LinkedList list, String path, LinkedList rhs){
if(list.size()==0) return true;
if(list.size()==2 && list.get(0).equals("<")){
double d=findDouble(list.get(1));
return (contentDouble(path) < d);
}
if(list.size()==2 && list.get(0).equals(">")){
double d=findDouble(list.get(1));
return (contentDouble(path) > d);
}
if(list.size()==2 && list.get(0).equals("divisible-by")){
int i=(int)findDouble(list.get(1));
int j=(int)contentDouble(path);
return ((j % i)==0);
}
if(list.size()==2 && list.get(0).equals("list-count")){
double d=findDouble(list.get(1));
LinkedList ll=contentList(path);
return (ll!=null && ll.size()==(int)d);
}
int becomes=list.indexOf("=>");
if(becomes!= -1){
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
if(becomes==0){ rewrites.put(path,rh2); return true; }
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,rh2);
if(ok && becomes>1) rewrites.put(path,rh2);
return ok;
}
becomes=list.indexOf("!=>");
if(becomes!= -1){
if(becomes==0) return false;
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,null);
if(!ok) rewrites.put(path,rh2);
return !ok;
}
LinkedList ll=contentListMayJump(path);
boolean matchEach=list.size()!=1;
if(ll==null){
if(matchEach) return false;
boolean ok=scanType(list.get(0),path);
if(ok && rhs!=null) rewrites.put(path,rhs);
return ok;
}
LinkedList<String> bl=new LinkedList<String>();
int i=0;
for(Object v: list){
+ boolean ok=false;
for(; i<ll.size(); i++){
String pk=String.format("%s:%d",path,i);
- if(scanTypeMayFail(v,pk)){ bl.add(pk); if(matchEach) break; if(rhs!=null) rewrites.put(pk,rhs); }
+ if(scanTypeMayFail(v,pk)){ ok=true; bl.add(pk); if(matchEach) break; if(rhs!=null) rewrites.put(pk,rhs); }
}
- if(matchEach){
- if(i==ll.size()) return false;
- i++;
- }
- else if(bl.size()==0) return false;
+ if(!ok) return false;
+ if(matchEach) i++;
}
bindings.put(path,bl);
return true;
}
private boolean scanType(Object v, String pk){ return scanType(v,pk,false); }
private boolean scanTypeMayFail(Object v, String pk){ return scanType(v,pk,true); }
private boolean scanType(Object v, String pk, boolean mayfail){
boolean r=doScanType(v,pk);
if(!r && extralogging && !mayfail) log("Failed to match "+v+" at: "+pk+" "+contentObject(pk));
return r;
}
@SuppressWarnings("unchecked")
private boolean doScanType(Object v, String pk){
if(v instanceof String) return scanString((String)v, pk);
if(v instanceof Number) return scanNumber((Number)v, pk);
if(v instanceof Boolean) return scanBoolean((Boolean)v, pk);
if(v instanceof LinkedHashMap) return scanHash((LinkedHashMap<String,Object>)v, pk);
if(v instanceof LinkedList) return scanList((LinkedList)v, pk, null);
log("oh noes "+v+" "+pk);
return false;
}
private boolean scanString(String v, String pk){
if(contentList(pk)!=null) return scanListFromSingleIfNotAlready(v,pk);
if(contentIs(pk,v)) return true;
if(v.equals("*")) return contentSet(pk);
if(v.equals("#")) return !contentSet(pk);
if(v.equals("@")) return contentIsThis(pk);
if(v.equals("number")) return isNumber( contentObject(pk));
if(v.equals("boolean")) return isBoolean(contentObject(pk));
if(v.startsWith("/") && v.endsWith("/")) return regexMatch(v.substring(1,v.length()-1),pk);
if(foundObjectSameOrNot(pk,v)) return true;
return false;
}
private boolean scanNumber(Number v, String pk){
if(contentList(pk)!=null) return scanListFromSingleIfNotAlready(v,pk);
if(contentDouble(pk)==v.doubleValue()) return true;
return false;
}
private boolean scanBoolean(Boolean v, String pk){
if(contentList(pk)!=null) return scanListFromSingleIfNotAlready(v,pk);
if(contentBool(pk)==v) return true;
return false;
}
private boolean scanListFromSingleIfNotAlready(Object v, String pk){
String[] parts=pk.split(":");
if(isNumber(parts[parts.length-1])) return false;
return scanList(list(v),pk,null);
}
private boolean regexMatch(String regex, String pk){
String s=content(pk);
if(s==null) return false;
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(s);
return m.find();
}
private boolean foundObjectSameOrNot(String pk, String vs){
boolean var=vs.startsWith("@");
boolean nov=vs.startsWith("!@");
if(!var && !nov) return false;
Object pko=contentObject(pk);
Object vso;
if(var) vso=findObject(vs);
else vso=findObject(vs.substring(1));
if(vso==null) return false;
if(vso.equals(pko)) return var;
if(pko instanceof Number && vso instanceof Number){
return (((Number)pko).doubleValue()==((Number)vso).doubleValue())? var: nov;
}
return false;
}
// ----------------------------------------------------
String currentRewritePath=null;
@SuppressWarnings("unchecked")
private void doRewrites(){
LinkedHashMap<String,Boolean> shufflists=new LinkedHashMap<String,Boolean>();
for(Map.Entry<String,LinkedList> entry: rewrites.entrySet()){
currentRewritePath=entry.getKey();
LinkedList ll=entry.getValue();
if(ll.size()==0) continue;
if(ll.size() >=3 && ll.get(0).equals("@.") && ll.get(1).equals("with")){
LinkedList e=copyFindEach(ll.subList(2,ll.size()));
if(e==null || e.size()==0) continue;
if(currentRewritePath.equals("Notifying")) for(Object o: e) notifying(o.toString());
else contentSetAddAll(currentRewritePath, e);
}
else
if(ll.size() >=3 && ll.get(0).equals("@.") && ll.get(1).equals("without")){
LinkedList e=findEach(ll.subList(2,ll.size()));
if(e==null || e.size()==0) continue;
if(currentRewritePath.equals("Notifying")) for(Object o: e) unnotifying(o.toString());
else contentListRemoveAll(currentRewritePath, e);
}
else{
Object e=(ll.size()==1)? copyFindObject(ll.get(0)): eval(ll);
if(e==null){ log("failed to rewrite "+currentRewritePath); continue; }
if("#".equals(e)){
String[] parts=currentRewritePath.split(":");
if(parts.length==1 || !isNumber(parts[parts.length-1])) contentRemove(currentRewritePath);
else { String p=currentRewritePath.substring(0,currentRewritePath.lastIndexOf(":"));
if(contentList(p)==null) contentRemove(currentRewritePath);
else{ content(currentRewritePath,"#"); shufflists.put(p,true); }
}
}
else
if(currentRewritePath.equals("")){
if(!(e instanceof LinkedHashMap)){ log("failed to rewrite entire object: "+e); continue; }
contentReplace(new JSON((LinkedHashMap)e));
}
else contentObject(currentRewritePath, e);
}
}
for(String p: shufflists.keySet()){ LinkedList lr=new LinkedList(), ll=contentList(p); for(Object o: ll) if(!"#".equals(o)) lr.add(o); contentList(p,lr); }
}
private Object eval(LinkedList ll){ try{
if(ll.size()==0) return null;
// if(ll.size()==1) return copyFindObject(ll.get(0));
if(ll.size()==1) return ll;
String ll0=findString(ll.get(0));
String ll1=findString(ll.get(1));
if(ll.size()==2 && "count".equals(ll0)) return Double.valueOf(sizeOf(findList(ll.get(1))));
if(ll.size()==3 && "random".equals(ll0)) return Double.valueOf(random(findDouble(ll.get(1)), findDouble(ll.get(2))));
if(ll.size()==4 && "clamp".equals(ll0)) return Double.valueOf(clamp(findDouble(ll.get(1)), findDouble(ll.get(2)), findDouble(ll.get(3))));
if(ll.size()==2 && "integer".equals(ll0)) return Integer.valueOf((int)(0.5+findDouble(ll.get(1))));
if(ll.size()==3 && "format".equals(ll0)) return String.format(findString(ll.get(1)), findString(ll.get(2)));
if(ll.size()==4 && "format".equals(ll0)) return String.format(findString(ll.get(1)), findString(ll.get(2)), findString(ll.get(3)));
if(ll.size()==5 && "format".equals(ll0)) return String.format(findString(ll.get(1)), findString(ll.get(2)), findString(ll.get(3)), findString(ll.get(4)));
if(ll.size()==6 && "if".equals(ll0)) return findBoolean(ll.get(1))? copyFindObject(ll.get(3)): copyFindObject(ll.get(5));
if(ll.size()==2 && "as-is".equals(ll0)) return copyObject(ll.get(1), true);
if(ll.size()==3 && "join".equals(ll0)) return join(findList(ll.get(2)), findString(ll.get(1)));
if(ll.size()==2 && "+".equals(ll0)) return Double.valueOf(sumAll(findList(ll.get(1))));
if(ll.size()==3 && "-".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) - findDouble(ll.get(2)));
if(ll.size()==3 && "+".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) + findDouble(ll.get(2)));
if(ll.size()==3 && "×".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) * findDouble(ll.get(2)));
if(ll.size()==3 && "*".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) * findDouble(ll.get(2)));
if(ll.size()==3 && "÷".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) / findDouble(ll.get(2)));
if(ll.size()==3 && "/".equals(ll1)) return Double.valueOf(findDouble(ll.get(0)) / findDouble(ll.get(2)));
if(ll.size()==3 && ".".equals(ll1)) return vmdot(findList(ll.get(0)), findList(ll.get(2)));
if(ll.size()==3 && "++".equals(ll1)) return vvadd(findList(ll.get(0)), findList(ll.get(2)));
if(ll.size()==3 && "<".equals(ll1)) return Boolean.valueOf(findDouble(ll.get(0)) < findDouble(ll.get(2)));
if(ll.size()==3 && ">".equals(ll1)) return Boolean.valueOf(findDouble(ll.get(0)) > findDouble(ll.get(2)));
if(ll.size()==3 && "select".equals(ll1)) return copyFindObject(findHashOrListAndGet(ll.get(0),ll.get(2)));
return copyFindEach(ll);
}catch(Throwable t){ t.printStackTrace(); log("something failed here: "+ll); return ll; } }
@SuppressWarnings("unchecked")
private LinkedList copyFindEach(List ll){
LinkedList r=new LinkedList();
for(Object o: ll) r.add(copyFindObject(o));
return r;
}
@SuppressWarnings("unchecked")
private LinkedList findEach(List ll){
LinkedList r=new LinkedList();
for(Object o: ll) r.add(findObject(o));
return r;
}
// ----------------------------------------------------
private Object findObject(Object o){
if(o==null) return null;
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentObject(((String)o).substring(1));
if(o instanceof LinkedList) o=eval((LinkedList)o);
return o;
}
private String findString(Object o){
if(o==null) return "";
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentString(((String)o).substring(1));
if(o instanceof LinkedList){ o=eval((LinkedList)o); if(o==null) return null; }
if(o instanceof Number) return toNicerString((Number)o);
return o.toString();
}
private double findDouble(Object o){
if(o==null) return 0;
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentDouble(((String)o).substring(1));
if(o instanceof LinkedList) o=eval((LinkedList)o);
return findNumberIn(o);
}
private boolean findBoolean(Object o){
if(o==null) return false;
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentBool(((String)o).substring(1));
if(o instanceof LinkedList) o=eval((LinkedList)o);
return findBooleanIn(o);
}
private LinkedHashMap findHash(Object o){
if(o==null) return new LinkedHashMap();
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentHash(((String)o).substring(1));
if(o instanceof LinkedList) o=eval((LinkedList)o);
return findHashIn(o);
}
private LinkedList findList(Object o){
if(o==null) return new LinkedList();
if(o instanceof String && ((String)o).startsWith("@")) return eitherBindingOrContentList(((String)o).substring(1));
if(o instanceof LinkedList) o=eval((LinkedList)o);
return findListIn(o);
}
private Object findHashOrListAndGet(Object collection, Object index){
if(collection==null || index==null) return null;
LinkedHashMap hm=findHash(collection);
if(hm!=null && hm.size() >0) return hm.get(findObject(index));
LinkedList ll=findList(collection);
int i=(int)findDouble(index);
if(ll!=null && ll.size() >i) return ll.get(i);
return null;
}
// ----------------------------------------------------
private Object eitherBindingOrContentObject(String path){
if(path.startsWith(".")) return contentObject(currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return getBinding(path.substring(1));
Object o=contentObject(path);
if(o!=null) return o;
return contentAll(path);
}
private String eitherBindingOrContentString(String path){
if(path.startsWith(".")) return content( currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return findStringIn(getBinding(path.substring(1)));
return contentString(path);
}
private double eitherBindingOrContentDouble(String path){
if(path.startsWith(".")) return contentDouble( currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return findNumberIn(getBinding(path.substring(1)));
return contentDouble(path);
}
private boolean eitherBindingOrContentBool(String path){
if(path.startsWith(".")) return contentBool( currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return findBooleanIn(getBinding(path.substring(1)));
return contentBool(path);
}
private LinkedList eitherBindingOrContentList(String path){
if(path.startsWith(".")) return contentList( currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return findListIn(getBinding(path.substring(1)));
LinkedList ll=contentList(path);
if(ll!=null) return ll;
return contentAll(path);
}
private LinkedHashMap eitherBindingOrContentHash(String path){
if(path.startsWith(".")) return contentHash(currentRewritePath+(path.equals(".")? "": ":"+path.substring(1)));
if(path.startsWith("=")) return findHashIn(getBinding(path.substring(1)));
return contentHashMayJump(path);
}
// ----------------------------------------------------
@SuppressWarnings("unchecked")
private Object getBinding(String path){
String pk=path;
LinkedList<String> ll=bindings.get(pk);
if(ll!=null) return objectsAt(ll,null);
do{
int e=pk.lastIndexOf(":");
if(e== -1) return null;
String p=pk.substring(e+1);
pk=pk.substring(0,e);
ll=bindings.get(pk);
if(ll==null) continue;
int i= -1;
try{ i=Integer.parseInt(p); }catch(Throwable t){}
if(i>=0 && i<ll.size()) return contentObject(ll.get(i));
return objectsAt(ll,p);
}while(true);
}
@SuppressWarnings("unchecked")
private LinkedList objectsAt(LinkedList<String> ll, String p){
LinkedList r=new LinkedList();
for(String s: ll){
Object o=contentObject(s+(p==null? "": ":"+p));
if(o!=null) r.add(o);
}
return r.isEmpty()? null: r;
}
// ----------------------------------------------------
private Object copyFindObject(Object o){
return copyObject(findObject(o), false);
}
@SuppressWarnings("unchecked")
public Object copyObject(Object o, boolean asis){
if(o==null) return null;
if(o instanceof String) return ((String)o).equals("uid-new")? spawn(new ObjectMash("{ \"is\": [ \"editable\" ] }")): o;
if(o instanceof Number) return o;
if(o instanceof Boolean) return o;
if(o instanceof LinkedHashMap) return copyHash(((LinkedHashMap)o), asis);
if(o instanceof LinkedList) return copyList(((LinkedList)o), asis);
return o;
}
@SuppressWarnings("unchecked")
public Object copyHash(LinkedHashMap<String,Object> hm, boolean asis){
boolean spawned=false;
LinkedHashMap r=new LinkedHashMap();
for(Map.Entry<String,Object> entry: hm.entrySet()){
String k=entry.getKey();
Object o=entry.getValue();
if(k.equals("UID") && !asis){ if(o.equals("new")){ spawned=true; }}
else r.put(k, asis? copyObject(o,true): copyFindObject(o));
}
if(spawned) try{ return spawn(getClass().newInstance().construct(r)); } catch(Throwable t){ t.printStackTrace(); }
return r;
}
@SuppressWarnings("unchecked")
public LinkedList copyList(LinkedList ll, boolean asis){
LinkedList r=new LinkedList();
for(Object o: ll) r.add(asis? copyObject(o,true): copyFindObject(o));
return r;
}
// ----------------------------------------------------
}
| false | true | private boolean scanList(LinkedList list, String path, LinkedList rhs){
if(list.size()==0) return true;
if(list.size()==2 && list.get(0).equals("<")){
double d=findDouble(list.get(1));
return (contentDouble(path) < d);
}
if(list.size()==2 && list.get(0).equals(">")){
double d=findDouble(list.get(1));
return (contentDouble(path) > d);
}
if(list.size()==2 && list.get(0).equals("divisible-by")){
int i=(int)findDouble(list.get(1));
int j=(int)contentDouble(path);
return ((j % i)==0);
}
if(list.size()==2 && list.get(0).equals("list-count")){
double d=findDouble(list.get(1));
LinkedList ll=contentList(path);
return (ll!=null && ll.size()==(int)d);
}
int becomes=list.indexOf("=>");
if(becomes!= -1){
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
if(becomes==0){ rewrites.put(path,rh2); return true; }
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,rh2);
if(ok && becomes>1) rewrites.put(path,rh2);
return ok;
}
becomes=list.indexOf("!=>");
if(becomes!= -1){
if(becomes==0) return false;
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,null);
if(!ok) rewrites.put(path,rh2);
return !ok;
}
LinkedList ll=contentListMayJump(path);
boolean matchEach=list.size()!=1;
if(ll==null){
if(matchEach) return false;
boolean ok=scanType(list.get(0),path);
if(ok && rhs!=null) rewrites.put(path,rhs);
return ok;
}
LinkedList<String> bl=new LinkedList<String>();
int i=0;
for(Object v: list){
for(; i<ll.size(); i++){
String pk=String.format("%s:%d",path,i);
if(scanTypeMayFail(v,pk)){ bl.add(pk); if(matchEach) break; if(rhs!=null) rewrites.put(pk,rhs); }
}
if(matchEach){
if(i==ll.size()) return false;
i++;
}
else if(bl.size()==0) return false;
}
bindings.put(path,bl);
return true;
}
| private boolean scanList(LinkedList list, String path, LinkedList rhs){
if(list.size()==0) return true;
if(list.size()==2 && list.get(0).equals("<")){
double d=findDouble(list.get(1));
return (contentDouble(path) < d);
}
if(list.size()==2 && list.get(0).equals(">")){
double d=findDouble(list.get(1));
return (contentDouble(path) > d);
}
if(list.size()==2 && list.get(0).equals("divisible-by")){
int i=(int)findDouble(list.get(1));
int j=(int)contentDouble(path);
return ((j % i)==0);
}
if(list.size()==2 && list.get(0).equals("list-count")){
double d=findDouble(list.get(1));
LinkedList ll=contentList(path);
return (ll!=null && ll.size()==(int)d);
}
int becomes=list.indexOf("=>");
if(becomes!= -1){
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
if(becomes==0){ rewrites.put(path,rh2); return true; }
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,rh2);
if(ok && becomes>1) rewrites.put(path,rh2);
return ok;
}
becomes=list.indexOf("!=>");
if(becomes!= -1){
if(becomes==0) return false;
LinkedList rh2=new LinkedList(list.subList(becomes+1,list.size()));
LinkedList lhs=new LinkedList(list.subList(0,becomes));
boolean ok=scanList(lhs,path,null);
if(!ok) rewrites.put(path,rh2);
return !ok;
}
LinkedList ll=contentListMayJump(path);
boolean matchEach=list.size()!=1;
if(ll==null){
if(matchEach) return false;
boolean ok=scanType(list.get(0),path);
if(ok && rhs!=null) rewrites.put(path,rhs);
return ok;
}
LinkedList<String> bl=new LinkedList<String>();
int i=0;
for(Object v: list){
boolean ok=false;
for(; i<ll.size(); i++){
String pk=String.format("%s:%d",path,i);
if(scanTypeMayFail(v,pk)){ ok=true; bl.add(pk); if(matchEach) break; if(rhs!=null) rewrites.put(pk,rhs); }
}
if(!ok) return false;
if(matchEach) i++;
}
bindings.put(path,bl);
return true;
}
|
diff --git a/src/org/openstreetmap/josm/gui/io/UploadStrategySelectionPanel.java b/src/org/openstreetmap/josm/gui/io/UploadStrategySelectionPanel.java
index 9b5c8c83..937c1ac9 100644
--- a/src/org/openstreetmap/josm/gui/io/UploadStrategySelectionPanel.java
+++ b/src/org/openstreetmap/josm/gui/io/UploadStrategySelectionPanel.java
@@ -1,479 +1,480 @@
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui.io;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.openstreetmap.josm.tools.I18n.trn;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.gui.JMultilineLabel;
import org.openstreetmap.josm.io.OsmApi;
import org.openstreetmap.josm.tools.ImageProvider;
/**
* UploadStrategySelectionPanel is a panel for selecting an upload strategy.
*
* Clients can listen for property change events for the property
* {@see #UPLOAD_STRATEGY_SPECIFICATION_PROP}.
*/
public class UploadStrategySelectionPanel extends JPanel implements PropertyChangeListener {
/**
* The property for the upload strategy
*/
public final static String UPLOAD_STRATEGY_SPECIFICATION_PROP =
UploadStrategySelectionPanel.class.getName() + ".uploadStrategySpecification";
private static final Color BG_COLOR_ERROR = new Color(255,224,224);
private ButtonGroup bgStrategies;
private ButtonGroup bgMultiChangesetPolicies;
private Map<UploadStrategy, JRadioButton> rbStrategy;
private Map<UploadStrategy, JLabel> lblNumRequests;
private Map<UploadStrategy, JMultilineLabel> lblStrategies;
private JTextField tfChunkSize;
private JPanel pnlMultiChangesetPolicyPanel;
private JRadioButton rbFillOneChangeset;
private JRadioButton rbUseMultipleChangesets;
private JMultilineLabel lblMultiChangesetPoliciesHeader;
private long numUploadedObjects = 0;
public UploadStrategySelectionPanel() {
build();
}
protected JPanel buildUploadStrategyPanel() {
JPanel pnl = new JPanel();
pnl.setLayout(new GridBagLayout());
bgStrategies = new ButtonGroup();
rbStrategy = new HashMap<UploadStrategy, JRadioButton>();
lblStrategies = new HashMap<UploadStrategy, JMultilineLabel>();
lblNumRequests = new HashMap<UploadStrategy, JLabel>();
for (UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.put(strategy, new JRadioButton());
lblNumRequests.put(strategy, new JLabel());
lblStrategies.put(strategy, new JMultilineLabel(""));
bgStrategies.add(rbStrategy.get(strategy));
}
- // -- single request strategy
+ // -- headline
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 4;
+ gc.fill = GridBagConstraints.HORIZONTAL;
gc.insets = new Insets(0,0,3,0);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(new JMultilineLabel(tr("Please select the upload strategy:")), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(rbStrategy.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
JLabel lbl = lblStrategies.get(UploadStrategy.SINGLE_REQUEST_STRATEGY);
lbl.setText(tr("Upload data in one request"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 1;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
// -- chunked dataset strategy
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
lbl = lblStrategies.get(UploadStrategy.CHUNKED_DATASET_STRATEGY);
lbl.setText(tr("Upload data in chunks of objects. Chunk size: "));
pnl.add(lbl, gc);
gc.gridx = 2;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(tfChunkSize = new JTextField(4), gc);
gc.gridx = 3;
gc.gridy = 2;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
lbl = lblStrategies.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY);
lbl.setText(tr("Upload each object individually"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 3;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
tfChunkSize.addFocusListener(new TextFieldFocusHandler());
tfChunkSize.getDocument().addDocumentListener(new ChunkSizeInputVerifier());
StrategyChangeListener strategyChangeListener = new StrategyChangeListener();
tfChunkSize.addFocusListener(strategyChangeListener);
tfChunkSize.addActionListener(strategyChangeListener);
for(UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.get(strategy).addItemListener(strategyChangeListener);
}
return pnl;
}
protected JPanel buildMultiChangesetPolicyPanel() {
pnlMultiChangesetPolicyPanel = new JPanel();
pnlMultiChangesetPolicyPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.weightx = 1.0;
pnlMultiChangesetPolicyPanel.add(lblMultiChangesetPoliciesHeader = new JMultilineLabel(tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. What policy shall be used?</html>", numUploadedObjects)), gc);
gc.gridy = 1;
pnlMultiChangesetPolicyPanel.add(rbFillOneChangeset = new JRadioButton(tr("Fill up one changeset and return to the Upload Dialog")),gc);
gc.gridy = 2;
pnlMultiChangesetPolicyPanel.add(rbUseMultipleChangesets = new JRadioButton(tr("Open and use as many new changesets as necessary")),gc);
bgMultiChangesetPolicies = new ButtonGroup();
bgMultiChangesetPolicies.add(rbFillOneChangeset);
bgMultiChangesetPolicies.add(rbUseMultipleChangesets);
return pnlMultiChangesetPolicyPanel;
}
protected void build() {
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(3,3,3,3);
add(buildUploadStrategyPanel(), gc);
gc.gridy = 1;
add(buildMultiChangesetPolicyPanel(), gc);
// consume remaining space
gc.gridy = 2;
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gc.weighty = 1.0;
add(new JPanel(), gc);
int maxChunkSize = OsmApi.getOsmApi().getCapabilities().getMaxChangsetSize();
pnlMultiChangesetPolicyPanel.setVisible(
maxChunkSize > 0 && numUploadedObjects > maxChunkSize
);
}
public void setNumUploadedObjects(int numUploadedObjects) {
this.numUploadedObjects = Math.max(numUploadedObjects,0);
updateNumRequestsLabels();
}
public void setUploadStrategySpecification(UploadStrategySpecification strategy) {
if (strategy == null) return;
rbStrategy.get(strategy.getStrategy()).setSelected(true);
tfChunkSize.setEnabled(strategy.equals(UploadStrategy.CHUNKED_DATASET_STRATEGY));
if (strategy.getStrategy().equals(UploadStrategy.CHUNKED_DATASET_STRATEGY)) {
if (strategy.getChunkSize() != UploadStrategySpecification.UNSPECIFIED_CHUNK_SIZE) {
tfChunkSize.setText(Integer.toString(strategy.getChunkSize()));
} else {
tfChunkSize.setText("1");
}
}
}
public UploadStrategySpecification getUploadStrategySpecification() {
UploadStrategy strategy = getUploadStrategy();
int chunkSize = getChunkSize();
UploadStrategySpecification spec = new UploadStrategySpecification();
switch(strategy) {
case INDIVIDUAL_OBJECTS_STRATEGY:
spec.setStrategy(strategy);
break;
case SINGLE_REQUEST_STRATEGY:
spec.setStrategy(strategy);
break;
case CHUNKED_DATASET_STRATEGY:
spec.setStrategy(strategy).setChunkSize(chunkSize);
break;
}
if(pnlMultiChangesetPolicyPanel.isVisible()) {
if (rbFillOneChangeset.isSelected()) {
spec.setPolicy(MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG);
} else if (rbUseMultipleChangesets.isSelected()) {
spec.setPolicy(MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS);
} else {
spec.setPolicy(null); // unknown policy
}
} else {
spec.setPolicy(null);
}
return spec;
}
protected UploadStrategy getUploadStrategy() {
UploadStrategy strategy = null;
for (UploadStrategy s: rbStrategy.keySet()) {
if (rbStrategy.get(s).isSelected()) {
strategy = s;
break;
}
}
return strategy;
}
protected int getChunkSize() {
int chunkSize;
try {
chunkSize = Integer.parseInt(tfChunkSize.getText().trim());
return chunkSize;
} catch(NumberFormatException e) {
return UploadStrategySpecification.UNSPECIFIED_CHUNK_SIZE;
}
}
public void initFromPreferences() {
UploadStrategy strategy = UploadStrategy.getFromPreferences();
rbStrategy.get(strategy).setSelected(true);
int chunkSize = Main.pref.getInteger("osm-server.upload-strategy.chunk-size", 1);
tfChunkSize.setText(Integer.toString(chunkSize));
updateNumRequestsLabels();
}
public void rememberUserInput() {
UploadStrategy strategy = getUploadStrategy();
UploadStrategy.saveToPreferences(strategy);
int chunkSize;
try {
chunkSize = Integer.parseInt(tfChunkSize.getText().trim());
Main.pref.putInteger("osm-server.upload-strategy.chunk-size", chunkSize);
} catch(NumberFormatException e) {
// don't save invalid value to preferences
}
}
protected void updateNumRequestsLabels() {
int maxChunkSize = OsmApi.getOsmApi().getCapabilities().getMaxChangsetSize();
if (maxChunkSize > 0 && numUploadedObjects > maxChunkSize) {
rbStrategy.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setEnabled(false);
JLabel lbl = lblStrategies.get(UploadStrategy.SINGLE_REQUEST_STRATEGY);
lbl.setIcon(ImageProvider.get("warning-small.png"));
lbl.setText(tr("Upload in one request not possible (too many objects to upload)"));
lbl.setToolTipText(tr("<html>Can''t upload {0} objects in one request because the<br>"
+ "max. changeset size {1} on server ''{2}'' is exceeded.</html>",
numUploadedObjects,
maxChunkSize,
OsmApi.getOsmApi().getBaseUrl()
)
);
rbStrategy.get(UploadStrategy.CHUNKED_DATASET_STRATEGY).setSelected(true);
lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setVisible(false);
lblMultiChangesetPoliciesHeader.setText(tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. What policy shall be used?</html>", numUploadedObjects));
if (!rbFillOneChangeset.isSelected() && ! rbUseMultipleChangesets.isSelected()) {
rbUseMultipleChangesets.setSelected(true);
}
pnlMultiChangesetPolicyPanel.setVisible(true);
} else {
rbStrategy.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setEnabled(true);
JLabel lbl = lblStrategies.get(UploadStrategy.SINGLE_REQUEST_STRATEGY);
lbl.setText(tr("Upload data in one request"));
lbl.setIcon(null);
lbl.setToolTipText("");
lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setVisible(true);
pnlMultiChangesetPolicyPanel.setVisible(false);
}
lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setText(tr("(1 request)"));
if (numUploadedObjects == 0) {
lblNumRequests.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY).setText(tr("(# requests unknown)"));
lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY).setText(tr("(# requests unknown)"));
} else {
lblNumRequests.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY).setText(
trn("({0} request)", "({0} requests)", numUploadedObjects, numUploadedObjects)
);
lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY).setText(tr("(# requests unknown)"));
int chunkSize = getChunkSize();
if (chunkSize == UploadStrategySpecification.UNSPECIFIED_CHUNK_SIZE) {
lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY).setText(tr("(# requests unknown)"));
} else {
int chunks = (int)Math.ceil((double)numUploadedObjects / (double)chunkSize);
lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY).setText(
trn("({0} request)", "({0} requests)", chunks, chunks)
);
}
}
}
public void initEditingOfChunkSize() {
tfChunkSize.requestFocusInWindow();
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(UploadedObjectsSummaryPanel.NUM_OBJECTS_TO_UPLOAD_PROP)) {
setNumUploadedObjects((Integer)evt.getNewValue());
}
}
class TextFieldFocusHandler implements FocusListener {
public void focusGained(FocusEvent e) {
Component c = e.getComponent();
if (c instanceof JTextField) {
JTextField tf = (JTextField)c;
tf.selectAll();
}
}
public void focusLost(FocusEvent e) {}
}
class ChunkSizeInputVerifier implements DocumentListener, PropertyChangeListener {
protected void setErrorFeedback(JTextField tf, String message) {
tf.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
tf.setToolTipText(message);
tf.setBackground(BG_COLOR_ERROR);
}
protected void clearErrorFeedback(JTextField tf, String message) {
tf.setBorder(UIManager.getBorder("TextField.border"));
tf.setToolTipText(message);
tf.setBackground(UIManager.getColor("TextField.background"));
}
protected void valiateChunkSize() {
try {
int chunkSize = Integer.parseInt(tfChunkSize.getText().trim());
int maxChunkSize = OsmApi.getOsmApi().getCapabilities().getMaxChangsetSize();
if (chunkSize <= 0) {
setErrorFeedback(tfChunkSize, tr("Illegal chunk size <= 0. Please enter an integer > 1"));
} else if (maxChunkSize > 0 && chunkSize > maxChunkSize) {
setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl()));
} else {
clearErrorFeedback(tfChunkSize, tr("Please enter an integer > 1"));
}
if (maxChunkSize > 0 && chunkSize > maxChunkSize) {
setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl()));
}
} catch(NumberFormatException e) {
setErrorFeedback(tfChunkSize, tr("Value ''{0}'' is not a number. Please enter an integer > 1", tfChunkSize.getText().trim()));
} finally {
updateNumRequestsLabels();
}
}
public void changedUpdate(DocumentEvent arg0) {
valiateChunkSize();
}
public void insertUpdate(DocumentEvent arg0) {
valiateChunkSize();
}
public void removeUpdate(DocumentEvent arg0) {
valiateChunkSize();
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == tfChunkSize
&& evt.getPropertyName().equals("enabled")
&& (Boolean)evt.getNewValue()
) {
valiateChunkSize();
}
}
}
class StrategyChangeListener implements ItemListener, FocusListener, ActionListener {
protected void notifyStrategy() {
firePropertyChange(UPLOAD_STRATEGY_SPECIFICATION_PROP, null, getUploadStrategySpecification());
}
public void itemStateChanged(ItemEvent e) {
UploadStrategy strategy = getUploadStrategy();
if (strategy == null) return;
switch(strategy) {
case CHUNKED_DATASET_STRATEGY:
tfChunkSize.setEnabled(true);
tfChunkSize.requestFocusInWindow();
break;
default:
tfChunkSize.setEnabled(false);
}
notifyStrategy();
}
public void focusGained(FocusEvent arg0) {}
public void focusLost(FocusEvent arg0) {
notifyStrategy();
}
public void actionPerformed(ActionEvent arg0) {
notifyStrategy();
}
}
}
| false | true | protected JPanel buildUploadStrategyPanel() {
JPanel pnl = new JPanel();
pnl.setLayout(new GridBagLayout());
bgStrategies = new ButtonGroup();
rbStrategy = new HashMap<UploadStrategy, JRadioButton>();
lblStrategies = new HashMap<UploadStrategy, JMultilineLabel>();
lblNumRequests = new HashMap<UploadStrategy, JLabel>();
for (UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.put(strategy, new JRadioButton());
lblNumRequests.put(strategy, new JLabel());
lblStrategies.put(strategy, new JMultilineLabel(""));
bgStrategies.add(rbStrategy.get(strategy));
}
// -- single request strategy
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 4;
gc.insets = new Insets(0,0,3,0);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(new JMultilineLabel(tr("Please select the upload strategy:")), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(rbStrategy.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
JLabel lbl = lblStrategies.get(UploadStrategy.SINGLE_REQUEST_STRATEGY);
lbl.setText(tr("Upload data in one request"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 1;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
// -- chunked dataset strategy
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
lbl = lblStrategies.get(UploadStrategy.CHUNKED_DATASET_STRATEGY);
lbl.setText(tr("Upload data in chunks of objects. Chunk size: "));
pnl.add(lbl, gc);
gc.gridx = 2;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(tfChunkSize = new JTextField(4), gc);
gc.gridx = 3;
gc.gridy = 2;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
lbl = lblStrategies.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY);
lbl.setText(tr("Upload each object individually"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 3;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
tfChunkSize.addFocusListener(new TextFieldFocusHandler());
tfChunkSize.getDocument().addDocumentListener(new ChunkSizeInputVerifier());
StrategyChangeListener strategyChangeListener = new StrategyChangeListener();
tfChunkSize.addFocusListener(strategyChangeListener);
tfChunkSize.addActionListener(strategyChangeListener);
for(UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.get(strategy).addItemListener(strategyChangeListener);
}
return pnl;
}
| protected JPanel buildUploadStrategyPanel() {
JPanel pnl = new JPanel();
pnl.setLayout(new GridBagLayout());
bgStrategies = new ButtonGroup();
rbStrategy = new HashMap<UploadStrategy, JRadioButton>();
lblStrategies = new HashMap<UploadStrategy, JMultilineLabel>();
lblNumRequests = new HashMap<UploadStrategy, JLabel>();
for (UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.put(strategy, new JRadioButton());
lblNumRequests.put(strategy, new JLabel());
lblStrategies.put(strategy, new JMultilineLabel(""));
bgStrategies.add(rbStrategy.get(strategy));
}
// -- headline
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 4;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.insets = new Insets(0,0,3,0);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(new JMultilineLabel(tr("Please select the upload strategy:")), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
pnl.add(rbStrategy.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 1;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
JLabel lbl = lblStrategies.get(UploadStrategy.SINGLE_REQUEST_STRATEGY);
lbl.setText(tr("Upload data in one request"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 1;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY), gc);
// -- chunked dataset strategy
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
lbl = lblStrategies.get(UploadStrategy.CHUNKED_DATASET_STRATEGY);
lbl.setText(tr("Upload data in chunks of objects. Chunk size: "));
pnl.add(lbl, gc);
gc.gridx = 2;
gc.gridy = 2;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(tfChunkSize = new JTextField(4), gc);
gc.gridx = 3;
gc.gridy = 2;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.CHUNKED_DATASET_STRATEGY), gc);
// -- single request strategy
gc.gridx = 0;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
pnl.add(rbStrategy.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
gc.gridx = 1;
gc.gridy = 3;
gc.weightx = 0.0;
gc.weighty = 0.0;
gc.gridwidth = 2;
lbl = lblStrategies.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY);
lbl.setText(tr("Upload each object individually"));
pnl.add(lbl, gc);
gc.gridx = 3;
gc.gridy = 3;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.gridwidth = 1;
pnl.add(lblNumRequests.get(UploadStrategy.INDIVIDUAL_OBJECTS_STRATEGY), gc);
tfChunkSize.addFocusListener(new TextFieldFocusHandler());
tfChunkSize.getDocument().addDocumentListener(new ChunkSizeInputVerifier());
StrategyChangeListener strategyChangeListener = new StrategyChangeListener();
tfChunkSize.addFocusListener(strategyChangeListener);
tfChunkSize.addActionListener(strategyChangeListener);
for(UploadStrategy strategy: UploadStrategy.values()) {
rbStrategy.get(strategy).addItemListener(strategyChangeListener);
}
return pnl;
}
|
diff --git a/Looting.java b/Looting.java
index 71adee3..478e953 100644
--- a/Looting.java
+++ b/Looting.java
@@ -1,87 +1,88 @@
package roachkiller;
import org.powerbot.core.script.job.Task;
import org.powerbot.core.script.job.state.Node;
import org.powerbot.game.api.methods.Game;
import org.powerbot.game.api.methods.Walking;
import org.powerbot.game.api.methods.interactive.Players;
import org.powerbot.game.api.methods.node.GroundItems;
import org.powerbot.game.api.methods.tab.Inventory;
import org.powerbot.game.api.wrappers.node.GroundItem;
import org.powerbot.game.api.wrappers.widget.WidgetChild;
import org.powerbot.game.bot.Context;
public class Looting extends Node{
@Override
public boolean activate() {
GroundItem g = GroundItems.getNearest(Variable.lootTier);
boolean inroacharea = Variable.currentArea.contains(Players.getLocal().getLocation());
boolean incombat = Players.getLocal().isInCombat();
return g != null && inroacharea && !incombat && Variable.currentArea.contains(g);
}
@SuppressWarnings("deprecation")
@Override
public void execute() {
GroundItem g = GroundItems.getNearest(Variable.lootTier);
GroundItem p = g;
if(Variable.currentArea.contains(g)){
Method.turnTo(g.getLocation(), 6);
if(Inventory.isFull()){
Variable.status="Eating for room";
WidgetChild e = Inventory.getItem(Variable.food).getWidgetChild();
e.interact("Eat");
+ Task.sleep(600);
}else{
if(g != null){
int t = 0;
while(!g.isOnScreen()){
Variable.status="Walking to loot";
Walking.walk(g.getLocation());
Task.sleep(1000,100);
t++;
if(t==20){
Variable.status="Something went wrong walking to loot";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
t = 0;
while(g!=null){
Variable.status="Picking up loot";
g.interact("Take", g.getGroundItem().getName());
Task.sleep(1000);
while(Players.getLocal().getInteracting() != null || Players.getLocal().isMoving()){
Task.sleep(40,10);
t++;
if(t==400){
Variable.status="Something went wrong looting";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
g = GroundItems.getNearest(Variable.lootTier);
}
System.out.println(Method.componentTime(Variable.runTime));
int id = p.getId();
int value = Variable.lootPrices.get(id);
int stack = p.getGroundItem().getStackSize();
if(value == 0) {
value = Variable.lootPrices.get(id - 1);
if(value != 0) {
int price = value * stack;
Variable.totalGained += price;
}
} else {
Variable.totalGained += value * stack;
}
Task.sleep(1000);
}
}
}
}
}
| true | true | public void execute() {
GroundItem g = GroundItems.getNearest(Variable.lootTier);
GroundItem p = g;
if(Variable.currentArea.contains(g)){
Method.turnTo(g.getLocation(), 6);
if(Inventory.isFull()){
Variable.status="Eating for room";
WidgetChild e = Inventory.getItem(Variable.food).getWidgetChild();
e.interact("Eat");
}else{
if(g != null){
int t = 0;
while(!g.isOnScreen()){
Variable.status="Walking to loot";
Walking.walk(g.getLocation());
Task.sleep(1000,100);
t++;
if(t==20){
Variable.status="Something went wrong walking to loot";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
t = 0;
while(g!=null){
Variable.status="Picking up loot";
g.interact("Take", g.getGroundItem().getName());
Task.sleep(1000);
while(Players.getLocal().getInteracting() != null || Players.getLocal().isMoving()){
Task.sleep(40,10);
t++;
if(t==400){
Variable.status="Something went wrong looting";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
g = GroundItems.getNearest(Variable.lootTier);
}
System.out.println(Method.componentTime(Variable.runTime));
int id = p.getId();
int value = Variable.lootPrices.get(id);
int stack = p.getGroundItem().getStackSize();
if(value == 0) {
value = Variable.lootPrices.get(id - 1);
if(value != 0) {
int price = value * stack;
Variable.totalGained += price;
}
} else {
Variable.totalGained += value * stack;
}
Task.sleep(1000);
}
}
}
}
| public void execute() {
GroundItem g = GroundItems.getNearest(Variable.lootTier);
GroundItem p = g;
if(Variable.currentArea.contains(g)){
Method.turnTo(g.getLocation(), 6);
if(Inventory.isFull()){
Variable.status="Eating for room";
WidgetChild e = Inventory.getItem(Variable.food).getWidgetChild();
e.interact("Eat");
Task.sleep(600);
}else{
if(g != null){
int t = 0;
while(!g.isOnScreen()){
Variable.status="Walking to loot";
Walking.walk(g.getLocation());
Task.sleep(1000,100);
t++;
if(t==20){
Variable.status="Something went wrong walking to loot";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
t = 0;
while(g!=null){
Variable.status="Picking up loot";
g.interact("Take", g.getGroundItem().getName());
Task.sleep(1000);
while(Players.getLocal().getInteracting() != null || Players.getLocal().isMoving()){
Task.sleep(40,10);
t++;
if(t==400){
Variable.status="Something went wrong looting";
Game.logout(false);
Context.get().getScriptHandler().stop();
}
}
g = GroundItems.getNearest(Variable.lootTier);
}
System.out.println(Method.componentTime(Variable.runTime));
int id = p.getId();
int value = Variable.lootPrices.get(id);
int stack = p.getGroundItem().getStackSize();
if(value == 0) {
value = Variable.lootPrices.get(id - 1);
if(value != 0) {
int price = value * stack;
Variable.totalGained += price;
}
} else {
Variable.totalGained += value * stack;
}
Task.sleep(1000);
}
}
}
}
|
diff --git a/src/com/android/exchange/adapter/ProvisionParser.java b/src/com/android/exchange/adapter/ProvisionParser.java
index 1aff0467..057ffaff 100644
--- a/src/com/android/exchange/adapter/ProvisionParser.java
+++ b/src/com/android/exchange/adapter/ProvisionParser.java
@@ -1,450 +1,450 @@
/* Copyright (C) 2010 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.adapter;
import com.android.email.SecurityPolicy;
import com.android.email.SecurityPolicy.PolicySet;
import com.android.exchange.EasSyncService;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Parse the result of the Provision command
*
* Assuming a successful parse, we store the PolicySet and the policy key
*/
public class ProvisionParser extends Parser {
private EasSyncService mService;
PolicySet mPolicySet = null;
String mPolicyKey = null;
boolean mRemoteWipe = false;
boolean mIsSupportable = true;
public ProvisionParser(InputStream in, EasSyncService service) throws IOException {
super(in);
mService = service;
}
public PolicySet getPolicySet() {
return mPolicySet;
}
public String getPolicyKey() {
return mPolicyKey;
}
public boolean getRemoteWipe() {
return mRemoteWipe;
}
public boolean hasSupportablePolicySet() {
return (mPolicySet != null) && mIsSupportable;
}
private void parseProvisionDocWbxml() throws IOException {
int minPasswordLength = 0;
int passwordMode = PolicySet.PASSWORD_MODE_NONE;
int maxPasswordFails = 0;
int maxScreenLockTime = 0;
int passwordExpiration = 0;
int passwordHistory = 0;
int passwordComplexChars = 0;
- boolean supported = true;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
+ boolean tagIsSupported = true;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
if (passwordMode == PolicySet.PASSWORD_MODE_NONE) {
passwordMode = PolicySet.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
minPasswordLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordMode = PolicySet.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
maxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
maxPasswordFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
passwordExpiration = getValueInt();
// We don't yet support this
if (passwordExpiration > 0) {
- supported = false;
+ tagIsSupported = false;
}
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
passwordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ATTACHMENTS_ENABLED:
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_CAMERA:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
- supported = false;
+ tagIsSupported = false;
}
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
- supported = false;
+ tagIsSupported = false;
}
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
if (getValueInt() == 1) {
- supported = false;
+ tagIsSupported = false;
}
break;
// The following, if greater than zero, can't be supported at the moment
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
if (getValueInt() > 0) {
- supported = false;
+ tagIsSupported = false;
}
break;
// Complex character setting is only used if we're in "strong" (alphanumeric) mode
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
passwordComplexChars = getValueInt();
- if ((passwordMode == PolicySet.PASSWORD_MODE_STRONG) &&
+ if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) &&
(passwordComplexChars > 0)) {
- supported = false;
+ tagIsSupported = false;
}
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
- supported = false;
+ tagIsSupported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
// 0 indicates no specified filter
if (getValueInt() != 0) {
- supported = false;
+ tagIsSupported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
- supported = false;
+ tagIsSupported = false;
}
break;
default:
skipTag();
}
- if (!supported) {
+ if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode,
maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory,
passwordComplexChars);
}
/**
* Return whether or not either of the application list tags specifies any applications
* @param endTag the tag whose children we're walking through
* @return whether any applications were specified (by name or by hash)
* @throws IOException
*/
private boolean specifiesApplications(int endTag) throws IOException {
boolean specifiesApplications = false;
while (nextTag(endTag) != END) {
switch (tag) {
case Tags.PROVISION_APPLICATION_NAME:
case Tags.PROVISION_HASH:
specifiesApplications = true;
break;
default:
skipTag();
}
}
return specifiesApplications;
}
class ShadowPolicySet {
int mMinPasswordLength = 0;
int mPasswordMode = PolicySet.PASSWORD_MODE_NONE;
int mMaxPasswordFails = 0;
int mMaxScreenLockTime = 0;
int mPasswordExpiration = 0;
int mPasswordHistory = 0;
int mPasswordComplexChars = 0;
}
/*package*/ void parseProvisionDocXml(String doc) throws IOException {
ShadowPolicySet sps = new ShadowPolicySet();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8");
int type = parser.getEventType();
if (type == XmlPullParser.START_DOCUMENT) {
type = parser.next();
if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("wap-provisioningdoc")) {
parseWapProvisioningDoc(parser, sps);
}
}
}
} catch (XmlPullParserException e) {
throw new IOException();
}
mPolicySet = new PolicySet(sps.mMinPasswordLength, sps.mPasswordMode, sps.mMaxPasswordFails,
sps.mMaxScreenLockTime, true, sps.mPasswordExpiration, sps.mPasswordHistory,
sps.mPasswordComplexChars);
}
/**
* Return true if password is required; otherwise false.
*/
private boolean parseSecurityPolicy(XmlPullParser parser, ShadowPolicySet sps)
throws XmlPullParserException, IOException {
boolean passwordRequired = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("parm")) {
String name = parser.getAttributeValue(null, "name");
if (name.equals("4131")) {
String value = parser.getAttributeValue(null, "value");
if (value.equals("1")) {
passwordRequired = false;
}
}
}
}
}
return passwordRequired;
}
private void parseCharacteristic(XmlPullParser parser, ShadowPolicySet sps)
throws XmlPullParserException, IOException {
boolean enforceInactivityTimer = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
if (parser.getName().equals("parm")) {
String name = parser.getAttributeValue(null, "name");
String value = parser.getAttributeValue(null, "value");
if (name.equals("AEFrequencyValue")) {
if (enforceInactivityTimer) {
if (value.equals("0")) {
sps.mMaxScreenLockTime = 1;
} else {
sps.mMaxScreenLockTime = 60*Integer.parseInt(value);
}
}
} else if (name.equals("AEFrequencyType")) {
// "0" here means we don't enforce an inactivity timeout
if (value.equals("0")) {
enforceInactivityTimer = false;
}
} else if (name.equals("DeviceWipeThreshold")) {
sps.mMaxPasswordFails = Integer.parseInt(value);
} else if (name.equals("CodewordFrequency")) {
// Ignore; has no meaning for us
} else if (name.equals("MinimumPasswordLength")) {
sps.mMinPasswordLength = Integer.parseInt(value);
} else if (name.equals("PasswordComplexity")) {
if (value.equals("0")) {
sps.mPasswordMode = PolicySet.PASSWORD_MODE_STRONG;
} else {
sps.mPasswordMode = PolicySet.PASSWORD_MODE_SIMPLE;
}
}
}
}
}
}
private void parseRegistry(XmlPullParser parser, ShadowPolicySet sps)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
parseCharacteristic(parser, sps);
}
}
}
}
private void parseWapProvisioningDoc(XmlPullParser parser, ShadowPolicySet sps)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
String atype = parser.getAttributeValue(null, "type");
if (atype.equals("SecurityPolicy")) {
// If a password isn't required, stop here
if (!parseSecurityPolicy(parser, sps)) {
return;
}
} else if (atype.equals("Registry")) {
parseRegistry(parser, sps);
return;
}
}
}
}
}
private void parseProvisionData() throws IOException {
while (nextTag(Tags.PROVISION_DATA) != END) {
if (tag == Tags.PROVISION_EAS_PROVISION_DOC) {
parseProvisionDocWbxml();
} else {
skipTag();
}
}
}
private void parsePolicy() throws IOException {
String policyType = null;
while (nextTag(Tags.PROVISION_POLICY) != END) {
switch (tag) {
case Tags.PROVISION_POLICY_TYPE:
policyType = getValue();
mService.userLog("Policy type: ", policyType);
break;
case Tags.PROVISION_POLICY_KEY:
mPolicyKey = getValue();
break;
case Tags.PROVISION_STATUS:
mService.userLog("Policy status: ", getValue());
break;
case Tags.PROVISION_DATA:
if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) {
// Parse the old style XML document
parseProvisionDocXml(getValue());
} else {
// Parse the newer WBXML data
parseProvisionData();
}
break;
default:
skipTag();
}
}
}
private void parsePolicies() throws IOException {
while (nextTag(Tags.PROVISION_POLICIES) != END) {
if (tag == Tags.PROVISION_POLICY) {
parsePolicy();
} else {
skipTag();
}
}
}
@Override
public boolean parse() throws IOException {
boolean res = false;
if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) {
throw new IOException();
}
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
switch (tag) {
case Tags.PROVISION_STATUS:
int status = getValueInt();
mService.userLog("Provision status: ", status);
res = (status == 1);
break;
case Tags.PROVISION_POLICIES:
parsePolicies();
break;
case Tags.PROVISION_REMOTE_WIPE:
// Indicate remote wipe command received
mRemoteWipe = true;
break;
default:
skipTag();
}
}
return res;
}
}
| false | true | private void parseProvisionDocWbxml() throws IOException {
int minPasswordLength = 0;
int passwordMode = PolicySet.PASSWORD_MODE_NONE;
int maxPasswordFails = 0;
int maxScreenLockTime = 0;
int passwordExpiration = 0;
int passwordHistory = 0;
int passwordComplexChars = 0;
boolean supported = true;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
if (passwordMode == PolicySet.PASSWORD_MODE_NONE) {
passwordMode = PolicySet.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
minPasswordLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordMode = PolicySet.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
maxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
maxPasswordFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
passwordExpiration = getValueInt();
// We don't yet support this
if (passwordExpiration > 0) {
supported = false;
}
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
passwordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ATTACHMENTS_ENABLED:
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_CAMERA:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
supported = false;
}
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
supported = false;
}
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
if (getValueInt() == 1) {
supported = false;
}
break;
// The following, if greater than zero, can't be supported at the moment
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
if (getValueInt() > 0) {
supported = false;
}
break;
// Complex character setting is only used if we're in "strong" (alphanumeric) mode
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
passwordComplexChars = getValueInt();
if ((passwordMode == PolicySet.PASSWORD_MODE_STRONG) &&
(passwordComplexChars > 0)) {
supported = false;
}
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
supported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
// 0 indicates no specified filter
if (getValueInt() != 0) {
supported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
supported = false;
}
break;
default:
skipTag();
}
if (!supported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode,
maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory,
passwordComplexChars);
}
| private void parseProvisionDocWbxml() throws IOException {
int minPasswordLength = 0;
int passwordMode = PolicySet.PASSWORD_MODE_NONE;
int maxPasswordFails = 0;
int maxScreenLockTime = 0;
int passwordExpiration = 0;
int passwordHistory = 0;
int passwordComplexChars = 0;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
if (passwordMode == PolicySet.PASSWORD_MODE_NONE) {
passwordMode = PolicySet.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
minPasswordLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordMode = PolicySet.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
maxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
maxPasswordFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
passwordExpiration = getValueInt();
// We don't yet support this
if (passwordExpiration > 0) {
tagIsSupported = false;
}
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
passwordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ATTACHMENTS_ENABLED:
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_CAMERA:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
}
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
}
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
if (getValueInt() == 1) {
tagIsSupported = false;
}
break;
// The following, if greater than zero, can't be supported at the moment
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
if (getValueInt() > 0) {
tagIsSupported = false;
}
break;
// Complex character setting is only used if we're in "strong" (alphanumeric) mode
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
passwordComplexChars = getValueInt();
if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) &&
(passwordComplexChars > 0)) {
tagIsSupported = false;
}
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
// 0 indicates no specified filter
if (getValueInt() != 0) {
tagIsSupported = false;
}
break;
// NOTE: We can support these entirely within the email application if we choose
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode,
maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory,
passwordComplexChars);
}
|
diff --git a/GameDriver.java b/GameDriver.java
index 73dcd06..159218e 100644
--- a/GameDriver.java
+++ b/GameDriver.java
@@ -1,32 +1,32 @@
import javax.swing.*;
public class GameDriver {
private static void createAndShowUI() {
- // crea te the model/view/control and connect them together
+ // create the model/view/control and connect them together
GameModel model = new GameModel();
GameView view = new GameView(model);
GameControl control = new GameControl(model);
GameMenu menu = new GameMenu(control);
view.setGuiControl(control);
// create the GUI to display the view
JFrame frame = new JFrame("Hollywood Squares");
frame.getContentPane().add(view.getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menu.getMenuBar());
frame.setSize(945,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// call Swing code in a thread-safe manner per the tutorials
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
| true | true | private static void createAndShowUI() {
// crea te the model/view/control and connect them together
GameModel model = new GameModel();
GameView view = new GameView(model);
GameControl control = new GameControl(model);
GameMenu menu = new GameMenu(control);
view.setGuiControl(control);
// create the GUI to display the view
JFrame frame = new JFrame("Hollywood Squares");
frame.getContentPane().add(view.getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menu.getMenuBar());
frame.setSize(945,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
| private static void createAndShowUI() {
// create the model/view/control and connect them together
GameModel model = new GameModel();
GameView view = new GameView(model);
GameControl control = new GameControl(model);
GameMenu menu = new GameMenu(control);
view.setGuiControl(control);
// create the GUI to display the view
JFrame frame = new JFrame("Hollywood Squares");
frame.getContentPane().add(view.getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menu.getMenuBar());
frame.setSize(945,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
|
diff --git a/src/com/modcrafting/ultrabans/commands/Unban.java b/src/com/modcrafting/ultrabans/commands/Unban.java
index e30d48f..ea39bb0 100644
--- a/src/com/modcrafting/ultrabans/commands/Unban.java
+++ b/src/com/modcrafting/ultrabans/commands/Unban.java
@@ -1,122 +1,129 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.modcrafting.ultrabans.UltraBan;
public class Unban implements CommandExecutor{
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
public Unban(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
if(plugin.bannedPlayers.contains(p.toLowerCase())){
plugin.bannedPlayers.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
+ Bukkit.getOfflinePlayer(p).setBanned(false);
+ String ip = plugin.db.getAddress(p);
+ if(plugin.bannedIPs.contains(ip)){
+ plugin.bannedIPs.remove(ip);
+ Bukkit.unbanIP(ip);
+ System.out.println("Also removed the IP ban!");
+ }
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
}
public String formatMessage(String str){
String funnyChar = new Character((char) 167).toString();
str = str.replaceAll("&", funnyChar);
return str;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
if(plugin.bannedPlayers.contains(p.toLowerCase())){
plugin.bannedPlayers.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
if(plugin.bannedPlayers.contains(p.toLowerCase())){
plugin.bannedPlayers.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
}
|
diff --git a/vcat-redis/src/main/java/vcat/cache/redis/MetadataRedisCache.java b/vcat-redis/src/main/java/vcat/cache/redis/MetadataRedisCache.java
index 6873b5d..47a6579 100644
--- a/vcat-redis/src/main/java/vcat/cache/redis/MetadataRedisCache.java
+++ b/vcat-redis/src/main/java/vcat/cache/redis/MetadataRedisCache.java
@@ -1,48 +1,48 @@
package vcat.cache.redis;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import vcat.cache.CacheException;
import vcat.cache.IMetadataCache;
import vcat.mediawiki.Metadata;
public class MetadataRedisCache extends StringRedisCache implements IMetadataCache {
private Log log = LogFactory.getLog(this.getClass());
public MetadataRedisCache(final JedisPool jedisPool, final String redisPrefix, final int maxAgeInSeconds) {
super(jedisPool, redisPrefix, maxAgeInSeconds);
}
public synchronized Metadata getMetadata(String key) throws CacheException {
if (this.containsKey(key)) {
final Jedis jedis = this.jedisPool.getResource();
final byte[] metadataObjectData = jedis.get(this.jedisKeyBytes(key));
this.jedisPool.returnResource(jedis);
Object metadataObject = SerializationUtils.deserialize(metadataObjectData);
if (metadataObject instanceof Metadata) {
return (Metadata) metadataObject;
} else {
// Wrong type - remove from cache and throw error
this.remove(key);
- String message = "Error while deserializing cached file to Metadata";
+ String message = "Error while deserializing cached data to Metadata";
log.error(message);
throw new CacheException(message);
}
} else {
return null;
}
}
public synchronized void put(String key, Metadata metadata) throws CacheException {
final Jedis jedis = this.jedisPool.getResource();
jedis.set(this.jedisKeyBytes(key), SerializationUtils.serialize(metadata));
this.jedisPool.returnResource(jedis);
}
}
| true | true | public synchronized Metadata getMetadata(String key) throws CacheException {
if (this.containsKey(key)) {
final Jedis jedis = this.jedisPool.getResource();
final byte[] metadataObjectData = jedis.get(this.jedisKeyBytes(key));
this.jedisPool.returnResource(jedis);
Object metadataObject = SerializationUtils.deserialize(metadataObjectData);
if (metadataObject instanceof Metadata) {
return (Metadata) metadataObject;
} else {
// Wrong type - remove from cache and throw error
this.remove(key);
String message = "Error while deserializing cached file to Metadata";
log.error(message);
throw new CacheException(message);
}
} else {
return null;
}
}
| public synchronized Metadata getMetadata(String key) throws CacheException {
if (this.containsKey(key)) {
final Jedis jedis = this.jedisPool.getResource();
final byte[] metadataObjectData = jedis.get(this.jedisKeyBytes(key));
this.jedisPool.returnResource(jedis);
Object metadataObject = SerializationUtils.deserialize(metadataObjectData);
if (metadataObject instanceof Metadata) {
return (Metadata) metadataObject;
} else {
// Wrong type - remove from cache and throw error
this.remove(key);
String message = "Error while deserializing cached data to Metadata";
log.error(message);
throw new CacheException(message);
}
} else {
return null;
}
}
|
diff --git a/wflow-wfengine/src/main/java/org/joget/workflow/shark/JSPClientUtilities.java b/wflow-wfengine/src/main/java/org/joget/workflow/shark/JSPClientUtilities.java
index c87ee0d..6112e20 100644
--- a/wflow-wfengine/src/main/java/org/joget/workflow/shark/JSPClientUtilities.java
+++ b/wflow-wfengine/src/main/java/org/joget/workflow/shark/JSPClientUtilities.java
@@ -1,477 +1,481 @@
package org.joget.workflow.shark;
import org.joget.commons.util.LogUtil;
import org.joget.workflow.model.WorkflowVariable;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.enhydra.shark.Shark;
import org.enhydra.shark.api.client.wfmc.wapi.WMFilter;
import org.enhydra.shark.api.client.wfmodel.WfActivity;
import org.enhydra.shark.api.client.wfmodel.WfAssignment;
import org.enhydra.shark.api.client.wfmodel.WfProcessIterator;
import org.enhydra.shark.api.client.wfmodel.WfProcessMgr;
import org.enhydra.shark.api.client.wfservice.AdminMisc;
import org.enhydra.shark.api.client.wfservice.SharkConnection;
import org.enhydra.shark.api.client.wfservice.WMEntity;
import org.enhydra.shark.api.client.wfservice.XPDLBrowser;
import org.enhydra.shark.api.common.SharkConstants;
import org.enhydra.shark.utilities.MiscUtilities;
import org.enhydra.shark.utilities.WMEntityUtilities;
public class JSPClientUtilities {
private static PackageFileFilter packageFileFilter = new PackageFileFilter();
private static Properties p = new Properties();
private static String EXTERNAL_PACKAGES_REPOSITORY = "repository/external";
private static boolean _debug_ = false;
private static boolean sharkConfigured = false;
private static boolean ipc = false;
private static String engineName = "SharkExampleJSP";
/* private static WMConnectInfo wmconnInfo = new WMConnectInfo("admin",
"enhydra",
engineName,
"");
*/
public static final String VARIABLE_TO_PROCESS_UPDATE = "VariableToProcess_UPDATE";
public static final String VARIABLE_TO_PROCESS_VIEW = "VariableToProcess_VIEW";
public static void initProperties(String realPath) throws Exception {
if (_debug_){
System.err.println("#_init_#");
}
if (!ipc) {
ipc = true;
try {
realPath = replaceAll(realPath, "\\", "/");
if (!realPath.endsWith("/")) {
realPath = realPath + "/";
}
p.load(JSPClientUtilities.class.getResourceAsStream(realPath + "conf/Shark.conf"));
for (Iterator it = p.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
String value = p.getProperty(key);
if (0 <= value.indexOf("@@")) {
if (_debug_){
System.err.print("key is " + key + ", old value is" + value);
}
value = replaceAll(value, "@@/", realPath);
p.setProperty(key, value);
if (_debug_){
System.err.println(", new value is" + value);
}
}
}
p.load(JSPClientUtilities.class.getResourceAsStream(realPath + "conf/SharkJSPClient.conf"));
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
}
p.setProperty("enginename", engineName);
}
}
public static void init() throws Exception {
if (!sharkConfigured) {
Shark.configure(p);
sharkConfigured = true;
}
}
public static String packageLoad(SharkConnection sc, String xpdlName) throws Exception {
return "";
/* if (_debug_){
System.err.println("#_packageLoad_#");
String realPath = EXTERNAL_PACKAGES_REPOSITORY + "/" + xpdlName;
PackageAdministration pa = Shark.getInstance().getPackageAdministration();
String pkgId = XMLUtil.getIdFromFile(realPath);
if (!pa.isPackageOpened(sc.getSessionHandle(), pkgId)) {
try {
pa.openPackage(sc.getSessionHandle(), realPath);
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), $1, "");
throw e;
}
}
return pkgId;
*/ }
public static void processStart(SharkConnection sc, String mgrName) throws Exception {
if (_debug_){
System.err.println("#_processStartName_#");
}
try {
if (!isProcessRunning(sc, mgrName)) {
WfProcessMgr mgr = sc.getProcessMgr(mgrName);
mgr.create_process(null).start();
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isProcessRunning(SharkConnection sc, String mgrName)
throws Exception {
System.err.println("#_isProcessRunning_# (" + mgrName + ")");
try {
WfProcessMgr pMgr = sc.getProcessMgr(mgrName);
WfProcessIterator pit = pMgr.get_iterator_process();
pit.set_query_expression("state.equals(\""
+ SharkConstants.STATE_OPEN_RUNNING + "\")");
if (_debug_) {
System.err.println("#_" + pit.how_many() + "_#");
System.err.println("#_" + pit.get_next_n_sequence(0).length + "_#");
}
return 0 < pit.get_next_n_sequence(0).length;
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void activityComplete(SharkConnection sConn, String activityId)
throws Exception {
try {
if (null != activityId) {
try {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
assignmentAccept(sConn, a);
}
a.activity().complete();
} catch (Exception e) {
throw e;
}
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isMine(SharkConnection sConn, String activityId)
throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
return isMine(sConn, a);
}
public static boolean isMine(SharkConnection sConn, WfAssignment a) throws Exception {
return a.get_accepted_status();
}
public static void assignmentAccept(SharkConnection sConn, String activityId)
throws Exception {
assignmentAccept(sConn, getAssignment(sConn, activityId));
}
private static void assignmentAccept(SharkConnection sConn, WfAssignment a)
throws Exception {
a.set_accepted_status(true);
}
public static WfAssignment getAssignment(SharkConnection sConn, String activityId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (activityId.equals(ar[i].activity().key())) {
return ar[i];
}
}
throw new Exception("Activity:"
+ activityId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
if (_debug_){
System.err.println("zvekseptsn");
}
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static WfAssignment getAssignmentByProcess(SharkConnection sConn, String processId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (processId.equals(ar[i].activity().container().key())) {
return ar[i];
}
}
throw new Exception("Activity for process:"
+ processId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void variableSet(SharkConnection sConn,
String activityId,
String vName,
String vValue) throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
throw new Exception("I don't own activity " + activityId);
}
Map _m = new HashMap();
Object c = a.activity().process_context().get(vName);
if (c instanceof Long) {
c = new Long(vValue);
} else if (c instanceof Boolean) {
c = Boolean.valueOf(vValue);
} else if (c instanceof Double) {
c = Double.valueOf(vValue);
} else {
c = vValue;
}
_m.put(vName, c);
a.activity().set_result(_m);
}
public static List getVariableData(SharkConnection sConn, WfActivity act)
throws Exception {
return getVariableData(sConn, act, true);
}
public static List getVariableData(SharkConnection sConn, WfActivity act, boolean onlyForUpdate)
throws Exception {
List ret = new ArrayList();
Map _m = act.process_context();
String[][] eas = getExtAttribNVPairs(sConn, act);
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
if (!onlyForUpdate || eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
String variableId = eas[i][1];
if (_m.containsKey(variableId)) {
Object c = _m.get(variableId);
+ // null check for Oracle DB to prevent missing workflow variable
+ if (c == null) {
+ c = "";
+ }
if (c instanceof String || c instanceof Long || c instanceof Boolean || c instanceof Double) {
WorkflowVariable vd = new WorkflowVariable();
vd.setId(variableId);
vd.setToUpdate(eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE));
vd.setVal(c);
vd.setJavaClass(c.getClass());
WMEntity varEnt = Shark.getInstance().getAdminMisc().getVariableDefinitionInfoByUniqueProcessDefinitionName(
sConn.getSessionHandle(),
act.container().manager().name(),variableId);
String varName = variableId;
if (varEnt != null) {
varName = varEnt.getName();
if (varName == null || varName.equals("")) {
varName = variableId;
}
}
String varDesc = "";
if (varEnt != null) {
WMFilter filter = new WMFilter("Name", WMFilter.EQ, "Description");
filter.setFilterType(XPDLBrowser.SIMPLE_TYPE_XPDL);
varDesc = Shark.getInstance()
.getXPDLBrowser()
.listAttributes(sConn.getSessionHandle(),
varEnt,
filter,
false)
.getArray()[0].getValue().toString();
}
vd.setName(varName);
vd.setDescription(varDesc);
ret.add(vd);
}
}
}
}
}
return ret;
}
public static String[] xpdlsToLoad() throws Exception {
List packageFiles = getDefinedPackageFiles(EXTERNAL_PACKAGES_REPOSITORY, true);
Collection pfls = new ArrayList();
Iterator pfi = packageFiles.iterator();
Collections.sort(packageFiles);
while (pfi.hasNext()) {
File f = (File) pfi.next();
String fileName;
try {
fileName = f.getCanonicalPath();
} catch (Exception ex) {
fileName = f.getAbsolutePath();
}
fileName = fileName.substring(EXTERNAL_PACKAGES_REPOSITORY.length() + 1);
pfls.add(fileName);
}
String[] pfs = new String[pfls.size()];
pfls.toArray(pfs);
return pfs;
}
public static String[] processesToStart(SharkConnection sc) throws Exception {
WfProcessMgr[] a = sc.get_iterator_processmgr().get_next_n_sequence(0);
String[] ret = new String[a.length];
for (int i = 0; i < a.length; ++i) {
String n = a[i].name();
if (_debug_){
System.err.println("processName " + n);
}
ret[i] = n;
}
return ret;
}
/**
* Replace all occurence of forReplace with replaceWith in input string.
*
* @param input represents input string
* @param forReplace represents substring for replace
* @param replaceWith represents replaced string value
* @return new string with replaced values
*/
private static String replaceAll(String input, String forReplace, String replaceWith) {
if (input == null){
return null;
}
StringBuffer result = new StringBuffer();
boolean hasMore = true;
while (hasMore) {
int start = input.indexOf(forReplace);
int end = start + forReplace.length();
if (start != -1) {
result.append(input.substring(0, start) + replaceWith);
input = input.substring(end);
} else {
hasMore = false;
result.append(input);
}
}
if (result.toString().equals("")){
return input; // nothing is changed
}else{
return result.toString();
}
}
static List getDefinedPackageFiles(String repository, boolean traverse) {
File startingFolder = new File(repository);
List packageFiles = new ArrayList();
if (!startingFolder.exists()) {
LogUtil.info(JSPClientUtilities.class.getName(), "Repository " + startingFolder + " doesn't exist");
}
if (traverse) {
MiscUtilities.traverse(startingFolder, packageFiles, null);
} else {
packageFiles = Arrays.asList(startingFolder.listFiles(packageFileFilter));
}
return packageFiles;
}
public static void setPathToXPDLRepositoryFolder(String xpdlRepFolder)
throws Exception {
EXTERNAL_PACKAGES_REPOSITORY = xpdlRepFolder;
System.err.println(xpdlRepFolder);
File f = new File(xpdlRepFolder);
System.err.println(f);
if (!f.isAbsolute()) {
System.err.println("isn't absolute");
f = f.getAbsoluteFile();
}
System.err.println(f);
if (!f.exists()) {
throw new Exception("Folder " + xpdlRepFolder + " does not exist");
}
try {
EXTERNAL_PACKAGES_REPOSITORY = f.getCanonicalPath();
} catch (Exception ex) {
EXTERNAL_PACKAGES_REPOSITORY = f.getAbsolutePath();
}
}
// -1 -> do not show
// 0 -> show for reading
// 1 -> show for updating
protected int variableType(String varId, String[][] eas) throws Exception {
int type = -1;
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
String eaVal = eas[i][1];
if (eaVal.equals(varId)) {
if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
type = 1;
break;
} else if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_VIEW)) {
type = 0;
break;
}
}
}
}
return type;
}
protected static String[][] getExtAttribNVPairs(SharkConnection sc, WfActivity act)
throws Exception {
XPDLBrowser xpdlb = Shark.getInstance().getXPDLBrowser();
AdminMisc am = Shark.getInstance().getAdminMisc();
WMEntity ent = am.getActivityDefinitionInfo(sc.getSessionHandle(), act.container()
.key(), act.key());
return WMEntityUtilities.getExtAttribNVPairs(sc.getSessionHandle(), xpdlb, ent);
}
/* public static UserTransaction getUserTransaction() throws Exception {
String lookupName = p.getProperty("XaUserTransactionLookupName");
InitialContext ic = new InitialContext();
return (UserTransaction) ic.lookup(lookupName);
}
*/
}
class PackageFileFilter implements FileFilter {
public boolean accept(File pathname) {
return !pathname.isDirectory();
}
}
| true | true | public static String packageLoad(SharkConnection sc, String xpdlName) throws Exception {
return "";
/* if (_debug_){
System.err.println("#_packageLoad_#");
String realPath = EXTERNAL_PACKAGES_REPOSITORY + "/" + xpdlName;
PackageAdministration pa = Shark.getInstance().getPackageAdministration();
String pkgId = XMLUtil.getIdFromFile(realPath);
if (!pa.isPackageOpened(sc.getSessionHandle(), pkgId)) {
try {
pa.openPackage(sc.getSessionHandle(), realPath);
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), $1, "");
throw e;
}
}
return pkgId;
*/ }
public static void processStart(SharkConnection sc, String mgrName) throws Exception {
if (_debug_){
System.err.println("#_processStartName_#");
}
try {
if (!isProcessRunning(sc, mgrName)) {
WfProcessMgr mgr = sc.getProcessMgr(mgrName);
mgr.create_process(null).start();
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isProcessRunning(SharkConnection sc, String mgrName)
throws Exception {
System.err.println("#_isProcessRunning_# (" + mgrName + ")");
try {
WfProcessMgr pMgr = sc.getProcessMgr(mgrName);
WfProcessIterator pit = pMgr.get_iterator_process();
pit.set_query_expression("state.equals(\""
+ SharkConstants.STATE_OPEN_RUNNING + "\")");
if (_debug_) {
System.err.println("#_" + pit.how_many() + "_#");
System.err.println("#_" + pit.get_next_n_sequence(0).length + "_#");
}
return 0 < pit.get_next_n_sequence(0).length;
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void activityComplete(SharkConnection sConn, String activityId)
throws Exception {
try {
if (null != activityId) {
try {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
assignmentAccept(sConn, a);
}
a.activity().complete();
} catch (Exception e) {
throw e;
}
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isMine(SharkConnection sConn, String activityId)
throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
return isMine(sConn, a);
}
public static boolean isMine(SharkConnection sConn, WfAssignment a) throws Exception {
return a.get_accepted_status();
}
public static void assignmentAccept(SharkConnection sConn, String activityId)
throws Exception {
assignmentAccept(sConn, getAssignment(sConn, activityId));
}
private static void assignmentAccept(SharkConnection sConn, WfAssignment a)
throws Exception {
a.set_accepted_status(true);
}
public static WfAssignment getAssignment(SharkConnection sConn, String activityId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (activityId.equals(ar[i].activity().key())) {
return ar[i];
}
}
throw new Exception("Activity:"
+ activityId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
if (_debug_){
System.err.println("zvekseptsn");
}
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static WfAssignment getAssignmentByProcess(SharkConnection sConn, String processId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (processId.equals(ar[i].activity().container().key())) {
return ar[i];
}
}
throw new Exception("Activity for process:"
+ processId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void variableSet(SharkConnection sConn,
String activityId,
String vName,
String vValue) throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
throw new Exception("I don't own activity " + activityId);
}
Map _m = new HashMap();
Object c = a.activity().process_context().get(vName);
if (c instanceof Long) {
c = new Long(vValue);
} else if (c instanceof Boolean) {
c = Boolean.valueOf(vValue);
} else if (c instanceof Double) {
c = Double.valueOf(vValue);
} else {
c = vValue;
}
_m.put(vName, c);
a.activity().set_result(_m);
}
public static List getVariableData(SharkConnection sConn, WfActivity act)
throws Exception {
return getVariableData(sConn, act, true);
}
public static List getVariableData(SharkConnection sConn, WfActivity act, boolean onlyForUpdate)
throws Exception {
List ret = new ArrayList();
Map _m = act.process_context();
String[][] eas = getExtAttribNVPairs(sConn, act);
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
if (!onlyForUpdate || eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
String variableId = eas[i][1];
if (_m.containsKey(variableId)) {
Object c = _m.get(variableId);
if (c instanceof String || c instanceof Long || c instanceof Boolean || c instanceof Double) {
WorkflowVariable vd = new WorkflowVariable();
vd.setId(variableId);
vd.setToUpdate(eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE));
vd.setVal(c);
vd.setJavaClass(c.getClass());
WMEntity varEnt = Shark.getInstance().getAdminMisc().getVariableDefinitionInfoByUniqueProcessDefinitionName(
sConn.getSessionHandle(),
act.container().manager().name(),variableId);
String varName = variableId;
if (varEnt != null) {
varName = varEnt.getName();
if (varName == null || varName.equals("")) {
varName = variableId;
}
}
String varDesc = "";
if (varEnt != null) {
WMFilter filter = new WMFilter("Name", WMFilter.EQ, "Description");
filter.setFilterType(XPDLBrowser.SIMPLE_TYPE_XPDL);
varDesc = Shark.getInstance()
.getXPDLBrowser()
.listAttributes(sConn.getSessionHandle(),
varEnt,
filter,
false)
.getArray()[0].getValue().toString();
}
vd.setName(varName);
vd.setDescription(varDesc);
ret.add(vd);
}
}
}
}
}
return ret;
}
public static String[] xpdlsToLoad() throws Exception {
List packageFiles = getDefinedPackageFiles(EXTERNAL_PACKAGES_REPOSITORY, true);
Collection pfls = new ArrayList();
Iterator pfi = packageFiles.iterator();
Collections.sort(packageFiles);
while (pfi.hasNext()) {
File f = (File) pfi.next();
String fileName;
try {
fileName = f.getCanonicalPath();
} catch (Exception ex) {
fileName = f.getAbsolutePath();
}
fileName = fileName.substring(EXTERNAL_PACKAGES_REPOSITORY.length() + 1);
pfls.add(fileName);
}
String[] pfs = new String[pfls.size()];
pfls.toArray(pfs);
return pfs;
}
public static String[] processesToStart(SharkConnection sc) throws Exception {
WfProcessMgr[] a = sc.get_iterator_processmgr().get_next_n_sequence(0);
String[] ret = new String[a.length];
for (int i = 0; i < a.length; ++i) {
String n = a[i].name();
if (_debug_){
System.err.println("processName " + n);
}
ret[i] = n;
}
return ret;
}
/**
* Replace all occurence of forReplace with replaceWith in input string.
*
* @param input represents input string
* @param forReplace represents substring for replace
* @param replaceWith represents replaced string value
* @return new string with replaced values
*/
private static String replaceAll(String input, String forReplace, String replaceWith) {
if (input == null){
return null;
}
StringBuffer result = new StringBuffer();
boolean hasMore = true;
while (hasMore) {
int start = input.indexOf(forReplace);
int end = start + forReplace.length();
if (start != -1) {
result.append(input.substring(0, start) + replaceWith);
input = input.substring(end);
} else {
hasMore = false;
result.append(input);
}
}
if (result.toString().equals("")){
return input; // nothing is changed
}else{
return result.toString();
}
}
static List getDefinedPackageFiles(String repository, boolean traverse) {
File startingFolder = new File(repository);
List packageFiles = new ArrayList();
if (!startingFolder.exists()) {
LogUtil.info(JSPClientUtilities.class.getName(), "Repository " + startingFolder + " doesn't exist");
}
if (traverse) {
MiscUtilities.traverse(startingFolder, packageFiles, null);
} else {
packageFiles = Arrays.asList(startingFolder.listFiles(packageFileFilter));
}
return packageFiles;
}
public static void setPathToXPDLRepositoryFolder(String xpdlRepFolder)
throws Exception {
EXTERNAL_PACKAGES_REPOSITORY = xpdlRepFolder;
System.err.println(xpdlRepFolder);
File f = new File(xpdlRepFolder);
System.err.println(f);
if (!f.isAbsolute()) {
System.err.println("isn't absolute");
f = f.getAbsoluteFile();
}
System.err.println(f);
if (!f.exists()) {
throw new Exception("Folder " + xpdlRepFolder + " does not exist");
}
try {
EXTERNAL_PACKAGES_REPOSITORY = f.getCanonicalPath();
} catch (Exception ex) {
EXTERNAL_PACKAGES_REPOSITORY = f.getAbsolutePath();
}
}
// -1 -> do not show
// 0 -> show for reading
// 1 -> show for updating
protected int variableType(String varId, String[][] eas) throws Exception {
int type = -1;
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
String eaVal = eas[i][1];
if (eaVal.equals(varId)) {
if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
type = 1;
break;
} else if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_VIEW)) {
type = 0;
break;
}
}
}
}
return type;
}
protected static String[][] getExtAttribNVPairs(SharkConnection sc, WfActivity act)
throws Exception {
XPDLBrowser xpdlb = Shark.getInstance().getXPDLBrowser();
AdminMisc am = Shark.getInstance().getAdminMisc();
WMEntity ent = am.getActivityDefinitionInfo(sc.getSessionHandle(), act.container()
.key(), act.key());
return WMEntityUtilities.getExtAttribNVPairs(sc.getSessionHandle(), xpdlb, ent);
}
/* public static UserTransaction getUserTransaction() throws Exception {
String lookupName = p.getProperty("XaUserTransactionLookupName");
InitialContext ic = new InitialContext();
return (UserTransaction) ic.lookup(lookupName);
}
| public static String packageLoad(SharkConnection sc, String xpdlName) throws Exception {
return "";
/* if (_debug_){
System.err.println("#_packageLoad_#");
String realPath = EXTERNAL_PACKAGES_REPOSITORY + "/" + xpdlName;
PackageAdministration pa = Shark.getInstance().getPackageAdministration();
String pkgId = XMLUtil.getIdFromFile(realPath);
if (!pa.isPackageOpened(sc.getSessionHandle(), pkgId)) {
try {
pa.openPackage(sc.getSessionHandle(), realPath);
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), $1, "");
throw e;
}
}
return pkgId;
*/ }
public static void processStart(SharkConnection sc, String mgrName) throws Exception {
if (_debug_){
System.err.println("#_processStartName_#");
}
try {
if (!isProcessRunning(sc, mgrName)) {
WfProcessMgr mgr = sc.getProcessMgr(mgrName);
mgr.create_process(null).start();
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isProcessRunning(SharkConnection sc, String mgrName)
throws Exception {
System.err.println("#_isProcessRunning_# (" + mgrName + ")");
try {
WfProcessMgr pMgr = sc.getProcessMgr(mgrName);
WfProcessIterator pit = pMgr.get_iterator_process();
pit.set_query_expression("state.equals(\""
+ SharkConstants.STATE_OPEN_RUNNING + "\")");
if (_debug_) {
System.err.println("#_" + pit.how_many() + "_#");
System.err.println("#_" + pit.get_next_n_sequence(0).length + "_#");
}
return 0 < pit.get_next_n_sequence(0).length;
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void activityComplete(SharkConnection sConn, String activityId)
throws Exception {
try {
if (null != activityId) {
try {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
assignmentAccept(sConn, a);
}
a.activity().complete();
} catch (Exception e) {
throw e;
}
}
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static boolean isMine(SharkConnection sConn, String activityId)
throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
return isMine(sConn, a);
}
public static boolean isMine(SharkConnection sConn, WfAssignment a) throws Exception {
return a.get_accepted_status();
}
public static void assignmentAccept(SharkConnection sConn, String activityId)
throws Exception {
assignmentAccept(sConn, getAssignment(sConn, activityId));
}
private static void assignmentAccept(SharkConnection sConn, WfAssignment a)
throws Exception {
a.set_accepted_status(true);
}
public static WfAssignment getAssignment(SharkConnection sConn, String activityId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (activityId.equals(ar[i].activity().key())) {
return ar[i];
}
}
throw new Exception("Activity:"
+ activityId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
if (_debug_){
System.err.println("zvekseptsn");
}
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static WfAssignment getAssignmentByProcess(SharkConnection sConn, String processId)
throws Exception {
try {
WfAssignment[] ar = sConn.getResourceObject().get_sequence_work_item(0);
for (int i = 0; i < ar.length; ++i) {
if (processId.equals(ar[i].activity().container().key())) {
return ar[i];
}
}
throw new Exception("Activity for process:"
+ processId + " not found in "
+ sConn.getResourceObject().resource_key() + "'s worklist");
} catch (Exception e) {
LogUtil.error(JSPClientUtilities.class.getName(), e, "");
throw e;
}
}
public static void variableSet(SharkConnection sConn,
String activityId,
String vName,
String vValue) throws Exception {
WfAssignment a = getAssignment(sConn, activityId);
if (!isMine(sConn, a)){
throw new Exception("I don't own activity " + activityId);
}
Map _m = new HashMap();
Object c = a.activity().process_context().get(vName);
if (c instanceof Long) {
c = new Long(vValue);
} else if (c instanceof Boolean) {
c = Boolean.valueOf(vValue);
} else if (c instanceof Double) {
c = Double.valueOf(vValue);
} else {
c = vValue;
}
_m.put(vName, c);
a.activity().set_result(_m);
}
public static List getVariableData(SharkConnection sConn, WfActivity act)
throws Exception {
return getVariableData(sConn, act, true);
}
public static List getVariableData(SharkConnection sConn, WfActivity act, boolean onlyForUpdate)
throws Exception {
List ret = new ArrayList();
Map _m = act.process_context();
String[][] eas = getExtAttribNVPairs(sConn, act);
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
if (!onlyForUpdate || eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
String variableId = eas[i][1];
if (_m.containsKey(variableId)) {
Object c = _m.get(variableId);
// null check for Oracle DB to prevent missing workflow variable
if (c == null) {
c = "";
}
if (c instanceof String || c instanceof Long || c instanceof Boolean || c instanceof Double) {
WorkflowVariable vd = new WorkflowVariable();
vd.setId(variableId);
vd.setToUpdate(eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE));
vd.setVal(c);
vd.setJavaClass(c.getClass());
WMEntity varEnt = Shark.getInstance().getAdminMisc().getVariableDefinitionInfoByUniqueProcessDefinitionName(
sConn.getSessionHandle(),
act.container().manager().name(),variableId);
String varName = variableId;
if (varEnt != null) {
varName = varEnt.getName();
if (varName == null || varName.equals("")) {
varName = variableId;
}
}
String varDesc = "";
if (varEnt != null) {
WMFilter filter = new WMFilter("Name", WMFilter.EQ, "Description");
filter.setFilterType(XPDLBrowser.SIMPLE_TYPE_XPDL);
varDesc = Shark.getInstance()
.getXPDLBrowser()
.listAttributes(sConn.getSessionHandle(),
varEnt,
filter,
false)
.getArray()[0].getValue().toString();
}
vd.setName(varName);
vd.setDescription(varDesc);
ret.add(vd);
}
}
}
}
}
return ret;
}
public static String[] xpdlsToLoad() throws Exception {
List packageFiles = getDefinedPackageFiles(EXTERNAL_PACKAGES_REPOSITORY, true);
Collection pfls = new ArrayList();
Iterator pfi = packageFiles.iterator();
Collections.sort(packageFiles);
while (pfi.hasNext()) {
File f = (File) pfi.next();
String fileName;
try {
fileName = f.getCanonicalPath();
} catch (Exception ex) {
fileName = f.getAbsolutePath();
}
fileName = fileName.substring(EXTERNAL_PACKAGES_REPOSITORY.length() + 1);
pfls.add(fileName);
}
String[] pfs = new String[pfls.size()];
pfls.toArray(pfs);
return pfs;
}
public static String[] processesToStart(SharkConnection sc) throws Exception {
WfProcessMgr[] a = sc.get_iterator_processmgr().get_next_n_sequence(0);
String[] ret = new String[a.length];
for (int i = 0; i < a.length; ++i) {
String n = a[i].name();
if (_debug_){
System.err.println("processName " + n);
}
ret[i] = n;
}
return ret;
}
/**
* Replace all occurence of forReplace with replaceWith in input string.
*
* @param input represents input string
* @param forReplace represents substring for replace
* @param replaceWith represents replaced string value
* @return new string with replaced values
*/
private static String replaceAll(String input, String forReplace, String replaceWith) {
if (input == null){
return null;
}
StringBuffer result = new StringBuffer();
boolean hasMore = true;
while (hasMore) {
int start = input.indexOf(forReplace);
int end = start + forReplace.length();
if (start != -1) {
result.append(input.substring(0, start) + replaceWith);
input = input.substring(end);
} else {
hasMore = false;
result.append(input);
}
}
if (result.toString().equals("")){
return input; // nothing is changed
}else{
return result.toString();
}
}
static List getDefinedPackageFiles(String repository, boolean traverse) {
File startingFolder = new File(repository);
List packageFiles = new ArrayList();
if (!startingFolder.exists()) {
LogUtil.info(JSPClientUtilities.class.getName(), "Repository " + startingFolder + " doesn't exist");
}
if (traverse) {
MiscUtilities.traverse(startingFolder, packageFiles, null);
} else {
packageFiles = Arrays.asList(startingFolder.listFiles(packageFileFilter));
}
return packageFiles;
}
public static void setPathToXPDLRepositoryFolder(String xpdlRepFolder)
throws Exception {
EXTERNAL_PACKAGES_REPOSITORY = xpdlRepFolder;
System.err.println(xpdlRepFolder);
File f = new File(xpdlRepFolder);
System.err.println(f);
if (!f.isAbsolute()) {
System.err.println("isn't absolute");
f = f.getAbsoluteFile();
}
System.err.println(f);
if (!f.exists()) {
throw new Exception("Folder " + xpdlRepFolder + " does not exist");
}
try {
EXTERNAL_PACKAGES_REPOSITORY = f.getCanonicalPath();
} catch (Exception ex) {
EXTERNAL_PACKAGES_REPOSITORY = f.getAbsolutePath();
}
}
// -1 -> do not show
// 0 -> show for reading
// 1 -> show for updating
protected int variableType(String varId, String[][] eas) throws Exception {
int type = -1;
if (eas != null) {
for (int i = 0; i < eas.length; i++) {
String eaName = eas[i][0];
String eaVal = eas[i][1];
if (eaVal.equals(varId)) {
if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_UPDATE)) {
type = 1;
break;
} else if (eaName.equalsIgnoreCase(VARIABLE_TO_PROCESS_VIEW)) {
type = 0;
break;
}
}
}
}
return type;
}
protected static String[][] getExtAttribNVPairs(SharkConnection sc, WfActivity act)
throws Exception {
XPDLBrowser xpdlb = Shark.getInstance().getXPDLBrowser();
AdminMisc am = Shark.getInstance().getAdminMisc();
WMEntity ent = am.getActivityDefinitionInfo(sc.getSessionHandle(), act.container()
.key(), act.key());
return WMEntityUtilities.getExtAttribNVPairs(sc.getSessionHandle(), xpdlb, ent);
}
/* public static UserTransaction getUserTransaction() throws Exception {
String lookupName = p.getProperty("XaUserTransactionLookupName");
InitialContext ic = new InitialContext();
return (UserTransaction) ic.lookup(lookupName);
}
|
diff --git a/src/de/hpi/InformationSpreading/StaticHelpers.java b/src/de/hpi/InformationSpreading/StaticHelpers.java
index 8471fcb..f1a215b 100644
--- a/src/de/hpi/InformationSpreading/StaticHelpers.java
+++ b/src/de/hpi/InformationSpreading/StaticHelpers.java
@@ -1,49 +1,49 @@
package de.hpi.InformationSpreading;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
public class StaticHelpers {
public static String getContentFromUrl(String urlString) throws Exception {
InputStream inputStream = null;
String line;
StringBuilder httpContent = new StringBuilder();
URL url;
try {
url = new URL(urlString);
inputStream = url.openStream(); // throws an IOException
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(
inputStream));
BufferedReader reader = new BufferedReader(new InputStreamReader(
- dataInputStream));
+ dataInputStream, "UTF-8"));
while ((line = reader.readLine()) != null){
httpContent.append(line);
httpContent.append("\n");
}
} catch (MalformedURLException e) {
throw e;
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
}
return httpContent.toString();
}
}
| true | true | public static String getContentFromUrl(String urlString) throws Exception {
InputStream inputStream = null;
String line;
StringBuilder httpContent = new StringBuilder();
URL url;
try {
url = new URL(urlString);
inputStream = url.openStream(); // throws an IOException
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(
inputStream));
BufferedReader reader = new BufferedReader(new InputStreamReader(
dataInputStream));
while ((line = reader.readLine()) != null){
httpContent.append(line);
httpContent.append("\n");
}
} catch (MalformedURLException e) {
throw e;
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
}
return httpContent.toString();
}
| public static String getContentFromUrl(String urlString) throws Exception {
InputStream inputStream = null;
String line;
StringBuilder httpContent = new StringBuilder();
URL url;
try {
url = new URL(urlString);
inputStream = url.openStream(); // throws an IOException
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(
inputStream));
BufferedReader reader = new BufferedReader(new InputStreamReader(
dataInputStream, "UTF-8"));
while ((line = reader.readLine()) != null){
httpContent.append(line);
httpContent.append("\n");
}
} catch (MalformedURLException e) {
throw e;
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
}
return httpContent.toString();
}
|
diff --git a/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/MapTask.java b/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/MapTask.java
index abab62e45..23d487fac 100644
--- a/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/MapTask.java
+++ b/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/MapTask.java
@@ -1,111 +1,111 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.pact.runtime.task;
import eu.stratosphere.nephele.annotations.ForceCheckpoint;
import eu.stratosphere.nephele.execution.Environment;
import eu.stratosphere.pact.common.stubs.Collector;
import eu.stratosphere.pact.common.stubs.MapStub;
import eu.stratosphere.pact.common.type.PactRecord;
import eu.stratosphere.pact.common.util.MutableObjectIterator;
import eu.stratosphere.pact.runtime.task.util.OutputCollector;
/**
* Map task which is executed by a Nephele task manager. The task has a single
* input and one or multiple outputs. It is provided with a MapStub
* implementation.
* <p>
* The MapTask creates an iterator over all key-value pairs of its input and hands that
* to the <code>map()</code> method of the MapStub.
*
* @see MapStub
* @author Fabian Hueske
* @author Stephan Ewen
*/
public class MapTask extends AbstractPactTask<MapStub>
{
/* (non-Javadoc)
* @see eu.stratosphere.pact.runtime.task.AbstractPactTask#getNumberOfInputs()
*/
@Override
public int getNumberOfInputs() {
return 1;
}
/* (non-Javadoc)
* @see eu.stratosphere.pact.runtime.task.AbstractPactTask#getStubType()
*/
@Override
public Class<MapStub> getStubType() {
return MapStub.class;
}
/* (non-Javadoc)
* @see eu.stratosphere.pact.runtime.task.AbstractPactTask#prepare()
*/
@Override
public void prepare() throws Exception {
// nothing, since a mapper does not need any preparation
}
/* (non-Javadoc)
* @see eu.stratosphere.pact.runtime.task.AbstractPactTask#run()
*/
@Override
public void run() throws Exception
{
// cache references on the stack
final MutableObjectIterator<PactRecord> input = this.inputs[0];
final MapStub stub = this.stub;
final Collector output = this.output;
final PactRecord record = new PactRecord();
// DW: Start to temporary code
int count = 0;
long consumedPactRecordsInBytes = 0L;
final Environment env = getEnvironment();
final OutputCollector oc = (OutputCollector) output;
// DW: End of temporary code
if(this.stub.getClass().isAnnotationPresent(ForceCheckpoint.class)){
env.isForced(this.stub.getClass().getAnnotation(ForceCheckpoint.class).checkpoint());
}
while (this.running && input.next(record)) {
// DW: Start to temporary code
- consumedPactRecordsInBytes =+ record.getBinaryLength();
+ consumedPactRecordsInBytes += record.getBinaryLength();
// DW: End of temporary code
stub.map(record, output);
// DW: Start to temporary code
if(++count == 10) {
env.reportPACTDataStatistics(consumedPactRecordsInBytes,
oc.getCollectedPactRecordsInBytes());
consumedPactRecordsInBytes = 0L;
count = 0;
}
// DW: End of temporary code
}
}
/* (non-Javadoc)
* @see eu.stratosphere.pact.runtime.task.AbstractPactTask#cleanup()
*/
@Override
public void cleanup() throws Exception {
// mappers need no cleanup, since no strategies are used.
}
}
| true | true | public void run() throws Exception
{
// cache references on the stack
final MutableObjectIterator<PactRecord> input = this.inputs[0];
final MapStub stub = this.stub;
final Collector output = this.output;
final PactRecord record = new PactRecord();
// DW: Start to temporary code
int count = 0;
long consumedPactRecordsInBytes = 0L;
final Environment env = getEnvironment();
final OutputCollector oc = (OutputCollector) output;
// DW: End of temporary code
if(this.stub.getClass().isAnnotationPresent(ForceCheckpoint.class)){
env.isForced(this.stub.getClass().getAnnotation(ForceCheckpoint.class).checkpoint());
}
while (this.running && input.next(record)) {
// DW: Start to temporary code
consumedPactRecordsInBytes =+ record.getBinaryLength();
// DW: End of temporary code
stub.map(record, output);
// DW: Start to temporary code
if(++count == 10) {
env.reportPACTDataStatistics(consumedPactRecordsInBytes,
oc.getCollectedPactRecordsInBytes());
consumedPactRecordsInBytes = 0L;
count = 0;
}
// DW: End of temporary code
}
}
| public void run() throws Exception
{
// cache references on the stack
final MutableObjectIterator<PactRecord> input = this.inputs[0];
final MapStub stub = this.stub;
final Collector output = this.output;
final PactRecord record = new PactRecord();
// DW: Start to temporary code
int count = 0;
long consumedPactRecordsInBytes = 0L;
final Environment env = getEnvironment();
final OutputCollector oc = (OutputCollector) output;
// DW: End of temporary code
if(this.stub.getClass().isAnnotationPresent(ForceCheckpoint.class)){
env.isForced(this.stub.getClass().getAnnotation(ForceCheckpoint.class).checkpoint());
}
while (this.running && input.next(record)) {
// DW: Start to temporary code
consumedPactRecordsInBytes += record.getBinaryLength();
// DW: End of temporary code
stub.map(record, output);
// DW: Start to temporary code
if(++count == 10) {
env.reportPACTDataStatistics(consumedPactRecordsInBytes,
oc.getCollectedPactRecordsInBytes());
consumedPactRecordsInBytes = 0L;
count = 0;
}
// DW: End of temporary code
}
}
|
diff --git a/trunk/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java b/trunk/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java
index 96e03eb3..2c998414 100644
--- a/trunk/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java
+++ b/trunk/kernel-impl/src/main/java/org/sakaiproject/content/impl/CollectionAccessFormatter.java
@@ -1,292 +1,292 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.content.impl;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
/**
* <p>
* CollectionAccessFormatter is formatter for collection access.
* </p>
*/
@SuppressWarnings("deprecation")
public class CollectionAccessFormatter
{
private static final Log M_log = LogFactory.getLog(CollectionAccessFormatter.class);
/**
* Format the collection as an HTML display.
*/
@SuppressWarnings({ "unchecked" })
public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res,
ResourceLoader rb, String accessPointTrue, String accessPointFalse)
{
// do not allow directory listings for /attachments and its subfolders
if(ContentHostingService.isAttachmentResource(x.getId()))
{
try
{
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
catch ( java.io.IOException e )
{
return;
}
}
PrintWriter out = null;
// don't set the writer until we verify that
// getallresources is going to work.
boolean printedHeader = false;
boolean printedDiv = false;
try
{
res.setContentType("text/html; charset=UTF-8");
out = res.getWriter();
ResourceProperties pl = x.getProperties();
String webappRoot = ServerConfigurationService.getServerUrl();
String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
String skinName = "default";
String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR);
// Is this a site folder (Resources or Dropbox)? If so, get the site skin
if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) ||
x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) {
if (parts.length > 1) {
String siteId = parts[1];
try {
Site site = SiteService.getSite(siteId);
if (site.getSkin() != null) {
skinName = site.getSkin();
}
} catch (IdUnusedException e) {
// Cannot get site - ignore it
}
}
}
// Output the headers
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html><head>");
out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle",
new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>");
out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName +
"/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">");
out.println("<script src=\"" + webappRoot
+ "/library/js/jquery.js\" type=\"text/javascript\">");
out.println("</script>");
out.println("</head><body class=\"specialLink\">");
- out.println("<script type=\"text/javascript\">$(document).ready(function(){resizeFrame();function resizeFrame(){if (window.name != \"\") {var frame = parent.document.getElementById(window.name);if (frame) {var clientH = document.body.clientHeight + 10;$(frame).height(clientH);}}}jQuery.fn.fadeToggle = function(speed, easing, callback){return this.animate({opacity: \'toggle\'}, speed, easing, callback);};if ($(\'.textPanel\').size() < 1){$(\'a#toggler\').hide();}$(\'a#toggler\').click(function(){$(\'.textPanel\').fadeToggle(\'1000\', \'\', \'resizeFrame\');});\n$(\'.file a\').each(function (i){\n$(this).addClass(getFileExtension($(this).attr(\'href\')));\n})\nfunction getFileExtension(filename)\n{\nvar ext = /^.+\\.([^.]+)$/.exec(filename);\nreturn ext == null ? \"\" : ext[1].toLowerCase();\n}\n});</script>");
+ out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>");
out.println("<div class=\"directoryIndex\">");
// for content listing it's best to use a real title
out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>");
out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>");
String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION);
if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>");
out.println("<ul>");
out.println("<li style=\"display:none\">");
out.println("</li>");
printedHeader = true;
printedDiv = true;
if (parts.length > 2)
{
// go up a level
out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>");
}
// Sort the collection items
List<ContentEntity> members = x.getMemberResources();
boolean hasCustomSort = false;
try {
hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
} catch (Exception e) {
// use false that's already there
}
if (hasCustomSort)
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true));
else
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true));
// Iterate through content items
URI baseUri = new URI(x.getUrl());
for (ContentEntity content : members) {
ResourceProperties properties = content.getProperties();
boolean isCollection = content.isCollection();
String xs = content.getId();
String contentUrl = content.getUrl();
// These both perform the same check in the implementation but we should observe the API.
// This also checks to see if a resource is hidden or time limited.
if ( isCollection) {
if (!ContentHostingService.allowGetCollection(xs)) {
continue;
}
} else {
if (!ContentHostingService.allowGetResource(xs)) {
continue;
}
}
if (isCollection)
{
xs = xs.substring(0, xs.length() - 1);
xs = xs.substring(xs.lastIndexOf('/') + 1) + '/';
}
else
{
xs = xs.substring(xs.lastIndexOf('/') + 1);
}
try
{
// Relativize the URL (canonical item URL relative to canonical collection URL).
// Inter alias this will preserve alternate access paths via aliases, e.g. /web/
URI contentUri = new URI(contentUrl);
URI relativeUri = baseUri.relativize(contentUri);
contentUrl = relativeUri.toString();
if (isCollection)
{
// Folder
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + desc + "</div>";
out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
else
{
// File
/*
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
ContentResource contentResource = (ContentResource) content;
long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1;
String filetype = contentResource.getContentType();
*/
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>";
String resourceType = content.getResourceType().replace('.', '_');
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\""
+ resourceType+"\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
}
catch (Exception ignore)
{
// TODO - what types of failures are being caught here?
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs)
+ "</a></li>");
}
}
}
catch (Exception e)
{
M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e);
}
if (out != null && printedHeader)
{
out.println("</ul>");
if (printedDiv) out.println("</div>");
out.println("</body></html>");
}
}
protected static User getUserProperty(ResourceProperties props, String name)
{
String id = props.getProperty(name);
if (id != null)
{
try
{
return UserDirectoryService.getUser(id);
}
catch (UserNotDefinedException e)
{
}
}
return null;
}
}
| true | true | public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res,
ResourceLoader rb, String accessPointTrue, String accessPointFalse)
{
// do not allow directory listings for /attachments and its subfolders
if(ContentHostingService.isAttachmentResource(x.getId()))
{
try
{
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
catch ( java.io.IOException e )
{
return;
}
}
PrintWriter out = null;
// don't set the writer until we verify that
// getallresources is going to work.
boolean printedHeader = false;
boolean printedDiv = false;
try
{
res.setContentType("text/html; charset=UTF-8");
out = res.getWriter();
ResourceProperties pl = x.getProperties();
String webappRoot = ServerConfigurationService.getServerUrl();
String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
String skinName = "default";
String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR);
// Is this a site folder (Resources or Dropbox)? If so, get the site skin
if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) ||
x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) {
if (parts.length > 1) {
String siteId = parts[1];
try {
Site site = SiteService.getSite(siteId);
if (site.getSkin() != null) {
skinName = site.getSkin();
}
} catch (IdUnusedException e) {
// Cannot get site - ignore it
}
}
}
// Output the headers
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html><head>");
out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle",
new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>");
out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName +
"/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">");
out.println("<script src=\"" + webappRoot
+ "/library/js/jquery.js\" type=\"text/javascript\">");
out.println("</script>");
out.println("</head><body class=\"specialLink\">");
out.println("<script type=\"text/javascript\">$(document).ready(function(){resizeFrame();function resizeFrame(){if (window.name != \"\") {var frame = parent.document.getElementById(window.name);if (frame) {var clientH = document.body.clientHeight + 10;$(frame).height(clientH);}}}jQuery.fn.fadeToggle = function(speed, easing, callback){return this.animate({opacity: \'toggle\'}, speed, easing, callback);};if ($(\'.textPanel\').size() < 1){$(\'a#toggler\').hide();}$(\'a#toggler\').click(function(){$(\'.textPanel\').fadeToggle(\'1000\', \'\', \'resizeFrame\');});\n$(\'.file a\').each(function (i){\n$(this).addClass(getFileExtension($(this).attr(\'href\')));\n})\nfunction getFileExtension(filename)\n{\nvar ext = /^.+\\.([^.]+)$/.exec(filename);\nreturn ext == null ? \"\" : ext[1].toLowerCase();\n}\n});</script>");
out.println("<div class=\"directoryIndex\">");
// for content listing it's best to use a real title
out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>");
out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>");
String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION);
if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>");
out.println("<ul>");
out.println("<li style=\"display:none\">");
out.println("</li>");
printedHeader = true;
printedDiv = true;
if (parts.length > 2)
{
// go up a level
out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>");
}
// Sort the collection items
List<ContentEntity> members = x.getMemberResources();
boolean hasCustomSort = false;
try {
hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
} catch (Exception e) {
// use false that's already there
}
if (hasCustomSort)
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true));
else
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true));
// Iterate through content items
URI baseUri = new URI(x.getUrl());
for (ContentEntity content : members) {
ResourceProperties properties = content.getProperties();
boolean isCollection = content.isCollection();
String xs = content.getId();
String contentUrl = content.getUrl();
// These both perform the same check in the implementation but we should observe the API.
// This also checks to see if a resource is hidden or time limited.
if ( isCollection) {
if (!ContentHostingService.allowGetCollection(xs)) {
continue;
}
} else {
if (!ContentHostingService.allowGetResource(xs)) {
continue;
}
}
if (isCollection)
{
xs = xs.substring(0, xs.length() - 1);
xs = xs.substring(xs.lastIndexOf('/') + 1) + '/';
}
else
{
xs = xs.substring(xs.lastIndexOf('/') + 1);
}
try
{
// Relativize the URL (canonical item URL relative to canonical collection URL).
// Inter alias this will preserve alternate access paths via aliases, e.g. /web/
URI contentUri = new URI(contentUrl);
URI relativeUri = baseUri.relativize(contentUri);
contentUrl = relativeUri.toString();
if (isCollection)
{
// Folder
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + desc + "</div>";
out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
else
{
// File
/*
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
ContentResource contentResource = (ContentResource) content;
long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1;
String filetype = contentResource.getContentType();
*/
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>";
String resourceType = content.getResourceType().replace('.', '_');
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\""
+ resourceType+"\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
}
catch (Exception ignore)
{
// TODO - what types of failures are being caught here?
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs)
+ "</a></li>");
}
}
}
catch (Exception e)
{
M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e);
}
if (out != null && printedHeader)
{
out.println("</ul>");
if (printedDiv) out.println("</div>");
out.println("</body></html>");
}
}
| public static void format(ContentCollection x, Reference ref, HttpServletRequest req, HttpServletResponse res,
ResourceLoader rb, String accessPointTrue, String accessPointFalse)
{
// do not allow directory listings for /attachments and its subfolders
if(ContentHostingService.isAttachmentResource(x.getId()))
{
try
{
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
catch ( java.io.IOException e )
{
return;
}
}
PrintWriter out = null;
// don't set the writer until we verify that
// getallresources is going to work.
boolean printedHeader = false;
boolean printedDiv = false;
try
{
res.setContentType("text/html; charset=UTF-8");
out = res.getWriter();
ResourceProperties pl = x.getProperties();
String webappRoot = ServerConfigurationService.getServerUrl();
String skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
String skinName = "default";
String[] parts= StringUtils.split(x.getId(), Entity.SEPARATOR);
// Is this a site folder (Resources or Dropbox)? If so, get the site skin
if (x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_SITE) ||
x.getId().startsWith(org.sakaiproject.content.api.ContentHostingService.COLLECTION_DROPBOX)) {
if (parts.length > 1) {
String siteId = parts[1];
try {
Site site = SiteService.getSite(siteId);
if (site.getSkin() != null) {
skinName = site.getSkin();
}
} catch (IdUnusedException e) {
// Cannot get site - ignore it
}
}
}
// Output the headers
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html><head>");
out.println("<title>" + rb.getFormattedMessage("colformat.pagetitle",
new Object[]{ Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME))}) + "</title>");
out.println("<link href=\"" + webappRoot + skinRepo+ "/" + skinName +
"/access.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\">");
out.println("<script src=\"" + webappRoot
+ "/library/js/jquery.js\" type=\"text/javascript\">");
out.println("</script>");
out.println("</head><body class=\"specialLink\">");
out.println("<script type=\"text/javascript\" src=\"/library/js/access.js\"></script>");
out.println("<div class=\"directoryIndex\">");
// for content listing it's best to use a real title
out.println("<h3>" + Validator.escapeHtml(pl.getProperty(ResourceProperties.PROP_DISPLAY_NAME)) + "</h3>");
out.println("<p id=\"toggle\"><a id=\"toggler\" href=\"#\">" + rb.getString("colformat.showhide") + "</a></p>");
String folderdesc = pl.getProperty(ResourceProperties.PROP_DESCRIPTION);
if (folderdesc != null && !folderdesc.equals("")) out.println("<div class=\"textPanel\">" + folderdesc + "</div>");
out.println("<ul>");
out.println("<li style=\"display:none\">");
out.println("</li>");
printedHeader = true;
printedDiv = true;
if (parts.length > 2)
{
// go up a level
out.println("<li class=\"upfolder\"><a href=\"../\"><img src=\"/library/image/sakai/folder-up.gif\" alt=\"" + rb.getString("colformat.uplevel.alttext") + "\"/>" + rb.getString("colformat.uplevel") + "</a></li>");
}
// Sort the collection items
List<ContentEntity> members = x.getMemberResources();
boolean hasCustomSort = false;
try {
hasCustomSort = x.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
} catch (Exception e) {
// use false that's already there
}
if (hasCustomSort)
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true));
else
Collections.sort(members, new ContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true));
// Iterate through content items
URI baseUri = new URI(x.getUrl());
for (ContentEntity content : members) {
ResourceProperties properties = content.getProperties();
boolean isCollection = content.isCollection();
String xs = content.getId();
String contentUrl = content.getUrl();
// These both perform the same check in the implementation but we should observe the API.
// This also checks to see if a resource is hidden or time limited.
if ( isCollection) {
if (!ContentHostingService.allowGetCollection(xs)) {
continue;
}
} else {
if (!ContentHostingService.allowGetResource(xs)) {
continue;
}
}
if (isCollection)
{
xs = xs.substring(0, xs.length() - 1);
xs = xs.substring(xs.lastIndexOf('/') + 1) + '/';
}
else
{
xs = xs.substring(xs.lastIndexOf('/') + 1);
}
try
{
// Relativize the URL (canonical item URL relative to canonical collection URL).
// Inter alias this will preserve alternate access paths via aliases, e.g. /web/
URI contentUri = new URI(contentUrl);
URI relativeUri = baseUri.relativize(contentUri);
contentUrl = relativeUri.toString();
if (isCollection)
{
// Folder
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + desc + "</div>";
out.println("<li class=\"folder\"><a href=\"" + contentUrl + "\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
else
{
// File
/*
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
ContentResource contentResource = (ContentResource) content;
long filesize = ((contentResource.getContentLength() - 1) / 1024) + 1;
String filetype = contentResource.getContentType();
*/
String desc = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
if ((desc == null) || desc.equals(""))
desc = "";
else
desc = "<div class=\"textPanel\">" + Validator.escapeHtml(desc) + "</div>";
String resourceType = content.getResourceType().replace('.', '_');
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank class=\""
+ resourceType+"\">"
+ Validator.escapeHtml(properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME))
+ "</a>" + desc + "</li>");
}
}
catch (Exception ignore)
{
// TODO - what types of failures are being caught here?
out.println("<li class=\"file\"><a href=\"" + contentUrl + "\" target=_blank>" + Validator.escapeHtml(xs)
+ "</a></li>");
}
}
}
catch (Exception e)
{
M_log.warn("Problem formatting HTML for collection: "+ x.getId(), e);
}
if (out != null && printedHeader)
{
out.println("</ul>");
if (printedDiv) out.println("</div>");
out.println("</body></html>");
}
}
|
diff --git a/src/minecraft/org/spoutcraft/client/gui/chat/GuiChatSettings.java b/src/minecraft/org/spoutcraft/client/gui/chat/GuiChatSettings.java
index fbecd37e..f3971692 100644
--- a/src/minecraft/org/spoutcraft/client/gui/chat/GuiChatSettings.java
+++ b/src/minecraft/org/spoutcraft/client/gui/chat/GuiChatSettings.java
@@ -1,155 +1,160 @@
package org.spoutcraft.client.gui.chat;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.src.GuiScreen;
import org.spoutcraft.client.SpoutClient;
import org.spoutcraft.client.config.ConfigReader;
import org.spoutcraft.client.gui.GuiSpoutScreen;
import org.spoutcraft.spoutcraftapi.Spoutcraft;
import org.spoutcraft.spoutcraftapi.addon.Addon;
import org.spoutcraft.spoutcraftapi.gui.Button;
import org.spoutcraft.spoutcraftapi.gui.ChatTextBox;
import org.spoutcraft.spoutcraftapi.gui.CheckBox;
import org.spoutcraft.spoutcraftapi.gui.GenericButton;
import org.spoutcraft.spoutcraftapi.gui.GenericCheckBox;
import org.spoutcraft.spoutcraftapi.gui.GenericLabel;
import org.spoutcraft.spoutcraftapi.gui.Label;
public class GuiChatSettings extends GuiSpoutScreen {
private GuiScreen parent;
private CheckBox checkShowMentions, checkShowJoins, checkShowColors, checkCloseOnDamage, checkGrabMouse, checkIgnorePeople, checkParseRegex;
private Button buttonAdvancedMentions, buttonConfigureIgnores, buttonDone;
private Label title;
public GuiChatSettings(GuiScreen parent) {
this.parent = parent;
}
@Override
protected void createInstances() {
title = new GenericLabel("Chat Options");
checkShowMentions = new GenericCheckBox("Show mentions");
checkShowMentions.setTooltip("Highlight chat messages where your name or words you specified are mentioned.");
checkShowMentions.setChecked(ConfigReader.highlightMentions);
checkShowJoins = new GenericCheckBox("Show joins");
checkShowJoins.setTooltip("Show player join messages when a new player logs in.");
checkShowJoins.setChecked(ConfigReader.showJoinMessages);
checkShowColors = new GenericCheckBox("Show colors");
checkShowColors.setTooltip("Shows the notation for chat color.");
checkShowColors.setChecked(ConfigReader.showChatColors);
checkCloseOnDamage = new GenericCheckBox("Close chat window on damage");
checkCloseOnDamage.setTooltip("Close the chat screen if your player is damaged.\nYour message will be saved.");
checkCloseOnDamage.setChecked(ConfigReader.showDamageAlerts);
checkGrabMouse = new GenericCheckBox("Chat window grabs mouse");
checkGrabMouse.setTooltip("Opening the chat screen grabs the mouse.\nON, players can not look around - default behavior\nOFF, players can look and pan the screen during chat.");
checkGrabMouse.setChecked(ConfigReader.chatGrabsMouse);
checkIgnorePeople = new GenericCheckBox("Ignore List");
checkIgnorePeople.setTooltip("This will prevent displaying chat messages from players in your ignore list");
checkIgnorePeople.setChecked(ConfigReader.ignorePeople);
checkParseRegex = new GenericCheckBox("Use regex");
checkParseRegex.setTooltip("Parse highlighted words and ignored players using regular expression syntax");
checkParseRegex.setChecked(ConfigReader.chatUsesRegex);
buttonAdvancedMentions = new GenericButton("Advanced options");
buttonAdvancedMentions.setTooltip("Configure words to be highlighted");
buttonConfigureIgnores = new GenericButton("Configure");
buttonConfigureIgnores.setTooltip("Configure people to ignore messages from");
buttonDone = new GenericButton("Done");
Addon spoutcraft = Spoutcraft.getAddonManager().getAddon("Spoutcraft");
getScreen().attachWidgets(spoutcraft, title, checkShowColors, checkShowJoins, checkShowMentions, checkCloseOnDamage, checkGrabMouse, checkIgnorePeople, buttonAdvancedMentions, buttonConfigureIgnores, buttonDone, checkParseRegex);
}
@Override
protected void layoutWidgets() {
title.setX(width / 2 - SpoutClient.getHandle().fontRenderer.getStringWidth(title.getText()) / 2);
title.setY(12);
int top = title.getY() + 13;
checkShowMentions.setGeometry(5, top, 200, 20);
buttonAdvancedMentions.setGeometry(width - 205, top, 150, 20);
top += 22;
checkShowJoins.setGeometry(5, top, 200, 20);
top += 22;
checkShowColors.setGeometry(5, top, 200, 20);
top += 22;
checkCloseOnDamage.setGeometry(5, top, 200, 20);
top += 22;
checkGrabMouse.setGeometry(5, top, 200, 20);
top += 22;
checkIgnorePeople.setGeometry(5, top, 200, 20);
buttonConfigureIgnores.setGeometry(width - 205, top, 150, 20);
top += 22;
checkParseRegex.setGeometry(5, top, 200, 20);
top += 22;
buttonDone.setGeometry(width - 205, height - 25, 200, 20);
}
@Override
protected void buttonClicked(Button btn) {
- final ChatTextBox chat = Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox();
+ final ChatTextBox chat;
+ if(Spoutcraft.getActivePlayer() != null) {
+ chat = Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox();
+ } else {
+ chat = null;
+ }
if(btn == buttonDone) {
mc.displayGuiScreen(parent);
return;
}
Runnable save = new Runnable() {
@Override
public void run() {
SpoutClient.getInstance().getChatManager().save();
chat.reparse();
}
};
boolean regex = ConfigReader.chatUsesRegex;
if(btn == buttonAdvancedMentions) {
GuiListEdit editor = new GuiListEdit(save, "Edit word highlight list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().wordHighlight);
mc.displayGuiScreen(editor);
return;
}
if(btn == buttonConfigureIgnores) {
GuiListEdit editor = new GuiListEdit(save, "Edit people ignore list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().ignorePeople);
mc.displayGuiScreen(editor);
return;
}
if(btn == checkShowMentions) {
ConfigReader.highlightMentions = checkShowMentions.isChecked();
}
if(btn == checkShowJoins) {
ConfigReader.showJoinMessages = checkShowJoins.isChecked();
}
if(btn == checkShowColors) {
ConfigReader.showChatColors = checkShowColors.isChecked();
}
if(btn == checkCloseOnDamage) {
ConfigReader.showDamageAlerts = checkCloseOnDamage.isChecked();
}
if(btn == checkIgnorePeople) {
ConfigReader.ignorePeople = checkIgnorePeople.isChecked();
}
if(btn == checkGrabMouse) {
ConfigReader.chatGrabsMouse = checkGrabMouse.isChecked();
}
if(btn == checkParseRegex) {
ConfigReader.chatUsesRegex = checkParseRegex.isChecked();
chat.reparse();
}
ConfigReader.write();
}
}
| true | true | protected void buttonClicked(Button btn) {
final ChatTextBox chat = Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox();
if(btn == buttonDone) {
mc.displayGuiScreen(parent);
return;
}
Runnable save = new Runnable() {
@Override
public void run() {
SpoutClient.getInstance().getChatManager().save();
chat.reparse();
}
};
boolean regex = ConfigReader.chatUsesRegex;
if(btn == buttonAdvancedMentions) {
GuiListEdit editor = new GuiListEdit(save, "Edit word highlight list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().wordHighlight);
mc.displayGuiScreen(editor);
return;
}
if(btn == buttonConfigureIgnores) {
GuiListEdit editor = new GuiListEdit(save, "Edit people ignore list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().ignorePeople);
mc.displayGuiScreen(editor);
return;
}
if(btn == checkShowMentions) {
ConfigReader.highlightMentions = checkShowMentions.isChecked();
}
if(btn == checkShowJoins) {
ConfigReader.showJoinMessages = checkShowJoins.isChecked();
}
if(btn == checkShowColors) {
ConfigReader.showChatColors = checkShowColors.isChecked();
}
if(btn == checkCloseOnDamage) {
ConfigReader.showDamageAlerts = checkCloseOnDamage.isChecked();
}
if(btn == checkIgnorePeople) {
ConfigReader.ignorePeople = checkIgnorePeople.isChecked();
}
if(btn == checkGrabMouse) {
ConfigReader.chatGrabsMouse = checkGrabMouse.isChecked();
}
if(btn == checkParseRegex) {
ConfigReader.chatUsesRegex = checkParseRegex.isChecked();
chat.reparse();
}
ConfigReader.write();
}
| protected void buttonClicked(Button btn) {
final ChatTextBox chat;
if(Spoutcraft.getActivePlayer() != null) {
chat = Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox();
} else {
chat = null;
}
if(btn == buttonDone) {
mc.displayGuiScreen(parent);
return;
}
Runnable save = new Runnable() {
@Override
public void run() {
SpoutClient.getInstance().getChatManager().save();
chat.reparse();
}
};
boolean regex = ConfigReader.chatUsesRegex;
if(btn == buttonAdvancedMentions) {
GuiListEdit editor = new GuiListEdit(save, "Edit word highlight list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().wordHighlight);
mc.displayGuiScreen(editor);
return;
}
if(btn == buttonConfigureIgnores) {
GuiListEdit editor = new GuiListEdit(save, "Edit people ignore list", regex?"You can use regular expressions.":"", this, SpoutClient.getInstance().getChatManager().ignorePeople);
mc.displayGuiScreen(editor);
return;
}
if(btn == checkShowMentions) {
ConfigReader.highlightMentions = checkShowMentions.isChecked();
}
if(btn == checkShowJoins) {
ConfigReader.showJoinMessages = checkShowJoins.isChecked();
}
if(btn == checkShowColors) {
ConfigReader.showChatColors = checkShowColors.isChecked();
}
if(btn == checkCloseOnDamage) {
ConfigReader.showDamageAlerts = checkCloseOnDamage.isChecked();
}
if(btn == checkIgnorePeople) {
ConfigReader.ignorePeople = checkIgnorePeople.isChecked();
}
if(btn == checkGrabMouse) {
ConfigReader.chatGrabsMouse = checkGrabMouse.isChecked();
}
if(btn == checkParseRegex) {
ConfigReader.chatUsesRegex = checkParseRegex.isChecked();
chat.reparse();
}
ConfigReader.write();
}
|
diff --git a/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/changelog/JGitChangeLogCommand.java b/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/changelog/JGitChangeLogCommand.java
index 624bbbd..fdbdd39 100644
--- a/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/changelog/JGitChangeLogCommand.java
+++ b/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/changelog/JGitChangeLogCommand.java
@@ -1,106 +1,106 @@
package org.apache.maven.scm.provider.git.jgit.command.changelog;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.scm.ScmBranch;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmVersion;
import org.apache.maven.scm.command.changelog.AbstractChangeLogCommand;
import org.apache.maven.scm.command.changelog.ChangeLogScmResult;
import org.apache.maven.scm.command.changelog.ChangeLogSet;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.git.GitChangeSet;
import org.apache.maven.scm.provider.git.command.GitCommand;
import org.spearce.jgit.simple.ChangeEntry;
import org.spearce.jgit.simple.SimpleRepository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Mark Struberg</a>
* @version $Id: JGitChangeLogCommand.java $
*/
public class JGitChangeLogCommand
extends AbstractChangeLogCommand
implements GitCommand
{
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss Z";
/** {@inheritDoc} */
protected ChangeLogScmResult executeChangeLogCommand( ScmProviderRepository repo, ScmFileSet fileSet,
ScmVersion startVersion, ScmVersion endVersion,
String datePattern )
throws ScmException
{
return executeChangeLogCommand( repo, fileSet, null, null, null, datePattern, startVersion, endVersion );
}
/** {@inheritDoc} */
protected ChangeLogScmResult executeChangeLogCommand( ScmProviderRepository repo, ScmFileSet fileSet,
Date startDate, Date endDate, ScmBranch branch,
String datePattern )
throws ScmException
{
return executeChangeLogCommand( repo, fileSet, startDate, endDate, branch, datePattern, null, null );
}
protected ChangeLogScmResult executeChangeLogCommand( ScmProviderRepository repo, ScmFileSet fileSet,
Date startDate, Date endDate, ScmBranch branch,
String datePattern, ScmVersion startVersion,
ScmVersion endVersion )
throws ScmException
{
try
{
SimpleRepository srep = SimpleRepository.existing( fileSet.getBasedir() );
List<GitChangeSet> modifications = new ArrayList<GitChangeSet>();
String startRev = startVersion != null ? startVersion.getName() : null;
String endRev = endVersion != null ? endVersion.getName() : null;
List<ChangeEntry> gitChanges = srep.whatchanged( null, startRev, endRev, startDate, endDate, -1 );
for ( ChangeEntry change : gitChanges ) {
GitChangeSet scmChange = new GitChangeSet();
scmChange.setAuthor( change.getAuthorName() );
scmChange.setComment( change.getBody() );
scmChange.setDate( change.getAuthorDate() );
//X TODO scmChange.setFiles( change.get )
modifications.add( scmChange );
}
ChangeLogSet changeLogSet = new ChangeLogSet( modifications, startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( "JGit changelog", changeLogSet );
}
catch ( Exception e )
{
- throw new ScmException("JGit changelog failure!", e );
+ throw new ScmException( "JGit changelog failure!", e );
}
}
}
| true | true | protected ChangeLogScmResult executeChangeLogCommand( ScmProviderRepository repo, ScmFileSet fileSet,
Date startDate, Date endDate, ScmBranch branch,
String datePattern, ScmVersion startVersion,
ScmVersion endVersion )
throws ScmException
{
try
{
SimpleRepository srep = SimpleRepository.existing( fileSet.getBasedir() );
List<GitChangeSet> modifications = new ArrayList<GitChangeSet>();
String startRev = startVersion != null ? startVersion.getName() : null;
String endRev = endVersion != null ? endVersion.getName() : null;
List<ChangeEntry> gitChanges = srep.whatchanged( null, startRev, endRev, startDate, endDate, -1 );
for ( ChangeEntry change : gitChanges ) {
GitChangeSet scmChange = new GitChangeSet();
scmChange.setAuthor( change.getAuthorName() );
scmChange.setComment( change.getBody() );
scmChange.setDate( change.getAuthorDate() );
//X TODO scmChange.setFiles( change.get )
modifications.add( scmChange );
}
ChangeLogSet changeLogSet = new ChangeLogSet( modifications, startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( "JGit changelog", changeLogSet );
}
catch ( Exception e )
{
throw new ScmException("JGit changelog failure!", e );
}
}
| protected ChangeLogScmResult executeChangeLogCommand( ScmProviderRepository repo, ScmFileSet fileSet,
Date startDate, Date endDate, ScmBranch branch,
String datePattern, ScmVersion startVersion,
ScmVersion endVersion )
throws ScmException
{
try
{
SimpleRepository srep = SimpleRepository.existing( fileSet.getBasedir() );
List<GitChangeSet> modifications = new ArrayList<GitChangeSet>();
String startRev = startVersion != null ? startVersion.getName() : null;
String endRev = endVersion != null ? endVersion.getName() : null;
List<ChangeEntry> gitChanges = srep.whatchanged( null, startRev, endRev, startDate, endDate, -1 );
for ( ChangeEntry change : gitChanges ) {
GitChangeSet scmChange = new GitChangeSet();
scmChange.setAuthor( change.getAuthorName() );
scmChange.setComment( change.getBody() );
scmChange.setDate( change.getAuthorDate() );
//X TODO scmChange.setFiles( change.get )
modifications.add( scmChange );
}
ChangeLogSet changeLogSet = new ChangeLogSet( modifications, startDate, endDate );
changeLogSet.setStartVersion( startVersion );
changeLogSet.setEndVersion( endVersion );
return new ChangeLogScmResult( "JGit changelog", changeLogSet );
}
catch ( Exception e )
{
throw new ScmException( "JGit changelog failure!", e );
}
}
|
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/EggHandler.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/EggHandler.java
index 7ec8ce2..6e93633 100644
--- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/EggHandler.java
+++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/egghandler/EggHandler.java
@@ -1,167 +1,167 @@
package com.runetooncraft.plugins.EasyMobArmory.egghandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import net.minecraft.server.v1_6_R2.NBTTagCompound;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.PigZombie;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Zombie;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import com.bergerkiller.bukkit.common.entity.CommonEntity;
import com.bergerkiller.bukkit.common.utils.EntityUtil;
import com.runetooncraft.plugins.EasyMobArmory.EMA;
import com.runetooncraft.plugins.EasyMobArmory.MobCache.*;
import com.runetooncraft.plugins.EasyMobArmory.core.Config;
import com.runetooncraft.plugins.EasyMobArmory.core.InventorySerializer;
public class EggHandler {
public static Eggs eggs = EMA.eggs;
public static HashMap<String, ZombieCache> ZombieCache = new HashMap<String, ZombieCache>();
public static HashMap<String, PigZombieCache> PigZombieCache = new HashMap<String, PigZombieCache>();
public static HashMap<String, SkeletonCache> SkeletonCache = new HashMap<String, SkeletonCache>();
public static ItemStack GetEggitem(Entity e,String name, String lore) {
ItemStack egg = new ItemStack(Material.MONSTER_EGG, 1, (short) e.getEntityId());
return renameItem(egg, name, lore);
}
public static ItemStack renameItem(ItemStack is, String newName, String lore){
ItemMeta meta = is.getItemMeta();
meta.setDisplayName(newName);
List<String> lorelist = new ArrayList<String>();
lorelist.add(lore);
meta.setLore(lorelist);
is.setItemMeta(meta);
return is;
}
public static void addegg(Entity e) {
YamlConfiguration eggsyml = eggs.GetConfig();
if(eggsyml.getList("Eggs.List") != null) {
if(!eggsyml.getList("Eggs.List").contains(Integer.toString(e.getEntityId()))) {
eggs.addtolist("Eggs.List", Integer.toString(e.getEntityId()));
eggsyml.set("Eggs.id." + e.getEntityId() + ".Type", e.getType().getTypeId());
if(e.getType().equals(EntityType.ZOMBIE)) {
Zombie z = (Zombie) e;
eggsyml.set("Eggs.id." + e.getEntityId() + ".Armor", InventorySerializer.tobase64(InventorySerializer.getArmorEntityInventory(z.getEquipment())));
Inventory HandItem = Bukkit.getServer().createInventory(null, InventoryType.PLAYER);
HandItem.setItem(0, z.getEquipment().getItemInHand());
eggsyml.set("Eggs.id." + e.getEntityId() + ".Hand", InventorySerializer.tobase64(HandItem));
eggsyml.set("Eggs.id." + e.getEntityId() + ".isbaby", z.isBaby());
eggs.save();
}else if(e.getType().equals(EntityType.SKELETON)) {
Skeleton s = (Skeleton) e;
Inventory HandItem = Bukkit.getServer().createInventory(null, InventoryType.PLAYER);
HandItem.setItem(0, s.getEquipment().getItemInHand());
eggsyml.set("Eggs.id." + e.getEntityId() + ".Armor", InventorySerializer.tobase64(InventorySerializer.getArmorEntityInventory(s.getEquipment())));
eggsyml.set("Eggs.id." + e.getEntityId() + ".Hand", InventorySerializer.tobase64(HandItem));
}else if(e.getType().equals(EntityType.PIG_ZOMBIE)) {
PigZombie pz = (PigZombie) e;
Inventory HandItem = Bukkit.getServer().createInventory(null, InventoryType.PLAYER);
HandItem.setItem(0, pz.getEquipment().getItemInHand());
eggsyml.set("Eggs.id." + e.getEntityId() + ".Armor", InventorySerializer.tobase64(InventorySerializer.getArmorEntityInventory(pz.getEquipment())));
eggsyml.set("Eggs.id." + e.getEntityId() + ".Hand", InventorySerializer.tobase64(HandItem));
eggsyml.set("Eggs.id." + e.getEntityId() + ".isbaby", pz.isBaby());
}
}else{
//Egg already existent
}
}
}
public static List<String> GetEggList() {
return (List<String>) eggs.getList("Eggs.List");
}
public static Entity Loadentity(String id, Location loc) {
int Entityid = eggs.getInt("Eggs.id." + id + ".Type");
EntityType etype = EntityType.fromId(Entityid);
if(etype.equals(EntityType.ZOMBIE) && !ZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.ZOMBIE)) {
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(Armorstackinv.getContents());
z.getEquipment().setItemInHand(iteminv.getItem(0));
z.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return z;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.ZOMBIE) && ZombieCache.containsKey(id)) {
ZombieCache set = ZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(set.Equip);
z.getEquipment().setItemInHand(set.handitem);
z.setBaby(set.isbaby);
return z;
}else if(etype.equals(EntityType.SKELETON) && !SkeletonCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.SKELETON)) {
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(Armorstackinv.getContents());
s.getEquipment().setItemInHand(iteminv.getItem(0));
SkeletonCache.put(id, new SkeletonCache(Armorstackinv.getContents(),iteminv.getItem(0)));
return s;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.SKELETON) && SkeletonCache.containsKey(id)) {
SkeletonCache set = SkeletonCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(set.Equip);
s.getEquipment().setItemInHand(set.handitem);
return s;
}else if(etype.equals(EntityType.PIG_ZOMBIE) && !PigZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
- if(etype.equals(EntityType.ZOMBIE)) {
+ if(etype.equals(EntityType.PIG_ZOMBIE)) {
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(Armorstackinv.getContents());
pz.getEquipment().setItemInHand(iteminv.getItem(0));
pz.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return pz;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.PIG_ZOMBIE) && PigZombieCache.containsKey(id)) {
PigZombieCache set = PigZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(set.Equip);
pz.getEquipment().setItemInHand(set.handitem);
pz.setBaby(set.isbaby);
return pz;
}
return CommonEntity.create(etype).getEntity();
}
}
| true | true | public static Entity Loadentity(String id, Location loc) {
int Entityid = eggs.getInt("Eggs.id." + id + ".Type");
EntityType etype = EntityType.fromId(Entityid);
if(etype.equals(EntityType.ZOMBIE) && !ZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.ZOMBIE)) {
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(Armorstackinv.getContents());
z.getEquipment().setItemInHand(iteminv.getItem(0));
z.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return z;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.ZOMBIE) && ZombieCache.containsKey(id)) {
ZombieCache set = ZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(set.Equip);
z.getEquipment().setItemInHand(set.handitem);
z.setBaby(set.isbaby);
return z;
}else if(etype.equals(EntityType.SKELETON) && !SkeletonCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.SKELETON)) {
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(Armorstackinv.getContents());
s.getEquipment().setItemInHand(iteminv.getItem(0));
SkeletonCache.put(id, new SkeletonCache(Armorstackinv.getContents(),iteminv.getItem(0)));
return s;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.SKELETON) && SkeletonCache.containsKey(id)) {
SkeletonCache set = SkeletonCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(set.Equip);
s.getEquipment().setItemInHand(set.handitem);
return s;
}else if(etype.equals(EntityType.PIG_ZOMBIE) && !PigZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.ZOMBIE)) {
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(Armorstackinv.getContents());
pz.getEquipment().setItemInHand(iteminv.getItem(0));
pz.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return pz;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.PIG_ZOMBIE) && PigZombieCache.containsKey(id)) {
PigZombieCache set = PigZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(set.Equip);
pz.getEquipment().setItemInHand(set.handitem);
pz.setBaby(set.isbaby);
return pz;
}
return CommonEntity.create(etype).getEntity();
}
| public static Entity Loadentity(String id, Location loc) {
int Entityid = eggs.getInt("Eggs.id." + id + ".Type");
EntityType etype = EntityType.fromId(Entityid);
if(etype.equals(EntityType.ZOMBIE) && !ZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.ZOMBIE)) {
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(Armorstackinv.getContents());
z.getEquipment().setItemInHand(iteminv.getItem(0));
z.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return z;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.ZOMBIE) && ZombieCache.containsKey(id)) {
ZombieCache set = ZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Zombie z = (Zombie) EntityUtil.getEntity(loc.getWorld(), entid);
z.getEquipment().setArmorContents(set.Equip);
z.getEquipment().setItemInHand(set.handitem);
z.setBaby(set.isbaby);
return z;
}else if(etype.equals(EntityType.SKELETON) && !SkeletonCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.SKELETON)) {
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(Armorstackinv.getContents());
s.getEquipment().setItemInHand(iteminv.getItem(0));
SkeletonCache.put(id, new SkeletonCache(Armorstackinv.getContents(),iteminv.getItem(0)));
return s;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.SKELETON) && SkeletonCache.containsKey(id)) {
SkeletonCache set = SkeletonCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
Skeleton s = (Skeleton) EntityUtil.getEntity(loc.getWorld(), entid);
s.getEquipment().setArmorContents(set.Equip);
s.getEquipment().setItemInHand(set.handitem);
return s;
}else if(etype.equals(EntityType.PIG_ZOMBIE) && !PigZombieCache.containsKey(id)) {
CommonEntity entity = CommonEntity.create(etype);
String entityLoc = "Eggs.id." + id + ".";
Inventory Armorstackinv = InventorySerializer.frombase64(eggs.getString(entityLoc + "Armor"));
Inventory iteminv = InventorySerializer.frombase64(eggs.getString(entityLoc +"Hand"));
Boolean isbaby = eggs.getBoolean(entityLoc + "isbaby");
Entity bukkitentity = entity.getEntity();
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
if(etype.equals(EntityType.PIG_ZOMBIE)) {
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(Armorstackinv.getContents());
pz.getEquipment().setItemInHand(iteminv.getItem(0));
pz.setBaby(isbaby);
ZombieCache.put(id, new ZombieCache(Armorstackinv.getContents(),iteminv.getItem(0),isbaby));
return pz;
}else{
return bukkitentity;
}
}else if(etype.equals(EntityType.PIG_ZOMBIE) && PigZombieCache.containsKey(id)) {
PigZombieCache set = PigZombieCache.get(id);
UUID entid = loc.getWorld().spawnEntity(loc, etype).getUniqueId();
PigZombie pz = (PigZombie) EntityUtil.getEntity(loc.getWorld(), entid);
pz.getEquipment().setArmorContents(set.Equip);
pz.getEquipment().setItemInHand(set.handitem);
pz.setBaby(set.isbaby);
return pz;
}
return CommonEntity.create(etype).getEntity();
}
|
diff --git a/src/com/android/phone/CallFeaturesSetting.java b/src/com/android/phone/CallFeaturesSetting.java
index 7ed08054..98502f24 100644
--- a/src/com/android/phone/CallFeaturesSetting.java
+++ b/src/com/android/phone/CallFeaturesSetting.java
@@ -1,2171 +1,2171 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.net.sip.SipManager;
import android.os.AsyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.ListAdapter;
import com.android.internal.telephony.CallForwardInfo;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.cdma.TtyIntent;
import com.android.phone.sip.SipSharedPreferences;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Top level "Call settings" UI; see res/xml/call_feature_setting.xml
*
* This preference screen is the root of the "Call settings" hierarchy
* available from the Phone app; the settings here let you control various
* features related to phone calls (including voicemail settings, SIP
* settings, the "Respond via SMS" feature, and others.) It's used only
* on voice-capable phone devices.
*
* Note that this activity is part of the package com.android.phone, even
* though you reach it from the "Phone" app (i.e. DialtactsActivity) which
* is from the package com.android.contacts.
*
* For the "Mobile network settings" screen under the main Settings app,
* See {@link MobileNetworkSettings}.
*
* @see com.android.phone.MobileNetworkSettings
*/
public class CallFeaturesSetting extends PreferenceActivity
implements DialogInterface.OnClickListener,
Preference.OnPreferenceChangeListener,
EditPhoneNumberPreference.OnDialogClosedListener,
EditPhoneNumberPreference.GetDefaultNumberListener{
private static final String LOG_TAG = "CallFeaturesSetting";
private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
/**
* Intent action to bring up Voicemail Provider settings.
*
* @see #IGNORE_PROVIDER_EXTRA
*/
public static final String ACTION_ADD_VOICEMAIL =
"com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL";
// intent action sent by this activity to a voice mail provider
// to trigger its configuration UI
public static final String ACTION_CONFIGURE_VOICEMAIL =
"com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL";
// Extra put in the return from VM provider config containing voicemail number to set
public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
// Extra put in the return from VM provider config containing call forwarding number to set
public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
// Extra put in the return from VM provider config containing call forwarding number to set
public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
// If the VM provider returns non null value in this extra we will force the user to
// choose another VM provider
public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
//Information about logical "up" Activity
private static final String UP_ACTIVITY_PACKAGE = "com.android.contacts";
private static final String UP_ACTIVITY_CLASS =
"com.android.contacts.activities.DialtactsActivity";
// Used to tell the saving logic to leave forwarding number as is
public static final CallForwardInfo[] FWD_SETTINGS_DONT_TOUCH = null;
// Suffix appended to provider key for storing vm number
public static final String VM_NUMBER_TAG = "#VMNumber";
// Suffix appended to provider key for storing forwarding settings
public static final String FWD_SETTINGS_TAG = "#FWDSettings";
// Suffix appended to forward settings key for storing length of settings array
public static final String FWD_SETTINGS_LENGTH_TAG = "#Length";
// Suffix appended to forward settings key for storing an individual setting
public static final String FWD_SETTING_TAG = "#Setting";
// Suffixes appended to forward setting key for storing an individual setting properties
public static final String FWD_SETTING_STATUS = "#Status";
public static final String FWD_SETTING_REASON = "#Reason";
public static final String FWD_SETTING_NUMBER = "#Number";
public static final String FWD_SETTING_TIME = "#Time";
// Key identifying the default vocie mail provider
public static final String DEFAULT_VM_PROVIDER_KEY = "";
/**
* String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
* in the list of providers presented to the user. This allows a provider which is being
* disabled (e.g. GV user logging out) to force the user to pick some other provider.
*/
public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
// string constants
private static final String NUM_PROJECTION[] = {CommonDataKinds.Phone.NUMBER};
// String keys for preference lookup
// TODO: Naming these "BUTTON_*" is confusing since they're not actually buttons(!)
private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
private static final String BUTTON_VOICEMAIL_CATEGORY_KEY = "button_voicemail_category_key";
private static final String BUTTON_MWI_NOTIFICATION_KEY = "button_mwi_notification_key";
private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
/* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY =
"button_voicemail_notification_vibrate_when_key";
/* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY =
"button_voicemail_notification_ringtone_key";
private static final String BUTTON_FDN_KEY = "button_fdn_key";
private static final String BUTTON_RESPOND_VIA_SMS_KEY = "button_respond_via_sms_key";
private static final String BUTTON_RINGTONE_KEY = "button_ringtone_key";
private static final String BUTTON_VIBRATE_ON_RING = "button_vibrate_on_ring";
private static final String BUTTON_PLAY_DTMF_TONE = "button_play_dtmf_tone";
private static final String BUTTON_DTMF_KEY = "button_dtmf_settings";
private static final String BUTTON_RETRY_KEY = "button_auto_retry_key";
private static final String BUTTON_TTY_KEY = "button_tty_mode_key";
private static final String BUTTON_HAC_KEY = "button_hac_key";
private static final String BUTTON_NOISE_SUPPRESSION_KEY = "button_noise_suppression_key";
private static final String BUTTON_GSM_UMTS_OPTIONS = "button_gsm_more_expand_key";
private static final String BUTTON_CDMA_OPTIONS = "button_cdma_more_expand_key";
private static final String VM_NUMBERS_SHARED_PREFERENCES_NAME = "vm_numbers";
private static final String BUTTON_SIP_CALL_OPTIONS =
"sip_call_options_key";
private static final String BUTTON_SIP_CALL_OPTIONS_WIFI_ONLY =
"sip_call_options_wifi_only_key";
private static final String SIP_SETTINGS_CATEGORY_KEY =
"sip_settings_category_key";
private Intent mContactListIntent;
/** Event for Async voicemail change call */
private static final int EVENT_VOICEMAIL_CHANGED = 500;
private static final int EVENT_FORWARDING_CHANGED = 501;
private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
private static final int MSG_UPDATE_RINGTONE_SUMMARY = 1;
// preferred TTY mode
// Phone.TTY_MODE_xxx
static final int preferredTtyMode = Phone.TTY_MODE_OFF;
// Dtmf tone types
static final int DTMF_TONE_TYPE_NORMAL = 0;
static final int DTMF_TONE_TYPE_LONG = 1;
public static final String HAC_KEY = "HACSetting";
public static final String HAC_VAL_ON = "ON";
public static final String HAC_VAL_OFF = "OFF";
/** Handle to voicemail pref */
private static final int VOICEMAIL_PREF_ID = 1;
private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
private Phone mPhone;
private AudioManager mAudioManager;
private SipManager mSipManager;
private static final int VM_NOCHANGE_ERROR = 400;
private static final int VM_RESPONSE_ERROR = 500;
private static final int FW_SET_RESPONSE_ERROR = 501;
private static final int FW_GET_RESPONSE_ERROR = 502;
// dialog identifiers for voicemail
private static final int VOICEMAIL_DIALOG_CONFIRM = 600;
private static final int VOICEMAIL_FWD_SAVING_DIALOG = 601;
private static final int VOICEMAIL_FWD_READING_DIALOG = 602;
private static final int VOICEMAIL_REVERTING_DIALOG = 603;
// status message sent back from handlers
private static final int MSG_OK = 100;
// special statuses for voicemail controls.
private static final int MSG_VM_EXCEPTION = 400;
private static final int MSG_FW_SET_EXCEPTION = 401;
private static final int MSG_FW_GET_EXCEPTION = 402;
private static final int MSG_VM_OK = 600;
private static final int MSG_VM_NOCHANGE = 700;
private EditPhoneNumberPreference mSubMenuVoicemailSettings;
private Runnable mRingtoneLookupRunnable;
private final Handler mRingtoneLookupComplete = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_RINGTONE_SUMMARY:
mRingtonePreference.setSummary((CharSequence) msg.obj);
break;
}
}
};
private Preference mRingtonePreference;
private CheckBoxPreference mVibrateWhenRinging;
/** Whether dialpad plays DTMF tone or not. */
private CheckBoxPreference mPlayDtmfTone;
private CheckBoxPreference mButtonAutoRetry;
private CheckBoxPreference mButtonHAC;
private ListPreference mButtonDTMF;
private ListPreference mButtonTTY;
private CheckBoxPreference mButtonNoiseSuppression;
private ListPreference mButtonSipCallOptions;
private CheckBoxPreference mMwiNotification;
private ListPreference mVoicemailProviders;
private PreferenceScreen mVoicemailSettings;
private ListPreference mVoicemailNotificationVibrateWhen;
private SipSharedPreferences mSipSharedPreferences;
private class VoiceMailProvider {
public VoiceMailProvider(String name, Intent intent) {
this.name = name;
this.intent = intent;
}
public String name;
public Intent intent;
}
/**
* Forwarding settings we are going to save.
*/
private static final int [] FORWARDING_SETTINGS_REASONS = new int[] {
CommandsInterface.CF_REASON_UNCONDITIONAL,
CommandsInterface.CF_REASON_BUSY,
CommandsInterface.CF_REASON_NO_REPLY,
CommandsInterface.CF_REASON_NOT_REACHABLE
};
private class VoiceMailProviderSettings {
/**
* Constructs settings object, setting all conditional forwarding to the specified number
*/
public VoiceMailProviderSettings(String voicemailNumber, String forwardingNumber,
int timeSeconds) {
this.voicemailNumber = voicemailNumber;
if (forwardingNumber == null || forwardingNumber.length() == 0) {
this.forwardingSettings = FWD_SETTINGS_DONT_TOUCH;
} else {
this.forwardingSettings = new CallForwardInfo[FORWARDING_SETTINGS_REASONS.length];
for (int i = 0; i < this.forwardingSettings.length; i++) {
CallForwardInfo fi = new CallForwardInfo();
this.forwardingSettings[i] = fi;
fi.reason = FORWARDING_SETTINGS_REASONS[i];
fi.status = (fi.reason == CommandsInterface.CF_REASON_UNCONDITIONAL) ? 0 : 1;
fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
fi.toa = PhoneNumberUtils.TOA_International;
fi.number = forwardingNumber;
fi.timeSeconds = timeSeconds;
}
}
}
public VoiceMailProviderSettings(String voicemailNumber, CallForwardInfo[] infos) {
this.voicemailNumber = voicemailNumber;
this.forwardingSettings = infos;
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof VoiceMailProviderSettings)) return false;
final VoiceMailProviderSettings v = (VoiceMailProviderSettings)o;
return ((this.voicemailNumber == null &&
v.voicemailNumber == null) ||
this.voicemailNumber != null &&
this.voicemailNumber.equals(v.voicemailNumber))
&&
forwardingSettingsEqual(this.forwardingSettings,
v.forwardingSettings);
}
private boolean forwardingSettingsEqual(CallForwardInfo[] infos1,
CallForwardInfo[] infos2) {
if (infos1 == infos2) return true;
if (infos1 == null || infos2 == null) return false;
if (infos1.length != infos2.length) return false;
for (int i = 0; i < infos1.length; i++) {
CallForwardInfo i1 = infos1[i];
CallForwardInfo i2 = infos2[i];
if (i1.status != i2.status ||
i1.reason != i2.reason ||
i1.serviceClass != i2.serviceClass ||
i1.toa != i2.toa ||
i1.number != i2.number ||
i1.timeSeconds != i2.timeSeconds) {
return false;
}
}
return true;
}
@Override
public String toString() {
return voicemailNumber + ((forwardingSettings != null ) ? (", " +
forwardingSettings.toString()) : "");
}
public String voicemailNumber;
public CallForwardInfo[] forwardingSettings;
}
private SharedPreferences mPerProviderSavedVMNumbers;
/**
* Results of reading forwarding settings
*/
private CallForwardInfo[] mForwardingReadResults = null;
/**
* Result of forwarding number change.
* Keys are reasons (eg. unconditional forwarding).
*/
private Map<Integer, AsyncResult> mForwardingChangeResults = null;
/**
* Expected CF read result types.
* This set keeps track of the CF types for which we've issued change
* commands so we can tell when we've received all of the responses.
*/
private Collection<Integer> mExpectedChangeResultReasons = null;
/**
* Result of vm number change
*/
private AsyncResult mVoicemailChangeResult = null;
/**
* Previous VM provider setting so we can return to it in case of failure.
*/
private String mPreviousVMProviderKey = null;
/**
* Id of the dialog being currently shown.
*/
private int mCurrentDialogId = 0;
/**
* Flag indicating that we are invoking settings for the voicemail provider programmatically
* due to vm provider change.
*/
private boolean mVMProviderSettingsForced = false;
/**
* Flag indicating that we are making changes to vm or fwd numbers
* due to vm provider change.
*/
private boolean mChangingVMorFwdDueToProviderChange = false;
/**
* True if we are in the process of vm & fwd number change and vm has already been changed.
* This is used to decide what to do in case of rollback.
*/
private boolean mVMChangeCompletedSuccessfully = false;
/**
* True if we had full or partial failure setting forwarding numbers and so need to roll them
* back.
*/
private boolean mFwdChangesRequireRollback = false;
/**
* Id of error msg to display to user once we are done reverting the VM provider to the previous
* one.
*/
private int mVMOrFwdSetError = 0;
/**
* Data about discovered voice mail settings providers.
* Is populated by querying which activities can handle ACTION_CONFIGURE_VOICEMAIL.
* They key in this map is package name + activity name.
* We always add an entry for the default provider with a key of empty
* string and intent value of null.
* @see #initVoiceMailProviders()
*/
private final Map<String, VoiceMailProvider> mVMProvidersData =
new HashMap<String, VoiceMailProvider>();
/** string to hold old voicemail number as it is being updated. */
private String mOldVmNumber;
// New call forwarding settings and vm number we will be setting
// Need to save these since before we get to saving we need to asynchronously
// query the existing forwarding settings.
private CallForwardInfo[] mNewFwdSettings;
private String mNewVMNumber;
private boolean mForeground;
@Override
public void onPause() {
super.onPause();
mForeground = false;
}
/**
* We have to pull current settings from the network for all kinds of
* voicemail providers so we can tell whether we have to update them,
* so use this bit to keep track of whether we're reading settings for the
* default provider and should therefore save them out when done.
*/
private boolean mReadingSettingsForDefaultProvider = false;
/*
* Click Listeners, handle click based on objects attached to UI.
*/
// Click listener for all toggle events
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mSubMenuVoicemailSettings) {
return true;
} else if (preference == mPlayDtmfTone) {
Settings.System.putInt(getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING,
mPlayDtmfTone.isChecked() ? 1 : 0);
} else if (preference == mMwiNotification) {
int mwi_notification = mMwiNotification.isChecked() ? 1 : 0;
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.ENABLE_MWI_NOTIFICATION, mwi_notification);
return true;
} else if (preference == mButtonDTMF) {
return true;
} else if (preference == mButtonTTY) {
return true;
} else if (preference == mButtonNoiseSuppression) {
int nsp = mButtonNoiseSuppression.isChecked() ? 1 : 0;
// Update Noise suppression value in Settings database
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.NOISE_SUPPRESSION, nsp);
return true;
} else if (preference == mButtonAutoRetry) {
android.provider.Settings.System.putInt(mPhone.getContext().getContentResolver(),
android.provider.Settings.System.CALL_AUTO_RETRY,
mButtonAutoRetry.isChecked() ? 1 : 0);
return true;
} else if (preference == mButtonHAC) {
int hac = mButtonHAC.isChecked() ? 1 : 0;
// Update HAC value in Settings database
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.HEARING_AID, hac);
// Update HAC Value in AudioManager
mAudioManager.setParameter(HAC_KEY, hac != 0 ? HAC_VAL_ON : HAC_VAL_OFF);
return true;
} else if (preference == mVoicemailSettings) {
if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
if (preference.getIntent() != null) {
if (DBG) {
log("onPreferenceTreeClick: Invoking cfg intent "
+ preference.getIntent().getPackage());
}
// onActivityResult() will be responsible for resetting some of variables.
this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
return true;
} else {
if (DBG) {
log("onPreferenceTreeClick:"
+ " No Intent is available. Use default behavior defined in xml.");
}
// There's no onActivityResult(), so we need to take care of some of variables
// which should be reset here.
mPreviousVMProviderKey = DEFAULT_VM_PROVIDER_KEY;
mVMProviderSettingsForced = false;
// This should let the preference use default behavior in the xml.
return false;
}
}
return false;
}
/**
* Implemented to support onPreferenceChangeListener to look for preference
* changes.
*
* @param preference is the preference to be changed
* @param objValue should be the value of the selection, NOT its localized
* display value.
*/
@Override
public boolean onPreferenceChange(Preference preference, Object objValue) {
if (DBG) {
log("onPreferenceChange(). preferenece: \"" + preference + "\""
+ ", value: \"" + objValue + "\"");
}
if (preference == mVibrateWhenRinging) {
boolean doVibrate = (Boolean) objValue;
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.VIBRATE_WHEN_RINGING, doVibrate ? 1 : 0);
} else if (preference == mButtonDTMF) {
int index = mButtonDTMF.findIndexOfValue((String) objValue);
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index);
} else if (preference == mButtonTTY) {
handleTTYChange(preference, objValue);
} else if (preference == mMwiNotification) {
int mwi_notification = mMwiNotification.isChecked() ? 1 : 0;
Settings.System.putInt(mPhone.getContext().getContentResolver(),
Settings.System.ENABLE_MWI_NOTIFICATION, mwi_notification);
} else if (preference == mVoicemailProviders) {
final String newProviderKey = (String) objValue;
if (DBG) {
log("Voicemail Provider changes from \"" + mPreviousVMProviderKey
+ "\" to \"" + newProviderKey + "\".");
}
// If previous provider key and the new one is same, we don't need to handle it.
if (mPreviousVMProviderKey.equals(newProviderKey)) {
if (DBG) log("No change is made toward VM provider setting.");
return true;
}
updateVMPreferenceWidgets(newProviderKey);
final VoiceMailProviderSettings newProviderSettings =
loadSettingsForVoiceMailProvider(newProviderKey);
// If the user switches to a voice mail provider and we have a
// numbers stored for it we will automatically change the
// phone's
// voice mail and forwarding number to the stored ones.
// Otherwise we will bring up provider's configuration UI.
if (newProviderSettings == null) {
// Force the user into a configuration of the chosen provider
Log.w(LOG_TAG, "Saved preferences not found - invoking config");
mVMProviderSettingsForced = true;
simulatePreferenceClick(mVoicemailSettings);
} else {
if (DBG) log("Saved preferences found - switching to them");
// Set this flag so if we get a failure we revert to previous provider
mChangingVMorFwdDueToProviderChange = true;
saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
}
} else if (preference == mVoicemailNotificationVibrateWhen) {
mVoicemailNotificationVibrateWhen.setValue((String) objValue);
mVoicemailNotificationVibrateWhen.setSummary(
mVoicemailNotificationVibrateWhen.getEntry());
} else if (preference == mButtonSipCallOptions) {
handleSipCallOptionsChange(objValue);
}
// always let the preference setting proceed.
return true;
}
@Override
public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
if (DBG) log("onPreferenceClick: request preference click on dialog close: " +
buttonClicked);
if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
return;
}
if (preference == mSubMenuVoicemailSettings) {
handleVMBtnClickRequest();
}
}
/**
* Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
* This method set the default values for the various
* EditPhoneNumberPreference dialogs.
*/
@Override
public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
if (preference == mSubMenuVoicemailSettings) {
// update the voicemail number field, which takes care of the
// mSubMenuVoicemailSettings itself, so we should return null.
if (DBG) log("updating default for voicemail dialog");
updateVoiceNumberField();
return null;
}
String vmDisplay = mPhone.getVoiceMailNumber();
if (TextUtils.isEmpty(vmDisplay)) {
// if there is no voicemail number, we just return null to
// indicate no contribution.
return null;
}
// Return the voicemail number prepended with "VM: "
if (DBG) log("updating default for call forwarding dialogs");
return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
}
// override the startsubactivity call to make changes in state consistent.
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode == -1) {
// this is an intent requested from the preference framework.
super.startActivityForResult(intent, requestCode);
return;
}
if (DBG) log("startSubActivity: starting requested subactivity");
super.startActivityForResult(intent, requestCode);
}
private void switchToPreviousVoicemailProvider() {
if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
if (mPreviousVMProviderKey != null) {
if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
// we have to revert with carrier
if (DBG) {
log("Needs to rollback."
+ " mVMChangeCompletedSuccessfully=" + mVMChangeCompletedSuccessfully
+ ", mFwdChangesRequireRollback=" + mFwdChangesRequireRollback);
}
showDialogIfForeground(VOICEMAIL_REVERTING_DIALOG);
final VoiceMailProviderSettings prevSettings =
loadSettingsForVoiceMailProvider(mPreviousVMProviderKey);
if (prevSettings == null) {
// prevSettings never becomes null since it should be already loaded!
Log.e(LOG_TAG, "VoiceMailProviderSettings for the key \""
+ mPreviousVMProviderKey + "\" becomes null, which is unexpected.");
if (DBG) {
Log.e(LOG_TAG,
"mVMChangeCompletedSuccessfully: " + mVMChangeCompletedSuccessfully
+ ", mFwdChangesRequireRollback: " + mFwdChangesRequireRollback);
}
}
if (mVMChangeCompletedSuccessfully) {
mNewVMNumber = prevSettings.voicemailNumber;
Log.i(LOG_TAG, "VM change is already completed successfully."
+ "Have to revert VM back to " + mNewVMNumber + " again.");
mPhone.setVoiceMailNumber(
mPhone.getVoiceMailAlphaTag().toString(),
mNewVMNumber,
Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
}
if (mFwdChangesRequireRollback) {
Log.i(LOG_TAG, "Requested to rollback Fwd changes.");
final CallForwardInfo[] prevFwdSettings =
prevSettings.forwardingSettings;
if (prevFwdSettings != null) {
Map<Integer, AsyncResult> results =
mForwardingChangeResults;
resetForwardingChangeState();
for (int i = 0; i < prevFwdSettings.length; i++) {
CallForwardInfo fi = prevFwdSettings[i];
if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
// Only revert the settings for which the update
// succeeded
AsyncResult result = results.get(fi.reason);
if (result != null && result.exception == null) {
mExpectedChangeResultReasons.add(fi.reason);
mPhone.setCallForwardingOption(
(fi.status == 1 ?
CommandsInterface.CF_ACTION_REGISTRATION :
CommandsInterface.CF_ACTION_DISABLE),
fi.reason,
fi.number,
fi.timeSeconds,
mRevertOptionComplete.obtainMessage(
EVENT_FORWARDING_CHANGED, i, 0));
}
}
}
}
} else {
if (DBG) log("No need to revert");
onRevertDone();
}
}
}
private void onRevertDone() {
if (DBG) log("Flipping provider key back to " + mPreviousVMProviderKey);
mVoicemailProviders.setValue(mPreviousVMProviderKey);
updateVMPreferenceWidgets(mPreviousVMProviderKey);
updateVoiceNumberField();
if (mVMOrFwdSetError != 0) {
showVMDialog(mVMOrFwdSetError);
mVMOrFwdSetError = 0;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (DBG) {
log("onActivityResult: requestCode: " + requestCode
+ ", resultCode: " + resultCode
+ ", data: " + data);
}
// there are cases where the contact picker may end up sending us more than one
// request. We want to ignore the request if we're not in the correct state.
if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
boolean failure = false;
// No matter how the processing of result goes lets clear the flag
if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
mVMProviderSettingsForced = false;
String vmNum = null;
if (resultCode != RESULT_OK) {
if (DBG) log("onActivityResult: vm provider cfg result not OK.");
failure = true;
} else {
if (data == null) {
if (DBG) log("onActivityResult: vm provider cfg result has no data");
failure = true;
} else {
if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
if (DBG) log("Provider requested signout");
if (isVMProviderSettingsForced) {
if (DBG) log("Going back to previous provider on signout");
switchToPreviousVoicemailProvider();
} else {
final String victim = getCurrentVoicemailProviderKey();
if (DBG) log("Relaunching activity and ignoring " + victim);
Intent i = new Intent(ACTION_ADD_VOICEMAIL);
i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(i);
}
return;
}
vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
if (vmNum == null || vmNum.length() == 0) {
if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
failure = true;
}
}
}
if (failure) {
if (DBG) log("Failure in return from voicemail provider");
if (isVMProviderSettingsForced) {
switchToPreviousVoicemailProvider();
} else {
if (DBG) log("Not switching back the provider since this is not forced config");
}
return;
}
mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
// TODO(iliat): It would be nice to load the current network setting for this and
// send it to the provider when it's config is invoked so it can use this as default
final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
if (DBG) log("onActivityResult: vm provider cfg result " +
(fwdNum != null ? "has" : " does not have") + " forwarding number");
saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(),
new VoiceMailProviderSettings(vmNum, fwdNum, fwdNumTime));
return;
}
if (requestCode == VOICEMAIL_PREF_ID) {
if (resultCode != RESULT_OK) {
if (DBG) log("onActivityResult: contact picker result not OK.");
return;
}
Cursor cursor = getContentResolver().query(data.getData(),
NUM_PROJECTION, null, null, null);
if ((cursor == null) || (!cursor.moveToFirst())) {
if (DBG) log("onActivityResult: bad contact data, no results found.");
return;
}
mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
// Voicemail button logic
private void handleVMBtnClickRequest() {
// normally called on the dialog close.
// Since we're stripping the formatting out on the getPhoneNumber()
// call now, we won't need to do so here anymore.
saveVoiceMailAndForwardingNumber(
getCurrentVoicemailProviderKey(),
new VoiceMailProviderSettings(mSubMenuVoicemailSettings.getPhoneNumber(),
FWD_SETTINGS_DONT_TOUCH));
}
/**
* Wrapper around showDialog() that will silently do nothing if we're
* not in the foreground.
*
* This is useful here because most of the dialogs we display from
* this class are triggered by asynchronous events (like
* success/failure messages from the telephony layer) and it's
* possible for those events to come in even after the user has gone
* to a different screen.
*/
// TODO: this is too brittle: it's still easy to accidentally add new
// code here that calls showDialog() directly (which will result in a
// WindowManager$BadTokenException if called after the activity has
// been stopped.)
//
// It would be cleaner to do the "if (mForeground)" check in one
// central place, maybe by using a single Handler for all asynchronous
// events (and have *that* discard events if we're not in the
// foreground.)
//
// Unfortunately it's not that simple, since we sometimes need to do
// actual work to handle these events whether or not we're in the
// foreground (see the Handler code in mSetOptionComplete for
// example.)
private void showDialogIfForeground(int id) {
if (mForeground) {
showDialog(id);
}
}
private void dismissDialogSafely(int id) {
try {
dismissDialog(id);
} catch (IllegalArgumentException e) {
// This is expected in the case where we were in the background
// at the time we would normally have shown the dialog, so we didn't
// show it.
}
}
private void saveVoiceMailAndForwardingNumber(String key,
VoiceMailProviderSettings newSettings) {
if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
mNewVMNumber = newSettings.voicemailNumber;
// empty vm number == clearing the vm number ?
if (mNewVMNumber == null) {
mNewVMNumber = "";
}
mNewFwdSettings = newSettings.forwardingSettings;
if (DBG) log("newFwdNumber " +
String.valueOf((mNewFwdSettings != null ? mNewFwdSettings.length : 0))
+ " settings");
// No fwd settings on CDMA
if (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
if (DBG) log("ignoring forwarding setting since this is CDMA phone");
mNewFwdSettings = FWD_SETTINGS_DONT_TOUCH;
}
//throw a warning if the vm is the same and we do not touch forwarding.
if (mNewVMNumber.equals(mOldVmNumber) && mNewFwdSettings == FWD_SETTINGS_DONT_TOUCH) {
showVMDialog(MSG_VM_NOCHANGE);
return;
}
maybeSaveSettingsForVoicemailProvider(key, newSettings);
mVMChangeCompletedSuccessfully = false;
mFwdChangesRequireRollback = false;
mVMOrFwdSetError = 0;
if (!key.equals(mPreviousVMProviderKey)) {
mReadingSettingsForDefaultProvider =
mPreviousVMProviderKey.equals(DEFAULT_VM_PROVIDER_KEY);
if (DBG) log("Reading current forwarding settings");
mForwardingReadResults = new CallForwardInfo[FORWARDING_SETTINGS_REASONS.length];
for (int i = 0; i < FORWARDING_SETTINGS_REASONS.length; i++) {
mForwardingReadResults[i] = null;
mPhone.getCallForwardingOption(FORWARDING_SETTINGS_REASONS[i],
mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
}
showDialogIfForeground(VOICEMAIL_FWD_READING_DIALOG);
} else {
saveVoiceMailAndForwardingNumberStage2();
}
}
private final Handler mGetOptionComplete = new Handler() {
@Override
public void handleMessage(Message msg) {
AsyncResult result = (AsyncResult) msg.obj;
switch (msg.what) {
case EVENT_FORWARDING_GET_COMPLETED:
handleForwardingSettingsReadResult(result, msg.arg1);
break;
}
}
};
private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
Throwable error = null;
if (ar.exception != null) {
if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" +
ar.exception.getMessage());
error = ar.exception;
}
if (ar.userObj instanceof Throwable) {
if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" +
((Throwable)ar.userObj).getMessage());
error = (Throwable)ar.userObj;
}
// We may have already gotten an error and decided to ignore the other results.
if (mForwardingReadResults == null) {
if (DBG) Log.d(LOG_TAG, "ignoring fwd reading result: " + idx);
return;
}
// In case of error ignore other results, show an error dialog
if (error != null) {
if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
mForwardingReadResults = null;
dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
showVMDialog(MSG_FW_GET_EXCEPTION);
return;
}
// Get the forwarding info
final CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
CallForwardInfo fi = null;
for (int i = 0 ; i < cfInfoArray.length; i++) {
if ((cfInfoArray[i].serviceClass & CommandsInterface.SERVICE_CLASS_VOICE) != 0) {
fi = cfInfoArray[i];
break;
}
}
if (fi == null) {
// In case we go nothing it means we need this reason disabled
// so create a CallForwardInfo for capturing this
if (DBG) Log.d(LOG_TAG, "Creating default info for " + idx);
fi = new CallForwardInfo();
fi.status = 0;
fi.reason = FORWARDING_SETTINGS_REASONS[idx];
fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
} else {
// if there is not a forwarding number, ensure the entry is set to "not active."
if (fi.number == null || fi.number.length() == 0) {
fi.status = 0;
}
if (DBG) Log.d(LOG_TAG, "Got " + fi.toString() + " for " + idx);
}
mForwardingReadResults[idx] = fi;
// Check if we got all the results already
boolean done = true;
for (int i = 0; i < mForwardingReadResults.length; i++) {
if (mForwardingReadResults[i] == null) {
done = false;
break;
}
}
if (done) {
if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
if (mReadingSettingsForDefaultProvider) {
maybeSaveSettingsForVoicemailProvider(DEFAULT_VM_PROVIDER_KEY,
new VoiceMailProviderSettings(this.mOldVmNumber,
mForwardingReadResults));
mReadingSettingsForDefaultProvider = false;
}
saveVoiceMailAndForwardingNumberStage2();
} else {
if (DBG) Log.d(LOG_TAG, "Not done receiving fwd info");
}
}
private CallForwardInfo infoForReason(CallForwardInfo[] infos, int reason) {
CallForwardInfo result = null;
if (null != infos) {
for (CallForwardInfo info : infos) {
if (info.reason == reason) {
result = info;
break;
}
}
}
return result;
}
private boolean isUpdateRequired(CallForwardInfo oldInfo,
CallForwardInfo newInfo) {
boolean result = true;
if (0 == newInfo.status) {
// If we're disabling a type of forwarding, and it's already
// disabled for the account, don't make any change
if (oldInfo != null && oldInfo.status == 0) {
result = false;
}
}
return result;
}
private void resetForwardingChangeState() {
mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
mExpectedChangeResultReasons = new HashSet<Integer>();
}
// Called after we are done saving the previous forwarding settings if
// we needed.
private void saveVoiceMailAndForwardingNumberStage2() {
mForwardingChangeResults = null;
mVoicemailChangeResult = null;
if (mNewFwdSettings != FWD_SETTINGS_DONT_TOUCH) {
resetForwardingChangeState();
for (int i = 0; i < mNewFwdSettings.length; i++) {
CallForwardInfo fi = mNewFwdSettings[i];
final boolean doUpdate = isUpdateRequired(infoForReason(
mForwardingReadResults, fi.reason), fi);
if (doUpdate) {
if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
mExpectedChangeResultReasons.add(i);
mPhone.setCallForwardingOption(
fi.status == 1 ?
CommandsInterface.CF_ACTION_REGISTRATION :
CommandsInterface.CF_ACTION_DISABLE,
fi.reason,
fi.number,
fi.timeSeconds,
mSetOptionComplete.obtainMessage(
EVENT_FORWARDING_CHANGED, fi.reason, 0));
}
}
showDialogIfForeground(VOICEMAIL_FWD_SAVING_DIALOG);
} else {
if (DBG) log("Not touching fwd #");
setVMNumberWithCarrier();
}
}
private void setVMNumberWithCarrier() {
if (DBG) log("save voicemail #: " + mNewVMNumber);
mPhone.setVoiceMailNumber(
mPhone.getVoiceMailAlphaTag().toString(),
mNewVMNumber,
Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
}
/**
* Callback to handle option update completions
*/
private final Handler mSetOptionComplete = new Handler() {
@Override
public void handleMessage(Message msg) {
AsyncResult result = (AsyncResult) msg.obj;
boolean done = false;
switch (msg.what) {
case EVENT_VOICEMAIL_CHANGED:
mVoicemailChangeResult = result;
mVMChangeCompletedSuccessfully = checkVMChangeSuccess() == null;
if (DBG) log("VM change complete msg, VM change done = " +
String.valueOf(mVMChangeCompletedSuccessfully));
done = true;
break;
case EVENT_FORWARDING_CHANGED:
mForwardingChangeResults.put(msg.arg1, result);
if (result.exception != null) {
Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
result.exception.getMessage());
} else {
if (DBG) log("Success in setting fwd# " + msg.arg1);
}
final boolean completed = checkForwardingCompleted();
if (completed) {
if (checkFwdChangeSuccess() == null) {
if (DBG) log("Overall fwd changes completed ok, starting vm change");
setVMNumberWithCarrier();
} else {
Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
"Check if we need to try rollback for some settings.");
mFwdChangesRequireRollback = false;
Iterator<Map.Entry<Integer,AsyncResult>> it =
mForwardingChangeResults.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer,AsyncResult> entry = it.next();
if (entry.getValue().exception == null) {
// If at least one succeeded we have to revert
Log.i(LOG_TAG, "Rollback will be required");
mFwdChangesRequireRollback = true;
break;
}
}
if (!mFwdChangesRequireRollback) {
Log.i(LOG_TAG, "No rollback needed.");
}
done = true;
}
}
break;
default:
// TODO: should never reach this, may want to throw exception
}
if (done) {
if (DBG) log("All VM provider related changes done");
if (mForwardingChangeResults != null) {
dismissDialogSafely(VOICEMAIL_FWD_SAVING_DIALOG);
}
handleSetVMOrFwdMessage();
}
}
};
/**
* Callback to handle option revert completions
*/
private final Handler mRevertOptionComplete = new Handler() {
@Override
public void handleMessage(Message msg) {
AsyncResult result = (AsyncResult) msg.obj;
switch (msg.what) {
case EVENT_VOICEMAIL_CHANGED:
mVoicemailChangeResult = result;
if (DBG) log("VM revert complete msg");
break;
case EVENT_FORWARDING_CHANGED:
mForwardingChangeResults.put(msg.arg1, result);
if (result.exception != null) {
if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
result.exception.getMessage());
} else {
if (DBG) log("Success in reverting fwd# " + msg.arg1);
}
if (DBG) log("FWD revert complete msg ");
break;
default:
// TODO: should never reach this, may want to throw exception
}
final boolean done =
(!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) &&
(!mFwdChangesRequireRollback || checkForwardingCompleted());
if (done) {
if (DBG) log("All VM reverts done");
dismissDialogSafely(VOICEMAIL_REVERTING_DIALOG);
onRevertDone();
}
}
};
/**
* @return true if forwarding change has completed
*/
private boolean checkForwardingCompleted() {
boolean result;
if (mForwardingChangeResults == null) {
result = true;
} else {
// return true iff there is a change result for every reason for
// which we expected a result
result = true;
for (Integer reason : mExpectedChangeResultReasons) {
if (mForwardingChangeResults.get(reason) == null) {
result = false;
break;
}
}
}
return result;
}
/**
* @return error string or null if successful
*/
private String checkFwdChangeSuccess() {
String result = null;
Iterator<Map.Entry<Integer,AsyncResult>> it =
mForwardingChangeResults.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer,AsyncResult> entry = it.next();
Throwable exception = entry.getValue().exception;
if (exception != null) {
result = exception.getMessage();
if (result == null) {
result = "";
}
break;
}
}
return result;
}
/**
* @return error string or null if successful
*/
private String checkVMChangeSuccess() {
if (mVoicemailChangeResult.exception != null) {
final String msg = mVoicemailChangeResult.exception.getMessage();
if (msg == null) {
return "";
}
return msg;
}
return null;
}
private void handleSetVMOrFwdMessage() {
if (DBG) {
log("handleSetVMMessage: set VM request complete");
}
boolean success = true;
boolean fwdFailure = false;
String exceptionMessage = "";
if (mForwardingChangeResults != null) {
exceptionMessage = checkFwdChangeSuccess();
if (exceptionMessage != null) {
success = false;
fwdFailure = true;
}
}
if (success) {
exceptionMessage = checkVMChangeSuccess();
if (exceptionMessage != null) {
success = false;
}
}
if (success) {
if (DBG) log("change VM success!");
handleVMAndFwdSetSuccess(MSG_VM_OK);
} else {
if (fwdFailure) {
Log.w(LOG_TAG, "Failed to change fowarding setting. Reason: " + exceptionMessage);
handleVMOrFwdSetError(MSG_FW_SET_EXCEPTION);
} else {
Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + exceptionMessage);
handleVMOrFwdSetError(MSG_VM_EXCEPTION);
}
}
}
/**
* Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
* changes to those settings and show "failure" dialog.
*
* @param msgId Message ID used for the specific error case. {@link #MSG_FW_SET_EXCEPTION} or
* {@link #MSG_VM_EXCEPTION}
*/
private void handleVMOrFwdSetError(int msgId) {
if (mChangingVMorFwdDueToProviderChange) {
mVMOrFwdSetError = msgId;
mChangingVMorFwdDueToProviderChange = false;
switchToPreviousVoicemailProvider();
return;
}
mChangingVMorFwdDueToProviderChange = false;
showVMDialog(msgId);
updateVoiceNumberField();
}
/**
* Called when Voicemail Provider and its forwarding settings were successfully finished.
* This updates a bunch of variables and show "success" dialog.
*/
private void handleVMAndFwdSetSuccess(int msg) {
if (DBG) {
log("handleVMAndFwdSetSuccess(). current voicemail provider key: "
+ getCurrentVoicemailProviderKey());
}
mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
mChangingVMorFwdDueToProviderChange = false;
showVMDialog(msg);
updateVoiceNumberField();
}
/**
* Update the voicemail number from what we've recorded on the sim.
*/
private void updateVoiceNumberField() {
if (DBG) {
log("updateVoiceNumberField(). mSubMenuVoicemailSettings=" + mSubMenuVoicemailSettings);
}
if (mSubMenuVoicemailSettings == null) {
return;
}
mOldVmNumber = mPhone.getVoiceMailNumber();
if (mOldVmNumber == null) {
mOldVmNumber = "";
}
mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
final String summary = (mOldVmNumber.length() > 0) ? mOldVmNumber :
getString(R.string.voicemail_number_not_set);
mSubMenuVoicemailSettings.setSummary(summary);
}
/*
* Helper Methods for Activity class.
* The initial query commands are split into two pieces now
* for individual expansion. This combined with the ability
* to cancel queries allows for a much better user experience,
* and also ensures that the user only waits to update the
* data that is relevant.
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
mCurrentDialogId = id;
}
// dialog creation method, called by showDialog()
@Override
protected Dialog onCreateDialog(int id) {
if ((id == VM_RESPONSE_ERROR) || (id == VM_NOCHANGE_ERROR) ||
(id == FW_SET_RESPONSE_ERROR) || (id == FW_GET_RESPONSE_ERROR) ||
(id == VOICEMAIL_DIALOG_CONFIRM)) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
int msgId;
int titleId = R.string.error_updating_title;
switch (id) {
case VOICEMAIL_DIALOG_CONFIRM:
msgId = R.string.vm_changed;
titleId = R.string.voicemail;
// Set Button 2
b.setNegativeButton(R.string.close_dialog, this);
break;
case VM_NOCHANGE_ERROR:
// even though this is technically an error,
// keep the title friendly.
msgId = R.string.no_change;
titleId = R.string.voicemail;
// Set Button 2
b.setNegativeButton(R.string.close_dialog, this);
break;
case VM_RESPONSE_ERROR:
msgId = R.string.vm_change_failed;
// Set Button 1
b.setPositiveButton(R.string.close_dialog, this);
break;
case FW_SET_RESPONSE_ERROR:
msgId = R.string.fw_change_failed;
// Set Button 1
b.setPositiveButton(R.string.close_dialog, this);
break;
case FW_GET_RESPONSE_ERROR:
msgId = R.string.fw_get_in_vm_failed;
b.setPositiveButton(R.string.alert_dialog_yes, this);
b.setNegativeButton(R.string.alert_dialog_no, this);
break;
default:
msgId = R.string.exception_error;
// Set Button 3, tells the activity that the error is
// not recoverable on dialog exit.
b.setNeutralButton(R.string.close_dialog, this);
break;
}
b.setTitle(getText(titleId));
String message = getText(msgId).toString();
b.setMessage(message);
b.setCancelable(false);
AlertDialog dialog = b.create();
// make the dialog more obvious by bluring the background.
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
return dialog;
} else if (id == VOICEMAIL_FWD_SAVING_DIALOG || id == VOICEMAIL_FWD_READING_DIALOG ||
id == VOICEMAIL_REVERTING_DIALOG) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(getText(R.string.updating_title));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage(getText(
id == VOICEMAIL_FWD_SAVING_DIALOG ? R.string.updating_settings :
(id == VOICEMAIL_REVERTING_DIALOG ? R.string.reverting_settings :
R.string.reading_settings)));
return dialog;
}
return null;
}
// This is a method implemented for DialogInterface.OnClickListener.
// Used with the error dialog to close the app, voicemail dialog to just dismiss.
// Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
// while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch (which){
case DialogInterface.BUTTON_NEUTRAL:
if (DBG) log("Neutral button");
break;
case DialogInterface.BUTTON_NEGATIVE:
if (DBG) log("Negative button");
if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
// We failed to get current forwarding settings and the user
// does not wish to continue.
switchToPreviousVoicemailProvider();
}
break;
case DialogInterface.BUTTON_POSITIVE:
if (DBG) log("Positive button");
if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
// We failed to get current forwarding settings but the user
// wishes to continue changing settings to the new vm provider
saveVoiceMailAndForwardingNumberStage2();
} else {
finish();
}
return;
default:
// just let the dialog close and go back to the input
}
// In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
// with settings UI. If we were called to explicitly configure voice mail then
// we finish the settings activity here to come back to whatever the user was doing.
if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
finish();
}
}
// set the app state with optional status.
private void showVMDialog(int msgStatus) {
switch (msgStatus) {
// It's a bit worrisome to punt in the error cases here when we're
// not in the foreground; maybe toast instead?
case MSG_VM_EXCEPTION:
showDialogIfForeground(VM_RESPONSE_ERROR);
break;
case MSG_FW_SET_EXCEPTION:
showDialogIfForeground(FW_SET_RESPONSE_ERROR);
break;
case MSG_FW_GET_EXCEPTION:
showDialogIfForeground(FW_GET_RESPONSE_ERROR);
break;
case MSG_VM_NOCHANGE:
showDialogIfForeground(VM_NOCHANGE_ERROR);
break;
case MSG_VM_OK:
showDialogIfForeground(VOICEMAIL_DIALOG_CONFIRM);
break;
case MSG_OK:
default:
// This should never happen.
}
}
/*
* Activity class methods
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (DBG) log("onCreate(). Intent: " + getIntent());
mPhone = PhoneApp.getPhone();
addPreferencesFromResource(R.xml.call_feature_setting);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// get buttons
PreferenceScreen prefSet = getPreferenceScreen();
mSubMenuVoicemailSettings = (EditPhoneNumberPreference)findPreference(BUTTON_VOICEMAIL_KEY);
if (mSubMenuVoicemailSettings != null) {
mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
}
mRingtonePreference = findPreference(BUTTON_RINGTONE_KEY);
mVibrateWhenRinging = (CheckBoxPreference) findPreference(BUTTON_VIBRATE_ON_RING);
mPlayDtmfTone = (CheckBoxPreference) findPreference(BUTTON_PLAY_DTMF_TONE);
mMwiNotification = (CheckBoxPreference) findPreference(BUTTON_MWI_NOTIFICATION_KEY);
if (mMwiNotification != null) {
if (getResources().getBoolean(R.bool.sprint_mwi_quirk)) {
mMwiNotification.setOnPreferenceChangeListener(this);
} else {
- PreferenceCategory voicemailCategory = (PreferenceCategory) findPreference(BUTTON_VOICEMAIL_CATEGORY_KEY);
+ PreferenceScreen voicemailCategory = (PreferenceScreen) findPreference(BUTTON_VOICEMAIL_CATEGORY_KEY);
voicemailCategory.removePreference(mMwiNotification);
mMwiNotification = null;
}
}
mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
mButtonNoiseSuppression = (CheckBoxPreference) findPreference(BUTTON_NOISE_SUPPRESSION_KEY);
mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
if (mVoicemailProviders != null) {
mVoicemailProviders.setOnPreferenceChangeListener(this);
mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
mVoicemailNotificationVibrateWhen =
(ListPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY);
mVoicemailNotificationVibrateWhen.setOnPreferenceChangeListener(this);
initVoiceMailProviders();
}
if (mVibrateWhenRinging != null) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
mVibrateWhenRinging.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mVibrateWhenRinging);
mVibrateWhenRinging = null;
}
}
if (mPlayDtmfTone != null) {
mPlayDtmfTone.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) != 0);
}
if (mButtonDTMF != null) {
if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
mButtonDTMF.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonDTMF);
mButtonDTMF = null;
}
}
if (mButtonAutoRetry != null) {
if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
mButtonAutoRetry.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonAutoRetry);
mButtonAutoRetry = null;
}
}
if (mButtonHAC != null) {
if (getResources().getBoolean(R.bool.hac_enabled)) {
mButtonHAC.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonHAC);
mButtonHAC = null;
}
}
if (mButtonTTY != null) {
if (getResources().getBoolean(R.bool.tty_enabled)) {
mButtonTTY.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonTTY);
mButtonTTY = null;
}
}
if (mButtonNoiseSuppression != null) {
if (getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
mButtonNoiseSuppression.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonNoiseSuppression);
mButtonNoiseSuppression = null;
}
}
if (!getResources().getBoolean(R.bool.world_phone)) {
Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
if (options != null)
prefSet.removePreference(options);
options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
if (options != null)
prefSet.removePreference(options);
int phoneType = mPhone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
if (fdnButton != null)
prefSet.removePreference(fdnButton);
if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
addPreferencesFromResource(R.xml.cdma_call_privacy);
}
} else if (phoneType == Phone.PHONE_TYPE_GSM) {
addPreferencesFromResource(R.xml.gsm_umts_call_options);
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
// create intent to bring up contact list
mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
// check the intent that started this activity and pop up the voicemail
// dialog if we've been asked to.
// If we have at least one non default VM provider registered then bring up
// the selection for the VM provider, otherwise bring up a VM number dialog.
// We only bring up the dialog the first time we are called (not after orientation change)
if (icicle == null) {
if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL) &&
mVoicemailProviders != null) {
if (DBG) {
log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
+ mVMProvidersData.size());
}
if (mVMProvidersData.size() > 1) {
simulatePreferenceClick(mVoicemailProviders);
} else {
onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
}
}
}
updateVoiceNumberField();
mVMProviderSettingsForced = false;
createSipCallSettings();
mRingtoneLookupRunnable = new Runnable() {
@Override
public void run() {
if (mRingtonePreference != null) {
updateRingtoneName(RingtoneManager.TYPE_RINGTONE, mRingtonePreference,
MSG_UPDATE_RINGTONE_SUMMARY);
}
}
};
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// android.R.id.home will be triggered in onOptionsItemSelected()
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* Updates ringtone name. This is a method copied from com.android.settings.SoundSettings
*
* @see com.android.settings.SoundSettings
*/
private void updateRingtoneName(int type, Preference preference, int msg) {
if (preference == null) return;
Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(this, type);
CharSequence summary = getString(com.android.internal.R.string.ringtone_unknown);
// Is it a silent ringtone?
if (ringtoneUri == null) {
summary = getString(com.android.internal.R.string.ringtone_silent);
} else {
// Fetch the ringtone title from the media provider
try {
Cursor cursor = getContentResolver().query(ringtoneUri,
new String[] { MediaStore.Audio.Media.TITLE }, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
summary = cursor.getString(0);
}
cursor.close();
}
} catch (SQLiteException sqle) {
// Unknown title for the ringtone
}
}
mRingtoneLookupComplete.sendMessage(mRingtoneLookupComplete.obtainMessage(msg, summary));
}
private void createSipCallSettings() {
// Add Internet call settings.
if (PhoneUtils.isVoipSupported()) {
mSipManager = SipManager.newInstance(this);
mSipSharedPreferences = new SipSharedPreferences(this);
addPreferencesFromResource(R.xml.sip_settings_category);
mButtonSipCallOptions = getSipCallOptionPreference();
mButtonSipCallOptions.setOnPreferenceChangeListener(this);
mButtonSipCallOptions.setValueIndex(
mButtonSipCallOptions.findIndexOfValue(
mSipSharedPreferences.getSipCallOption()));
mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
}
}
// Gets the call options for SIP depending on whether SIP is allowed only
// on Wi-Fi only; also make the other options preference invisible.
private ListPreference getSipCallOptionPreference() {
ListPreference wifiAnd3G = (ListPreference)
findPreference(BUTTON_SIP_CALL_OPTIONS);
ListPreference wifiOnly = (ListPreference)
findPreference(BUTTON_SIP_CALL_OPTIONS_WIFI_ONLY);
PreferenceGroup sipSettings = (PreferenceGroup)
findPreference(SIP_SETTINGS_CATEGORY_KEY);
if (SipManager.isSipWifiOnly(this)) {
sipSettings.removePreference(wifiAnd3G);
return wifiOnly;
} else {
sipSettings.removePreference(wifiOnly);
return wifiAnd3G;
}
}
@Override
protected void onResume() {
super.onResume();
mForeground = true;
if (isAirplaneModeOn()) {
Preference sipSettings = findPreference(SIP_SETTINGS_CATEGORY_KEY);
PreferenceScreen screen = getPreferenceScreen();
int count = screen.getPreferenceCount();
for (int i = 0 ; i < count ; ++i) {
Preference pref = screen.getPreference(i);
if (pref != sipSettings) pref.setEnabled(false);
}
return;
}
if (mVibrateWhenRinging != null) {
mVibrateWhenRinging.setChecked(getVibrateWhenRinging(this));
}
if (mMwiNotification != null) {
int mwi_notification = Settings.System.getInt(getContentResolver(), Settings.System.ENABLE_MWI_NOTIFICATION, 0);
mMwiNotification.setChecked(mwi_notification != 0);
}
if (mButtonDTMF != null) {
int dtmf = Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, DTMF_TONE_TYPE_NORMAL);
mButtonDTMF.setValueIndex(dtmf);
}
if (mButtonAutoRetry != null) {
int autoretry = Settings.System.getInt(getContentResolver(),
Settings.System.CALL_AUTO_RETRY, 0);
mButtonAutoRetry.setChecked(autoretry != 0);
}
if (mButtonHAC != null) {
int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
mButtonHAC.setChecked(hac != 0);
}
if (mButtonTTY != null) {
int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
Settings.Secure.PREFERRED_TTY_MODE,
Phone.TTY_MODE_OFF);
mButtonTTY.setValue(Integer.toString(settingsTtyMode));
updatePreferredTtyModeSummary(settingsTtyMode);
}
if (mButtonNoiseSuppression != null) {
int nsp = Settings.System.getInt(getContentResolver(), Settings.System.NOISE_SUPPRESSION, 1);
mButtonNoiseSuppression.setChecked(nsp != 0);
}
lookupRingtoneName();
}
/**
* Obtain the setting for "vibrate when ringing" setting.
*
* Watch out: if the setting is missing in the device, this will try obtaining the old
* "vibrate on ring" setting from AudioManager, and save the previous setting to the new one.
*/
public static boolean getVibrateWhenRinging(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator == null || !vibrator.hasVibrator()) {
return false;
}
return Settings.System.getInt(context.getContentResolver(),
Settings.System.VIBRATE_WHEN_RINGING, 0) != 0;
}
/**
* Lookups ringtone name asynchronously and updates the relevant Preference.
*/
private void lookupRingtoneName() {
new Thread(mRingtoneLookupRunnable).start();
}
private boolean isAirplaneModeOn() {
return Settings.System.getInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void handleTTYChange(Preference preference, Object objValue) {
int buttonTtyMode;
buttonTtyMode = Integer.valueOf((String) objValue).intValue();
int settingsTtyMode = android.provider.Settings.Secure.getInt(
getContentResolver(),
android.provider.Settings.Secure.PREFERRED_TTY_MODE, preferredTtyMode);
if (DBG) log("handleTTYChange: requesting set TTY mode enable (TTY) to" +
Integer.toString(buttonTtyMode));
if (buttonTtyMode != settingsTtyMode) {
switch(buttonTtyMode) {
case Phone.TTY_MODE_OFF:
case Phone.TTY_MODE_FULL:
case Phone.TTY_MODE_HCO:
case Phone.TTY_MODE_VCO:
android.provider.Settings.Secure.putInt(getContentResolver(),
android.provider.Settings.Secure.PREFERRED_TTY_MODE, buttonTtyMode);
break;
default:
buttonTtyMode = Phone.TTY_MODE_OFF;
}
mButtonTTY.setValue(Integer.toString(buttonTtyMode));
updatePreferredTtyModeSummary(buttonTtyMode);
Intent ttyModeChanged = new Intent(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
ttyModeChanged.putExtra(TtyIntent.TTY_PREFFERED_MODE, buttonTtyMode);
sendBroadcast(ttyModeChanged);
}
}
private void handleSipCallOptionsChange(Object objValue) {
String option = objValue.toString();
mSipSharedPreferences.setSipCallOption(option);
mButtonSipCallOptions.setValueIndex(
mButtonSipCallOptions.findIndexOfValue(option));
mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
}
private void updatePreferredTtyModeSummary(int TtyMode) {
String [] txts = getResources().getStringArray(R.array.tty_mode_entries);
switch(TtyMode) {
case Phone.TTY_MODE_OFF:
case Phone.TTY_MODE_HCO:
case Phone.TTY_MODE_VCO:
case Phone.TTY_MODE_FULL:
mButtonTTY.setSummary(txts[TtyMode]);
break;
default:
mButtonTTY.setEnabled(false);
mButtonTTY.setSummary(txts[Phone.TTY_MODE_OFF]);
}
}
private static void log(String msg) {
Log.d(LOG_TAG, msg);
}
/**
* Updates the look of the VM preference widgets based on current VM provider settings.
* Note that the provider name is loaded form the found activity via loadLabel in
* {@link #initVoiceMailProviders()} in order for it to be localizable.
*/
private void updateVMPreferenceWidgets(String currentProviderSetting) {
final String key = currentProviderSetting;
final VoiceMailProvider provider = mVMProvidersData.get(key);
/* This is the case when we are coming up on a freshly wiped phone and there is no
persisted value for the list preference mVoicemailProviders.
In this case we want to show the UI asking the user to select a voicemail provider as
opposed to silently falling back to default one. */
if (provider == null) {
if (DBG) {
log("updateVMPreferenceWidget: provider for the key \"" + key + "\" is null.");
}
mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
mVoicemailSettings.setEnabled(false);
mVoicemailSettings.setIntent(null);
mVoicemailNotificationVibrateWhen.setEnabled(false);
mVoicemailNotificationVibrateWhen.setSummary("");
} else {
if (DBG) {
log("updateVMPreferenceWidget: provider for the key \"" + key + "\".."
+ "name: " + provider.name
+ ", intent: " + provider.intent);
}
final String providerName = provider.name;
mVoicemailProviders.setSummary(providerName);
mVoicemailSettings.setEnabled(true);
mVoicemailSettings.setIntent(provider.intent);
mVoicemailNotificationVibrateWhen.setEnabled(true);
mVoicemailNotificationVibrateWhen.setSummary(
mVoicemailNotificationVibrateWhen.getEntry());
}
}
/**
* Enumerates existing VM providers and puts their data into the list and populates
* the preference list objects with their names.
* In case we are called with ACTION_ADD_VOICEMAIL intent the intent may have
* an extra string called IGNORE_PROVIDER_EXTRA with "package.activityName" of the provider
* which should be hidden when we bring up the list of possible VM providers to choose.
*/
private void initVoiceMailProviders() {
if (DBG) log("initVoiceMailProviders()");
mPerProviderSavedVMNumbers =
this.getApplicationContext().getSharedPreferences(
VM_NUMBERS_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
String providerToIgnore = null;
if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
if (getIntent().hasExtra(IGNORE_PROVIDER_EXTRA)) {
providerToIgnore = getIntent().getStringExtra(IGNORE_PROVIDER_EXTRA);
}
if (DBG) log("Found ACTION_ADD_VOICEMAIL. providerToIgnore=" + providerToIgnore);
if (providerToIgnore != null) {
// IGNORE_PROVIDER_EXTRA implies we want to remove the choice from the list.
deleteSettingsForVoicemailProvider(providerToIgnore);
}
}
mVMProvidersData.clear();
// Stick the default element which is always there
final String myCarrier = getString(R.string.voicemail_default);
mVMProvidersData.put(DEFAULT_VM_PROVIDER_KEY, new VoiceMailProvider(myCarrier, null));
// Enumerate providers
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction(ACTION_CONFIGURE_VOICEMAIL);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
int len = resolveInfos.size() + 1; // +1 for the default choice we will insert.
// Go through the list of discovered providers populating the data map
// skip the provider we were instructed to ignore if there was one
for (int i = 0; i < resolveInfos.size(); i++) {
final ResolveInfo ri= resolveInfos.get(i);
final ActivityInfo currentActivityInfo = ri.activityInfo;
final String key = makeKeyForActivity(currentActivityInfo);
if (key.equals(providerToIgnore)) {
if (DBG) log("Ignoring key: " + key);
len--;
continue;
}
if (DBG) log("Loading key: " + key);
final String nameForDisplay = ri.loadLabel(pm).toString();
Intent providerIntent = new Intent();
providerIntent.setAction(ACTION_CONFIGURE_VOICEMAIL);
providerIntent.setClassName(currentActivityInfo.packageName,
currentActivityInfo.name);
if (DBG) {
log("Store loaded VoiceMailProvider. key: " + key
+ " -> name: " + nameForDisplay + ", intent: " + providerIntent);
}
mVMProvidersData.put(
key,
new VoiceMailProvider(nameForDisplay, providerIntent));
}
// Now we know which providers to display - create entries and values array for
// the list preference
String [] entries = new String [len];
String [] values = new String [len];
entries[0] = myCarrier;
values[0] = DEFAULT_VM_PROVIDER_KEY;
int entryIdx = 1;
for (int i = 0; i < resolveInfos.size(); i++) {
final String key = makeKeyForActivity(resolveInfos.get(i).activityInfo);
if (!mVMProvidersData.containsKey(key)) {
continue;
}
entries[entryIdx] = mVMProvidersData.get(key).name;
values[entryIdx] = key;
entryIdx++;
}
// ListPreference is now updated.
mVoicemailProviders.setEntries(entries);
mVoicemailProviders.setEntryValues(values);
// Remember the current Voicemail Provider key as a "previous" key. This will be used
// when we fail to update Voicemail Provider, which requires rollback.
// We will update this when the VM Provider setting is successfully updated.
mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
if (DBG) log("Set up the first mPreviousVMProviderKey: " + mPreviousVMProviderKey);
// Finally update the preference texts.
updateVMPreferenceWidgets(mPreviousVMProviderKey);
}
private String makeKeyForActivity(ActivityInfo ai) {
return ai.name;
}
/**
* Simulates user clicking on a passed preference.
* Usually needed when the preference is a dialog preference and we want to invoke
* a dialog for this preference programmatically.
* TODO(iliat): figure out if there is a cleaner way to cause preference dlg to come up
*/
private void simulatePreferenceClick(Preference preference) {
// Go through settings until we find our setting
// and then simulate a click on it to bring up the dialog
final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
for (int idx = 0; idx < adapter.getCount(); idx++) {
if (adapter.getItem(idx) == preference) {
getPreferenceScreen().onItemClick(this.getListView(),
null, idx, adapter.getItemId(idx));
break;
}
}
}
/**
* Saves new VM provider settings associating them with the currently selected
* provider if settings are different than the ones already stored for this
* provider.
* Later on these will be used when the user switches a provider.
*/
private void maybeSaveSettingsForVoicemailProvider(String key,
VoiceMailProviderSettings newSettings) {
if (mVoicemailProviders == null) {
return;
}
final VoiceMailProviderSettings curSettings = loadSettingsForVoiceMailProvider(key);
if (newSettings.equals(curSettings)) {
if (DBG) {
log("maybeSaveSettingsForVoicemailProvider:"
+ " Not saving setting for " + key + " since they have not changed");
}
return;
}
if (DBG) log("Saving settings for " + key + ": " + newSettings.toString());
Editor editor = mPerProviderSavedVMNumbers.edit();
editor.putString(key + VM_NUMBER_TAG, newSettings.voicemailNumber);
String fwdKey = key + FWD_SETTINGS_TAG;
CallForwardInfo[] s = newSettings.forwardingSettings;
if (s != FWD_SETTINGS_DONT_TOUCH) {
editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, s.length);
for (int i = 0; i < s.length; i++) {
final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
final CallForwardInfo fi = s[i];
editor.putInt(settingKey + FWD_SETTING_STATUS, fi.status);
editor.putInt(settingKey + FWD_SETTING_REASON, fi.reason);
editor.putString(settingKey + FWD_SETTING_NUMBER, fi.number);
editor.putInt(settingKey + FWD_SETTING_TIME, fi.timeSeconds);
}
} else {
editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
}
editor.apply();
}
/**
* Returns settings previously stored for the currently selected
* voice mail provider. If none is stored returns null.
* If the user switches to a voice mail provider and we have settings
* stored for it we will automatically change the phone's voice mail number
* and forwarding number to the stored one. Otherwise we will bring up provider's configuration
* UI.
*/
private VoiceMailProviderSettings loadSettingsForVoiceMailProvider(String key) {
final String vmNumberSetting = mPerProviderSavedVMNumbers.getString(key + VM_NUMBER_TAG,
null);
if (vmNumberSetting == null) {
Log.w(LOG_TAG, "VoiceMailProvider settings for the key \"" + key + "\""
+ " was not found. Returning null.");
return null;
}
CallForwardInfo[] cfi = FWD_SETTINGS_DONT_TOUCH;
String fwdKey = key + FWD_SETTINGS_TAG;
final int fwdLen = mPerProviderSavedVMNumbers.getInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
if (fwdLen > 0) {
cfi = new CallForwardInfo[fwdLen];
for (int i = 0; i < cfi.length; i++) {
final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
cfi[i] = new CallForwardInfo();
cfi[i].status = mPerProviderSavedVMNumbers.getInt(
settingKey + FWD_SETTING_STATUS, 0);
cfi[i].reason = mPerProviderSavedVMNumbers.getInt(
settingKey + FWD_SETTING_REASON,
CommandsInterface.CF_REASON_ALL_CONDITIONAL);
cfi[i].serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
cfi[i].toa = PhoneNumberUtils.TOA_International;
cfi[i].number = mPerProviderSavedVMNumbers.getString(
settingKey + FWD_SETTING_NUMBER, "");
cfi[i].timeSeconds = mPerProviderSavedVMNumbers.getInt(
settingKey + FWD_SETTING_TIME, 20);
}
}
VoiceMailProviderSettings settings = new VoiceMailProviderSettings(vmNumberSetting, cfi);
if (DBG) log("Loaded settings for " + key + ": " + settings.toString());
return settings;
}
/**
* Deletes settings for the specified provider.
*/
private void deleteSettingsForVoicemailProvider(String key) {
if (DBG) log("Deleting settings for" + key);
if (mVoicemailProviders == null) {
return;
}
mPerProviderSavedVMNumbers.edit()
.putString(key + VM_NUMBER_TAG, null)
.putInt(key + FWD_SETTINGS_TAG + FWD_SETTINGS_LENGTH_TAG, 0)
.commit();
}
private String getCurrentVoicemailProviderKey() {
final String key = mVoicemailProviders.getValue();
return (key != null) ? key : DEFAULT_VM_PROVIDER_KEY;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == android.R.id.home) { // See ActionBar#setDisplayHomeAsUpEnabled()
Intent intent = new Intent();
intent.setClassName(UP_ACTIVITY_PACKAGE, UP_ACTIVITY_CLASS);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Finish current Activity and go up to the top level Settings ({@link CallFeaturesSetting}).
* This is useful for implementing "HomeAsUp" capability for second-level Settings.
*/
public static void goUpToTopLevelSetting(Activity activity) {
Intent intent = new Intent(activity, CallFeaturesSetting.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
activity.finish();
}
}
| true | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (DBG) log("onCreate(). Intent: " + getIntent());
mPhone = PhoneApp.getPhone();
addPreferencesFromResource(R.xml.call_feature_setting);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// get buttons
PreferenceScreen prefSet = getPreferenceScreen();
mSubMenuVoicemailSettings = (EditPhoneNumberPreference)findPreference(BUTTON_VOICEMAIL_KEY);
if (mSubMenuVoicemailSettings != null) {
mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
}
mRingtonePreference = findPreference(BUTTON_RINGTONE_KEY);
mVibrateWhenRinging = (CheckBoxPreference) findPreference(BUTTON_VIBRATE_ON_RING);
mPlayDtmfTone = (CheckBoxPreference) findPreference(BUTTON_PLAY_DTMF_TONE);
mMwiNotification = (CheckBoxPreference) findPreference(BUTTON_MWI_NOTIFICATION_KEY);
if (mMwiNotification != null) {
if (getResources().getBoolean(R.bool.sprint_mwi_quirk)) {
mMwiNotification.setOnPreferenceChangeListener(this);
} else {
PreferenceCategory voicemailCategory = (PreferenceCategory) findPreference(BUTTON_VOICEMAIL_CATEGORY_KEY);
voicemailCategory.removePreference(mMwiNotification);
mMwiNotification = null;
}
}
mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
mButtonNoiseSuppression = (CheckBoxPreference) findPreference(BUTTON_NOISE_SUPPRESSION_KEY);
mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
if (mVoicemailProviders != null) {
mVoicemailProviders.setOnPreferenceChangeListener(this);
mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
mVoicemailNotificationVibrateWhen =
(ListPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY);
mVoicemailNotificationVibrateWhen.setOnPreferenceChangeListener(this);
initVoiceMailProviders();
}
if (mVibrateWhenRinging != null) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
mVibrateWhenRinging.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mVibrateWhenRinging);
mVibrateWhenRinging = null;
}
}
if (mPlayDtmfTone != null) {
mPlayDtmfTone.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) != 0);
}
if (mButtonDTMF != null) {
if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
mButtonDTMF.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonDTMF);
mButtonDTMF = null;
}
}
if (mButtonAutoRetry != null) {
if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
mButtonAutoRetry.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonAutoRetry);
mButtonAutoRetry = null;
}
}
if (mButtonHAC != null) {
if (getResources().getBoolean(R.bool.hac_enabled)) {
mButtonHAC.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonHAC);
mButtonHAC = null;
}
}
if (mButtonTTY != null) {
if (getResources().getBoolean(R.bool.tty_enabled)) {
mButtonTTY.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonTTY);
mButtonTTY = null;
}
}
if (mButtonNoiseSuppression != null) {
if (getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
mButtonNoiseSuppression.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonNoiseSuppression);
mButtonNoiseSuppression = null;
}
}
if (!getResources().getBoolean(R.bool.world_phone)) {
Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
if (options != null)
prefSet.removePreference(options);
options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
if (options != null)
prefSet.removePreference(options);
int phoneType = mPhone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
if (fdnButton != null)
prefSet.removePreference(fdnButton);
if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
addPreferencesFromResource(R.xml.cdma_call_privacy);
}
} else if (phoneType == Phone.PHONE_TYPE_GSM) {
addPreferencesFromResource(R.xml.gsm_umts_call_options);
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
// create intent to bring up contact list
mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
// check the intent that started this activity and pop up the voicemail
// dialog if we've been asked to.
// If we have at least one non default VM provider registered then bring up
// the selection for the VM provider, otherwise bring up a VM number dialog.
// We only bring up the dialog the first time we are called (not after orientation change)
if (icicle == null) {
if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL) &&
mVoicemailProviders != null) {
if (DBG) {
log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
+ mVMProvidersData.size());
}
if (mVMProvidersData.size() > 1) {
simulatePreferenceClick(mVoicemailProviders);
} else {
onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
}
}
}
updateVoiceNumberField();
mVMProviderSettingsForced = false;
createSipCallSettings();
mRingtoneLookupRunnable = new Runnable() {
@Override
public void run() {
if (mRingtonePreference != null) {
updateRingtoneName(RingtoneManager.TYPE_RINGTONE, mRingtonePreference,
MSG_UPDATE_RINGTONE_SUMMARY);
}
}
};
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// android.R.id.home will be triggered in onOptionsItemSelected()
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (DBG) log("onCreate(). Intent: " + getIntent());
mPhone = PhoneApp.getPhone();
addPreferencesFromResource(R.xml.call_feature_setting);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// get buttons
PreferenceScreen prefSet = getPreferenceScreen();
mSubMenuVoicemailSettings = (EditPhoneNumberPreference)findPreference(BUTTON_VOICEMAIL_KEY);
if (mSubMenuVoicemailSettings != null) {
mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
}
mRingtonePreference = findPreference(BUTTON_RINGTONE_KEY);
mVibrateWhenRinging = (CheckBoxPreference) findPreference(BUTTON_VIBRATE_ON_RING);
mPlayDtmfTone = (CheckBoxPreference) findPreference(BUTTON_PLAY_DTMF_TONE);
mMwiNotification = (CheckBoxPreference) findPreference(BUTTON_MWI_NOTIFICATION_KEY);
if (mMwiNotification != null) {
if (getResources().getBoolean(R.bool.sprint_mwi_quirk)) {
mMwiNotification.setOnPreferenceChangeListener(this);
} else {
PreferenceScreen voicemailCategory = (PreferenceScreen) findPreference(BUTTON_VOICEMAIL_CATEGORY_KEY);
voicemailCategory.removePreference(mMwiNotification);
mMwiNotification = null;
}
}
mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
mButtonNoiseSuppression = (CheckBoxPreference) findPreference(BUTTON_NOISE_SUPPRESSION_KEY);
mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
if (mVoicemailProviders != null) {
mVoicemailProviders.setOnPreferenceChangeListener(this);
mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
mVoicemailNotificationVibrateWhen =
(ListPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY);
mVoicemailNotificationVibrateWhen.setOnPreferenceChangeListener(this);
initVoiceMailProviders();
}
if (mVibrateWhenRinging != null) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
mVibrateWhenRinging.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mVibrateWhenRinging);
mVibrateWhenRinging = null;
}
}
if (mPlayDtmfTone != null) {
mPlayDtmfTone.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) != 0);
}
if (mButtonDTMF != null) {
if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
mButtonDTMF.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonDTMF);
mButtonDTMF = null;
}
}
if (mButtonAutoRetry != null) {
if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
mButtonAutoRetry.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonAutoRetry);
mButtonAutoRetry = null;
}
}
if (mButtonHAC != null) {
if (getResources().getBoolean(R.bool.hac_enabled)) {
mButtonHAC.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonHAC);
mButtonHAC = null;
}
}
if (mButtonTTY != null) {
if (getResources().getBoolean(R.bool.tty_enabled)) {
mButtonTTY.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonTTY);
mButtonTTY = null;
}
}
if (mButtonNoiseSuppression != null) {
if (getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
mButtonNoiseSuppression.setOnPreferenceChangeListener(this);
} else {
prefSet.removePreference(mButtonNoiseSuppression);
mButtonNoiseSuppression = null;
}
}
if (!getResources().getBoolean(R.bool.world_phone)) {
Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
if (options != null)
prefSet.removePreference(options);
options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
if (options != null)
prefSet.removePreference(options);
int phoneType = mPhone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
if (fdnButton != null)
prefSet.removePreference(fdnButton);
if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
addPreferencesFromResource(R.xml.cdma_call_privacy);
}
} else if (phoneType == Phone.PHONE_TYPE_GSM) {
addPreferencesFromResource(R.xml.gsm_umts_call_options);
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
// create intent to bring up contact list
mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
// check the intent that started this activity and pop up the voicemail
// dialog if we've been asked to.
// If we have at least one non default VM provider registered then bring up
// the selection for the VM provider, otherwise bring up a VM number dialog.
// We only bring up the dialog the first time we are called (not after orientation change)
if (icicle == null) {
if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL) &&
mVoicemailProviders != null) {
if (DBG) {
log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
+ mVMProvidersData.size());
}
if (mVMProvidersData.size() > 1) {
simulatePreferenceClick(mVoicemailProviders);
} else {
onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
}
}
}
updateVoiceNumberField();
mVMProviderSettingsForced = false;
createSipCallSettings();
mRingtoneLookupRunnable = new Runnable() {
@Override
public void run() {
if (mRingtonePreference != null) {
updateRingtoneName(RingtoneManager.TYPE_RINGTONE, mRingtonePreference,
MSG_UPDATE_RINGTONE_SUMMARY);
}
}
};
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// android.R.id.home will be triggered in onOptionsItemSelected()
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java
index 749db3d..2d24d3e 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java
@@ -1,175 +1,174 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.tests.integration;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.mylyn.context.tests.UiTestUtil;
import org.eclipse.mylyn.internal.context.ui.TaskListInterestFilter;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.LocalTask;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.ui.AbstractTaskListFilter;
import org.eclipse.mylyn.internal.tasks.ui.TaskListManager;
import org.eclipse.mylyn.internal.tasks.ui.TaskWorkingSetFilter;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.internal.tasks.ui.workingsets.TaskWorkingSetUpdater;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.Workbench;
/**
* @author Mik Kersten
*/
public class TaskListFilterTest extends TestCase {
private TaskListView view;
private final TaskListManager manager = TasksUiPlugin.getTaskListManager();
private Set<AbstractTaskListFilter> previousFilters;
private AbstractTask taskCompleted;
private AbstractTask taskIncomplete;
private AbstractTask taskOverdue;
private AbstractTask taskDueToday;
private AbstractTask taskCompletedToday;
private AbstractTask taskScheduledLastWeek;
private AbstractTask taskCompleteAndOverdue;
@Override
protected void setUp() throws Exception {
super.setUp();
view = TaskListView.openInActivePerspective();
assertNotNull(view);
previousFilters = view.getFilters();
view.clearFilters(false);
manager.getTaskList().reset();
assertEquals(0, manager.getTaskList().getAllTasks().size());
taskCompleted = new LocalTask("1", "completed");
taskCompleted.setCompletionDate(TaskActivityUtil.snapForwardNumDays(Calendar.getInstance(), -1).getTime());
manager.getTaskList().addTask(taskCompleted);
taskIncomplete = new LocalTask("2", "t-incomplete");
manager.getTaskList().addTask(taskIncomplete);
taskOverdue = new LocalTask("3", "t-overdue");
- taskOverdue.setScheduledForDate(TaskActivityUtil.snapForwardNumDays(Calendar.getInstance(), -1).getTime());
+ taskOverdue.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday().previous());
manager.getTaskList().addTask(taskOverdue);
taskDueToday = new LocalTask("4", "t-today");
- taskDueToday.setScheduledForDate(TaskActivityUtil.snapEndOfWorkDay(Calendar.getInstance()).getTime());
+ taskDueToday.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday());
manager.getTaskList().addTask(taskDueToday);
taskCompletedToday = new LocalTask("5", "t-donetoday");
- taskCompletedToday.setScheduledForDate(TaskActivityUtil.snapEndOfWorkDay(Calendar.getInstance()).getTime());
+ taskCompletedToday.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday());
taskCompletedToday.setCompletionDate(new Date());
manager.getTaskList().addTask(taskCompletedToday);
taskScheduledLastWeek = new LocalTask("6", "t-scheduledLastWeek");
manager.getTaskList().addTask(taskScheduledLastWeek);
- Calendar lastWeek = Calendar.getInstance();
- lastWeek.add(Calendar.WEEK_OF_MONTH, -1);
- TasksUiPlugin.getTaskActivityManager().setScheduledFor(taskScheduledLastWeek, lastWeek.getTime(), true);
+ TasksUiPlugin.getTaskActivityManager().setScheduledFor(taskScheduledLastWeek,
+ TaskActivityUtil.getCurrentWeek().previous());
taskCompleteAndOverdue = new LocalTask("7", "t-completeandoverdue");
manager.getTaskList().addTask(taskCompleteAndOverdue);
Calendar cal = TaskActivityUtil.getCalendar();
cal.add(Calendar.DAY_OF_MONTH, -1);
TasksUiPlugin.getTaskActivityManager().setDueDate(taskCompleteAndOverdue, cal.getTime());
taskCompleteAndOverdue.setCompletionDate(cal.getTime());
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
view.clearFilters(true);
for (AbstractTaskListFilter filter : previousFilters) {
view.addFilter(filter);
}
}
public void testSearchScheduledWorkingSet() throws InterruptedException {
TaskCategory category = new TaskCategory("category");
manager.getTaskList().addCategory(category);
manager.getTaskList().addTask(taskOverdue, category);
manager.getTaskList().addTask(taskIncomplete, category);
view.getViewer().refresh();
view.getViewer().expandAll();
List<Object> items = UiTestUtil.getAllData(view.getViewer().getTree());
assertTrue(items.contains(taskCompleted));
assertTrue(items.contains(taskOverdue));
IWorkingSetManager workingSetManager = Workbench.getInstance().getWorkingSetManager();
IWorkingSet workingSet = workingSetManager.createWorkingSet("Task Working Set", new IAdaptable[] { category });
workingSet.setId(TaskWorkingSetUpdater.ID_TASK_WORKING_SET);
assertTrue(Arrays.asList(workingSet.getElements()).contains(category));
workingSetManager.addWorkingSet(workingSet);
TaskWorkingSetFilter workingSetFilter = new TaskWorkingSetFilter();
view.addFilter(workingSetFilter);
IWorkingSet[] workingSets = { workingSet };
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().setWorkingSets(workingSets);
view.getFilteredTree().setFilterText("over");
view.getFilteredTree().getRefreshPolicy().internalForceRefresh();
items = UiTestUtil.getAllData(view.getViewer().getTree());
assertFalse(items.contains(taskCompleted));
assertTrue(items.contains(taskOverdue));
workingSets = new IWorkingSet[0];
view.removeFilter(workingSetFilter);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().setWorkingSets(workingSets);
manager.getTaskList().removeFromContainer(category, taskOverdue);
manager.getTaskList().removeFromContainer(category, taskIncomplete);
view.getFilteredTree().setFilterText("");
view.getFilteredTree().getRefreshPolicy().internalForceRefresh();
}
public void testInterestFilter() {
TaskListInterestFilter interestFilter = new TaskListInterestFilter();
view.addFilter(interestFilter);
view.getViewer().refresh();
view.getViewer().expandAll();
List<Object> items = UiTestUtil.getAllData(view.getViewer().getTree());
assertFalse(items.contains(taskCompleted));
assertFalse(items.contains(taskIncomplete));
assertTrue(items.contains(taskOverdue));
assertTrue(items.contains(taskDueToday));
assertTrue(items.contains(taskCompletedToday));
assertTrue(items.contains(taskScheduledLastWeek));
assertFalse(items.contains(taskCompleteAndOverdue));
view.removeFilter(interestFilter);
}
public void testNoFilters() {
assertEquals("should have working set filter and orphan/archive filter: " + view.getFilters(), 2,
view.getFilters().size());
view.getViewer().refresh();
assertEquals("should only have Uncategorized folder present in stock task list: "
+ view.getViewer().getTree().getItems(), 1, view.getViewer().getTree().getItemCount());
}
}
| false | true | protected void setUp() throws Exception {
super.setUp();
view = TaskListView.openInActivePerspective();
assertNotNull(view);
previousFilters = view.getFilters();
view.clearFilters(false);
manager.getTaskList().reset();
assertEquals(0, manager.getTaskList().getAllTasks().size());
taskCompleted = new LocalTask("1", "completed");
taskCompleted.setCompletionDate(TaskActivityUtil.snapForwardNumDays(Calendar.getInstance(), -1).getTime());
manager.getTaskList().addTask(taskCompleted);
taskIncomplete = new LocalTask("2", "t-incomplete");
manager.getTaskList().addTask(taskIncomplete);
taskOverdue = new LocalTask("3", "t-overdue");
taskOverdue.setScheduledForDate(TaskActivityUtil.snapForwardNumDays(Calendar.getInstance(), -1).getTime());
manager.getTaskList().addTask(taskOverdue);
taskDueToday = new LocalTask("4", "t-today");
taskDueToday.setScheduledForDate(TaskActivityUtil.snapEndOfWorkDay(Calendar.getInstance()).getTime());
manager.getTaskList().addTask(taskDueToday);
taskCompletedToday = new LocalTask("5", "t-donetoday");
taskCompletedToday.setScheduledForDate(TaskActivityUtil.snapEndOfWorkDay(Calendar.getInstance()).getTime());
taskCompletedToday.setCompletionDate(new Date());
manager.getTaskList().addTask(taskCompletedToday);
taskScheduledLastWeek = new LocalTask("6", "t-scheduledLastWeek");
manager.getTaskList().addTask(taskScheduledLastWeek);
Calendar lastWeek = Calendar.getInstance();
lastWeek.add(Calendar.WEEK_OF_MONTH, -1);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(taskScheduledLastWeek, lastWeek.getTime(), true);
taskCompleteAndOverdue = new LocalTask("7", "t-completeandoverdue");
manager.getTaskList().addTask(taskCompleteAndOverdue);
Calendar cal = TaskActivityUtil.getCalendar();
cal.add(Calendar.DAY_OF_MONTH, -1);
TasksUiPlugin.getTaskActivityManager().setDueDate(taskCompleteAndOverdue, cal.getTime());
taskCompleteAndOverdue.setCompletionDate(cal.getTime());
}
| protected void setUp() throws Exception {
super.setUp();
view = TaskListView.openInActivePerspective();
assertNotNull(view);
previousFilters = view.getFilters();
view.clearFilters(false);
manager.getTaskList().reset();
assertEquals(0, manager.getTaskList().getAllTasks().size());
taskCompleted = new LocalTask("1", "completed");
taskCompleted.setCompletionDate(TaskActivityUtil.snapForwardNumDays(Calendar.getInstance(), -1).getTime());
manager.getTaskList().addTask(taskCompleted);
taskIncomplete = new LocalTask("2", "t-incomplete");
manager.getTaskList().addTask(taskIncomplete);
taskOverdue = new LocalTask("3", "t-overdue");
taskOverdue.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday().previous());
manager.getTaskList().addTask(taskOverdue);
taskDueToday = new LocalTask("4", "t-today");
taskDueToday.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday());
manager.getTaskList().addTask(taskDueToday);
taskCompletedToday = new LocalTask("5", "t-donetoday");
taskCompletedToday.setScheduledForDate(TaskActivityUtil.getCurrentWeek().getToday());
taskCompletedToday.setCompletionDate(new Date());
manager.getTaskList().addTask(taskCompletedToday);
taskScheduledLastWeek = new LocalTask("6", "t-scheduledLastWeek");
manager.getTaskList().addTask(taskScheduledLastWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(taskScheduledLastWeek,
TaskActivityUtil.getCurrentWeek().previous());
taskCompleteAndOverdue = new LocalTask("7", "t-completeandoverdue");
manager.getTaskList().addTask(taskCompleteAndOverdue);
Calendar cal = TaskActivityUtil.getCalendar();
cal.add(Calendar.DAY_OF_MONTH, -1);
TasksUiPlugin.getTaskActivityManager().setDueDate(taskCompleteAndOverdue, cal.getTime());
taskCompleteAndOverdue.setCompletionDate(cal.getTime());
}
|
diff --git a/JPL/ch17/ex17_04/ResourceManager.java b/JPL/ch17/ex17_04/ResourceManager.java
index 3c4c414..767ad07 100644
--- a/JPL/ch17/ex17_04/ResourceManager.java
+++ b/JPL/ch17/ex17_04/ResourceManager.java
@@ -1,101 +1,103 @@
package ch17.ex17_04;
import java.lang.ref.*;
import java.util.*;
public final class ResourceManager {
final ReferenceQueue<Object> queue;
final Map<Reference<?>, Resource> refs;
final Thread reaper;
boolean shutdown = false;
public ResourceManager() {
queue = new ReferenceQueue<Object>();
refs = new HashMap<Reference<?>, Resource>();
reaper = new ReaperThread();
reaper.start();
// ... リソースの初期化 ...
}
public synchronized void shutdown() {
if (!shutdown) {
shutdown = true;
reaper.interrupt();
}
}
public synchronized Resource getResource(Object key) {
if (shutdown)
throw new IllegalStateException();
Resource res = new ResourceImpl(key);
Reference<?> ref = new PhantomReference<Object>(key, queue);
refs.put(ref, res);
return res;
}
private static class ResourceImpl implements Resource {
WeakReference<Object> key;
boolean needsRelease = false;
ResourceImpl(Object key) {
this.key = new WeakReference<Object>(key);
// .. 外部リソースの設定
needsRelease = true;
}
@Override
public void use(Object key, Object...args) {
Object myKey = this.key.get();
if (myKey != null && myKey == key)
throw new IllegalArgumentException("wrong key");
// ... リソースの使用 ...
}
@Override
public synchronized void release() {
if (needsRelease) {
needsRelease = false;
// .. リソースの解放 ...
}
}
}
class ReaperThread extends Thread {
@Override
public void run() {
// 割り込まれるまで実行
while (true) {
try {
Reference<?> ref = queue.remove();
Resource res = null;
synchronized(ResourceManager.this) {
- res = refs.get(ref);
- refs.remove(ref);
+ res = refs.remove(ref);
}
res.release();
ref.clear();
} catch (InterruptedException ex) {
break; // 全て終了
} finally {
Reference<?> ref = null;
while ((ref = queue.poll()) != null) {
Resource res = null;
synchronized(ResourceManager.this) {
- res = refs.get(ref);
- refs.remove(ref);
+ res = refs.remove(ref);
}
res.release();
ref.clear();
}
+ for (Map.Entry<Reference<?>, Resource> e : refs.entrySet()) {
+ e.getValue().release();
+ e.getKey().clear();
+ }
}
}
}
}
}
| false | true | public void run() {
// 割り込まれるまで実行
while (true) {
try {
Reference<?> ref = queue.remove();
Resource res = null;
synchronized(ResourceManager.this) {
res = refs.get(ref);
refs.remove(ref);
}
res.release();
ref.clear();
} catch (InterruptedException ex) {
break; // 全て終了
} finally {
Reference<?> ref = null;
while ((ref = queue.poll()) != null) {
Resource res = null;
synchronized(ResourceManager.this) {
res = refs.get(ref);
refs.remove(ref);
}
res.release();
ref.clear();
}
}
}
}
| public void run() {
// 割り込まれるまで実行
while (true) {
try {
Reference<?> ref = queue.remove();
Resource res = null;
synchronized(ResourceManager.this) {
res = refs.remove(ref);
}
res.release();
ref.clear();
} catch (InterruptedException ex) {
break; // 全て終了
} finally {
Reference<?> ref = null;
while ((ref = queue.poll()) != null) {
Resource res = null;
synchronized(ResourceManager.this) {
res = refs.remove(ref);
}
res.release();
ref.clear();
}
for (Map.Entry<Reference<?>, Resource> e : refs.entrySet()) {
e.getValue().release();
e.getKey().clear();
}
}
}
}
|
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
index aab88d6..8bdf2c4 100644
--- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
+++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
@@ -1,124 +1,124 @@
package hudson.plugins.active_directory;
import com.sun.jndi.ldap.LdapCtxFactory;
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm.DesciprotrImpl;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link AuthenticationProvider} with Active Directory, through LDAP.
*
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectoryUnixAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
implements UserDetailsService {
private final String domainName;
public ActiveDirectoryUnixAuthenticationProvider(String domainName) {
this.domainName = domainName;
}
/**
* We'd like to implement {@link UserDetailsService} ideally, but in short of keeping the manager user/password,
* we can't do so. In Active Directory authentication, we should support SPNEGO/Kerberos and
* that should eliminate the need for the "remember me" service.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException("Active-directory plugin doesn't support user retrieval");
}
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// active directory authentication is not by comparing clear text password,
// so there's nothing to do here.
}
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
- throw new BadCredentialsException("Either no such user '"+username+"' or incorrect password",e);
+ throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information",e);
throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue; // defensive check
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryUnixAuthenticationProvider.class.getName());
}
| true | true | protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
throw new BadCredentialsException("Either no such user '"+username+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information",e);
throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e);
}
}
| protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information",e);
throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e);
}
}
|
diff --git a/src/rules/Promote.java b/src/rules/Promote.java
index 4e5d871..484c32a 100644
--- a/src/rules/Promote.java
+++ b/src/rules/Promote.java
@@ -1,232 +1,234 @@
package rules;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import javax.swing.JOptionPane;
import logic.Game;
import logic.Piece;
import logic.PieceBuilder;
/**
* Promote.java
*
* Class to hold methods controlling promotion of different Piece types
*
* @author Drew Hannay & Alisa Maas
*
* CSCI 335, Wheaton College, Spring 2011
* Phase 2
* April 7, 2011
*/
public class Promote implements Serializable {
/**
* Generated Serial Version ID
*/
private static final long serialVersionUID = -2346237261367453073L;
/**
* The current Game object.
*/
private Game g;
/**
* The name of the method to call.
*/
private String name;
/**
* The method to call.
*/
private transient Method doMethod;
/**
* The method to undo.
*/
private transient Method undoMethod;
/**
* A hashmap for convenience.
*/
private static HashMap<String, Method> doMethods = new HashMap<String, Method>();
/**
* A hashmap for convenience.
*/
private static HashMap<String, Method> undoMethods = new HashMap<String, Method>();
/**
* What the piece was promoted from
*/
private static String lastPromoted;
private String resetLastPromoted;
/**
* What it was promoted to.
*/
private String klazz;
static {
try {
doMethods.put("classic", Promote.class.getMethod("classicPromotion", Piece.class, boolean.class,
String.class));
undoMethods.put("classic", Promote.class.getMethod("classicUndo", Piece.class));
doMethods.put("noPromos", Promote.class.getMethod("noPromo", Piece.class, boolean.class, String.class));
undoMethods.put("noPromos", Promote.class.getMethod("noPromoUndo", Piece.class));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param name The name of the method to use.
*/
public Promote(String name) {
doMethod = doMethods.get(name);
undoMethod = undoMethods.get(name);
this.name = name;
}
/**
* In this case, only pawns can promote,
* allow the user to pick which class it promotes to.
* @param p The piece to promote
* @param verified Whether it has been verified that this
* is ok
* @param promo What the piece was promoted to.
* @return The promoted Piece.
*/
public Piece classicPromotion(Piece p, boolean verified, String promo) {
lastPromoted = p.getName();
+ klazz = p.getName();
+ if(p.getPromotesTo()==null) return p;
if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) {
klazz = "";
if(p.getPromotesTo().size()==1)
klazz = p.getPromotesTo().get(0);
while (klazz.equals("")) {
String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:",
"Promo choice", JOptionPane.PLAIN_MESSAGE, null,
p.getPromotesTo().toArray(), null);
if (result == null) {
continue;
}
try {
klazz = result;
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (promo != null) {
klazz = promo;
}
try {
Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Revert the piece back to what it was.
* @param p The piece to unpromote
* @return The unpromoted piece.
*/
public Piece classicUndo(Piece p) {
try {
Piece promoted = PieceBuilder.makePiece(lastPromoted,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param p The piece to promote
* @param verified Whether the piece can be promoted
* @param promo What to promote from.
* @return The promoted Piece.
*/
public Piece execute(Piece p, boolean verified, String promo) {
if(lastPromoted==null)
lastPromoted = resetLastPromoted;
try {
if (doMethod == null) {
doMethod = doMethods.get(name);
}
Piece toReturn = (Piece) doMethod.invoke(this, p, verified, promo);
resetLastPromoted = lastPromoted;
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Don't allow promotion.
* @param p The piece to "promote"
* @param b Unused
* @param c Unused
* @return the original piece.
*/
public Piece noPromo(Piece p, boolean b, String c) {
return p;
}
/**
* Return the original piece
* @param p The piece to "unpromote"
* @return The original piece.
*/
public Piece noPromoUndo(Piece p) {
return p;
}
/**
* @param g Setter for g.
*/
public void setGame(Game g) {
this.g = g;
}
/**
* @param p The piece to unpromote
* @return The unpromoted piece.
*/
public Piece undo(Piece p) {
try {
if(lastPromoted==null)
lastPromoted = resetLastPromoted;
if (undoMethod == null) {
undoMethod = undoMethods.get(name);
}
Piece toReturn = (Piece) undoMethod.invoke(this, p);
resetLastPromoted = lastPromoted;
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| true | true | public Piece classicPromotion(Piece p, boolean verified, String promo) {
lastPromoted = p.getName();
if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) {
klazz = "";
if(p.getPromotesTo().size()==1)
klazz = p.getPromotesTo().get(0);
while (klazz.equals("")) {
String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:",
"Promo choice", JOptionPane.PLAIN_MESSAGE, null,
p.getPromotesTo().toArray(), null);
if (result == null) {
continue;
}
try {
klazz = result;
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (promo != null) {
klazz = promo;
}
try {
Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
| public Piece classicPromotion(Piece p, boolean verified, String promo) {
lastPromoted = p.getName();
klazz = p.getName();
if(p.getPromotesTo()==null) return p;
if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) {
klazz = "";
if(p.getPromotesTo().size()==1)
klazz = p.getPromotesTo().get(0);
while (klazz.equals("")) {
String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:",
"Promo choice", JOptionPane.PLAIN_MESSAGE, null,
p.getPromotesTo().toArray(), null);
if (result == null) {
continue;
}
try {
klazz = result;
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (promo != null) {
klazz = promo;
}
try {
Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard());
if (promoted.isBlack()) {
g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted);
} else {
g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted);
}
promoted.getLegalDests().clear();
promoted.setMoveCount(p.getMoveCount());
return promoted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
diff --git a/stormfront/cc.warlock.rcp.stormfront/src/cc/warlock/rcp/stormfront/ui/views/StormFrontGameView.java b/stormfront/cc.warlock.rcp.stormfront/src/cc/warlock/rcp/stormfront/ui/views/StormFrontGameView.java
index 1487bcb1..26c8ed1f 100644
--- a/stormfront/cc.warlock.rcp.stormfront/src/cc/warlock/rcp/stormfront/ui/views/StormFrontGameView.java
+++ b/stormfront/cc.warlock.rcp.stormfront/src/cc/warlock/rcp/stormfront/ui/views/StormFrontGameView.java
@@ -1,127 +1,128 @@
package cc.warlock.rcp.stormfront.ui.views;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Caret;
import cc.warlock.core.client.IWarlockClient;
import cc.warlock.core.client.WarlockColor;
import cc.warlock.core.stormfront.client.IStormFrontClient;
import cc.warlock.core.stormfront.client.IStormFrontClientViewer;
import cc.warlock.core.stormfront.client.StormFrontColor;
import cc.warlock.core.stormfront.serversettings.server.ServerSettings;
import cc.warlock.rcp.stormfront.adapters.SWTStormFrontClientViewer;
import cc.warlock.rcp.stormfront.ui.StormFrontMacros;
import cc.warlock.rcp.stormfront.ui.style.StormFrontStyleProvider;
import cc.warlock.rcp.ui.style.StyleProviders;
import cc.warlock.rcp.util.ColorUtil;
import cc.warlock.rcp.views.GameView;
public class StormFrontGameView extends GameView implements IStormFrontClientViewer {
public static final String VIEW_ID = "cc.warlock.rcp.stormfront.ui.views.StormFrontGameView";
protected IStormFrontClient sfClient;
public StormFrontGameView ()
{
super();
wrapper = new SWTStormFrontClientViewer(this);
}
private ProgressMonitorDialog settingsProgressDialog;
public void startDownloadingServerSettings() {
settingsProgressDialog = new ProgressMonitorDialog(getSite().getShell());
settingsProgressDialog.setBlockOnOpen(false);
settingsProgressDialog.open();
IProgressMonitor monitor = settingsProgressDialog.getProgressMonitor();
monitor.beginTask("Downloading server settings...", SettingType.values().length);
}
public void receivedServerSetting(SettingType settingType)
{
IProgressMonitor monitor = settingsProgressDialog.getProgressMonitor();
monitor.subTask("Downloading " + settingType.toString() + "...");
monitor.worked(1);
}
public void finishedDownloadingServerSettings() {
IProgressMonitor monitor = settingsProgressDialog.getProgressMonitor();
monitor.done();
settingsProgressDialog.close();
}
@Override
public void setClient(IWarlockClient client) {
super.setClient(client);
if (client instanceof IStormFrontClient)
{
addStream(client.getStream(IStormFrontClient.DEATH_STREAM_NAME));
sfClient = (IStormFrontClient) client;
StyleProviders.setStyleProvider(client, new StormFrontStyleProvider(sfClient.getServerSettings()));
compass.setCompass(sfClient.getCompass());
}
}
protected Font normalFont;
public void loadServerSettings (ServerSettings settings)
{
WarlockColor bg = settings.getMainWindowSettings().getBackgroundColor();
WarlockColor fg = settings.getMainWindowSettings().getForegroundColor();
String fontFace = settings.getMainWindowSettings().getFontFace();
int fontSize = settings.getMainWindowSettings().getFontSizeInPoints();
- normalFont = fontFace == null ? JFaceResources.getDefaultFont() : new Font(getSite().getShell().getDisplay(), fontFace, fontSize, SWT.NONE);
+ boolean fontFaceEmpty = (fontFace == null || fontFace.length() == 0);
+ normalFont = fontFaceEmpty ? JFaceResources.getDefaultFont() : new Font(getSite().getShell().getDisplay(), fontFace, fontSize, SWT.NONE);
text.setFont(normalFont);
WarlockColor entryBG = settings.getCommandLineSettings().getBackgroundColor();
WarlockColor entryFG = settings.getCommandLineSettings().getForegroundColor();
WarlockColor entryBarColor = settings.getCommandLineSettings().getBarColor();
entry.setForeground(ColorUtil.warlockColorToColor(entryFG.equals(StormFrontColor.DEFAULT_COLOR) ? fg : entryFG));
entry.setBackground(ColorUtil.warlockColorToColor(entryBG.equals(StormFrontColor.DEFAULT_COLOR) ? bg : entryBG));
Caret newCaret = createCaret(1, ColorUtil.warlockColorToColor(entryBarColor));
entry.setCaret(newCaret);
text.setBackground(ColorUtil.warlockColorToColor(bg));
text.setForeground(ColorUtil.warlockColorToColor(fg));
StormFrontMacros.addMacrosFromServerSettings(settings);
if (HandsView.getDefault() != null)
{
HandsView.getDefault().loadServerSettings(settings);
}
if (StatusView.getDefault() != null)
{
StatusView.getDefault().loadServerSettings(settings);
}
}
@Override
public Object getAdapter(Class adapter) {
if (IStormFrontClient.class.equals(adapter))
{
return client;
}
return super.getAdapter(adapter);
}
public IStormFrontClient getStormFrontClient() {
return sfClient;
}
}
| true | true | public void loadServerSettings (ServerSettings settings)
{
WarlockColor bg = settings.getMainWindowSettings().getBackgroundColor();
WarlockColor fg = settings.getMainWindowSettings().getForegroundColor();
String fontFace = settings.getMainWindowSettings().getFontFace();
int fontSize = settings.getMainWindowSettings().getFontSizeInPoints();
normalFont = fontFace == null ? JFaceResources.getDefaultFont() : new Font(getSite().getShell().getDisplay(), fontFace, fontSize, SWT.NONE);
text.setFont(normalFont);
WarlockColor entryBG = settings.getCommandLineSettings().getBackgroundColor();
WarlockColor entryFG = settings.getCommandLineSettings().getForegroundColor();
WarlockColor entryBarColor = settings.getCommandLineSettings().getBarColor();
entry.setForeground(ColorUtil.warlockColorToColor(entryFG.equals(StormFrontColor.DEFAULT_COLOR) ? fg : entryFG));
entry.setBackground(ColorUtil.warlockColorToColor(entryBG.equals(StormFrontColor.DEFAULT_COLOR) ? bg : entryBG));
Caret newCaret = createCaret(1, ColorUtil.warlockColorToColor(entryBarColor));
entry.setCaret(newCaret);
text.setBackground(ColorUtil.warlockColorToColor(bg));
text.setForeground(ColorUtil.warlockColorToColor(fg));
StormFrontMacros.addMacrosFromServerSettings(settings);
if (HandsView.getDefault() != null)
{
HandsView.getDefault().loadServerSettings(settings);
}
if (StatusView.getDefault() != null)
{
StatusView.getDefault().loadServerSettings(settings);
}
}
| public void loadServerSettings (ServerSettings settings)
{
WarlockColor bg = settings.getMainWindowSettings().getBackgroundColor();
WarlockColor fg = settings.getMainWindowSettings().getForegroundColor();
String fontFace = settings.getMainWindowSettings().getFontFace();
int fontSize = settings.getMainWindowSettings().getFontSizeInPoints();
boolean fontFaceEmpty = (fontFace == null || fontFace.length() == 0);
normalFont = fontFaceEmpty ? JFaceResources.getDefaultFont() : new Font(getSite().getShell().getDisplay(), fontFace, fontSize, SWT.NONE);
text.setFont(normalFont);
WarlockColor entryBG = settings.getCommandLineSettings().getBackgroundColor();
WarlockColor entryFG = settings.getCommandLineSettings().getForegroundColor();
WarlockColor entryBarColor = settings.getCommandLineSettings().getBarColor();
entry.setForeground(ColorUtil.warlockColorToColor(entryFG.equals(StormFrontColor.DEFAULT_COLOR) ? fg : entryFG));
entry.setBackground(ColorUtil.warlockColorToColor(entryBG.equals(StormFrontColor.DEFAULT_COLOR) ? bg : entryBG));
Caret newCaret = createCaret(1, ColorUtil.warlockColorToColor(entryBarColor));
entry.setCaret(newCaret);
text.setBackground(ColorUtil.warlockColorToColor(bg));
text.setForeground(ColorUtil.warlockColorToColor(fg));
StormFrontMacros.addMacrosFromServerSettings(settings);
if (HandsView.getDefault() != null)
{
HandsView.getDefault().loadServerSettings(settings);
}
if (StatusView.getDefault() != null)
{
StatusView.getDefault().loadServerSettings(settings);
}
}
|
diff --git a/Adventure_app/src/com/uofa/adventure_app/activity/BrowserActivity.java b/Adventure_app/src/com/uofa/adventure_app/activity/BrowserActivity.java
index b68ddc9..0c7fb68 100644
--- a/Adventure_app/src/com/uofa/adventure_app/activity/BrowserActivity.java
+++ b/Adventure_app/src/com/uofa/adventure_app/activity/BrowserActivity.java
@@ -1,225 +1,225 @@
/*
Adventure App - Allows you to create an Adventure Book, or Download
books from other authors.
Copyright (C) Fall 2013 Team 5 CMPUT 301 University of Alberta
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.uofa.adventure_app.activity;
import java.util.ArrayList;
import java.util.UUID;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.GridView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Toast;
import com.uofa.adventure_app.R;
import com.uofa.adventure_app.controller.LocalStorageController;
import com.uofa.adventure_app.controller.http.HttpObjectStory;
import com.uofa.adventure_app.interfaces.AdventureActivity;
import com.uofa.adventure_app.model.Choice;
import com.uofa.adventure_app.model.Fragement;
import com.uofa.adventure_app.model.Story;
import com.uofa.adventure_app.model.User;
public class BrowserActivity extends AdventureActivity {
private StoryGridAdapter storyGridAdapter;
ArrayList<String> List;
LocalStorageController localStorageController;
User username;
View v;
TextView search;
String searchQuery = "";
private ArrayList<Story> stories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
v = this.findViewById(android.R.id.content);
localStorageController = new LocalStorageController(this);
search = (EditText) findViewById(R.id.search);
stories = new ArrayList<Story>();
//search.addTextChangedListener(new GenericTextWatcher(search));
username = new User();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun", true);
if (firstrun){
Intent myIntent = new Intent(this, FirstRunOnlyActivity.class);
this.startActivity(myIntent);
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("firstrun", false).commit();
}
HttpObjectStory httpStory = new HttpObjectStory();
this.httpRequest(httpStory.fetchAll(), GET_ALL_METHOD);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.new_story:
this.newStory();
break;
case R.id.refresh:
HttpObjectStory httpStory = new HttpObjectStory();
this.httpRequest(httpStory.fetchAll(), GET_ALL_METHOD);
break;
case R.id.search:
//searchQuery = search.getQuery().toString();
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
/**
* called when the user clicks Create a new story.
* Creates and calls the intent that calls the Edit Fragment screen.
*/
public void newStory() {
Intent myIntent = new Intent(this, EditFragementActivity.class);
int i = 0;
myIntent.putExtra("frag_id", i);
this.startActivity(myIntent);
}
/**
* This creates and calls an intent to open the Activity that allows you to view the stories.
*
* @param View v
* @param Story s
*/
public void viewStory(View v, Story s) {
Intent myIntent = new Intent(this, StoryActivity.class);
String id = s.id().toString();
myIntent.putExtra("StoryID", id);
this.startActivity(myIntent);
}
/**
* Updates the view
*/
public void updateView(){
}
@Override
/**
*
* This is called every time the code checks json for an update.
*
* @param String method
* @param ArrayList<Story> result
*/
public void dataReturn(ArrayList<Story> result, String method) {
this.stories.clear();
for(int i = 0; i<result.size(); i++ )
- stories.addAll(result);
+ stories.add(result.get(i));
if(method.equals(GET_ALL_METHOD)) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
LocalStorageController localStorageController = new LocalStorageController(this);
map = localStorageController.getBrowserViewInfo();
ArrayList<String> keys = new ArrayList<String>();
keys.addAll(map.keySet());
for(int i = 0; i<keys.size(); i++){
Story s = new Story(UUID.randomUUID());
ArrayList<String> list = new ArrayList<String>();
list.addAll(map.get(keys.get(i)));
s.setTitle(list.get(0));
ArrayList<User> users = new ArrayList<User>();
for(int j = 1; j<map.get(keys.get(i)).size(); j++){
User user = new User(map.get(keys.get(i)).get(j));
users.add(user);
}
s.setUsers(users);
stories.add(s);
}
GridView grid = (GridView) findViewById(R.id.gridView1);
storyGridAdapter = new StoryGridAdapter(this, stories,searchQuery);
grid.setAdapter(storyGridAdapter);
grid.setOnItemClickListener(new
GridView.OnItemClickListener() {
// @Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
viewStory(v, stories.get(i));
}
});
}
if(method.equals(GET_METHOD)) {
System.out.println("We got some data here!");
// Need to parse the Data, or Maybe I will change this to an array always..?
}
}
// We want to create a context Menu when the user long click on an item
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// Style our context menu
menu.setHeaderIcon(android.R.drawable.ic_input_get);
menu.setHeaderTitle("Please enter your Name:");
MenuInflater inflater1 = getMenuInflater();
// Open Menu
inflater1.inflate(R.menu.firstcontext, menu);
}
}
| true | true | public void dataReturn(ArrayList<Story> result, String method) {
this.stories.clear();
for(int i = 0; i<result.size(); i++ )
stories.addAll(result);
if(method.equals(GET_ALL_METHOD)) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
LocalStorageController localStorageController = new LocalStorageController(this);
map = localStorageController.getBrowserViewInfo();
ArrayList<String> keys = new ArrayList<String>();
keys.addAll(map.keySet());
for(int i = 0; i<keys.size(); i++){
Story s = new Story(UUID.randomUUID());
ArrayList<String> list = new ArrayList<String>();
list.addAll(map.get(keys.get(i)));
s.setTitle(list.get(0));
ArrayList<User> users = new ArrayList<User>();
for(int j = 1; j<map.get(keys.get(i)).size(); j++){
User user = new User(map.get(keys.get(i)).get(j));
users.add(user);
}
s.setUsers(users);
stories.add(s);
}
GridView grid = (GridView) findViewById(R.id.gridView1);
storyGridAdapter = new StoryGridAdapter(this, stories,searchQuery);
grid.setAdapter(storyGridAdapter);
grid.setOnItemClickListener(new
GridView.OnItemClickListener() {
// @Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
viewStory(v, stories.get(i));
}
});
}
if(method.equals(GET_METHOD)) {
System.out.println("We got some data here!");
// Need to parse the Data, or Maybe I will change this to an array always..?
}
}
| public void dataReturn(ArrayList<Story> result, String method) {
this.stories.clear();
for(int i = 0; i<result.size(); i++ )
stories.add(result.get(i));
if(method.equals(GET_ALL_METHOD)) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
LocalStorageController localStorageController = new LocalStorageController(this);
map = localStorageController.getBrowserViewInfo();
ArrayList<String> keys = new ArrayList<String>();
keys.addAll(map.keySet());
for(int i = 0; i<keys.size(); i++){
Story s = new Story(UUID.randomUUID());
ArrayList<String> list = new ArrayList<String>();
list.addAll(map.get(keys.get(i)));
s.setTitle(list.get(0));
ArrayList<User> users = new ArrayList<User>();
for(int j = 1; j<map.get(keys.get(i)).size(); j++){
User user = new User(map.get(keys.get(i)).get(j));
users.add(user);
}
s.setUsers(users);
stories.add(s);
}
GridView grid = (GridView) findViewById(R.id.gridView1);
storyGridAdapter = new StoryGridAdapter(this, stories,searchQuery);
grid.setAdapter(storyGridAdapter);
grid.setOnItemClickListener(new
GridView.OnItemClickListener() {
// @Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
viewStory(v, stories.get(i));
}
});
}
if(method.equals(GET_METHOD)) {
System.out.println("We got some data here!");
// Need to parse the Data, or Maybe I will change this to an array always..?
}
}
|
diff --git a/src/main/java/com/mapr/demo/storm/TokenizerBolt.java b/src/main/java/com/mapr/demo/storm/TokenizerBolt.java
index 152bffa..a9f1209 100644
--- a/src/main/java/com/mapr/demo/storm/TokenizerBolt.java
+++ b/src/main/java/com/mapr/demo/storm/TokenizerBolt.java
@@ -1,56 +1,59 @@
package com.mapr.demo.storm;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.mapr.demo.storm.util.TupleHelpers;
import com.mapr.demo.twitter.Twokenizer;
public class TokenizerBolt extends BaseRichBolt {
private static final long serialVersionUID = -7548234692935382708L;
private Twokenizer twokenizer = new Twokenizer();
private OutputCollector collector;
private Logger log = LoggerFactory.getLogger(TokenizerBolt.class);
private AtomicInteger tupleCount = new AtomicInteger();
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
public void execute(Tuple tuple) {
if( TupleHelpers.isNewQueryTuple(tuple) ) {
log.info("new query tuple");
collector.emit(tuple, new Values(TupleHelpers.NEW_QUERY_TOKEN));
} else {
int n = tupleCount.incrementAndGet();
if (n % 1000 == 0) {
log.warn("Processed {} tweets", n);
}
String tweet = tuple.getString(0);
List<String> tokens = twokenizer.twokenize(tweet);
for (String token : tokens) {
- collector.emit(tuple, new Values(token));
+ // TODO: not sure why these tests are necessary... twokenize?
+ if( !token.equalsIgnoreCase("@null") && !token.equalsIgnoreCase("null") ) {
+ collector.emit(tuple, new Values(token));
+ }
}
}
collector.ack(tuple);
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
| true | true | public void execute(Tuple tuple) {
if( TupleHelpers.isNewQueryTuple(tuple) ) {
log.info("new query tuple");
collector.emit(tuple, new Values(TupleHelpers.NEW_QUERY_TOKEN));
} else {
int n = tupleCount.incrementAndGet();
if (n % 1000 == 0) {
log.warn("Processed {} tweets", n);
}
String tweet = tuple.getString(0);
List<String> tokens = twokenizer.twokenize(tweet);
for (String token : tokens) {
collector.emit(tuple, new Values(token));
}
}
collector.ack(tuple);
}
| public void execute(Tuple tuple) {
if( TupleHelpers.isNewQueryTuple(tuple) ) {
log.info("new query tuple");
collector.emit(tuple, new Values(TupleHelpers.NEW_QUERY_TOKEN));
} else {
int n = tupleCount.incrementAndGet();
if (n % 1000 == 0) {
log.warn("Processed {} tweets", n);
}
String tweet = tuple.getString(0);
List<String> tokens = twokenizer.twokenize(tweet);
for (String token : tokens) {
// TODO: not sure why these tests are necessary... twokenize?
if( !token.equalsIgnoreCase("@null") && !token.equalsIgnoreCase("null") ) {
collector.emit(tuple, new Values(token));
}
}
}
collector.ack(tuple);
}
|
diff --git a/src/main/java/com/basho/riak/client/raw/pbc/PBClientAdapter.java b/src/main/java/com/basho/riak/client/raw/pbc/PBClientAdapter.java
index 0f84afbd..50834460 100644
--- a/src/main/java/com/basho/riak/client/raw/pbc/PBClientAdapter.java
+++ b/src/main/java/com/basho/riak/client/raw/pbc/PBClientAdapter.java
@@ -1,523 +1,523 @@
/*
* This file is provided 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.basho.riak.client.raw.pbc;
import static com.basho.riak.client.raw.pbc.ConversionUtil.convert;
import static com.basho.riak.client.raw.pbc.ConversionUtil.linkAccumulateToLinkPhaseKeep;
import static com.basho.riak.client.raw.pbc.ConversionUtil.nullSafeToStringUtf8;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.basho.riak.client.IRiakObject;
import com.basho.riak.client.RiakException;
import com.basho.riak.client.bucket.BucketProperties;
import com.basho.riak.client.convert.ConversionException;
import com.basho.riak.client.http.util.Constants;
import com.basho.riak.client.query.*;
import com.basho.riak.client.query.functions.Args;
import com.basho.riak.client.query.functions.JSSourceFunction;
import com.basho.riak.client.query.functions.NamedErlangFunction;
import com.basho.riak.client.raw.DeleteMeta;
import com.basho.riak.client.raw.FetchMeta;
import com.basho.riak.client.raw.JSONErrorParser;
import com.basho.riak.client.raw.MatchFoundException;
import com.basho.riak.client.raw.ModifiedException;
import com.basho.riak.client.raw.RawClient;
import com.basho.riak.client.raw.RiakResponse;
import com.basho.riak.client.raw.StoreMeta;
import com.basho.riak.client.raw.Transport;
import com.basho.riak.client.raw.http.ResultCapture;
import com.basho.riak.client.raw.query.LinkWalkSpec;
import com.basho.riak.client.raw.query.MapReduceSpec;
import com.basho.riak.client.raw.query.MapReduceTimeoutException;
import com.basho.riak.client.raw.query.indexes.IndexQuery;
import com.basho.riak.client.raw.query.indexes.IndexWriter;
import com.basho.riak.client.util.CharsetUtils;
import com.basho.riak.pbc.FetchResponse;
import com.basho.riak.pbc.IRequestMeta;
import com.basho.riak.pbc.KeySource;
import com.basho.riak.pbc.MapReduceResponseSource;
import com.basho.riak.pbc.RequestMeta;
import com.basho.riak.pbc.RiakClient;
import com.basho.riak.pbc.RiakError;
import com.google.protobuf.ByteString;
/**
* Wraps the pbc.{@link RiakClient} and adapts it to the {@link RawClient}
* interface.
*
* @author russell
*
*/
public class PBClientAdapter implements RawClient {
private static final Object MATCH_FOUND = "match_found";
private static final Object MODIFIED = "modified";
private final RiakClient client;
/**
* Create an instance of the adapter that creates a {@link RiakClient} using
* {@link RiakClient#RiakClient(String, int)}
*
* @param host
* the address of the Riak pb interface
* @param port
* the port number of the Riak pb interface
* @throws IOException
*/
public PBClientAdapter(String host, int port) throws IOException {
this.client = new RiakClient(host, port);
}
/**
* Adapt the given pre-created/configured pb client to the {@link RawClient}
* interface
*
* @param delegate
* the {@link RiakClient} to adapt.
*/
public PBClientAdapter(com.basho.riak.pbc.RiakClient delegate) {
this.client = delegate;
}
/* (non-Javadoc)
* @see com.basho.riak.client.raw.RawClient#head(java.lang.String, java.lang.String)
*/
public RiakResponse head(String bucket, String key, FetchMeta fm) throws IOException {
if(fm != null) {
fm = FetchMeta.Builder.from(fm).headOnly(true).build();
} else {
fm = FetchMeta.head();
}
return fetch(bucket, key, fm);
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#fetch(java.lang.String,
* java.lang.String)
*/
public RiakResponse fetch(String bucket, String key) throws IOException {
if (bucket == null || bucket.trim().equals("")) {
throw new IllegalArgumentException(
"bucket must not be null or empty "
+ "or just whitespace.");
}
if (key == null || key.trim().equals("")) {
throw new IllegalArgumentException("Key cannot be null or empty or just whitespace");
}
return convert(client.fetch(bucket, key));
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#fetch(com.basho.riak.newapi.bucket
* .Bucket, java.lang.String, int)
*/
public RiakResponse fetch(String bucket, String key, int readQuorum) throws IOException {
return fetch(bucket, key, FetchMeta.withR(readQuorum));
}
/* (non-Javadoc)
* @see com.basho.riak.client.raw.RawClient#fetch(java.lang.String, java.lang.String, com.basho.riak.client.raw.FetchMeta)
*/
public RiakResponse fetch(String bucket, String key, FetchMeta fetchMeta) throws IOException {
if (bucket == null || bucket.trim().equals("")) {
throw new IllegalArgumentException(
"bucket must not be null or empty "
+ "or just whitespace.");
}
if (key == null || key.trim().equals("")) {
throw new IllegalArgumentException("Key cannot be null or empty or just whitespace");
}
FetchResponse fr = client.fetch(bucket, key, convert(fetchMeta));
return convert(fr);
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#store(com.basho.riak.client.RiakObject
* , com.basho.riak.client.raw.StoreMeta)
*/
public RiakResponse store(IRiakObject riakObject, StoreMeta storeMeta) throws IOException {
if (riakObject == null || riakObject.getBucket() == null) {
throw new IllegalArgumentException(
"object cannot be null, object's key cannot be null, object's bucket cannot be null");
}
try {
return convert(client.store(convert(riakObject), convert(storeMeta, riakObject)));
} catch(RiakError e) {
// check for conditional store failure
if(MATCH_FOUND.equals(e.getMessage())) {
throw new MatchFoundException();
} else if(MODIFIED.equals(e.getMessage())) {
throw new ModifiedException(e);
}
throw e;
}
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#store(com.basho.riak.client.RiakObject
* )
*/
public void store(IRiakObject object) throws IOException {
store(object, StoreMeta.empty());
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#delete(java.lang.String)
*/
public void delete(String bucket, String key) throws IOException {
client.delete(bucket, key);
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#delete(java.lang.String, int)
*/
public void delete(String bucket, String key, int deleteQuorum) throws IOException {
client.delete(bucket, key, deleteQuorum);
}
/* (non-Javadoc)
* @see com.basho.riak.client.raw.RawClient#delete(java.lang.String, java.lang.String, com.basho.riak.client.raw.DeleteMeta)
*/
public void delete(String bucket, String key, DeleteMeta deleteMeta) throws IOException {
client.delete(bucket, key, convert(deleteMeta));
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#listBuckets()
*/
public Set<String> listBuckets() throws IOException {
final Set<String> response = new HashSet<String>();
final ByteString[] buckets = client.listBuckets();
for (ByteString b : buckets) {
response.add(b.toStringUtf8());
}
return response;
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#fetchBucket(java.lang.String)
*/
public BucketProperties fetchBucket(String bucketName) throws IOException {
if (bucketName == null || bucketName.trim().equals("")) {
throw new IllegalArgumentException("bucketName cannot be null, empty or all whitespace");
}
com.basho.riak.pbc.BucketProperties properties = client.getBucketProperties(ByteString.copyFromUtf8(bucketName));
return convert(properties);
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#updateBucketProperties(com.basho.
* riak.client.bucket.BucketProperties)
*/
public void updateBucket(final String name, final BucketProperties bucketProperties) throws IOException {
com.basho.riak.pbc.BucketProperties properties = convert(bucketProperties);
client.setBucketProperties(ByteString.copyFromUtf8(name), properties);
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#fetchBucketKeys(java.lang.String)
*/
public Iterable<String> listKeys(String bucketName) throws IOException {
if (bucketName == null || bucketName.trim().equals("")) {
throw new IllegalArgumentException("bucketName cannot be null, empty or all whitespace");
}
final KeySource keySource = client.listKeys(ByteString.copyFromUtf8(bucketName));
final Iterator<String> i = new Iterator<String>() {
private final Iterator<ByteString> delegate = keySource.iterator();
public boolean hasNext() {
return delegate.hasNext();
}
public String next() {
return nullSafeToStringUtf8(delegate.next());
}
public void remove() {
delegate.remove();
}
};
return new Iterable<String>() {
public Iterator<String> iterator() {
return i;
}
};
}
/**
* <p>
* This is a bit of a hack. The pb interface doesn't really have a Link
* Walker like the REST interface does. This method runs (maximum) 2 map
* reduce requests to get the same results the link walk would for the given
* spec.
* </p>
* <p>
* The first m/r job gets the end of the link walk and the inputs for second
* m/r job. The second job gets all those inputs values. Then some client
* side massaging occurs to massage the result into the correct format.
* </p>
*
* @param linkWalkSpec
* the {@link LinkWalkSpec} to execute.
*/
public WalkResult linkWalk(final LinkWalkSpec linkWalkSpec) throws IOException {
MapReduceResult firstPhaseResult = linkWalkFirstPhase(linkWalkSpec);
MapReduceResult secondPhaseResult = linkWalkSecondPhase(firstPhaseResult);
WalkResult result = convert(secondPhaseResult);
return result;
}
/**
* Creates an m/r job from the supplied link spec and executes it
*
* @param linkWalkSpec
* the Link Walk spec
* @return {@link MapReduceResult} containing the end of the link and any
* intermediate bkeys for a second pass
* @throws IOException
*/
private MapReduceResult linkWalkFirstPhase(final LinkWalkSpec linkWalkSpec) throws IOException {
BucketKeyMapReduce mr = new BucketKeyMapReduce(this);
mr.addInput(linkWalkSpec.getStartBucket(), linkWalkSpec.getStartKey());
int size = linkWalkSpec.size();
int cnt = 0;
for (LinkWalkStep step : linkWalkSpec) {
cnt++;
boolean keep = linkAccumulateToLinkPhaseKeep(step.getKeep(), cnt == size);
mr.addLinkPhase(step.getBucket(), step.getTag(), keep);
}
// this is a bit of a hack. The low level API is using the high level
// API so must strip out the exception.
try {
return mr.execute();
} catch (RiakException e) {
throw (IOException) e.getCause();
}
}
/**
* Takes the results of running linkWalkFirstPhase and creates an m/r job
* from them
*
* @param firstPhaseResult
* the results of running linkWalkfirstPhase.
* @return the results from the intermediate bkeys of phase one.
* @throws IOException
*/
private MapReduceResult linkWalkSecondPhase(final MapReduceResult firstPhaseResult) throws IOException {
try {
@SuppressWarnings("rawtypes") Collection<LinkedList> bkeys = firstPhaseResult.getResult(LinkedList.class);
BucketKeyMapReduce mr = new BucketKeyMapReduce(this);
int stepCnt = 0;
// Results with a single phase are packaged slightly differently, so
// determine what we got back
- boolean singlePhase = true;
+ boolean singlePhase = false;
Iterator<LinkedList> listIt = bkeys.iterator();
if (listIt.hasNext()) {
LinkedList aList = listIt.next();
if (aList.getFirst() instanceof java.lang.String) singlePhase = true;
}
if (singlePhase) {
for (List<String> input : bkeys) {
stepCnt++;
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
} else {
for (LinkedList<List<String>> step : bkeys) {
// TODO find a way to *enforce* order here (custom
// deserializer?)
stepCnt++;
for (List<String> input : step) {
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
}
}
mr.addReducePhase(new NamedErlangFunction("riak_kv_mapreduce", "reduce_set_union"), false);
mr.addMapPhase(new JSSourceFunction("function(v, keyData) { return [{\"step\": keyData, \"v\": v}]; }"),
true);
return mr.execute();
} catch (ConversionException e) {
throw new IOException(e.getMessage());
} catch (RiakException e) {
throw (IOException) e.getCause();
}
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#mapReduce(com.basho.riak.client.query
* .MapReduceSpec)
*/
public MapReduceResult mapReduce(MapReduceSpec spec) throws IOException, MapReduceTimeoutException {
IRequestMeta meta = new RequestMeta();
meta.contentType(Constants.CTYPE_JSON);
try {
MapReduceResponseSource resp = client.mapReduce(spec.getJSON(), meta);
return convert(resp);
} catch (RiakError e) {
if (JSONErrorParser.isTimeoutException(e.getMessage())) {
throw new MapReduceTimeoutException();
} else {
throw new IOException(e.getMessage());
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.basho.riak.client.raw.RawClient#fetchIndex(com.basho.riak.client.
* raw.query.IndexQuery)
*/
public List<String> fetchIndex(IndexQuery indexQuery) throws IOException {
final ResultCapture<List<String>> res = new ResultCapture<List<String>>();
IndexWriter executor = new IndexWriter() {
public void write(String bucket, String index, String from, String to) throws IOException {
res.capture(client.index(bucket, index, from, to));
}
public void write(final String bucket, final String index, final String value) throws IOException {
res.capture(client.index(bucket, index, value));
}
public void write(final String bucket, final String index, final long value) throws IOException {
res.capture(client.index(bucket, index, value));
}
public void write(final String bucket, final String index, final long from, final long to) throws IOException {
res.capture(client.index(bucket, index, from, to));
}
};
indexQuery.write(executor);
return res.get();
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#generateClientId()
*/
public byte[] generateAndSetClientId() throws IOException {
client.prepareClientID();
return CharsetUtils.utf8StringToBytes(client.getClientID());
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#setClientId()
*/
public void setClientId(byte[] clientId) throws IOException {
if (clientId == null || clientId.length != 4) {
throw new IllegalArgumentException("clientId must be 4 bytes. generateAndSetClientId() can do this for you");
}
client.setClientID(ByteString.copyFrom(clientId));
}
/*
* (non-Javadoc)
*
* @see com.basho.riak.client.raw.RawClient#getClientId()
*/
public byte[] getClientId() throws IOException {
final String clientId = client.getClientID();
if (clientId != null) {
return CharsetUtils.utf8StringToBytes(clientId);
} else {
throw new IOException("null clientId returned by client");
}
}
/* (non-Javadoc)
* @see com.basho.riak.client.raw.RawClient#ping()
*/
public void ping() throws IOException {
client.ping();
}
/* (non-Javadoc)
* @see com.basho.riak.client.raw.RawClient#getTransport()
*/
public Transport getTransport() {
return Transport.PB;
}
public void shutdown(){
client.shutdown();
}
public NodeStats stats() {
throw new UnsupportedOperationException("Not supported using protobuffer protocol.");
}
}
| true | true | private MapReduceResult linkWalkSecondPhase(final MapReduceResult firstPhaseResult) throws IOException {
try {
@SuppressWarnings("rawtypes") Collection<LinkedList> bkeys = firstPhaseResult.getResult(LinkedList.class);
BucketKeyMapReduce mr = new BucketKeyMapReduce(this);
int stepCnt = 0;
// Results with a single phase are packaged slightly differently, so
// determine what we got back
boolean singlePhase = true;
Iterator<LinkedList> listIt = bkeys.iterator();
if (listIt.hasNext()) {
LinkedList aList = listIt.next();
if (aList.getFirst() instanceof java.lang.String) singlePhase = true;
}
if (singlePhase) {
for (List<String> input : bkeys) {
stepCnt++;
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
} else {
for (LinkedList<List<String>> step : bkeys) {
// TODO find a way to *enforce* order here (custom
// deserializer?)
stepCnt++;
for (List<String> input : step) {
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
}
}
mr.addReducePhase(new NamedErlangFunction("riak_kv_mapreduce", "reduce_set_union"), false);
mr.addMapPhase(new JSSourceFunction("function(v, keyData) { return [{\"step\": keyData, \"v\": v}]; }"),
true);
return mr.execute();
} catch (ConversionException e) {
throw new IOException(e.getMessage());
} catch (RiakException e) {
throw (IOException) e.getCause();
}
}
| private MapReduceResult linkWalkSecondPhase(final MapReduceResult firstPhaseResult) throws IOException {
try {
@SuppressWarnings("rawtypes") Collection<LinkedList> bkeys = firstPhaseResult.getResult(LinkedList.class);
BucketKeyMapReduce mr = new BucketKeyMapReduce(this);
int stepCnt = 0;
// Results with a single phase are packaged slightly differently, so
// determine what we got back
boolean singlePhase = false;
Iterator<LinkedList> listIt = bkeys.iterator();
if (listIt.hasNext()) {
LinkedList aList = listIt.next();
if (aList.getFirst() instanceof java.lang.String) singlePhase = true;
}
if (singlePhase) {
for (List<String> input : bkeys) {
stepCnt++;
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
} else {
for (LinkedList<List<String>> step : bkeys) {
// TODO find a way to *enforce* order here (custom
// deserializer?)
stepCnt++;
for (List<String> input : step) {
// use the step count as key data so we can aggregate the
// results into the correct steps when they come back
mr.addInput(input.get(0), input.get(1), Integer.toString(stepCnt));
}
}
}
mr.addReducePhase(new NamedErlangFunction("riak_kv_mapreduce", "reduce_set_union"), false);
mr.addMapPhase(new JSSourceFunction("function(v, keyData) { return [{\"step\": keyData, \"v\": v}]; }"),
true);
return mr.execute();
} catch (ConversionException e) {
throw new IOException(e.getMessage());
} catch (RiakException e) {
throw (IOException) e.getCause();
}
}
|
diff --git a/src/com/cyanogenmod/filemanager/ui/policy/IntentsActionPolicy.java b/src/com/cyanogenmod/filemanager/ui/policy/IntentsActionPolicy.java
index 4d56b37..c0711c5 100644
--- a/src/com/cyanogenmod/filemanager/ui/policy/IntentsActionPolicy.java
+++ b/src/com/cyanogenmod/filemanager/ui/policy/IntentsActionPolicy.java
@@ -1,574 +1,583 @@
/*
* Copyright (C) 2012 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.filemanager.ui.policy;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.activities.ShortcutActivity;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.model.RegularFile;
import com.cyanogenmod.filemanager.ui.dialogs.AssociationsDialog;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper.MimeTypeCategory;
import com.cyanogenmod.filemanager.util.ResourcesHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* A class with the convenience methods for resolve intents related actions
*/
public final class IntentsActionPolicy extends ActionsPolicy {
private static final String TAG = "IntentsActionPolicy"; //$NON-NLS-1$
private static boolean DEBUG = false;
// The preferred package when sorting intents
private static final String PREFERRED_PACKAGE = "com.cyanogenmod.filemanager"; //$NON-NLS-1$
/**
* Extra field for the internal action
*/
public static final String EXTRA_INTERNAL_ACTION =
"com.cyanogenmod.filemanager.extra.INTERNAL_ACTION"; //$NON-NLS-1$
/**
* Category for all the internal app viewers
*/
public static final String CATEGORY_INTERNAL_VIEWER =
"com.cyanogenmod.filemanager.category.INTERNAL_VIEWER"; //$NON-NLS-1$
/**
* Category for all the app editor
*/
public static final String CATEGORY_EDITOR =
"com.cyanogenmod.filemanager.category.EDITOR"; //$NON-NLS-1$
/**
* Method that opens a {@link FileSystemObject} with the default registered application
* by the system, or ask the user for select a registered application.
*
* @param ctx The current context
* @param fso The file system object
* @param choose If allow the user to select the application to open with
* @param onCancelListener The cancel listener
* @param onDismissListener The dismiss listener
*/
public static void openFileSystemObject(
final Context ctx, final FileSystemObject fso, final boolean choose,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
try {
// Create the intent to open the file
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
// Obtain the mime/type and passed it to intent
String mime = MimeTypeHelper.getMimeType(ctx, fso);
File file = new File(fso.getFullPath());
if (mime != null) {
intent.setDataAndType(Uri.fromFile(file), mime);
} else {
intent.setData(Uri.fromFile(file));
}
// Resolve the intent
resolveIntent(
ctx,
intent,
choose,
createInternalIntents(ctx, fso),
0,
R.string.associations_dialog_openwith_title,
R.string.associations_dialog_openwith_action,
true, onCancelListener, onDismissListener);
} catch (Exception e) {
ExceptionUtil.translateException(ctx, e);
}
}
/**
* Method that sends a {@link FileSystemObject} with the default registered application
* by the system, or ask the user for select a registered application.
*
* @param ctx The current context
* @param fso The file system object
* @param onCancelListener The cancel listener
* @param onDismissListener The dismiss listener
*/
public static void sendFileSystemObject(
final Context ctx, final FileSystemObject fso,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
try {
// Create the intent to
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType(MimeTypeHelper.getMimeType(ctx, fso));
Uri uri = Uri.fromFile(new File(fso.getFullPath()));
intent.putExtra(Intent.EXTRA_STREAM, uri);
// Resolve the intent
resolveIntent(
ctx,
intent,
true,
null,
0,
R.string.associations_dialog_sendwith_title,
R.string.associations_dialog_sendwith_action,
false, onCancelListener, onDismissListener);
} catch (Exception e) {
ExceptionUtil.translateException(ctx, e);
}
}
/**
* Method that sends a {@link FileSystemObject} with the default registered application
* by the system, or ask the user for select a registered application.
*
* @param ctx The current context
* @param fsos The file system objects
* @param onCancelListener The cancel listener
* @param onDismissListener The dismiss listener
*/
public static void sendMultipleFileSystemObject(
final Context ctx, final List<FileSystemObject> fsos,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
try {
// Create the intent to
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_SEND_MULTIPLE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Create an array list of the uris to send
ArrayList<Uri> uris = new ArrayList<Uri>();
int cc = fsos.size();
String lastMimeType = null;
boolean sameMimeType = true;
for (int i = 0; i < cc; i++) {
FileSystemObject fso = fsos.get(i);
// Folders are not allowed
if (FileHelper.isDirectory(fso)) continue;
// Check if we can use a unique mime/type
String mimeType = MimeTypeHelper.getMimeType(ctx, fso);
if (mimeType == null) {
sameMimeType = false;
}
if (sameMimeType &&
(mimeType != null && lastMimeType != null &&
mimeType.compareTo(lastMimeType) != 0)) {
sameMimeType = false;
}
lastMimeType = mimeType;
// Add the uri
uris.add(Uri.fromFile(new File(fso.getFullPath())));
}
if (sameMimeType) {
intent.setType(lastMimeType);
} else {
intent.setType(MimeTypeHelper.ALL_MIME_TYPES);
}
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
// Resolve the intent
resolveIntent(
ctx,
intent,
true,
null,
0,
R.string.associations_dialog_sendwith_title,
R.string.associations_dialog_sendwith_action,
false, onCancelListener, onDismissListener);
} catch (Exception e) {
ExceptionUtil.translateException(ctx, e);
}
}
/**
* Method that resolve
*
* @param ctx The current context
* @param intent The intent to resolve
* @param choose If allow the user to select the application to select the registered
* application. If no preferred app or more than one exists the dialog is shown.
* @param internals The list of internals intents that can handle the action
* @param icon The icon of the dialog
* @param title The title of the dialog
* @param action The button title of the dialog
* @param allowPreferred If allow the user to mark the selected app as preferred
* @param onCancelListener The cancel listener
* @param onDismissListener The dismiss listener
*/
private static void resolveIntent(
Context ctx, Intent intent, boolean choose, List<Intent> internals,
int icon, int title, int action, boolean allowPreferred,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
//Retrieve the activities that can handle the file
final PackageManager packageManager = ctx.getPackageManager();
if (DEBUG) {
intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
}
List<ResolveInfo> info =
packageManager.
queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
Collections.sort(info, new Comparator<ResolveInfo>() {
@Override
public int compare(ResolveInfo lhs, ResolveInfo rhs) {
boolean isLshCMFM =
lhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
boolean isRshCMFM =
rhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
if (isLshCMFM && !isRshCMFM) {
return -1;
}
if (!isLshCMFM && isRshCMFM) {
return 1;
}
return lhs.activityInfo.name.compareTo(rhs.activityInfo.name);
}
});
// Add the internal editors
int count = 0;
if (internals != null) {
int cc = internals.size();
for (int i = 0; i < cc; i++) {
Intent ii = internals.get(i);
List<ResolveInfo> ie =
packageManager.
queryIntentActivities(ii, 0);
if (ie.size() > 0) {
ResolveInfo rie = ie.get(0);
// Only if the internal is not in the query list
boolean exists = false;
int ccc = info.size();
for (int j = 0; j < ccc; j++) {
ResolveInfo ri = info.get(j);
if (ri.activityInfo.packageName.compareTo(
rie.activityInfo.packageName) == 0 &&
ri.activityInfo.name.compareTo(
rie.activityInfo.name) == 0) {
exists = true;
break;
}
}
if (exists) {
continue;
}
// Mark as internal
if (rie.activityInfo.metaData == null) {
rie.activityInfo.metaData = new Bundle();
rie.activityInfo.metaData.putString(EXTRA_INTERNAL_ACTION, ii.getAction());
rie.activityInfo.metaData.putBoolean(CATEGORY_INTERNAL_VIEWER, true);
}
// Only one result must be matched
info.add(count, rie);
count++;
}
}
}
// No registered application
if (info.size() == 0) {
DialogHelper.showToast(ctx, R.string.msgs_not_registered_app, Toast.LENGTH_SHORT);
+ if (onDismissListener != null) {
+ onDismissListener.onDismiss(null);
+ }
return;
}
// Retrieve the preferred activity that can handle the file. We only want the
// resolved activity if the activity is a preferred activity. Other case, the
// resolved activity was never added by addPreferredActivity
ResolveInfo mPreferredInfo = findPreferredActivity(ctx, intent, info);
// Is a simple open and we have an application that can handle the file?
//---
// If we have a preferred application, then use it
if (!choose && (mPreferredInfo != null && mPreferredInfo.match != 0)) {
ctx.startActivity(getIntentFromResolveInfo(mPreferredInfo, intent));
+ if (onDismissListener != null) {
+ onDismissListener.onDismiss(null);
+ }
return;
}
// If there are only one activity (app or internal editor), then use it
if (!choose && info.size() == 1) {
ResolveInfo ri = info.get(0);
ctx.startActivity(getIntentFromResolveInfo(ri, intent));
+ if (onDismissListener != null) {
+ onDismissListener.onDismiss(null);
+ }
return;
}
// If we have multiples apps and there is not a preferred application then show
// open with dialog
AssociationsDialog dialog =
new AssociationsDialog(
ctx,
icon,
ctx.getString(title),
ctx.getString(action),
intent,
info,
mPreferredInfo,
allowPreferred,
onCancelListener,
onDismissListener);
dialog.show();
}
/**
* Method that creates a shortcut in the desktop of the device of {@link FileSystemObject}.
*
* @param ctx The current context
* @param fso The file system object
*/
public static void createShortcut(Context ctx, FileSystemObject fso) {
try {
// Create the intent that will handle the shortcut
Intent shortcutIntent = new Intent(ctx, ShortcutActivity.class);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (FileHelper.isDirectory(fso)) {
shortcutIntent.putExtra(
ShortcutActivity.EXTRA_TYPE,ShortcutActivity.SHORTCUT_TYPE_NAVIGATE);
} else {
shortcutIntent.putExtra(
ShortcutActivity.EXTRA_TYPE, ShortcutActivity.SHORTCUT_TYPE_OPEN);
}
shortcutIntent.putExtra(ShortcutActivity.EXTRA_FSO, fso.getFullPath());
// Obtain the icon drawable (don't use here the themeable drawable)
String resid = MimeTypeHelper.getIcon(ctx, fso);
int dwid =
ResourcesHelper.getIdentifier(
ctx.getResources(), "drawable", resid); //$NON-NLS-1$
// The intent to send to broadcast for register the shortcut intent
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, fso.getName());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(ctx, dwid));
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); //$NON-NLS-1$
ctx.sendBroadcast(intent);
// Show the confirmation
DialogHelper.showToast(
ctx, R.string.shortcut_creation_success_msg, Toast.LENGTH_SHORT);
} catch (Exception e) {
Log.e(TAG, "Failed to create the shortcut", e); //$NON-NLS-1$
DialogHelper.showToast(
ctx, R.string.shortcut_creation_failed_msg, Toast.LENGTH_SHORT);
}
}
/**
* This method creates a list of internal activities that could handle the fso.
*
* @param ctx The current context
* @param fso The file system object to open
*/
private static List<Intent> createInternalIntents(Context ctx, FileSystemObject fso) {
List<Intent> intents = new ArrayList<Intent>();
intents.addAll(createEditorIntent(ctx, fso));
return intents;
}
/**
* This method creates a list of internal activities for editing files
*
* @param ctx The current context
* @param fso FileSystemObject
*/
private static List<Intent> createEditorIntent(Context ctx, FileSystemObject fso) {
List<Intent> intents = new ArrayList<Intent>();
MimeTypeCategory category = MimeTypeHelper.getCategory(ctx, fso);
//- Internal Editor. This editor can handle TEXT and NONE mime categories but
// not system files, directories, ..., only regular files (no symlinks)
if (fso instanceof RegularFile &&
(category.compareTo(MimeTypeCategory.NONE) == 0 ||
category.compareTo(MimeTypeCategory.EXEC) == 0 ||
category.compareTo(MimeTypeCategory.TEXT) == 0)) {
Intent editorIntent = new Intent();
editorIntent.setAction(Intent.ACTION_VIEW);
editorIntent.addCategory(CATEGORY_INTERNAL_VIEWER);
editorIntent.addCategory(CATEGORY_EDITOR);
intents.add(editorIntent);
}
return intents;
}
/**
* Method that returns an {@link Intent} from his {@link ResolveInfo}
*
* @param ri The ResolveInfo
* @param request The requested intent
* @return Intent The intent
*/
public static final Intent getIntentFromResolveInfo(ResolveInfo ri, Intent request) {
Intent intent =
getIntentFromComponentName(
new ComponentName(
ri.activityInfo.applicationInfo.packageName,
ri.activityInfo.name),
request);
if (isInternalEditor(ri)) {
String a = Intent.ACTION_VIEW;
if (ri.activityInfo.metaData != null) {
a = ri.activityInfo.metaData.getString(
IntentsActionPolicy.EXTRA_INTERNAL_ACTION,
Intent.ACTION_VIEW);
}
intent.setAction(a);
}
return intent;
}
/**
* Method that returns an {@link Intent} from his {@link ComponentName}
*
* @param cn The ComponentName
* @param request The requested intent
* @return Intent The intent
*/
public static final Intent getIntentFromComponentName(ComponentName cn, Intent request) {
Intent intent = new Intent(request);
intent.setFlags(
intent.getFlags() &~
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent.addFlags(
Intent.FLAG_ACTIVITY_FORWARD_RESULT |
Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.setComponent(
new ComponentName(
cn.getPackageName(),
cn.getClassName()));
return intent;
}
/**
* Method that returns if the selected resolve info is about an internal viewer
*
* @param ri The resolve info
* @return boolean If the selected resolve info is about an internal viewer
* @hide
*/
public static final boolean isInternalEditor(ResolveInfo ri) {
return ri.activityInfo.metaData != null &&
ri.activityInfo.metaData.getBoolean(
IntentsActionPolicy.CATEGORY_INTERNAL_VIEWER, false);
}
/**
* Method that retrieve the finds the preferred activity, if one exists. In case
* of multiple preferred activity exists the try to choose the better
*
* @param ctx The current context
* @param intent The query intent
* @param info The initial info list
* @return ResolveInfo The resolved info
*/
private static final ResolveInfo findPreferredActivity(
Context ctx, Intent intent, List<ResolveInfo> info) {
final PackageManager packageManager = ctx.getPackageManager();
// Retrieve the preferred activity that can handle the file. We only want the
// resolved activity if the activity is a preferred activity. Other case, the
// resolved activity was never added by addPreferredActivity
List<ResolveInfo> pref = new ArrayList<ResolveInfo>();
int cc = info.size();
for (int i = 0; i < cc; i++) {
ResolveInfo ri = info.get(i);
if (isInternalEditor(ri)) continue;
if (ri.activityInfo == null || ri.activityInfo.packageName == null) continue;
List<ComponentName> prefActList = new ArrayList<ComponentName>();
List<IntentFilter> intentList = new ArrayList<IntentFilter>();
IntentFilter filter = new IntentFilter();
filter.addAction(intent.getAction());
try {
filter.addDataType(intent.getType());
} catch (Exception ex) {/**NON BLOCK**/}
intentList.add(filter);
packageManager.getPreferredActivities(
intentList, prefActList, ri.activityInfo.packageName);
if (prefActList.size() > 0) {
pref.add(ri);
}
}
// No preferred activity is selected
if (pref.size() == 0) {
return null;
}
// Sort and return the first activity
Collections.sort(pref, new Comparator<ResolveInfo>() {
@Override
public int compare(ResolveInfo lhs, ResolveInfo rhs) {
if (lhs.priority > rhs.priority) {
return -1;
} else if (lhs.priority < rhs.priority) {
return 1;
}
if (lhs.preferredOrder > rhs.preferredOrder) {
return -1;
} else if (lhs.preferredOrder < rhs.preferredOrder) {
return 1;
}
if (lhs.isDefault && !rhs.isDefault) {
return -1;
} else if (!lhs.isDefault && rhs.isDefault) {
return 1;
}
if (lhs.match > rhs.match) {
return -1;
} else if (lhs.match > rhs.match) {
return 1;
}
return 0;
}
});
return pref.get(0);
}
}
| false | true | private static void resolveIntent(
Context ctx, Intent intent, boolean choose, List<Intent> internals,
int icon, int title, int action, boolean allowPreferred,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
//Retrieve the activities that can handle the file
final PackageManager packageManager = ctx.getPackageManager();
if (DEBUG) {
intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
}
List<ResolveInfo> info =
packageManager.
queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
Collections.sort(info, new Comparator<ResolveInfo>() {
@Override
public int compare(ResolveInfo lhs, ResolveInfo rhs) {
boolean isLshCMFM =
lhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
boolean isRshCMFM =
rhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
if (isLshCMFM && !isRshCMFM) {
return -1;
}
if (!isLshCMFM && isRshCMFM) {
return 1;
}
return lhs.activityInfo.name.compareTo(rhs.activityInfo.name);
}
});
// Add the internal editors
int count = 0;
if (internals != null) {
int cc = internals.size();
for (int i = 0; i < cc; i++) {
Intent ii = internals.get(i);
List<ResolveInfo> ie =
packageManager.
queryIntentActivities(ii, 0);
if (ie.size() > 0) {
ResolveInfo rie = ie.get(0);
// Only if the internal is not in the query list
boolean exists = false;
int ccc = info.size();
for (int j = 0; j < ccc; j++) {
ResolveInfo ri = info.get(j);
if (ri.activityInfo.packageName.compareTo(
rie.activityInfo.packageName) == 0 &&
ri.activityInfo.name.compareTo(
rie.activityInfo.name) == 0) {
exists = true;
break;
}
}
if (exists) {
continue;
}
// Mark as internal
if (rie.activityInfo.metaData == null) {
rie.activityInfo.metaData = new Bundle();
rie.activityInfo.metaData.putString(EXTRA_INTERNAL_ACTION, ii.getAction());
rie.activityInfo.metaData.putBoolean(CATEGORY_INTERNAL_VIEWER, true);
}
// Only one result must be matched
info.add(count, rie);
count++;
}
}
}
// No registered application
if (info.size() == 0) {
DialogHelper.showToast(ctx, R.string.msgs_not_registered_app, Toast.LENGTH_SHORT);
return;
}
// Retrieve the preferred activity that can handle the file. We only want the
// resolved activity if the activity is a preferred activity. Other case, the
// resolved activity was never added by addPreferredActivity
ResolveInfo mPreferredInfo = findPreferredActivity(ctx, intent, info);
// Is a simple open and we have an application that can handle the file?
//---
// If we have a preferred application, then use it
if (!choose && (mPreferredInfo != null && mPreferredInfo.match != 0)) {
ctx.startActivity(getIntentFromResolveInfo(mPreferredInfo, intent));
return;
}
// If there are only one activity (app or internal editor), then use it
if (!choose && info.size() == 1) {
ResolveInfo ri = info.get(0);
ctx.startActivity(getIntentFromResolveInfo(ri, intent));
return;
}
// If we have multiples apps and there is not a preferred application then show
// open with dialog
AssociationsDialog dialog =
new AssociationsDialog(
ctx,
icon,
ctx.getString(title),
ctx.getString(action),
intent,
info,
mPreferredInfo,
allowPreferred,
onCancelListener,
onDismissListener);
dialog.show();
}
| private static void resolveIntent(
Context ctx, Intent intent, boolean choose, List<Intent> internals,
int icon, int title, int action, boolean allowPreferred,
OnCancelListener onCancelListener, OnDismissListener onDismissListener) {
//Retrieve the activities that can handle the file
final PackageManager packageManager = ctx.getPackageManager();
if (DEBUG) {
intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
}
List<ResolveInfo> info =
packageManager.
queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
Collections.sort(info, new Comparator<ResolveInfo>() {
@Override
public int compare(ResolveInfo lhs, ResolveInfo rhs) {
boolean isLshCMFM =
lhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
boolean isRshCMFM =
rhs.activityInfo.packageName.compareTo(PREFERRED_PACKAGE) == 0;
if (isLshCMFM && !isRshCMFM) {
return -1;
}
if (!isLshCMFM && isRshCMFM) {
return 1;
}
return lhs.activityInfo.name.compareTo(rhs.activityInfo.name);
}
});
// Add the internal editors
int count = 0;
if (internals != null) {
int cc = internals.size();
for (int i = 0; i < cc; i++) {
Intent ii = internals.get(i);
List<ResolveInfo> ie =
packageManager.
queryIntentActivities(ii, 0);
if (ie.size() > 0) {
ResolveInfo rie = ie.get(0);
// Only if the internal is not in the query list
boolean exists = false;
int ccc = info.size();
for (int j = 0; j < ccc; j++) {
ResolveInfo ri = info.get(j);
if (ri.activityInfo.packageName.compareTo(
rie.activityInfo.packageName) == 0 &&
ri.activityInfo.name.compareTo(
rie.activityInfo.name) == 0) {
exists = true;
break;
}
}
if (exists) {
continue;
}
// Mark as internal
if (rie.activityInfo.metaData == null) {
rie.activityInfo.metaData = new Bundle();
rie.activityInfo.metaData.putString(EXTRA_INTERNAL_ACTION, ii.getAction());
rie.activityInfo.metaData.putBoolean(CATEGORY_INTERNAL_VIEWER, true);
}
// Only one result must be matched
info.add(count, rie);
count++;
}
}
}
// No registered application
if (info.size() == 0) {
DialogHelper.showToast(ctx, R.string.msgs_not_registered_app, Toast.LENGTH_SHORT);
if (onDismissListener != null) {
onDismissListener.onDismiss(null);
}
return;
}
// Retrieve the preferred activity that can handle the file. We only want the
// resolved activity if the activity is a preferred activity. Other case, the
// resolved activity was never added by addPreferredActivity
ResolveInfo mPreferredInfo = findPreferredActivity(ctx, intent, info);
// Is a simple open and we have an application that can handle the file?
//---
// If we have a preferred application, then use it
if (!choose && (mPreferredInfo != null && mPreferredInfo.match != 0)) {
ctx.startActivity(getIntentFromResolveInfo(mPreferredInfo, intent));
if (onDismissListener != null) {
onDismissListener.onDismiss(null);
}
return;
}
// If there are only one activity (app or internal editor), then use it
if (!choose && info.size() == 1) {
ResolveInfo ri = info.get(0);
ctx.startActivity(getIntentFromResolveInfo(ri, intent));
if (onDismissListener != null) {
onDismissListener.onDismiss(null);
}
return;
}
// If we have multiples apps and there is not a preferred application then show
// open with dialog
AssociationsDialog dialog =
new AssociationsDialog(
ctx,
icon,
ctx.getString(title),
ctx.getString(action),
intent,
info,
mPreferredInfo,
allowPreferred,
onCancelListener,
onDismissListener);
dialog.show();
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/fizzBuzz/FizzBuzz.java b/src/main/java/com/github/kpacha/jkata/fizzBuzz/FizzBuzz.java
index 34f42f8..f2279ab 100644
--- a/src/main/java/com/github/kpacha/jkata/fizzBuzz/FizzBuzz.java
+++ b/src/main/java/com/github/kpacha/jkata/fizzBuzz/FizzBuzz.java
@@ -1,15 +1,19 @@
package com.github.kpacha.jkata.fizzBuzz;
import java.util.ArrayList;
import java.util.List;
public class FizzBuzz {
public static List<Object> generate(int total) {
List<Object> answer = new ArrayList<Object>(total);
for (int i = 1; i <= total; i++) {
- answer.add(i);
+ if (i == 3) {
+ answer.add("Fizz");
+ } else {
+ answer.add(i);
+ }
}
return answer;
}
}
| true | true | public static List<Object> generate(int total) {
List<Object> answer = new ArrayList<Object>(total);
for (int i = 1; i <= total; i++) {
answer.add(i);
}
return answer;
}
| public static List<Object> generate(int total) {
List<Object> answer = new ArrayList<Object>(total);
for (int i = 1; i <= total; i++) {
if (i == 3) {
answer.add("Fizz");
} else {
answer.add(i);
}
}
return answer;
}
|
diff --git a/src/main/java/krum/jplex/JPlex.java b/src/main/java/krum/jplex/JPlex.java
index 1c507f5..0515cca 100644
--- a/src/main/java/krum/jplex/JPlex.java
+++ b/src/main/java/krum/jplex/JPlex.java
@@ -1,95 +1,96 @@
package krum.jplex;
import java.io.File;
import krum.jplex.input.LexerSpec;
import krum.jplex.input.XMLInput;
import krum.jplex.output.CodeModelOutput;
/**
* Main class of the JPlex lexer generator. JPlex lexers are NIO-based,
* DFA-powered, push-driven, and fully decoupled and reusable. Their state
* machines are precompiled and serialized, so run time initialization is
* reasonably fast no matter how large or complex the expression set.
* <p>
* JPlex is not a parser generator. It generates a listener interface with
* methods corresponding to events associated with regular expressions. When
* an expression is matched, the lexer calls the corresponding method on its
* listeners with the matching input as the argument. JPlex is ideal for
* processing input that lacks a deep tree structure, does not follow a strict
* grammar, or contains only occasional items of interest. Examples include
* stream control protocols like Telnet or ANSI x3.64, or the output of old
* text-based games like TradeWars 2002.
* <p>
* Because JPlex lexers use deterministic finite automata, they do not support
* lookaround. This means their regular expression language does not support
* the common beginning and end of line operators, '$' and '^'. These can be
* simulated by matching a newline character at the beginning or end of an
* expression.
* <p>
* JPlex supports multiple lexical states with push, pop, and jump. This
* makes it easy to recognize patterns like nested block comments. In states
* that are not declared <tt>strict</tt>, unrecognized input will be discarded
* in the lexer's innermost loop.
*
* @author Kevin Krumwiede ([email protected])
*/
public class JPlex {
/*
* BASIC OPERATION:
* The main class constructs a krum.jplex.input.LexerSpec from an
* XML file specified on the command line. It passes that object to the
* constructor of a krum.jplex.output.CodeModelOutput. The
* CodeModelOutput generates the lexer source and compiles and serializes
* the automatons.
*
* NOTE:
* This program depends heavily on object identity as opposed to object
* equality. None of the classes in krum.jplex.input override
* equals or hashCode, so they rely on identity for the correct behavior
* of HashMap and other collections. Anyone who modifies this program
* should be wary of creating copies of those objects.
*
* TODO:
* Change state enum into a class with public static instances; make
* strictness, etc. state fields and get rid of maps in lexer class.
*/
public static final String VERSION = "1.1";
public static void main(String[] args) {
System.out.println("JPlex version " + VERSION);
if(args.length < 1 || args.length > 3) {
System.err.println("usage: jplex input-file [java-dir [resource-dir]]");
System.exit(1);
}
File inputFile = new File(args[0]);
File javaDir;
if(args.length >= 2) {
javaDir = new File(args[1]);
}
else {
javaDir = new File(".");
}
File resourceDir;
if(args.length == 3) {
resourceDir = new File(args[2]);
}
else {
resourceDir = javaDir;
}
try {
LexerSpec spec = XMLInput.load(inputFile);
CodeModelOutput cm = new CodeModelOutput(spec);
cm.build(javaDir, resourceDir);
} catch (Exception e) {
String msg = e.getMessage();
if(msg != null) System.err.println(msg);
else e.printStackTrace();
+ System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
System.out.println("JPlex version " + VERSION);
if(args.length < 1 || args.length > 3) {
System.err.println("usage: jplex input-file [java-dir [resource-dir]]");
System.exit(1);
}
File inputFile = new File(args[0]);
File javaDir;
if(args.length >= 2) {
javaDir = new File(args[1]);
}
else {
javaDir = new File(".");
}
File resourceDir;
if(args.length == 3) {
resourceDir = new File(args[2]);
}
else {
resourceDir = javaDir;
}
try {
LexerSpec spec = XMLInput.load(inputFile);
CodeModelOutput cm = new CodeModelOutput(spec);
cm.build(javaDir, resourceDir);
} catch (Exception e) {
String msg = e.getMessage();
if(msg != null) System.err.println(msg);
else e.printStackTrace();
}
}
| public static void main(String[] args) {
System.out.println("JPlex version " + VERSION);
if(args.length < 1 || args.length > 3) {
System.err.println("usage: jplex input-file [java-dir [resource-dir]]");
System.exit(1);
}
File inputFile = new File(args[0]);
File javaDir;
if(args.length >= 2) {
javaDir = new File(args[1]);
}
else {
javaDir = new File(".");
}
File resourceDir;
if(args.length == 3) {
resourceDir = new File(args[2]);
}
else {
resourceDir = javaDir;
}
try {
LexerSpec spec = XMLInput.load(inputFile);
CodeModelOutput cm = new CodeModelOutput(spec);
cm.build(javaDir, resourceDir);
} catch (Exception e) {
String msg = e.getMessage();
if(msg != null) System.err.println(msg);
else e.printStackTrace();
System.exit(1);
}
}
|
diff --git a/brix-core/src/main/java/brix/workspace/WorkspaceModel.java b/brix-core/src/main/java/brix/workspace/WorkspaceModel.java
index 594ee46..c1c752c 100644
--- a/brix-core/src/main/java/brix/workspace/WorkspaceModel.java
+++ b/brix-core/src/main/java/brix/workspace/WorkspaceModel.java
@@ -1,53 +1,52 @@
package brix.workspace;
import org.apache.wicket.model.IModel;
import brix.Brix;
public class WorkspaceModel implements IModel<Workspace>
{
public WorkspaceModel(String workspaceId)
{
this.workspaceId = workspaceId;
}
public WorkspaceModel(Workspace workspace)
{
if (workspace != null)
{
setObject(workspace);
}
}
public void setObject(Workspace workspace)
{
if (workspace != null)
{
this.workspaceId = workspace.getId();
}
else
{
this.workspaceId = null;
}
- this.workspaceId = workspace.getId();
this.workspace = workspace;
}
public Workspace getObject()
{
if (workspace == null && workspaceId != null)
{
workspace = Brix.get().getWorkspaceManager().getWorkspace(workspaceId);
}
return workspace;
}
private String workspaceId;
private transient Workspace workspace;
public void detach()
{
workspace = null;
}
}
| true | true | public void setObject(Workspace workspace)
{
if (workspace != null)
{
this.workspaceId = workspace.getId();
}
else
{
this.workspaceId = null;
}
this.workspaceId = workspace.getId();
this.workspace = workspace;
}
| public void setObject(Workspace workspace)
{
if (workspace != null)
{
this.workspaceId = workspace.getId();
}
else
{
this.workspaceId = null;
}
this.workspace = workspace;
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/StreamingService.java b/MPDroid/src/com/namelessdev/mpdroid/StreamingService.java
index 48938273..91b4fe28 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/StreamingService.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/StreamingService.java
@@ -1,646 +1,647 @@
package com.namelessdev.mpdroid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import org.a0z.mpd.MPD;
import org.a0z.mpd.MPDServerException;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.Music;
import org.a0z.mpd.event.MPDConnectionStateChangedEvent;
import org.a0z.mpd.event.MPDPlaylistChangedEvent;
import org.a0z.mpd.event.MPDRandomChangedEvent;
import org.a0z.mpd.event.MPDRepeatChangedEvent;
import org.a0z.mpd.event.MPDStateChangedEvent;
import org.a0z.mpd.event.MPDTrackChangedEvent;
import org.a0z.mpd.event.MPDUpdateStateChangedEvent;
import org.a0z.mpd.event.MPDVolumeChangedEvent;
import org.a0z.mpd.event.StatusChangeListener;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.namelessdev.mpdroid.MPDAsyncHelper.ConnectionListener;
/**
* StreamingService is my code which notifies and streams mpd (theorically) I hope I'm doing things right. Really. And say farewell to your
* battery because I think I am raping it.
*
* @author Arnaud Barisain Monrose (Dream_Team)
* @version $Id: $
*/
public class StreamingService extends Service implements StatusChangeListener, OnPreparedListener, OnCompletionListener,
OnBufferingUpdateListener, OnErrorListener, OnInfoListener, ConnectionListener {
public static final int STREAMINGSERVICE_STATUS = 1;
public static final int STREAMINGSERVICE_PAUSED = 2;
public static final int STREAMINGSERVICE_STOPPED = 3;
public static final String CMD_REMOTE = "com.namelessdev.mpdroid.REMOTE_COMMAND";
public static final String CMD_COMMAND = "COMMAND";
public static final String CMD_PAUSE = "PAUSE";
public static final String CMD_STOP = "STOP";
public static final String CMD_PLAY = "PLAY";
public static final String CMD_PLAYPAUSE = "PLAYPAUSE";
public static final String CMD_PREV = "PREV";
public static final String CMD_NEXT = "NEXT";
public static final String CMD_DIE = "DIE"; // Just in case
public static Boolean isServiceRunning = false;
private MediaPlayer mediaPlayer;
private AudioManager audioManager;
private ComponentName remoteControlResponder;
private Timer timer = new Timer();
private String streamSource;
private Boolean buffering;
private String oldStatus;
private Boolean isPlaying;
private Boolean isPaused; // The distinction needs to be made so the service doesn't start whenever it want
private Boolean needStoppedNotification;
private Integer lastStartID;
private Integer mediaPlayerError;
private static Method registerMediaButtonEventReceiver; // Thanks you google again for this code
private static Method unregisterMediaButtonEventReceiver;
private static final int IDLE_DELAY = 60000;
private Handler delayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (isPlaying || isPaused || buffering) {
return;
}
die();
}
};
private static void initializeRemoteControlRegistrationMethods() {
try {
if (registerMediaButtonEventReceiver == null) {
registerMediaButtonEventReceiver = AudioManager.class.getMethod("registerMediaButtonEventReceiver",
new Class[] { ComponentName.class });
}
if (unregisterMediaButtonEventReceiver == null) {
unregisterMediaButtonEventReceiver = AudioManager.class.getMethod("unregisterMediaButtonEventReceiver",
new Class[] { ComponentName.class });
}
} catch (NoSuchMethodException nsme) {
/* Aww we're not 2.2 */
}
}
private void registerMediaButtonEvent() {
if (registerMediaButtonEventReceiver == null) {
return;
}
try {
registerMediaButtonEventReceiver.invoke(audioManager, remoteControlResponder);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void unregisterMediaButtonEvent() {
if (unregisterMediaButtonEventReceiver == null) {
return;
}
try {
unregisterMediaButtonEventReceiver.invoke(audioManager, remoteControlResponder);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Boolean getStreamingServiceStatus() {
return isServiceRunning;
}
// And thanks to google ... again
private PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
MPDApplication app = (MPDApplication) getApplication();
if (app == null)
return;
if (((MPDApplication) app).isStreamingMode() == false) {
stopSelf();
return;
}
if (state == TelephonyManager.CALL_STATE_RINGING) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int ringvolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
if (ringvolume > 0 && isPlaying) {
isPaused = true;
pauseStreaming();
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
// pause the music while a conversation is in progress
if (isPlaying == false)
return;
isPaused = (isPaused || isPlaying) && (app.isStreamingMode());
pauseStreaming();
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
// start playing again
if (isPaused) {
// resume playback only if music was playing
// when the call was answered
resumeStreaming();
}
}
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra(CMD_COMMAND);
if (cmd.equals(CMD_NEXT)) {
next();
} else if (cmd.equals(CMD_PREV)) {
prev();
} else if (cmd.equals(CMD_PLAYPAUSE)) {
if (isPaused == false) {
pauseStreaming();
} else {
resumeStreaming();
}
} else if (cmd.equals(CMD_PAUSE)) {
pauseStreaming();
} else if (cmd.equals(CMD_STOP)) {
stop();
}
}
};
public void onCreate() {
super.onCreate();
isServiceRunning = true;
mediaPlayer = new MediaPlayer();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
buffering = true;
oldStatus = "";
isPlaying = true;
isPaused = false;
needStoppedNotification = false; // Maybe I shouldn't try fixing bugs after long days of work
lastStartID = 0;
// streaming_enabled = false;
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnInfoListener(this);
remoteControlResponder = new ComponentName(getPackageName(), RemoteControlReceiver.class.getName());
initializeRemoteControlRegistrationMethods();
registerMediaButtonEvent();
TelephonyManager tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tmgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
MPDApplication app = (MPDApplication) getApplication();
app.oMPDAsyncHelper.addStatusChangeListener(this);
app.oMPDAsyncHelper.addConnectionListener(this);
streamSource = "http://" + app.oMPDAsyncHelper.getConnectionStreamingServer() + ":"
+ app.oMPDAsyncHelper.getConnectionInfoPortStreaming() + "/";
}
@Override
public void onDestroy() {
if (needStoppedNotification) {
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_PAUSED);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.icon);
Notification status = null;
views.setTextViewText(R.id.trackname, getString(R.string.streamStopped));
views.setTextViewText(R.id.album, getString(R.string.app_name));
views.setTextViewText(R.id.artist, "");
status = new Notification(R.drawable.icon, getString(R.string.streamStopped), System.currentTimeMillis());
status.contentView = views;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(STREAMINGSERVICE_STOPPED, status);
}
isServiceRunning = false;
unregisterMediaButtonEvent();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) { // Stupid 1.6 compatibility
onStartCommand(intent, 0, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
lastStartID = startId;
if (((MPDApplication) getApplication()).isStreamingMode() == false) {
stopSelfResult(lastStartID);
return 0;
}
if (intent.getAction().equals("com.namelessdev.mpdroid.START_STREAMING")) {
// streaming_enabled = true;
resumeStreaming();
} else if (intent.getAction().equals("com.namelessdev.mpdroid.STOP_STREAMING")) {
stopStreaming();
} else if (intent.getAction().equals("com.namelessdev.mpdroid.RESET_STREAMING")) {
stopStreaming();
resumeStreaming();
} else if (intent.getAction().equals("com.namelessdev.mpdroid.DIE")) {
die();
} else if (intent.getAction().equals(CMD_REMOTE)) {
String cmd = intent.getStringExtra(CMD_COMMAND);
if (cmd.equals(CMD_NEXT)) {
next();
} else if (cmd.equals(CMD_PREV)) {
prev();
} else if (cmd.equals(CMD_PLAYPAUSE)) {
if (isPaused == false) {
pauseStreaming();
} else {
resumeStreaming();
}
} else if (cmd.equals(CMD_PAUSE)) {
pauseStreaming();
} else if (cmd.equals(CMD_STOP)) {
stop();
}
}
// Toast.makeText(this, "onStartCommand : "+(intent.getAction() == "com.namelessdev.mpdroid.START_STREAMING"),
// Toast.LENGTH_SHORT).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void showNotification() {
MPDApplication app = (MPDApplication) getApplication();
MPDStatus statusMpd = null;
try {
statusMpd = app.oMPDAsyncHelper.oMPD.getStatus();
} catch (MPDServerException e) {
// Do nothing cause I suck hard at android programming
}
if (statusMpd != null && !isPaused) {
String state = statusMpd.getState();
if (state != null) {
if (state == oldStatus)
return;
oldStatus = state;
int songId = statusMpd.getSongPos();
if (songId >= 0) {
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_PAUSED);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_STOPPED);
stopForeground(true);
Music actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getMusic(songId);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (buffering) {
views.setTextViewText(R.id.trackname, getString(R.string.buffering));
views.setTextViewText(R.id.album, actSong.getTitle());
views.setTextViewText(R.id.artist, actSong.getAlbum() + " - " + actSong.getArtist());
status = new Notification(R.drawable.icon, getString(R.string.buffering), System.currentTimeMillis());
} else {
views.setTextViewText(R.id.trackname, actSong.getTitle());
views.setTextViewText(R.id.album, actSong.getAlbum());
views.setTextViewText(R.id.artist, actSong.getArtist());
status = new Notification(R.drawable.icon, actSong.getTitle() + " - " + actSong.getArtist(),
System.currentTimeMillis());
}
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(STREAMINGSERVICE_STATUS, status);
}
}
} else if (isPaused) {
+ Context context = getApplicationContext();
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (mediaPlayerError != 0)
- views.setTextViewText(R.id.trackname, getString(R.string.streamError));
+ views.setTextViewText(R.id.trackname, context.getString(R.string.streamError));
else
- views.setTextViewText(R.id.trackname, getString(R.string.streamPaused));
+ views.setTextViewText(R.id.trackname, context.getString(R.string.streamPaused));
- views.setTextViewText(R.id.album, getString(R.string.streamPauseBattery));
+ views.setTextViewText(R.id.album, context.getString(R.string.streamPauseBattery));
views.setTextViewText(R.id.artist, "");
- status = new Notification(R.drawable.icon, getString(R.string.streamPaused), System.currentTimeMillis());
+ status = new Notification(R.drawable.icon, context.getString(R.string.streamPaused), System.currentTimeMillis());
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(STREAMINGSERVICE_PAUSED, status);
}
}
public void pauseStreaming() {
if (isPlaying == false)
return;
isPlaying = false;
isPaused = true;
buffering = false;
mediaPlayer.stop(); // So it stops faster
showNotification();
MPDApplication app = (MPDApplication) getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
try {
String state = mpd.getStatus().getState();
if (state.equals(MPDStatus.MPD_STATE_PLAYING))
mpd.pause();
} catch (MPDServerException e) {
}
}
public void resumeStreaming() {
// just to be sure, we do not want to start when we're not supposed to
if (((MPDApplication) getApplication()).isStreamingMode() == false)
return;
needStoppedNotification = false;
buffering = true;
MPDApplication app = (MPDApplication) getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
registerMediaButtonEvent();
if (isPaused == true) {
try {
String state = mpd.getStatus().getState();
if (state.equals(MPDStatus.MPD_STATE_PAUSED)) {
mpd.pause();
}
isPaused = false;
} catch (MPDServerException e) {
}
}
if (mediaPlayer == null)
return;
try {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(streamSource);
mediaPlayer.prepareAsync();
showNotification();
} catch (IOException e) {
// Error ? Notify the user ! (Another day)
buffering = false; // Obviously if it failed we are not buffering.
isPlaying = false;
} catch (IllegalStateException e) {
// wtf what state ?
// Toast.makeText(this, "Error IllegalStateException isPlaying : "+mediaPlayer.isPlaying(), Toast.LENGTH_SHORT).show();
isPlaying = false;
}
}
public void stopStreaming() {
oldStatus = "";
if (mediaPlayer == null)
return;
mediaPlayer.stop();
stopForeground(true);
}
public void prev() {
MPDApplication app = (MPDApplication) getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
try {
mpd.previous();
} catch (MPDServerException e) {
}
stopStreaming();
resumeStreaming();
}
public void next() {
MPDApplication app = (MPDApplication) getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
try {
mpd.next();
} catch (MPDServerException e) {
}
stopStreaming();
resumeStreaming();
}
public void stop() {
MPDApplication app = (MPDApplication) getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
try {
mpd.stop();
} catch (MPDServerException e) {
}
stopStreaming();
die();
}
public void die() {
((MPDApplication) getApplication()).setStreamingMode(false);
// Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show();
stopSelfResult(lastStartID);
}
@Override
public void trackChanged(MPDTrackChangedEvent event) {
oldStatus = "";
showNotification();
}
@Override
public void connectionStateChanged(MPDConnectionStateChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void playlistChanged(MPDPlaylistChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void randomChanged(MPDRandomChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void repeatChanged(MPDRepeatChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void stateChanged(MPDStateChangedEvent event) {
// TODO Auto-generated method stub
// Toast.makeText(this, "stateChanged :", Toast.LENGTH_SHORT).show();
Message msg = delayedStopHandler.obtainMessage();
delayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
MPDApplication app = (MPDApplication) getApplication();
MPDStatus statusMpd = null;
try {
statusMpd = app.oMPDAsyncHelper.oMPD.getStatus();
} catch (MPDServerException e) {
// Do nothing cause I suck hard at android programming
}
if (statusMpd != null) {
String state = statusMpd.getState();
if (state != null) {
if (state == oldStatus)
return;
if (state == MPDStatus.MPD_STATE_PLAYING) {
isPaused = false;
resumeStreaming();
isPlaying = true;
} else {
oldStatus = state;
isPlaying = false;
stopStreaming();
}
}
}
}
@Override
public void updateStateChanged(MPDUpdateStateChangedEvent event) {
// TODO Auto-generated method stub
// Toast.makeText(this, "updateStateChanged :", Toast.LENGTH_SHORT).show();
}
@Override
public void volumeChanged(MPDVolumeChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void onPrepared(MediaPlayer mp) {
// Buffering done
buffering = false;
isPlaying = true;
oldStatus = "";
showNotification();
mediaPlayer.start();
}
@Override
public void onCompletion(MediaPlayer mp) {
// Toast.makeText(this, "Completion", Toast.LENGTH_SHORT).show();
Message msg = delayedStopHandler.obtainMessage();
delayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); // Don't suck the battery too much
MPDApplication app = (MPDApplication) getApplication();
MPDStatus statusMpd = null;
try {
statusMpd = app.oMPDAsyncHelper.oMPD.getStatus();
} catch (MPDServerException e) {
// Do nothing cause I suck hard at android programming
}
if (statusMpd != null) {
String state = statusMpd.getState();
if (state != null) {
if (state == MPDStatus.MPD_STATE_PLAYING) {
// Resume playing
// TODO Stop resuming if no 3G. There's no point. Add something that says "ok we're waiting for 3G/wifi !"
resumeStreaming();
} else {
oldStatus = state;
// Something's happening, like crappy network or MPD just stopped..
die();
}
}
}
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
// Toast.makeText(this, "Buf update", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// Toast.makeText(this, "onError", Toast.LENGTH_SHORT).show();
// mediaPlayer.reset();
mediaPlayerError = what;
pauseStreaming();
return false;
}
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// Toast.makeText(this, "onInfo :", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void connectionFailed(String message) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connection Failed !", Toast.LENGTH_SHORT).show();
}
@Override
public void connectionSucceeded(String message) {
// TODO Auto-generated method stub
// Toast.makeText(this, "connectionSucceeded :", Toast.LENGTH_SHORT).show();
}
}
| false | true | public void showNotification() {
MPDApplication app = (MPDApplication) getApplication();
MPDStatus statusMpd = null;
try {
statusMpd = app.oMPDAsyncHelper.oMPD.getStatus();
} catch (MPDServerException e) {
// Do nothing cause I suck hard at android programming
}
if (statusMpd != null && !isPaused) {
String state = statusMpd.getState();
if (state != null) {
if (state == oldStatus)
return;
oldStatus = state;
int songId = statusMpd.getSongPos();
if (songId >= 0) {
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_PAUSED);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_STOPPED);
stopForeground(true);
Music actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getMusic(songId);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (buffering) {
views.setTextViewText(R.id.trackname, getString(R.string.buffering));
views.setTextViewText(R.id.album, actSong.getTitle());
views.setTextViewText(R.id.artist, actSong.getAlbum() + " - " + actSong.getArtist());
status = new Notification(R.drawable.icon, getString(R.string.buffering), System.currentTimeMillis());
} else {
views.setTextViewText(R.id.trackname, actSong.getTitle());
views.setTextViewText(R.id.album, actSong.getAlbum());
views.setTextViewText(R.id.artist, actSong.getArtist());
status = new Notification(R.drawable.icon, actSong.getTitle() + " - " + actSong.getArtist(),
System.currentTimeMillis());
}
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(STREAMINGSERVICE_STATUS, status);
}
}
} else if (isPaused) {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (mediaPlayerError != 0)
views.setTextViewText(R.id.trackname, getString(R.string.streamError));
else
views.setTextViewText(R.id.trackname, getString(R.string.streamPaused));
views.setTextViewText(R.id.album, getString(R.string.streamPauseBattery));
views.setTextViewText(R.id.artist, "");
status = new Notification(R.drawable.icon, getString(R.string.streamPaused), System.currentTimeMillis());
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(STREAMINGSERVICE_PAUSED, status);
}
}
| public void showNotification() {
MPDApplication app = (MPDApplication) getApplication();
MPDStatus statusMpd = null;
try {
statusMpd = app.oMPDAsyncHelper.oMPD.getStatus();
} catch (MPDServerException e) {
// Do nothing cause I suck hard at android programming
}
if (statusMpd != null && !isPaused) {
String state = statusMpd.getState();
if (state != null) {
if (state == oldStatus)
return;
oldStatus = state;
int songId = statusMpd.getSongPos();
if (songId >= 0) {
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_PAUSED);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(STREAMINGSERVICE_STOPPED);
stopForeground(true);
Music actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getMusic(songId);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (buffering) {
views.setTextViewText(R.id.trackname, getString(R.string.buffering));
views.setTextViewText(R.id.album, actSong.getTitle());
views.setTextViewText(R.id.artist, actSong.getAlbum() + " - " + actSong.getArtist());
status = new Notification(R.drawable.icon, getString(R.string.buffering), System.currentTimeMillis());
} else {
views.setTextViewText(R.id.trackname, actSong.getTitle());
views.setTextViewText(R.id.album, actSong.getAlbum());
views.setTextViewText(R.id.artist, actSong.getArtist());
status = new Notification(R.drawable.icon, actSong.getTitle() + " - " + actSong.getArtist(),
System.currentTimeMillis());
}
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
startForeground(STREAMINGSERVICE_STATUS, status);
}
}
} else if (isPaused) {
Context context = getApplicationContext();
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
Notification status = null;
if (mediaPlayerError != 0)
views.setTextViewText(R.id.trackname, context.getString(R.string.streamError));
else
views.setTextViewText(R.id.trackname, context.getString(R.string.streamPaused));
views.setTextViewText(R.id.album, context.getString(R.string.streamPauseBattery));
views.setTextViewText(R.id.artist, "");
status = new Notification(R.drawable.icon, context.getString(R.string.streamPaused), System.currentTimeMillis());
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.icon;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.namelessdev.mpdroid.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(STREAMINGSERVICE_PAUSED, status);
}
}
|
diff --git a/runtime/android/java/src/org/xwalk/core/client/XWalkDefaultClient.java b/runtime/android/java/src/org/xwalk/core/client/XWalkDefaultClient.java
index 49fb4ecc..81e540ab 100755
--- a/runtime/android/java/src/org/xwalk/core/client/XWalkDefaultClient.java
+++ b/runtime/android/java/src/org/xwalk/core/client/XWalkDefaultClient.java
@@ -1,159 +1,159 @@
// Copyright (c) 2013 Intel Corporation. All rights reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.core.client;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.http.SslError;
import android.net.Uri;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.xwalk.core.HttpAuthDatabase;
import org.xwalk.core.XWalkHttpAuthHandler;
import org.xwalk.core.R;
import org.xwalk.core.SslErrorHandler;
import org.xwalk.core.XWalkClient;
import org.xwalk.core.XWalkView;
public class XWalkDefaultClient extends XWalkClient {
// Strings for displaying Dialog.
private static String mAlertTitle;
private static String mSslAlertTitle;
private static String mOKButton;
private static String mCancelButton;
private Context mContext;
private AlertDialog mDialog;
private XWalkView mView;
private HttpAuthDatabase mDatabase;
private static final String HTTP_AUTH_DATABASE_FILE = "http_auth.db";
public XWalkDefaultClient(Context context, XWalkView view) {
mDatabase = new HttpAuthDatabase(context.getApplicationContext(), HTTP_AUTH_DATABASE_FILE);
mContext = context;
mView = view;
}
/***
* Retrieve the HTTP authentication username and password for a given
* host & realm pair.
*
* @param host The host for which the credentials apply.
* @param realm The realm for which the credentials apply.
* @return String[] if found, String[0] is username, which can be null and
* String[1] is password. Return null if it can't find anything.
*/
public String[] getHttpAuthUsernamePassword(String host, String realm) {
return mDatabase.getHttpAuthUsernamePassword(host, realm);
}
@Override
public void onReceivedError(XWalkView view, int errorCode,
String description, String failingUrl) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle(android.R.string.dialog_alert_title)
.setMessage(description)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mDialog = dialogBuilder.create();
mDialog.show();
}
@Override
public void onReceivedSslError(XWalkView view, SslErrorHandler handler,
SslError error) {
final SslErrorHandler sslHandler = handler;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle(R.string.ssl_alert_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sslHandler.proceed();
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sslHandler.cancel();
dialog.cancel();
}
});
mDialog = dialogBuilder.create();
mDialog.show();
}
/***
* Set the HTTP authentication credentials for a given host and realm.
*
* @param host The host for the credentials.
* @param realm The realm for the credentials.
* @param username The username for the password. If it is null, it means
* password can't be saved.
* @param password The password
*/
public void setHttpAuthUsernamePassword(String host, String realm,
String username, String password) {
mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
}
private void showHttpAuthDialog( final XWalkHttpAuthHandler handler,
final String host, final String realm) {
LinearLayout layout = new LinearLayout(mContext);
final EditText userNameEditText = new EditText(mContext);
final EditText passwordEditText = new EditText(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
- layout.setPaddingRelative(20, 0, 20, 0);
+ layout.setPaddingRelative(10, 0, 10, 20);
userNameEditText.setHint(R.string.http_auth_user_name);
passwordEditText.setHint(R.string.http_auth_password);
layout.addView(userNameEditText);
layout.addView(passwordEditText);
final Activity curActivity = mView.getActivity();
AlertDialog.Builder httpAuthDialog = new AlertDialog.Builder(curActivity);
httpAuthDialog.setTitle(R.string.http_auth_title)
.setView(layout)
.setCancelable(false)
.setPositiveButton(R.string.http_auth_log_in, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
setHttpAuthUsernamePassword(host, realm, userName, password);
handler.proceed(userName, password);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
handler.cancel();
dialog.dismiss();
}
})
.create().show();
}
@Override
public void onReceivedHttpAuthRequest(XWalkView view,
XWalkHttpAuthHandler handler, String host, String realm) {
if (view != null) {
showHttpAuthDialog(handler, host, realm);
}
}
}
| true | true | private void showHttpAuthDialog( final XWalkHttpAuthHandler handler,
final String host, final String realm) {
LinearLayout layout = new LinearLayout(mContext);
final EditText userNameEditText = new EditText(mContext);
final EditText passwordEditText = new EditText(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPaddingRelative(20, 0, 20, 0);
userNameEditText.setHint(R.string.http_auth_user_name);
passwordEditText.setHint(R.string.http_auth_password);
layout.addView(userNameEditText);
layout.addView(passwordEditText);
final Activity curActivity = mView.getActivity();
AlertDialog.Builder httpAuthDialog = new AlertDialog.Builder(curActivity);
httpAuthDialog.setTitle(R.string.http_auth_title)
.setView(layout)
.setCancelable(false)
.setPositiveButton(R.string.http_auth_log_in, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
setHttpAuthUsernamePassword(host, realm, userName, password);
handler.proceed(userName, password);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
handler.cancel();
dialog.dismiss();
}
})
.create().show();
}
| private void showHttpAuthDialog( final XWalkHttpAuthHandler handler,
final String host, final String realm) {
LinearLayout layout = new LinearLayout(mContext);
final EditText userNameEditText = new EditText(mContext);
final EditText passwordEditText = new EditText(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPaddingRelative(10, 0, 10, 20);
userNameEditText.setHint(R.string.http_auth_user_name);
passwordEditText.setHint(R.string.http_auth_password);
layout.addView(userNameEditText);
layout.addView(passwordEditText);
final Activity curActivity = mView.getActivity();
AlertDialog.Builder httpAuthDialog = new AlertDialog.Builder(curActivity);
httpAuthDialog.setTitle(R.string.http_auth_title)
.setView(layout)
.setCancelable(false)
.setPositiveButton(R.string.http_auth_log_in, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
setHttpAuthUsernamePassword(host, realm, userName, password);
handler.proceed(userName, password);
dialog.dismiss();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
handler.cancel();
dialog.dismiss();
}
})
.create().show();
}
|
diff --git a/src/main/java/org/jcompas/view/ControlPaneFactory.java b/src/main/java/org/jcompas/view/ControlPaneFactory.java
index 2e09421..5e35af8 100644
--- a/src/main/java/org/jcompas/view/ControlPaneFactory.java
+++ b/src/main/java/org/jcompas/view/ControlPaneFactory.java
@@ -1,153 +1,154 @@
/* *********************************************************************** *
* project: org.jcompas.*
* ControlPane.java
* *
* *********************************************************************** *
* *
* copyright : (C) 2012 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.jcompas.view;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSlider;
import org.apache.log4j.Logger;
import org.jcompas.control.Controller;
/**
* @author thibautd
*/
public class ControlPaneFactory {
private static final Logger log =
Logger.getLogger(ControlPaneFactory.class);
private static final int BPM_MIN = 50;
private static final int BPM_MAX = 250;
private static final int VERT_GAP = 20;
private static final String START_ACTION = "cocorico";
private static final String STOP_ACTION = "turlututu";
public static JPanel createControlPane(final Controller controller) {
// init pane
final JPanel pane = new JPanel();
pane.setLayout( new BoxLayout( pane , BoxLayout.Y_AXIS ) );
// init components and add them
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox paloBox = new JComboBox( controller.getPalos().toArray() );
paloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( paloBox );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox estiloBox = new JComboBox();
estiloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( estiloBox );
final JButton startButton = new JButton( "Start" );
startButton.setEnabled( false );
startButton.setActionCommand( START_ACTION );
final JButton stopButton = new JButton( "Stop" );
stopButton.setEnabled( false );
stopButton.setActionCommand( STOP_ACTION );
pane.add( Box.createVerticalGlue() );
JPanel buttons = new JPanel();
buttons.setLayout( new BoxLayout( buttons , BoxLayout.X_AXIS ) );
buttons.add( Box.createHorizontalGlue() );
buttons.add( startButton );
buttons.add( Box.createHorizontalGlue() );
buttons.add( stopButton );
buttons.add( Box.createHorizontalGlue() );
pane.add( buttons );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JSlider bpmSlider =
new JSlider(
JSlider.HORIZONTAL,
BPM_MIN,
BPM_MAX,
BPM_MIN );
bpmSlider.setMajorTickSpacing( 50 );
bpmSlider.setMinorTickSpacing( 10 );
bpmSlider.setPaintTicks( true );
bpmSlider.setPaintLabels( true );
bpmSlider.setBorder( BorderFactory.createTitledBorder( "Tempo" ) );
bpmSlider.setEnabled( false );
pane.add( bpmSlider );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
// listenners
paloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectPalo( (String) box.getSelectedItem() );
log.debug( "adding estilos "+controller.getEstilos() );
estiloBox.setModel(
new DefaultComboBoxModel(
controller.getEstilos().toArray() ) );
}
});
estiloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectEstilo( (String) box.getSelectedItem() );
for (String p : controller.getPatterns()) {
controller.addPatternToSelection( p );
}
startButton.setEnabled( true );
bpmSlider.setEnabled( true );
bpmSlider.setValue( controller.getBpm() );
}
});
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean start = e.getActionCommand().equals( START_ACTION );
startButton.setEnabled( !start );
stopButton.setEnabled( start );
paloBox.setEnabled( !start );
estiloBox.setEnabled( !start );
bpmSlider.setEnabled( !start );
+ controller.setBpm( bpmSlider.getValue() );
if (start) controller.start();
else controller.stop();
}
};
startButton.addActionListener( buttonListener );
stopButton.addActionListener( buttonListener );
return pane;
}
}
| true | true | public static JPanel createControlPane(final Controller controller) {
// init pane
final JPanel pane = new JPanel();
pane.setLayout( new BoxLayout( pane , BoxLayout.Y_AXIS ) );
// init components and add them
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox paloBox = new JComboBox( controller.getPalos().toArray() );
paloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( paloBox );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox estiloBox = new JComboBox();
estiloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( estiloBox );
final JButton startButton = new JButton( "Start" );
startButton.setEnabled( false );
startButton.setActionCommand( START_ACTION );
final JButton stopButton = new JButton( "Stop" );
stopButton.setEnabled( false );
stopButton.setActionCommand( STOP_ACTION );
pane.add( Box.createVerticalGlue() );
JPanel buttons = new JPanel();
buttons.setLayout( new BoxLayout( buttons , BoxLayout.X_AXIS ) );
buttons.add( Box.createHorizontalGlue() );
buttons.add( startButton );
buttons.add( Box.createHorizontalGlue() );
buttons.add( stopButton );
buttons.add( Box.createHorizontalGlue() );
pane.add( buttons );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JSlider bpmSlider =
new JSlider(
JSlider.HORIZONTAL,
BPM_MIN,
BPM_MAX,
BPM_MIN );
bpmSlider.setMajorTickSpacing( 50 );
bpmSlider.setMinorTickSpacing( 10 );
bpmSlider.setPaintTicks( true );
bpmSlider.setPaintLabels( true );
bpmSlider.setBorder( BorderFactory.createTitledBorder( "Tempo" ) );
bpmSlider.setEnabled( false );
pane.add( bpmSlider );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
// listenners
paloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectPalo( (String) box.getSelectedItem() );
log.debug( "adding estilos "+controller.getEstilos() );
estiloBox.setModel(
new DefaultComboBoxModel(
controller.getEstilos().toArray() ) );
}
});
estiloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectEstilo( (String) box.getSelectedItem() );
for (String p : controller.getPatterns()) {
controller.addPatternToSelection( p );
}
startButton.setEnabled( true );
bpmSlider.setEnabled( true );
bpmSlider.setValue( controller.getBpm() );
}
});
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean start = e.getActionCommand().equals( START_ACTION );
startButton.setEnabled( !start );
stopButton.setEnabled( start );
paloBox.setEnabled( !start );
estiloBox.setEnabled( !start );
bpmSlider.setEnabled( !start );
if (start) controller.start();
else controller.stop();
}
};
startButton.addActionListener( buttonListener );
stopButton.addActionListener( buttonListener );
return pane;
}
| public static JPanel createControlPane(final Controller controller) {
// init pane
final JPanel pane = new JPanel();
pane.setLayout( new BoxLayout( pane , BoxLayout.Y_AXIS ) );
// init components and add them
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox paloBox = new JComboBox( controller.getPalos().toArray() );
paloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( paloBox );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JComboBox estiloBox = new JComboBox();
estiloBox.setMaximumSize( new Dimension( 200, 20 ) );
pane.add( estiloBox );
final JButton startButton = new JButton( "Start" );
startButton.setEnabled( false );
startButton.setActionCommand( START_ACTION );
final JButton stopButton = new JButton( "Stop" );
stopButton.setEnabled( false );
stopButton.setActionCommand( STOP_ACTION );
pane.add( Box.createVerticalGlue() );
JPanel buttons = new JPanel();
buttons.setLayout( new BoxLayout( buttons , BoxLayout.X_AXIS ) );
buttons.add( Box.createHorizontalGlue() );
buttons.add( startButton );
buttons.add( Box.createHorizontalGlue() );
buttons.add( stopButton );
buttons.add( Box.createHorizontalGlue() );
pane.add( buttons );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
final JSlider bpmSlider =
new JSlider(
JSlider.HORIZONTAL,
BPM_MIN,
BPM_MAX,
BPM_MIN );
bpmSlider.setMajorTickSpacing( 50 );
bpmSlider.setMinorTickSpacing( 10 );
bpmSlider.setPaintTicks( true );
bpmSlider.setPaintLabels( true );
bpmSlider.setBorder( BorderFactory.createTitledBorder( "Tempo" ) );
bpmSlider.setEnabled( false );
pane.add( bpmSlider );
pane.add( Box.createRigidArea( new Dimension( 0 , VERT_GAP ) ) );
// listenners
paloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectPalo( (String) box.getSelectedItem() );
log.debug( "adding estilos "+controller.getEstilos() );
estiloBox.setModel(
new DefaultComboBoxModel(
controller.getEstilos().toArray() ) );
}
});
estiloBox.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
controller.selectEstilo( (String) box.getSelectedItem() );
for (String p : controller.getPatterns()) {
controller.addPatternToSelection( p );
}
startButton.setEnabled( true );
bpmSlider.setEnabled( true );
bpmSlider.setValue( controller.getBpm() );
}
});
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean start = e.getActionCommand().equals( START_ACTION );
startButton.setEnabled( !start );
stopButton.setEnabled( start );
paloBox.setEnabled( !start );
estiloBox.setEnabled( !start );
bpmSlider.setEnabled( !start );
controller.setBpm( bpmSlider.getValue() );
if (start) controller.start();
else controller.stop();
}
};
startButton.addActionListener( buttonListener );
stopButton.addActionListener( buttonListener );
return pane;
}
|
diff --git a/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java b/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java
index db458d4f..d2fc1ced 100644
--- a/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java
+++ b/src/plugin/lib-parsems/src/java/org/apache/nutch/parse/ms/MSBaseParser.java
@@ -1,163 +1,165 @@
/**
* Copyright 2005 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.nutch.parse.ms;
// JDK imports
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// Hadoop imports
import org.apache.hadoop.conf.Configuration;
// Nutch imports
import org.apache.nutch.metadata.DublinCore;
import org.apache.nutch.metadata.Metadata;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.parse.OutlinkExtractor;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseImpl;
import org.apache.nutch.parse.ParseStatus;
import org.apache.nutch.parse.Parser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.LogUtil;
import org.apache.nutch.util.NutchConfiguration;
/**
* A generic Microsoft document parser.
*
* @author Jérôme Charron
*/
public abstract class MSBaseParser implements Parser {
private Configuration conf;
protected static final Log LOG = LogFactory.getLog(MSBaseParser.class);
/**
* Parses a Content with a specific {@link MSExtractor Microsoft document
* extractor}.
*/
protected Parse getParse(MSExtractor extractor, Content content) {
String text = null;
String title = null;
Outlink[] outlinks = null;
Properties properties = null;
try {
byte[] raw = content.getContent();
String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH);
if ((contentLength != null) &&
(raw.length != Integer.parseInt(contentLength))) {
return new ParseStatus(ParseStatus.FAILED,
ParseStatus.FAILED_TRUNCATED,
"Content truncated at " + raw.length +" bytes. " +
"Parser can't handle incomplete file.")
.getEmptyParse(this.conf);
}
extractor.extract(new ByteArrayInputStream(raw));
text = extractor.getText();
properties = extractor.getProperties();
outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf());
} catch (Exception e) {
return new ParseStatus(ParseStatus.FAILED,
- "Can't be handled as micrsosoft document. " + e)
+ "Can't be handled as Microsoft document. " + e)
.getEmptyParse(this.conf);
}
// collect meta data
Metadata metadata = new Metadata();
- title = properties.getProperty(DublinCore.TITLE);
- properties.remove(DublinCore.TITLE);
- metadata.setAll(properties);
+ if (properties != null) {
+ title = properties.getProperty(DublinCore.TITLE);
+ properties.remove(DublinCore.TITLE);
+ metadata.setAll(properties);
+ }
if (text == null) { text = ""; }
if (title == null) { title = ""; }
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
outlinks, content.getMetadata(),
metadata);
parseData.setConf(this.conf);
return new ParseImpl(text, parseData);
}
/**
* Main for testing. Pass a ms document as argument
*/
public static void main(String mime, MSBaseParser parser, String args[]) {
if (args.length < 1) {
System.err.println("Usage:");
System.err.println("\t" + parser.getClass().getName() + " <file>");
System.exit(1);
}
String file = args[0];
byte[] raw = getRawBytes(new File(file));
Metadata meta = new Metadata();
meta.set(Response.CONTENT_LENGTH, "" + raw.length);
Content content = new Content(file, file, raw, mime, meta,
NutchConfiguration.create());
System.out.println(parser.getParse(content).getText());
}
private final static byte[] getRawBytes(File f) {
try {
if (!f.exists())
return null;
FileInputStream fin = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
fin.read(buffer);
fin.close();
return buffer;
} catch (Exception err) {
err.printStackTrace(LogUtil.getErrorStream(LOG));
return null;
}
}
/* ---------------------------- *
* <implemenation:Configurable> *
* ---------------------------- */
public void setConf(Configuration conf) {
this.conf = conf;
}
public Configuration getConf() {
return this.conf;
}
/* ----------------------------- *
* </implemenation:Configurable> *
* ----------------------------- */
}
| false | true | protected Parse getParse(MSExtractor extractor, Content content) {
String text = null;
String title = null;
Outlink[] outlinks = null;
Properties properties = null;
try {
byte[] raw = content.getContent();
String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH);
if ((contentLength != null) &&
(raw.length != Integer.parseInt(contentLength))) {
return new ParseStatus(ParseStatus.FAILED,
ParseStatus.FAILED_TRUNCATED,
"Content truncated at " + raw.length +" bytes. " +
"Parser can't handle incomplete file.")
.getEmptyParse(this.conf);
}
extractor.extract(new ByteArrayInputStream(raw));
text = extractor.getText();
properties = extractor.getProperties();
outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf());
} catch (Exception e) {
return new ParseStatus(ParseStatus.FAILED,
"Can't be handled as micrsosoft document. " + e)
.getEmptyParse(this.conf);
}
// collect meta data
Metadata metadata = new Metadata();
title = properties.getProperty(DublinCore.TITLE);
properties.remove(DublinCore.TITLE);
metadata.setAll(properties);
if (text == null) { text = ""; }
if (title == null) { title = ""; }
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
outlinks, content.getMetadata(),
metadata);
parseData.setConf(this.conf);
return new ParseImpl(text, parseData);
}
| protected Parse getParse(MSExtractor extractor, Content content) {
String text = null;
String title = null;
Outlink[] outlinks = null;
Properties properties = null;
try {
byte[] raw = content.getContent();
String contentLength = content.getMetadata().get(Metadata.CONTENT_LENGTH);
if ((contentLength != null) &&
(raw.length != Integer.parseInt(contentLength))) {
return new ParseStatus(ParseStatus.FAILED,
ParseStatus.FAILED_TRUNCATED,
"Content truncated at " + raw.length +" bytes. " +
"Parser can't handle incomplete file.")
.getEmptyParse(this.conf);
}
extractor.extract(new ByteArrayInputStream(raw));
text = extractor.getText();
properties = extractor.getProperties();
outlinks = OutlinkExtractor.getOutlinks(text, content.getUrl(), getConf());
} catch (Exception e) {
return new ParseStatus(ParseStatus.FAILED,
"Can't be handled as Microsoft document. " + e)
.getEmptyParse(this.conf);
}
// collect meta data
Metadata metadata = new Metadata();
if (properties != null) {
title = properties.getProperty(DublinCore.TITLE);
properties.remove(DublinCore.TITLE);
metadata.setAll(properties);
}
if (text == null) { text = ""; }
if (title == null) { title = ""; }
ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title,
outlinks, content.getMetadata(),
metadata);
parseData.setConf(this.conf);
return new ParseImpl(text, parseData);
}
|
diff --git a/corelib-solr/src/main/java/eu/europeana/corelib/solr/bean/impl/FullBeanImpl.java b/corelib-solr/src/main/java/eu/europeana/corelib/solr/bean/impl/FullBeanImpl.java
index f42651d3..e3003ad5 100644
--- a/corelib-solr/src/main/java/eu/europeana/corelib/solr/bean/impl/FullBeanImpl.java
+++ b/corelib-solr/src/main/java/eu/europeana/corelib/solr/bean/impl/FullBeanImpl.java
@@ -1,362 +1,362 @@
/*
* Copyright 2007-2012 The Europeana Foundation
*
* Licenced under the EUPL, Version 1.1 (the "Licence") and subsequent versions as approved
* by the European Commission;
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the Licence is distributed on an "AS IS" basis, without warranties or conditions of
* any kind, either express or implied.
* See the Licence for the specific language governing permissions and limitations under
* the Licence.
*/
package eu.europeana.corelib.solr.bean.impl;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Reference;
import com.google.code.morphia.annotations.Transient;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.definitions.solr.beans.BriefBean;
import eu.europeana.corelib.definitions.solr.beans.FullBean;
import eu.europeana.corelib.definitions.solr.entity.Agent;
import eu.europeana.corelib.definitions.solr.entity.Aggregation;
import eu.europeana.corelib.definitions.solr.entity.Concept;
import eu.europeana.corelib.definitions.solr.entity.EuropeanaAggregation;
import eu.europeana.corelib.definitions.solr.entity.Place;
import eu.europeana.corelib.definitions.solr.entity.ProvidedCHO;
import eu.europeana.corelib.definitions.solr.entity.Proxy;
import eu.europeana.corelib.definitions.solr.entity.Timespan;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.AggregationImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProvidedCHOImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.web.service.impl.EuropeanaUrlServiceImpl;
/**
* @see eu.europeana.corelib.definitions.solr.beans.FullBean
*
* @author Yorgos.Mamakis@ kb.nl
*/
@SuppressWarnings("unchecked")
@JsonSerialize(include = Inclusion.NON_EMPTY)
@Entity("record")
public class FullBeanImpl implements FullBean {
@Id
protected ObjectId europeanaId;
@Indexed(unique = true)
protected String about;
protected String[] title;
protected String[] year;
protected String[] provider;
protected String[] language;
protected Date timestamp;
protected DocType type;
protected int europeanaCompleteness;
protected boolean optOut;
@Transient
protected List<BriefBeanImpl> similarItems;
@Reference
protected List<PlaceImpl> places;
@Reference
protected List<AgentImpl> agents;
@Reference
protected List<TimespanImpl> timespans;
@Reference
protected List<ConceptImpl> concepts;
@Reference
protected List<AggregationImpl> aggregations;
@Reference
protected List<ProvidedCHOImpl> providedCHOs;
@Reference
protected EuropeanaAggregationImpl europeanaAggregation;
@Reference
protected List<ProxyImpl> proxies;
protected String[] country;
protected String[] userTags;
protected String[] europeanaCollectionName;
/**
* GETTERS & SETTTERS
*/
@Override
public List<PlaceImpl> getPlaces() {
return this.places;
}
@Override
public void setPlaces(List<? extends Place> places) {
this.places = (List<PlaceImpl>) places;
}
@Override
public List<AgentImpl> getAgents() {
return this.agents;
}
@Override
public String getAbout() {
return this.about;
}
@Override
public void setAbout(String about) {
this.about = about;
}
@Override
public void setAgents(List<? extends Agent> agents) {
this.agents = (List<AgentImpl>) agents;
}
@Override
public List<TimespanImpl> getTimespans() {
return this.timespans;
}
@Override
public void setTimespans(List<? extends Timespan> timespans) {
this.timespans = (List<TimespanImpl>) timespans;
}
@Override
public List<ConceptImpl> getConcepts() {
return this.concepts;
}
@Override
public void setConcepts(List<? extends Concept> concepts) {
this.concepts = (List<ConceptImpl>) concepts;
}
@Override
public List<AggregationImpl> getAggregations() {
return this.aggregations;
}
@Override
public void setAggregations(List<? extends Aggregation> aggregations) {
this.aggregations = (List<AggregationImpl>) aggregations;
}
@Override
public EuropeanaAggregation getEuropeanaAggregation() {
String previewUrl = null;
if (this.getAggregations().get(0).getEdmObject() != null) {
previewUrl = this.getAggregations().get(0).getEdmObject();
}
if (previewUrl != null) {
this.europeanaAggregation.setEdmPreview(EuropeanaUrlServiceImpl
- .getBeanInstance().getThumbnailUrl(previewUrl, type)
+ .getBeanInstance().getThumbnailUrl(previewUrl, getType())
.toString());
} else {
this.europeanaAggregation.setEdmPreview("");
}
return this.europeanaAggregation;
}
@Override
public void setEuropeanaAggregation(
EuropeanaAggregation europeanaAggregation) {
this.europeanaAggregation = (EuropeanaAggregationImpl) europeanaAggregation;
}
@Override
public List<ProxyImpl> getProxies() {
return this.proxies;
}
@Override
public void setProxies(List<? extends Proxy> proxies) {
this.proxies = (List<ProxyImpl>) proxies;
}
@Override
public List<ProvidedCHOImpl> getProvidedCHOs() {
return this.providedCHOs;
}
@Override
public void setProvidedCHOs(List<? extends ProvidedCHO> providedCHOs) {
this.providedCHOs = (List<ProvidedCHOImpl>) providedCHOs;
}
@Override
public void setEuropeanaId(ObjectId europeanaId) {
this.europeanaId = europeanaId;
}
@Override
public void setTitle(String[] title) {
this.title = title.clone();
}
@Override
public void setYear(String[] year) {
this.year = year.clone();
}
@Override
public void setProvider(String[] provider) {
this.provider = provider.clone();
}
@Override
public void setLanguage(String[] language) {
this.language = language.clone();
}
@Override
public void setType(DocType type) {
this.type = type;
}
@Override
public void setEuropeanaCompleteness(int europeanaCompleteness) {
this.europeanaCompleteness = europeanaCompleteness;
}
@Override
public String[] getTitle() {
return (this.title != null ? this.title.clone() : null);
}
@Override
public String[] getYear() {
return (this.year != null ? this.year.clone() : null);
}
@Override
public String[] getProvider() {
return (this.provider != null ? this.provider.clone() : null);
}
@Override
public String[] getLanguage() {
return (this.language != null ? this.language.clone() : null);
}
@Override
public DocType getType() {
if (type != null) {
return this.type;
}
return this.getProxies().get(0).getEdmType();
}
@Override
public int getEuropeanaCompleteness() {
return this.europeanaCompleteness;
}
@Override
public String[] getUserTags() {
return this.userTags != null ? this.userTags.clone() : null;
}
public void setUserTags(String[] userTags) {
this.userTags = userTags.clone();
}
@Override
public String getId() {
if (this.europeanaId != null) {
return this.europeanaId.toString();
}
return null;
}
@Override
public int hashCode() {
return StringUtils.isNotBlank(this.about) ? this.about.hashCode()
: this.europeanaId.toStringMongod().hashCode();
}
@Override
public String[] getCountry() {
return this.country != null ? country.clone() : null;
}
@Override
public void setCountry(String[] country) {
this.country = country.clone();
}
@Override
public String[] getEuropeanaCollectionName() {
return this.europeanaCollectionName != null ? this.europeanaCollectionName
.clone() : null;
}
@Override
public void setEuropeanaCollectionName(String[] europeanaCollectionName) {
this.europeanaCollectionName = europeanaCollectionName != null ? europeanaCollectionName
.clone() : null;
}
@Override
public Date getTimestamp() {
return timestamp;
}
@Override
public List<? extends BriefBean> getSimilarItems() {
return this.similarItems;
}
@Override
public void setSimilarItems(List<? extends BriefBean> similarItems) {
this.similarItems = (List<BriefBeanImpl>) similarItems;
}
@Override
public Boolean isOptedOut() {
return this.optOut;
}
@Override
public void setOptOut(boolean optOut) {
this.optOut = optOut;
}
}
| true | true | public EuropeanaAggregation getEuropeanaAggregation() {
String previewUrl = null;
if (this.getAggregations().get(0).getEdmObject() != null) {
previewUrl = this.getAggregations().get(0).getEdmObject();
}
if (previewUrl != null) {
this.europeanaAggregation.setEdmPreview(EuropeanaUrlServiceImpl
.getBeanInstance().getThumbnailUrl(previewUrl, type)
.toString());
} else {
this.europeanaAggregation.setEdmPreview("");
}
return this.europeanaAggregation;
}
| public EuropeanaAggregation getEuropeanaAggregation() {
String previewUrl = null;
if (this.getAggregations().get(0).getEdmObject() != null) {
previewUrl = this.getAggregations().get(0).getEdmObject();
}
if (previewUrl != null) {
this.europeanaAggregation.setEdmPreview(EuropeanaUrlServiceImpl
.getBeanInstance().getThumbnailUrl(previewUrl, getType())
.toString());
} else {
this.europeanaAggregation.setEdmPreview("");
}
return this.europeanaAggregation;
}
|
diff --git a/src/org/ssgwt/client/ui/form/ComplexInput.java b/src/org/ssgwt/client/ui/form/ComplexInput.java
index 065374b..c250a3a 100644
--- a/src/org/ssgwt/client/ui/form/ComplexInput.java
+++ b/src/org/ssgwt/client/ui/form/ComplexInput.java
@@ -1,666 +1,667 @@
package org.ssgwt.client.ui.form;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import org.ssgwt.client.ui.form.event.ComplexInputFormRemoveEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormAddEvent;
/**
* Abstract Complex Input is an input field that contains a dynamic form and a
* view ui that is binded and used to display the view state of the field
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param <T> is the type if data used like a VO
*/
public abstract class ComplexInput<T> extends Composite
implements
HasValue<T>,
InputField<T, T>,
ComplexInputFormRemoveEvent.ComplexInputFormRemoveHasHandlers,
ComplexInputFormAddEvent.ComplexInputFormAddHasHandlers {
/**
* This is the main panel.
*/
protected FlowPanel mainPanel = new FlowPanel();
/**
* The panel that holds the dynamicForm.
*/
protected FlowPanel dynamicFormPanel = new FlowPanel();
/**
* The panel that holds the view.
*
* The ui binder is added to it
*/
protected FlowPanel viewPanel = new FlowPanel();
/**
* The panel data contains the data of the field.
*
* The view and dynamicForm.
*/
protected FlowPanel dataPanel = new FlowPanel();
/**
* Panel that holds the action buttons
*/
private FlowPanel actionPanel = new FlowPanel();
/**
* The Panel that holds the view buttons
*/
protected FlowPanel viewButtons = new FlowPanel();
/**
* The Panel that holds the edit buttons
*/
protected FlowPanel editButtons = new FlowPanel();
/**
* The save buttons.
*/
protected Button saveButton = new Button("Save");
/**
* The undo button
*/
protected Button undoButton = new Button("Undo");
/**
* The add buttons
*/
protected Button addButton = new Button("Add");
/**
* The edit label
*/
protected Label editLabel = new Label("Edit /");
/**
* The remove label
*/
protected Label removeLabel = new Label("Remove");
/**
* The panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messagePanel;
/**
* The table-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageTable;
/**
* The row-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageRow;
/**
* The cell-label that will hold either the info message or the
* validation error
*/
private Label messageCell;
/**
* Flowpanel to hold the message panel
*/
private FlowPanel messageContainer;
/**
* Injected Object
*/
protected Object injectedObject;
/**
* Class constructor
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public ComplexInput() {
initWidget(mainPanel);
}
/**
* Style to display elements inline
*/
private String displayInline = "ssGWT-displayInlineBlockMiddel";
/**
* language Input Click Labels style
*/
private String languageInputClickLabels = "ssGWT-languageInputClickLabels";
/**
* Save Button style
*/
private String complexSaveButton = "ssGWT-complexSaveButton";
/**
* Label Button style
*/
private String complexLabelButton = "ssGWT-complexLabelButton";
/**
* Undo Button style
*/
private String complexUndoButton = "ssGWT-complexUndoButton";
/**
* Add Button style
*/
private String complexAddButton = "ssGWT-complexAddButton";
/**
* Action Container style
*/
private String complexActionContainer = "ssGWT-complexActionContainer";
/**
* Function to construct all the components and add it to the main panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
+ clearMessage();
setViewState();
}
});
}
/**
* Abstract function for the get of the ui view
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the ui as a Widget
*/
public abstract Widget getUiBinder();
/**
* Abstract function for the get of the DynamicForm
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the DynamicForm
*/
public abstract DynamicForm<T> getDynamicForm();
/**
* Abstract function to set the field in a view state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setViewState();
/**
* Abstract function to set the field in a edit state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setEditDtate();
/**
* Abstract function to set the field in a add state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setAddState();
/**
* Abstract function that will be called on click of the save button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void saveField();
/**
* Abstract function that will be called on click of the add button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void addField();
/**
* Abstract function that will be called on click of the remove button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void removeField();
/**
* If the need arise for the field to have ValueChangeHandler added to it
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param handler - The Value Change Handler
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
return null;
}
/**
* Function that will set a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to set
*/
protected void setActionPanel(Widget widget) {
actionPanel.clear();
actionPanel.add(widget);
}
/**
* Function that will add a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to add
*/
protected void addToActionPanel(Widget widget) {
actionPanel.add(widget);
}
/**
* Function that will remove a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to remove
*/
protected void removeFromActionPanel(Widget widget) {
actionPanel.remove(widget);
}
/**
* Function that will clear the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void clearActionPanel() {
actionPanel.clear();
}
/**
* Getter for the view panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the view panel
*/
protected FlowPanel getViewPanel() {
return this.viewPanel;
}
/**
* Getter for the dynamic panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the dynamic panel
*/
protected FlowPanel getDynamicFormPanel() {
return this.dynamicFormPanel;
}
/**
* Set the add button to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setAddButton() {
setActionPanel(addButton);
}
/**
* Set the view buttons to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setViewButtons() {
setActionPanel(viewButtons);
}
/**
* Set the edit button to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setEditButtons() {
setActionPanel(editButtons);
}
/**
* A setter for an inject object
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param object - The object to inject
*/
public void setInjectedObject(Object object) {
this.injectedObject = object;
}
/**
* Return the field as a widget
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the field as a widget
*/
@Override
public Widget getInputFieldWidget() {
return this.getWidget();
}
/**
* Set the message panel to visible and sets an error message
* on it. Also applies the error style.
*
* @param message String to display as message
*
* @author Alec Erasmus <[email protected]>
* @since 26 November 2012
*/
public void displayValidationError(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageErrorCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Set the message panel to visible and sets an info message
* on it. Also applies the info style.
*
* @param message String to display as message
*
* @author Alec Erasmus <[email protected]>
* @since 26 November 2012
*/
public void displayInfoMessage(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageInfoCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Clear the message panel of messages and sets it's
* visibility to false.
*
* @author Ashwin Arendse <[email protected]>
* @since 12 November 2012
*/
public void clearMessage() {
messagePanel.setVisible(false);
messageCell.setText("");
messagePanel.clear();
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public Class<T> getReturnType() {
return null;
}
/**
* Function force implementation due to class inheritance
*/
@Deprecated
@Override
public boolean isRequired() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setRequired(boolean required) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setReadOnly(boolean readOnly) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public boolean isReadOnly() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T value, boolean fireEvents) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T object, T value) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public T getValue(T object) {
return null;
}
}
| true | true | public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setViewState();
}
});
}
| public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
clearMessage();
setViewState();
}
});
}
|
diff --git a/com.dubture.symfony.ui/src/com/dubture/symfony/ui/wizards/project/SymfonyProjectCreationWizard.java b/com.dubture.symfony.ui/src/com/dubture/symfony/ui/wizards/project/SymfonyProjectCreationWizard.java
index 2af1fd59..67cfd390 100644
--- a/com.dubture.symfony.ui/src/com/dubture/symfony/ui/wizards/project/SymfonyProjectCreationWizard.java
+++ b/com.dubture.symfony.ui/src/com/dubture/symfony/ui/wizards/project/SymfonyProjectCreationWizard.java
@@ -1,107 +1,108 @@
/*******************************************************************************
* This file is part of the Symfony eclipse plugin.
*
* (c) Robert Gruendler <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
******************************************************************************/
package com.dubture.symfony.ui.wizards.project;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.dltk.ui.DLTKUIPlugin;
import org.eclipse.php.internal.ui.PHPUIMessages;
import org.eclipse.php.internal.ui.wizards.PHPProjectCreationWizard;
import com.dubture.symfony.core.builder.SymfonyNature;
import com.dubture.symfony.core.log.Logger;
import com.dubture.symfony.ui.SymfonyPluginImages;
import com.dubture.symfony.ui.wizards.ISymfonyProjectWizardExtension;
/**
* Simple extension of the {@link PHPProjectCreationWizard} to add the symfony nature after the project is
* created.
*
* @author Robert Gruendler <[email protected]>
*/
@SuppressWarnings("restriction")
public class SymfonyProjectCreationWizard extends PHPProjectCreationWizard {
public SymfonyProjectCreationWizard() {
setDefaultPageImageDescriptor(SymfonyPluginImages.DESC_WIZBAN_ADD_SYMFONY_FILE);
setDialogSettings(DLTKUIPlugin.getDefault().getDialogSettings());
setWindowTitle("New Symfony Project");
}
public void addPages() {
fFirstPage = new SymfonyProjectWizardFirstPage();
// First page
fFirstPage.setTitle("New Symfony project");
fFirstPage.setDescription("Create a Symfony project in the workspace or in an external location.");
addPage(fFirstPage);
// Second page (Include Path)
fSecondPage = new SymfonyProjectWizardSecondPage(fFirstPage);
fSecondPage.setTitle(PHPUIMessages.PHPProjectCreationWizard_Page2Title);
fSecondPage.setDescription(PHPUIMessages.PHPProjectCreationWizard_Page2Description);
addPage(fSecondPage);
// Third page (Include Path)
fThirdPage = new SymfonyProjectWizardThirdPage(fFirstPage);
fThirdPage.setTitle(PHPUIMessages.PHPProjectCreationWizard_Page3Title);
fThirdPage.setDescription(PHPUIMessages.PHPProjectCreationWizard_Page3Description);
addPage(fThirdPage);
fLastPage = fSecondPage;
}
@Override
public boolean performFinish() {
boolean res = super.performFinish();
try {
IProject project = fFirstPage.getProjectHandle();
SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;
List<String> extensionNatures = new ArrayList<String>();
// let extensions handle the project first
for (ISymfonyProjectWizardExtension e : firstPage.getExtensions()) {
ISymfonyProjectWizardExtension extension = (ISymfonyProjectWizardExtension) e;
String nature = extension.getNature();
if (nature != null && extension.isActivated())
extensionNatures.add(nature);
}
IProjectDescription description = project.getDescription();
String[] natures = description.getNatureIds();
- String[] newNatures = new String[natures.length + extensionNatures.size() + 1];
- System.arraycopy(natures, 0, newNatures, 1, natures.length);
+ String[] newNatures = new String[natures.length + extensionNatures.size() + 2];
+ System.arraycopy(natures, 0, newNatures, 2, natures.length);
newNatures[0] = SymfonyNature.NATURE_ID;
+ newNatures[1] = "com.dubture.composer.core.composerNature";
for (int i = 0; i < extensionNatures.size(); i++) {
- newNatures[natures.length + 1 + i] = extensionNatures.get(i);
+ newNatures[natures.length + 2 + i] = extensionNatures.get(i);
}
description.setNatureIds(newNatures);
project.setDescription(description, null);
} catch (CoreException exception) {
Logger.logException(exception);
}
return res;
}
}
| false | true | public boolean performFinish() {
boolean res = super.performFinish();
try {
IProject project = fFirstPage.getProjectHandle();
SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;
List<String> extensionNatures = new ArrayList<String>();
// let extensions handle the project first
for (ISymfonyProjectWizardExtension e : firstPage.getExtensions()) {
ISymfonyProjectWizardExtension extension = (ISymfonyProjectWizardExtension) e;
String nature = extension.getNature();
if (nature != null && extension.isActivated())
extensionNatures.add(nature);
}
IProjectDescription description = project.getDescription();
String[] natures = description.getNatureIds();
String[] newNatures = new String[natures.length + extensionNatures.size() + 1];
System.arraycopy(natures, 0, newNatures, 1, natures.length);
newNatures[0] = SymfonyNature.NATURE_ID;
for (int i = 0; i < extensionNatures.size(); i++) {
newNatures[natures.length + 1 + i] = extensionNatures.get(i);
}
description.setNatureIds(newNatures);
project.setDescription(description, null);
} catch (CoreException exception) {
Logger.logException(exception);
}
return res;
}
| public boolean performFinish() {
boolean res = super.performFinish();
try {
IProject project = fFirstPage.getProjectHandle();
SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;
List<String> extensionNatures = new ArrayList<String>();
// let extensions handle the project first
for (ISymfonyProjectWizardExtension e : firstPage.getExtensions()) {
ISymfonyProjectWizardExtension extension = (ISymfonyProjectWizardExtension) e;
String nature = extension.getNature();
if (nature != null && extension.isActivated())
extensionNatures.add(nature);
}
IProjectDescription description = project.getDescription();
String[] natures = description.getNatureIds();
String[] newNatures = new String[natures.length + extensionNatures.size() + 2];
System.arraycopy(natures, 0, newNatures, 2, natures.length);
newNatures[0] = SymfonyNature.NATURE_ID;
newNatures[1] = "com.dubture.composer.core.composerNature";
for (int i = 0; i < extensionNatures.size(); i++) {
newNatures[natures.length + 2 + i] = extensionNatures.get(i);
}
description.setNatureIds(newNatures);
project.setDescription(description, null);
} catch (CoreException exception) {
Logger.logException(exception);
}
return res;
}
|
diff --git a/src/View/ShoppingView.java b/src/View/ShoppingView.java
index acb994f..2c925ae 100644
--- a/src/View/ShoppingView.java
+++ b/src/View/ShoppingView.java
@@ -1,762 +1,763 @@
package View;
//import java.awt.Image;
import java.awt.Font;
import java.awt.font.*;
import java.util.ArrayList;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.UnicodeFont;
import Model.MainHub;
import Model.Player;
import Model.PlayerModel;
import Model.Items.Item;
import Model.Items.ItemHunterArmor;
import Model.Items.ItemHunterBow;
import Model.Items.ItemHunterCap;
import Model.Items.ItemWarriorArmor;
import Model.Items.ItemWarriorHelmet;
import Model.Items.ItemWarriorSword;
import Model.Items.ItemWizardHat;
import Model.Items.ItemWizardRobe;
import Model.Items.ItemWizardStaff;
import Model.Skills.Skill;
import Model.Skills.Hunter.SkillArrow;
import Model.Skills.Hunter.SkillArrowFlurry;
import Model.Skills.Hunter.SkillBarrelRoll;
import Model.Skills.Hunter.SkillCripplingTrap;
import Model.Skills.Hunter.SkillFlamingArrow;
import Model.Skills.Hunter.SkillGuidedArrow;
import Model.Skills.Hunter.SkillLifestealingArrows;
import Model.Skills.Hunter.SkillPassiveDodge;
import Model.Skills.Hunter.SkillSprint;
import Model.Skills.Hunter.SkillStealth;
import Model.Skills.Warrior.SkillAdrenaline;
import Model.Skills.Warrior.SkillFirstAid;
import Model.Skills.Warrior.SkillGrapplingHook;
import Model.Skills.Warrior.SkillImprovedArmor;
import Model.Skills.Warrior.SkillIncreasedMovement;
import Model.Skills.Warrior.SkillLeapAttack;
import Model.Skills.Warrior.SkillShieldStance;
import Model.Skills.Warrior.SkillSlash;
import Model.Skills.Warrior.SkillThrowingAxe;
import Model.Skills.Warrior.SkillWarstomp;
import Model.Skills.Wizard.SkillAbsorb;
import Model.Skills.Wizard.SkillBlizzard;
import Model.Skills.Wizard.SkillFireball;
import Model.Skills.Wizard.SkillFirestorm;
import Model.Skills.Wizard.SkillFlamewave;
import Model.Skills.Wizard.SkillIceblock;
import Model.Skills.Wizard.SkillIroncloak;
import Model.Skills.Wizard.SkillTeleport;
import Model.Skills.Wizard.SkillUnstableMagic;
import Model.Skills.Wizard.SkillWandattack;
import Model.Timers.RegularTimer;
public class ShoppingView extends BasicGameState {
Player activePlayer;
ArrayList<Skill> ownedSkillList;
ArrayList<Item> ownedItemList;
String buyString = " ";
String classtype="Hunter";
Image skillDescBg;
String costText;
private String itemName;
boolean showingSkillDescription = false;
boolean showingItemDescription = false;
private int xPos = 0;
private int yPos = 0;
Image buyUpgradeButton;
private Image playerGold;
private String playerGoldText;
private boolean buyOneTime = false;
private int grabbedFromChosenIndex = -1;
private boolean dragMouse = false;
private boolean allIsReady = false;
private RegularTimer startCheckTimer = new RegularTimer(5000, 0);
private boolean canResetTimer = true;
private int chosenSkillsXStart = 17;
private int chosenSkillsYStart = 280;
private String mouse = "No input yet";
Image menuTab;
Skill[] chosenSkills = new Skill[5];
Skill[] allSkills = new Skill[9];
Skill basicSkill;
Skill selectedSkill = null;
Item[] allItems = new Item[3];
Item selectedItem = null;
Image playButton;
Image optionsButton;
Image goButton;
Image classPortrait;
String skillText;
Image background;
Image skillsText;
Image shopText;
Image lobbyPlayer;
Image lobbyPlayerReady;
Image [] LevelofSkills = new Image [9];
Player [] LobbyPlayers;
Image headSlotItem;
Image chestSlotItem;
Image weaponSlotItem;
//UnicodeFont uFont;
//Font font;
public ShoppingView (int state){
}
public int getID(){
return 4;
}
@Override
public void init(GameContainer gc, StateBasedGame sbg)throws SlickException {
//font = new Font("Calibri", Font.PLAIN, 20);
//uFont = new UnicodeFont(font, font.getSize(), font.isBold(), font.isItalic());
LevelofSkills [0] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [1] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [2] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [3] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [4] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [5] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [6] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [7] = new Image ("res/skillIcons/Level 0.png");
LevelofSkills [8] = new Image ("res/skillIcons/Level 0.png");
headSlotItem = new Image ("res/Items/Headwear Empty.png");
chestSlotItem = new Image ("res/Items/Armor Empty.png");
weaponSlotItem = new Image ("res/Items/Weapon Empty.png");
lobbyPlayer = new Image ("res/miscImages/LobbyPlayer.png");
lobbyPlayerReady = new Image ("res/miscImages/LobbyPlayerReady.png");
/*
for (int i=0;i<MainHub.getController().getPlayerControllers().length;i++){
LobbyPlayers[i] = new Image ("res/miscImages/LobbyPlayer.png");
}*/
background = new Image("res/miscImages/ShoppingviewBackground.png");
skillsText = new Image("res/miscImages/skillsText.png");
shopText = new Image("res/miscImages/shopText.png");
playerGold = new Image("res/miscImages/PlayerGold.png");
if(MainHub.getController().getPlayer(MainHub.getController().getActivePlayerIndex()) != null)
playerGoldText = "" + MainHub.getController().getPlayers()[MainHub.getController().getActivePlayerIndex()].getGold();
skillText = " ";
costText = " ";
skillDescBg = new Image("res/miscImages/initEmptyPic.png");
canResetTimer = true;
playButton = new Image("res/buttons/playButtons.png");
buyUpgradeButton = new Image("res/miscImages/initEmptyPic.png");
optionsButton = new Image ("res/buttons/options.png");
goButton = new Image ("res/buttons/Ready.png");
}
public void enter(GameContainer container, StateBasedGame game) throws SlickException {
// TODO Auto-generated method stub
super.enter(container, game);
//Waiting for the connection to give the correct playerIndex
int connectionCheck=0;
while(MainHub.getController().getPlayer(MainHub.getController().getActivePlayerIndex()) == null){
System.out.println(connectionCheck);
connectionCheck++;
if(connectionCheck >= 100000){
container.exit();
}
}
activePlayer = MainHub.getController().getPlayer(MainHub.getController().getActivePlayerIndex());
activePlayer.setReady(false);
activePlayer.setHasClickedStartGame(false);
updateSkillLists();
ownedItemList = activePlayer.getOwnedItems();
classPortrait = activePlayer.getPortraitImage();
LobbyPlayers = MainHub.getController().getPlayers();
switch(MainHub.getController().getPlayers()[MainHub.getController().getActivePlayerIndex()].getType()){
case "Wizard":
//Init wizard basic, offensive, defensive and mobility skillists
basicSkill = new SkillWandattack();
allSkills[0] = new SkillFireball();
allSkills[1] = new SkillIroncloak();
allSkills[2] = new SkillUnstableMagic();
allSkills[3] = new SkillFirestorm();
allSkills[4] = new SkillAbsorb();
allSkills[5] = new SkillBlizzard();
allSkills[6] = new SkillFlamewave();
allSkills[7] = new SkillIceblock();
allSkills[8] = new SkillTeleport();
allItems[0] = new ItemWizardHat();
allItems[1] = new ItemWizardRobe();
allItems[2] = new ItemWizardStaff();
break;
case "Hunter":
//Init Hunter basic, offensive, defensive and mobility skillists
basicSkill = new SkillArrow();
allSkills[0] = new SkillFlamingArrow();
allSkills[1] = new SkillPassiveDodge();
allSkills[2] = new SkillSprint();
allSkills[3] = new SkillGuidedArrow();
allSkills[4] = new SkillLifestealingArrows();
allSkills[5] = new SkillCripplingTrap();
allSkills[6] = new SkillArrowFlurry();
allSkills[7] = new SkillStealth();
allSkills[8] = new SkillBarrelRoll();
allItems[0] = new ItemHunterCap();
allItems[1] = new ItemHunterArmor();
allItems[2] = new ItemHunterBow();
break;
case "Warrior":
//Init warrior basic, offensive, defensive and mobility skillists
basicSkill = new SkillSlash();
allSkills[0] = new SkillThrowingAxe();
allSkills[1] = new SkillImprovedArmor();
allSkills[2] = new SkillIncreasedMovement();
allSkills[3] = new SkillWarstomp();
allSkills[4] = new SkillShieldStance();
allSkills[5] = new SkillGrapplingHook();
allSkills[6] = new SkillAdrenaline();
allSkills[7] = new SkillFirstAid();
allSkills[8] = new SkillLeapAttack();
allItems[0] = new ItemWarriorHelmet();
allItems[1] = new ItemWarriorArmor();
allItems[2] = new ItemWarriorSword();
break;
}
activePlayer.setIndex(MainHub.getController().getActivePlayerIndex());
MainHub.getController().addPlayer(activePlayer, MainHub.getController().getActivePlayerIndex());
MainHub.getController().getSocketClient().changePlayer(activePlayer);
activePlayer.setMode("lobby");
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)throws SlickException {
//g.setFont(uFont);
g.drawImage(background, 0, 0);
g.drawImage(playButton, 1120, 670);
g.drawImage(optionsButton,980,670);
g.setColor(Color.white);
if (showingSkillDescription||showingItemDescription){
g.drawImage(skillDescBg, 485, 460);
g.drawImage(buyUpgradeButton, 710, 610);
if (showingItemDescription){
g.drawImage(selectedItem.getImage(), 490, 490);
g.drawString(costText, 490, 625);
g.drawString(skillText, 580, 490);
g.drawString(itemName, 490, 470);
}else{
g.drawImage(selectedSkill.getSkillBarImage(), 490, 470);
g.drawString(costText, 490, 625);
g.drawString(skillText, 560, 475);
}
}
/*
if(selectedSkill != null)
g.drawImage(selectedSkill.getSkillBarImage(), 490, 470);
*/
g.drawString(mouse, 900, 10);
g.drawImage(classPortrait, 70, 30);
g.drawImage(playerGold,70,185);
g.drawString(""+activePlayer.getGold(), 140, 198);
g.drawString(activePlayer.getName() + "\nHP: "+activePlayer.getHP() + "\nArmor: " + (int)(activePlayer.getArmor()*100)
+ "%\nKills: " + activePlayer.getKills() , 80 + classPortrait.getWidth(), 20 + classPortrait.getHeight()/2);
for(int j=0; j<chosenSkills.length; j++){
g.drawString("" + (j+1), chosenSkillsXStart+30 + 69*j, chosenSkillsYStart-25);
if(chosenSkills[j] != null)
g.drawImage(chosenSkills[j].getSkillBarImage(), chosenSkillsXStart + 69*j, chosenSkillsYStart);
}
// Draw out the itemslots
g.drawImage(headSlotItem,365,10 );
g.drawImage(chestSlotItem,365,100 );
g.drawImage(weaponSlotItem,365,190);
//Draws out owned items
if(ownedItemList.size()!=0){
for (int i=0;i<ownedItemList.size();i++){
switch (ownedItemList.get(i).getItemSlot()){
case "Headwear" :
g.drawImage(ownedItemList.get(i).getImage(),365,10);
break;
case "Armor":
g.drawImage(ownedItemList.get(i).getImage(),365,100);
break;
case "Weapon":
g.drawImage(ownedItemList.get(i).getImage(),365,190);
break;
}
}
}
// Draws out players in lobby
for (int i=0; i<LobbyPlayers.length;i++){
if (LobbyPlayers[i] != null){
g.drawString(MainHub.getController().getPlayer(i).getName(), 910, 120+40*i);
g.drawString(MainHub.getController().getPlayer(i).getKills() + "/" + MainHub.getController().getPlayer(i).getDeaths(), 1075, 120+40*i);
g.drawImage(lobbyPlayer,897,400+60*i);
// System.out.println(LobbyPlayers[i].getName() + " " + LobbyPlayers[i].isReady());
if (LobbyPlayers[i].isReady()){
g.drawImage(lobbyPlayerReady,897,400+60*i);
}
g.drawImage(MainHub.getController().getPlayer(i).getPortraitImageMini(),920,405+60*i);
g.drawString(MainHub.getController().getPlayer(i).getName(), 980, 420+60*i);
}
}
//Offensive skills
g.drawImage((findOwnedSkill(allSkills[0].getName())) != null ? allSkills[0].getRegularSkillBarImage() : allSkills[0].getDisabledSkillBarImage(), 60, 440);
g.drawImage(LevelofSkills[0],114,494);
g.drawImage((findOwnedSkill(allSkills[3].getName())) != null ? allSkills[3].getRegularSkillBarImage() : allSkills[3].getDisabledSkillBarImage(), 60, 515);
g.drawImage(LevelofSkills[3],114,569);
g.drawImage((findOwnedSkill(allSkills[6].getName())) != null ? allSkills[6].getRegularSkillBarImage() : allSkills[6].getDisabledSkillBarImage(), 60, 590);
g.drawImage(LevelofSkills[6],114,644);
//Defensive skills
g.drawImage((findOwnedSkill(allSkills[1].getName())) != null ? allSkills[1].getRegularSkillBarImage() : allSkills[1].getDisabledSkillBarImage(), 200, 440);
g.drawImage(LevelofSkills[1],254,494);
g.drawImage((findOwnedSkill(allSkills[4].getName())) != null ? allSkills[4].getRegularSkillBarImage() : allSkills[4].getDisabledSkillBarImage(), 200, 515);
g.drawImage(LevelofSkills[4],254,569);
g.drawImage((findOwnedSkill(allSkills[7].getName())) != null ? allSkills[7].getRegularSkillBarImage() : allSkills[7].getDisabledSkillBarImage(), 200, 590);
g.drawImage(LevelofSkills[7],254,644);
//Mobility skills
g.drawImage((findOwnedSkill(allSkills[2].getName())) != null ? allSkills[2].getRegularSkillBarImage() : allSkills[2].getDisabledSkillBarImage(), 335, 440);
g.drawImage(LevelofSkills[2],389,494);
g.drawImage((findOwnedSkill(allSkills[5].getName())) != null ? allSkills[5].getRegularSkillBarImage() : allSkills[5].getDisabledSkillBarImage(), 335, 515);
g.drawImage(LevelofSkills[5],389,569);
g.drawImage((findOwnedSkill(allSkills[8].getName())) != null ? allSkills[8].getRegularSkillBarImage() : allSkills[8].getDisabledSkillBarImage(), 335, 590);
g.drawImage(LevelofSkills[8],389,644);
g.drawString(buyString, 500, 675);
if(dragMouse){
g.drawImage(selectedSkill.getSkillBarImage(), xPos, yPos);
}
//Draw out the items
for (int i=0;i<allItems.length;i++){
g.drawImage(allItems[i].getImage(),475,80+145*i);
}
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
xPos = Mouse.getX();
yPos = 720 - Mouse.getY();
activePlayer.setGold(5000);
for(int i=0;i<9;i++){
if (findOwnedSkill(allSkills[i].getName()) != null){
switch (allSkills[i].getCurrentLvl()){
case 1:
LevelofSkills [i] = new Image ("res/skillIcons/Level 1.png");
break;
case 2:
LevelofSkills [i] = new Image ("res/skillIcons/Level 2.png");
break;
case 3:
LevelofSkills [i] = new Image ("res/skillIcons/Level 3.png");
break;
case 4:
LevelofSkills [i] = new Image ("res/skillIcons/Level 4.png");
break;
}
}
}
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
Input input = gc.getInput();
buyOneTime = true;
if(showingSkillDescription||showingItemDescription){
skillDescBg = new Image("res/miscImages/skillDescBg.png");
if((710<xPos && xPos<830) && (600<yPos && yPos<645)){
buyUpgradeButton = new Image("res/buttons/buyOver.png");
if(input.isMousePressed(0) && buyOneTime){
buyOneTime = false;
if(showingSkillDescription){
if(activePlayer.getGold()>=selectedSkill.getCost()){
buySkill(selectedSkill);
}
}else{
if(activePlayer.getGold()>=selectedItem.getCost()){
buyItem(selectedItem);
}
}
}
}else{
buyUpgradeButton = new Image("res/buttons/buy.png");
}
}
if((1120<xPos && xPos<1240) && (670<yPos && yPos<715)){
if (!activePlayer.isReady()){
playButton = new Image("res/buttons/ReadyOver.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButtonOver.png");
}else {
playButton = new Image ("res/buttons/OptionsOver.png");
}
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
if( activePlayer.isReady()&& activePlayer != LobbyPlayers[0]){
playButton = new Image ("res/buttons/Ready.png");
activePlayer.setReady(false);
}else{
playButton = new Image ("res/buttons/Options.png");
if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
if(activePlayer.isReady()){
activePlayer.setHasClickedStartGame(true);
+ startCheckTimer.resetTimer();
}
}
activePlayer.setReady(true);
}
}
}else if(!activePlayer.isReady()){
playButton = new Image("res/buttons/Ready.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
}else{
playButton = new Image ("res/buttons/Options.png");
}
allIsReady = true;
for(int i=0; i<LobbyPlayers.length; i++){
if(LobbyPlayers[i] != null && !LobbyPlayers[i].isReady()){
allIsReady = false;
}
}
System.out.println(startCheckTimer.checkTimer());
if(LobbyPlayers[0].hasClickedStartGame() && canResetTimer){
canResetTimer = false;
startCheckTimer.resetTimer();
}
if(allIsReady&&LobbyPlayers[0].hasClickedStartGame() && startCheckTimer.checkTimer() == startCheckTimer.getInterval()){
pressedReadyOrGo(sbg);
}
if((980<xPos && xPos<1100) && (670<yPos && yPos<715)){
optionsButton = new Image("res/buttons/OptionsOver.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
optionsButton = new Image("res/buttons/Options.png");
sbg.enterState(5);
}
}else{
optionsButton = new Image("res/buttons/Options.png");
}
//Checking if mouse is pressed down
if(input.isMousePressed(0) && !dragMouse){
int chosenIndex;
System.out.println("Tomas");
int xAllIndex = -1;
int yAllIndex = -1;
int xItemIndex = -1;
int yItemIndex = -1;
int totalIndex = -1;
if(475<=xPos && xPos<=555){
xItemIndex = 1;
}/*else if(565<=xPos && xPos<=645){
xItemIndex = 2;
}else if(655<=xPos && xPos<=735){
xItemIndex = 3;
}If we want to add more Items */
if(yPos >= 80 && yPos <= 160){
yItemIndex = 0;
}else if(yPos >= 225 && yPos <= 305){
yItemIndex = 1;
}else if(yPos >= 370 && yPos <= 450){
yItemIndex = 2;
}
if(60<=xPos && xPos<=124){
xAllIndex = 0;
}else if(200<=xPos && xPos<=264){
xAllIndex = 1;
}else if(335<=xPos && xPos<=399){
xAllIndex = 2;
}
if(yPos >= 440 && yPos <= 504){
yAllIndex = 0;
}else if(yPos >= 515 && yPos <= 579){
yAllIndex = 1;
}else if(yPos >= 590 && yPos <= 654){
yAllIndex = 2;
}
if(xAllIndex != -1 && yAllIndex != -1){
totalIndex = xAllIndex + 3*yAllIndex;
}else if (xItemIndex != -1 && yItemIndex != -1){
totalIndex = xItemIndex * yItemIndex; /* + xItemIndex; Stays if we want to add more Items */
setSelectedItem(allItems[totalIndex]);
}
if(totalIndex >= 0 && xAllIndex != -1 && yAllIndex != -1){
Skill newChosenSkill = findOwnedSkill(allSkills[totalIndex].getName());
if(newChosenSkill != null){
setSelectedSkill(newChosenSkill);
if (!allSkills[totalIndex].isPassive()){
dragMouse=true;
grabbedFromChosenIndex = -1;
}
}else{
setSelectedSkill(allSkills[totalIndex]);
dragMouse=false;
}
}else if((chosenIndex = getChosenSkillIndex()) > 0){
if(chosenSkills[chosenIndex] != null){
setSelectedSkill(chosenSkills[chosenIndex]);
dragMouse = true;
grabbedFromChosenIndex = chosenIndex;
}
}
}
//Checking if mouse is released
if(dragMouse && !input.isMouseButtonDown(0)){
int xIndex = getChosenSkillIndex();
if(xIndex == 0){
buyString = "You can not change that skill";
}else if(xIndex >= 1){
boolean alreadyInChosenSkills = false;
for(int i=0; i<chosenSkills.length; i++){
if(chosenSkills[i] != null && chosenSkills[i].getName() == selectedSkill.getName())
alreadyInChosenSkills = true;
}
if(alreadyInChosenSkills){
if(grabbedFromChosenIndex != -1){
Skill tempSkill = chosenSkills[xIndex];
activePlayer.setSkill(selectedSkill, xIndex);
activePlayer.setSkill(tempSkill, grabbedFromChosenIndex);
}else{
buyString = "Already got that skill in your skillbar";
}
}else{
activePlayer.setSkill(selectedSkill, xIndex);
updateSkillLists();
}
}else{
if(grabbedFromChosenIndex != -1){
activePlayer.setSkill(null, grabbedFromChosenIndex);
}
}
grabbedFromChosenIndex = -1;
dragMouse = false;
}
}
/**
* Returns the index in chosen skills that the mouse is above
* @return the index of chosen skills and -1 if mouse is not over
*/
private int getChosenSkillIndex(){
if(xPos >= chosenSkillsXStart && xPos <= 5*69+chosenSkillsXStart && yPos >= chosenSkillsYStart && yPos <= chosenSkillsYStart+64){
int xRange = xPos - chosenSkillsXStart;
int xIndex = -1;
while(xRange > 0){
xIndex++;
xRange -= 69;
}
return xIndex;
}
return -1;
}
private void updateSkillLists(){
chosenSkills = activePlayer.getSkillList();
ownedSkillList = activePlayer.getOwnedSkills();
}
private void buyItem(Item item){
boolean alreadyOwnItem = false;
for (int i=0; i<ownedItemList.size();i++){
if(ownedItemList.get(i).getName()==item.getName()){
buyString = "Already own Item";
alreadyOwnItem = true;
break;
}
}
if(!alreadyOwnItem){
buyString = "Succesfully bought the item for " + item.getCost() + "!";
activePlayer.addGold(-item.getCost());
activePlayer.addItemOwned(item);
activePlayer.addPassiveItem(item);
}
}
private void buySkill(Skill skill){
boolean alreadyOwnSkill = false;
for(int i=0; i<ownedSkillList.size(); i++){
if(ownedSkillList.get(i).getName() == skill.getName()){
buyString = "Already own skill";
alreadyOwnSkill = true;
break;
}
}
if(!alreadyOwnSkill){
buyString = "Succesfully bought a skill for " + skill.getCost() + "!";
activePlayer.addGold(-skill.getCost());
activePlayer.addSkillAsOwned(skill);
if(skill.isPassive()){
activePlayer.addPassiveSkill(skill);
}
}else{
Skill ownedSkill = findOwnedSkill(skill.getName());
if(ownedSkill.getCurrentLvl() < 4){
buyString = "Succesfully upgraded a skill for " + skill.getCost() + "!";
activePlayer.addGold(-skill.getCost());
if(skill.isPassive()){
activePlayer.removePassiveSkill(ownedSkill);
ownedSkill.upgradeSkill();
activePlayer.addPassiveSkill(ownedSkill);
}else{
ownedSkill.upgradeSkill();
}
}else{
buyString = "Skill already max level!";
}
}
updateSkillLists();
updateSkillInformation();
}
private Skill findOwnedSkill(String skillName){
for(int i=0; i<ownedSkillList.size(); i++){
if(ownedSkillList.get(i).getName() == skillName){
return ownedSkillList.get(i);
}
}
return null;
}
private void setSelectedSkill(Skill skill){
skillText = "Level " + skill.getCurrentLvl() + " " + skill.getDescription();
costText = "Cost : " + skill.getCost();
selectedSkill = skill;
showingItemDescription = false;
showingSkillDescription = true;
}
private void setSelectedItem(Item item){
System.out.println("kom in");
itemName = item.getName();
skillText = item.getDescription() ;
costText ="Cost : " + item.getCost();
selectedItem = item;
showingItemDescription = true;
showingSkillDescription =false;
}
private void updateSkillInformation(){
setSelectedSkill(selectedSkill);
}
private void pressedReadyOrGo(StateBasedGame sbg){
if(MainHub.getController().isMulti()){
activePlayer.setMode("arena");
sbg.enterState(1);
}else{
sbg.enterState(1);
}
}
}
| true | true | public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
xPos = Mouse.getX();
yPos = 720 - Mouse.getY();
activePlayer.setGold(5000);
for(int i=0;i<9;i++){
if (findOwnedSkill(allSkills[i].getName()) != null){
switch (allSkills[i].getCurrentLvl()){
case 1:
LevelofSkills [i] = new Image ("res/skillIcons/Level 1.png");
break;
case 2:
LevelofSkills [i] = new Image ("res/skillIcons/Level 2.png");
break;
case 3:
LevelofSkills [i] = new Image ("res/skillIcons/Level 3.png");
break;
case 4:
LevelofSkills [i] = new Image ("res/skillIcons/Level 4.png");
break;
}
}
}
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
Input input = gc.getInput();
buyOneTime = true;
if(showingSkillDescription||showingItemDescription){
skillDescBg = new Image("res/miscImages/skillDescBg.png");
if((710<xPos && xPos<830) && (600<yPos && yPos<645)){
buyUpgradeButton = new Image("res/buttons/buyOver.png");
if(input.isMousePressed(0) && buyOneTime){
buyOneTime = false;
if(showingSkillDescription){
if(activePlayer.getGold()>=selectedSkill.getCost()){
buySkill(selectedSkill);
}
}else{
if(activePlayer.getGold()>=selectedItem.getCost()){
buyItem(selectedItem);
}
}
}
}else{
buyUpgradeButton = new Image("res/buttons/buy.png");
}
}
if((1120<xPos && xPos<1240) && (670<yPos && yPos<715)){
if (!activePlayer.isReady()){
playButton = new Image("res/buttons/ReadyOver.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButtonOver.png");
}else {
playButton = new Image ("res/buttons/OptionsOver.png");
}
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
if( activePlayer.isReady()&& activePlayer != LobbyPlayers[0]){
playButton = new Image ("res/buttons/Ready.png");
activePlayer.setReady(false);
}else{
playButton = new Image ("res/buttons/Options.png");
if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
if(activePlayer.isReady()){
activePlayer.setHasClickedStartGame(true);
}
}
activePlayer.setReady(true);
}
}
}else if(!activePlayer.isReady()){
playButton = new Image("res/buttons/Ready.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
}else{
playButton = new Image ("res/buttons/Options.png");
}
allIsReady = true;
for(int i=0; i<LobbyPlayers.length; i++){
if(LobbyPlayers[i] != null && !LobbyPlayers[i].isReady()){
allIsReady = false;
}
}
System.out.println(startCheckTimer.checkTimer());
if(LobbyPlayers[0].hasClickedStartGame() && canResetTimer){
canResetTimer = false;
startCheckTimer.resetTimer();
}
if(allIsReady&&LobbyPlayers[0].hasClickedStartGame() && startCheckTimer.checkTimer() == startCheckTimer.getInterval()){
pressedReadyOrGo(sbg);
}
if((980<xPos && xPos<1100) && (670<yPos && yPos<715)){
optionsButton = new Image("res/buttons/OptionsOver.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
optionsButton = new Image("res/buttons/Options.png");
sbg.enterState(5);
}
}else{
optionsButton = new Image("res/buttons/Options.png");
}
//Checking if mouse is pressed down
if(input.isMousePressed(0) && !dragMouse){
int chosenIndex;
System.out.println("Tomas");
int xAllIndex = -1;
int yAllIndex = -1;
int xItemIndex = -1;
int yItemIndex = -1;
int totalIndex = -1;
if(475<=xPos && xPos<=555){
xItemIndex = 1;
}/*else if(565<=xPos && xPos<=645){
xItemIndex = 2;
}else if(655<=xPos && xPos<=735){
xItemIndex = 3;
}If we want to add more Items */
if(yPos >= 80 && yPos <= 160){
yItemIndex = 0;
}else if(yPos >= 225 && yPos <= 305){
yItemIndex = 1;
}else if(yPos >= 370 && yPos <= 450){
yItemIndex = 2;
}
if(60<=xPos && xPos<=124){
xAllIndex = 0;
}else if(200<=xPos && xPos<=264){
xAllIndex = 1;
}else if(335<=xPos && xPos<=399){
xAllIndex = 2;
}
if(yPos >= 440 && yPos <= 504){
yAllIndex = 0;
}else if(yPos >= 515 && yPos <= 579){
yAllIndex = 1;
}else if(yPos >= 590 && yPos <= 654){
yAllIndex = 2;
}
if(xAllIndex != -1 && yAllIndex != -1){
totalIndex = xAllIndex + 3*yAllIndex;
}else if (xItemIndex != -1 && yItemIndex != -1){
totalIndex = xItemIndex * yItemIndex; /* + xItemIndex; Stays if we want to add more Items */
setSelectedItem(allItems[totalIndex]);
}
if(totalIndex >= 0 && xAllIndex != -1 && yAllIndex != -1){
Skill newChosenSkill = findOwnedSkill(allSkills[totalIndex].getName());
if(newChosenSkill != null){
setSelectedSkill(newChosenSkill);
if (!allSkills[totalIndex].isPassive()){
dragMouse=true;
grabbedFromChosenIndex = -1;
}
}else{
setSelectedSkill(allSkills[totalIndex]);
dragMouse=false;
}
}else if((chosenIndex = getChosenSkillIndex()) > 0){
if(chosenSkills[chosenIndex] != null){
setSelectedSkill(chosenSkills[chosenIndex]);
dragMouse = true;
grabbedFromChosenIndex = chosenIndex;
}
}
}
//Checking if mouse is released
if(dragMouse && !input.isMouseButtonDown(0)){
int xIndex = getChosenSkillIndex();
if(xIndex == 0){
buyString = "You can not change that skill";
}else if(xIndex >= 1){
boolean alreadyInChosenSkills = false;
for(int i=0; i<chosenSkills.length; i++){
if(chosenSkills[i] != null && chosenSkills[i].getName() == selectedSkill.getName())
alreadyInChosenSkills = true;
}
if(alreadyInChosenSkills){
if(grabbedFromChosenIndex != -1){
Skill tempSkill = chosenSkills[xIndex];
activePlayer.setSkill(selectedSkill, xIndex);
activePlayer.setSkill(tempSkill, grabbedFromChosenIndex);
}else{
buyString = "Already got that skill in your skillbar";
}
}else{
activePlayer.setSkill(selectedSkill, xIndex);
updateSkillLists();
}
}else{
if(grabbedFromChosenIndex != -1){
activePlayer.setSkill(null, grabbedFromChosenIndex);
}
}
grabbedFromChosenIndex = -1;
dragMouse = false;
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
xPos = Mouse.getX();
yPos = 720 - Mouse.getY();
activePlayer.setGold(5000);
for(int i=0;i<9;i++){
if (findOwnedSkill(allSkills[i].getName()) != null){
switch (allSkills[i].getCurrentLvl()){
case 1:
LevelofSkills [i] = new Image ("res/skillIcons/Level 1.png");
break;
case 2:
LevelofSkills [i] = new Image ("res/skillIcons/Level 2.png");
break;
case 3:
LevelofSkills [i] = new Image ("res/skillIcons/Level 3.png");
break;
case 4:
LevelofSkills [i] = new Image ("res/skillIcons/Level 4.png");
break;
}
}
}
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
Input input = gc.getInput();
buyOneTime = true;
if(showingSkillDescription||showingItemDescription){
skillDescBg = new Image("res/miscImages/skillDescBg.png");
if((710<xPos && xPos<830) && (600<yPos && yPos<645)){
buyUpgradeButton = new Image("res/buttons/buyOver.png");
if(input.isMousePressed(0) && buyOneTime){
buyOneTime = false;
if(showingSkillDescription){
if(activePlayer.getGold()>=selectedSkill.getCost()){
buySkill(selectedSkill);
}
}else{
if(activePlayer.getGold()>=selectedItem.getCost()){
buyItem(selectedItem);
}
}
}
}else{
buyUpgradeButton = new Image("res/buttons/buy.png");
}
}
if((1120<xPos && xPos<1240) && (670<yPos && yPos<715)){
if (!activePlayer.isReady()){
playButton = new Image("res/buttons/ReadyOver.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButtonOver.png");
}else {
playButton = new Image ("res/buttons/OptionsOver.png");
}
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
if( activePlayer.isReady()&& activePlayer != LobbyPlayers[0]){
playButton = new Image ("res/buttons/Ready.png");
activePlayer.setReady(false);
}else{
playButton = new Image ("res/buttons/Options.png");
if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
if(activePlayer.isReady()){
activePlayer.setHasClickedStartGame(true);
startCheckTimer.resetTimer();
}
}
activePlayer.setReady(true);
}
}
}else if(!activePlayer.isReady()){
playButton = new Image("res/buttons/Ready.png");
}else if (activePlayer == LobbyPlayers[0]){
playButton = new Image("res/buttons/GoButton.png");
}else{
playButton = new Image ("res/buttons/Options.png");
}
allIsReady = true;
for(int i=0; i<LobbyPlayers.length; i++){
if(LobbyPlayers[i] != null && !LobbyPlayers[i].isReady()){
allIsReady = false;
}
}
System.out.println(startCheckTimer.checkTimer());
if(LobbyPlayers[0].hasClickedStartGame() && canResetTimer){
canResetTimer = false;
startCheckTimer.resetTimer();
}
if(allIsReady&&LobbyPlayers[0].hasClickedStartGame() && startCheckTimer.checkTimer() == startCheckTimer.getInterval()){
pressedReadyOrGo(sbg);
}
if((980<xPos && xPos<1100) && (670<yPos && yPos<715)){
optionsButton = new Image("res/buttons/OptionsOver.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
optionsButton = new Image("res/buttons/Options.png");
sbg.enterState(5);
}
}else{
optionsButton = new Image("res/buttons/Options.png");
}
//Checking if mouse is pressed down
if(input.isMousePressed(0) && !dragMouse){
int chosenIndex;
System.out.println("Tomas");
int xAllIndex = -1;
int yAllIndex = -1;
int xItemIndex = -1;
int yItemIndex = -1;
int totalIndex = -1;
if(475<=xPos && xPos<=555){
xItemIndex = 1;
}/*else if(565<=xPos && xPos<=645){
xItemIndex = 2;
}else if(655<=xPos && xPos<=735){
xItemIndex = 3;
}If we want to add more Items */
if(yPos >= 80 && yPos <= 160){
yItemIndex = 0;
}else if(yPos >= 225 && yPos <= 305){
yItemIndex = 1;
}else if(yPos >= 370 && yPos <= 450){
yItemIndex = 2;
}
if(60<=xPos && xPos<=124){
xAllIndex = 0;
}else if(200<=xPos && xPos<=264){
xAllIndex = 1;
}else if(335<=xPos && xPos<=399){
xAllIndex = 2;
}
if(yPos >= 440 && yPos <= 504){
yAllIndex = 0;
}else if(yPos >= 515 && yPos <= 579){
yAllIndex = 1;
}else if(yPos >= 590 && yPos <= 654){
yAllIndex = 2;
}
if(xAllIndex != -1 && yAllIndex != -1){
totalIndex = xAllIndex + 3*yAllIndex;
}else if (xItemIndex != -1 && yItemIndex != -1){
totalIndex = xItemIndex * yItemIndex; /* + xItemIndex; Stays if we want to add more Items */
setSelectedItem(allItems[totalIndex]);
}
if(totalIndex >= 0 && xAllIndex != -1 && yAllIndex != -1){
Skill newChosenSkill = findOwnedSkill(allSkills[totalIndex].getName());
if(newChosenSkill != null){
setSelectedSkill(newChosenSkill);
if (!allSkills[totalIndex].isPassive()){
dragMouse=true;
grabbedFromChosenIndex = -1;
}
}else{
setSelectedSkill(allSkills[totalIndex]);
dragMouse=false;
}
}else if((chosenIndex = getChosenSkillIndex()) > 0){
if(chosenSkills[chosenIndex] != null){
setSelectedSkill(chosenSkills[chosenIndex]);
dragMouse = true;
grabbedFromChosenIndex = chosenIndex;
}
}
}
//Checking if mouse is released
if(dragMouse && !input.isMouseButtonDown(0)){
int xIndex = getChosenSkillIndex();
if(xIndex == 0){
buyString = "You can not change that skill";
}else if(xIndex >= 1){
boolean alreadyInChosenSkills = false;
for(int i=0; i<chosenSkills.length; i++){
if(chosenSkills[i] != null && chosenSkills[i].getName() == selectedSkill.getName())
alreadyInChosenSkills = true;
}
if(alreadyInChosenSkills){
if(grabbedFromChosenIndex != -1){
Skill tempSkill = chosenSkills[xIndex];
activePlayer.setSkill(selectedSkill, xIndex);
activePlayer.setSkill(tempSkill, grabbedFromChosenIndex);
}else{
buyString = "Already got that skill in your skillbar";
}
}else{
activePlayer.setSkill(selectedSkill, xIndex);
updateSkillLists();
}
}else{
if(grabbedFromChosenIndex != -1){
activePlayer.setSkill(null, grabbedFromChosenIndex);
}
}
grabbedFromChosenIndex = -1;
dragMouse = false;
}
}
|
diff --git a/src/org/protege/editor/owl/ui/explanation/io/IntroductoryPanel.java b/src/org/protege/editor/owl/ui/explanation/io/IntroductoryPanel.java
index c819f78c..f4e151ee 100644
--- a/src/org/protege/editor/owl/ui/explanation/io/IntroductoryPanel.java
+++ b/src/org/protege/editor/owl/ui/explanation/io/IntroductoryPanel.java
@@ -1,91 +1,92 @@
package org.protege.editor.owl.ui.explanation.io;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.Set;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLDocument;
import org.apache.log4j.Logger;
import org.protege.editor.core.ui.util.ComponentFactory;
import org.protege.editor.owl.OWLEditorKit;
public class IntroductoryPanel extends JPanel {
private static final long serialVersionUID = 2168617534333064174L;
public static final Logger LOGGER = Logger.getLogger(IntroductoryPanel.class);
private InconsistentOntologyPlugin selectedPlugin;
public IntroductoryPanel(OWLEditorKit owlEditorKit, InconsistentOntologyPlugin lastSelectedPlugin) throws IOException {
setLayout(new BorderLayout());
add(createCenterPanel(owlEditorKit, lastSelectedPlugin));
}
private JPanel createCenterPanel(OWLEditorKit owlEditorKit, InconsistentOntologyPlugin lastSelectedPlugin) throws IOException {
JPanel center = new JPanel();
center.setLayout(new BoxLayout(center, BoxLayout.PAGE_AXIS));
JTextPane tp = new JTextPane();
+ tp.setEditable(false);
URL help = IntroductoryPanel.class.getResource("/InconsistentOntologyHelp.html");
tp.setPage(help);
Font font = UIManager.getFont("TextArea.font");
if (font != null) {
String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) tp.getDocument()).getStyleSheet().addRule(bodyRule);
}
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(tp);
scrollPane.setPreferredSize(new Dimension(480, 300));
center.add(scrollPane);
InconsistentOntologyPluginLoader loader= new InconsistentOntologyPluginLoader(owlEditorKit);
Set<InconsistentOntologyPlugin> plugins = loader.getPlugins();
if (plugins.size() > 1) {
Box optBox = new Box(BoxLayout.Y_AXIS);
optBox.setAlignmentX(0.0f);
optBox.setBorder(ComponentFactory.createTitledBorder("Explanation Plugins"));
ButtonGroup group = new ButtonGroup();
boolean selectedOne = false;
for (final InconsistentOntologyPlugin plugin : plugins) {
JRadioButton button = new JRadioButton(plugin.getName());
if (!selectedOne) {
button.setSelected(true);
selectedOne = true;
selectedPlugin = plugin;
}
if (lastSelectedPlugin != null && plugin.getName().equals(lastSelectedPlugin.getName())) {
button.setSelected(true);
selectedPlugin = plugin;
}
group.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedPlugin = plugin;
}
});
optBox.add(button);
}
center.add(optBox);
}
else {
selectedPlugin = plugins.iterator().next();
}
return center;
}
public InconsistentOntologyPlugin getSelectedPlugin() {
return selectedPlugin;
}
}
| true | true | private JPanel createCenterPanel(OWLEditorKit owlEditorKit, InconsistentOntologyPlugin lastSelectedPlugin) throws IOException {
JPanel center = new JPanel();
center.setLayout(new BoxLayout(center, BoxLayout.PAGE_AXIS));
JTextPane tp = new JTextPane();
URL help = IntroductoryPanel.class.getResource("/InconsistentOntologyHelp.html");
tp.setPage(help);
Font font = UIManager.getFont("TextArea.font");
if (font != null) {
String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) tp.getDocument()).getStyleSheet().addRule(bodyRule);
}
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(tp);
scrollPane.setPreferredSize(new Dimension(480, 300));
center.add(scrollPane);
InconsistentOntologyPluginLoader loader= new InconsistentOntologyPluginLoader(owlEditorKit);
Set<InconsistentOntologyPlugin> plugins = loader.getPlugins();
if (plugins.size() > 1) {
Box optBox = new Box(BoxLayout.Y_AXIS);
optBox.setAlignmentX(0.0f);
optBox.setBorder(ComponentFactory.createTitledBorder("Explanation Plugins"));
ButtonGroup group = new ButtonGroup();
boolean selectedOne = false;
for (final InconsistentOntologyPlugin plugin : plugins) {
JRadioButton button = new JRadioButton(plugin.getName());
if (!selectedOne) {
button.setSelected(true);
selectedOne = true;
selectedPlugin = plugin;
}
if (lastSelectedPlugin != null && plugin.getName().equals(lastSelectedPlugin.getName())) {
button.setSelected(true);
selectedPlugin = plugin;
}
group.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedPlugin = plugin;
}
});
optBox.add(button);
}
center.add(optBox);
}
else {
selectedPlugin = plugins.iterator().next();
}
return center;
}
| private JPanel createCenterPanel(OWLEditorKit owlEditorKit, InconsistentOntologyPlugin lastSelectedPlugin) throws IOException {
JPanel center = new JPanel();
center.setLayout(new BoxLayout(center, BoxLayout.PAGE_AXIS));
JTextPane tp = new JTextPane();
tp.setEditable(false);
URL help = IntroductoryPanel.class.getResource("/InconsistentOntologyHelp.html");
tp.setPage(help);
Font font = UIManager.getFont("TextArea.font");
if (font != null) {
String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) tp.getDocument()).getStyleSheet().addRule(bodyRule);
}
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(tp);
scrollPane.setPreferredSize(new Dimension(480, 300));
center.add(scrollPane);
InconsistentOntologyPluginLoader loader= new InconsistentOntologyPluginLoader(owlEditorKit);
Set<InconsistentOntologyPlugin> plugins = loader.getPlugins();
if (plugins.size() > 1) {
Box optBox = new Box(BoxLayout.Y_AXIS);
optBox.setAlignmentX(0.0f);
optBox.setBorder(ComponentFactory.createTitledBorder("Explanation Plugins"));
ButtonGroup group = new ButtonGroup();
boolean selectedOne = false;
for (final InconsistentOntologyPlugin plugin : plugins) {
JRadioButton button = new JRadioButton(plugin.getName());
if (!selectedOne) {
button.setSelected(true);
selectedOne = true;
selectedPlugin = plugin;
}
if (lastSelectedPlugin != null && plugin.getName().equals(lastSelectedPlugin.getName())) {
button.setSelected(true);
selectedPlugin = plugin;
}
group.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedPlugin = plugin;
}
});
optBox.add(button);
}
center.add(optBox);
}
else {
selectedPlugin = plugins.iterator().next();
}
return center;
}
|
diff --git a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoMarkerUtils.java b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoMarkerUtils.java
index 93ce6a80..8a57ae5b 100644
--- a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoMarkerUtils.java
+++ b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoMarkerUtils.java
@@ -1,260 +1,263 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.internal.ide.ui.builders;
import java.util.List;
import org.eclipse.acceleo.ide.ui.resources.AcceleoProject;
import org.eclipse.acceleo.internal.ide.ui.AcceleoUIMessages;
import org.eclipse.acceleo.parser.AcceleoParserInfo;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.osgi.service.resolver.BundleDescription;
import org.eclipse.osgi.service.resolver.ExportPackageDescription;
import org.eclipse.pde.core.plugin.IPluginModelBase;
import org.eclipse.pde.core.plugin.PluginRegistry;
/**
* Acceleo Marker Utils.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
*/
public final class AcceleoMarkerUtils {
/**
* Acceleo Problem marker ID.
*/
public static final String PROBLEM_MARKER_ID = "org.eclipse.acceleo.ide.ui.problem"; //$NON-NLS-1$
/**
* Acceleo Warning marker ID.
*/
public static final String WARNING_MARKER_ID = "org.eclipse.acceleo.ide.ui.warning"; //$NON-NLS-1$
/**
* Acceleo Info marker ID.
*/
public static final String INFO_MARKER_ID = "org.eclipse.acceleo.ide.ui.info"; //$NON-NLS-1$
/**
* Acceleo Override marker ID.
*/
public static final String OVERRIDE_MARKER_ID = "org.eclipse.acceleo.ide.ui.override"; //$NON-NLS-1$
/**
* The ID of the marker of a task, those marker will appear in the Tasks view.
*/
public static final String TASK_MARKER_ID = "org.eclipse.core.resources.taskmarker"; //$NON-NLS-1$
/**
* The constructor.
*/
private AcceleoMarkerUtils() {
// prevent instantiation
}
/**
* Creates a marker on the given file.
*
* @param markerId
* The ID of the marker
* @param file
* File on which to create a marker.
* @param line
* is the line of the problem
* @param posBegin
* is the beginning position of the data
* @param posEnd
* is the ending position of the data
* @param message
* Message of the data, it is the message displayed when you hover on the marker.
* @throws CoreException
* This will be thrown if we couldn't set marker attributes.
*/
public static void createMarkerOnFile(String markerId, IFile file, int line, int posBegin, int posEnd,
String message) throws CoreException {
IMarker marker = createMarker(markerId, file, message);
int priority = determinePriority(markerId, message);
if (marker != null) {
marker.setAttribute(IMarker.PRIORITY, priority);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
marker.setAttribute(IMarker.LINE_NUMBER, line);
marker.setAttribute(IMarker.CHAR_START, posBegin);
marker.setAttribute(IMarker.CHAR_END, posEnd);
marker.setAttribute(IMarker.MESSAGE, message);
} else {
return;
}
if (AcceleoMarkerUtils.PROBLEM_MARKER_ID.equals(markerId)) {
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
} else if (AcceleoMarkerUtils.INFO_MARKER_ID.equals(markerId)) {
if (message.startsWith(AcceleoParserInfo.TEMPLATE_OVERRIDE)) {
// Info markers that start with the template override message appears as a green arrow
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
marker.setAttribute(IMarker.MESSAGE, message.substring(AcceleoParserInfo.TEMPLATE_OVERRIDE
.length()));
} else if (message.startsWith(AcceleoParserInfo.TODO_COMMENT)) {
// Info markers that start with the todo comment appears as todo tasks
marker.setAttribute(IMarker.USER_EDITABLE, false);
marker.setAttribute(IMarker.MESSAGE, message.substring(AcceleoParserInfo.TODO_COMMENT
.length()));
} else if (message.startsWith(AcceleoParserInfo.FIXME_COMMENT)) {
// Info markers that start with the fixme comment appears as fixme tasks
marker.setAttribute(IMarker.USER_EDITABLE, false);
marker.setAttribute(IMarker.MESSAGE, message.substring(AcceleoParserInfo.FIXME_COMMENT
.length()));
} else if (message.startsWith(AcceleoParserInfo.SERVICE_INVOCATION)) {
computeAccessibleService(file, message, marker);
}
}
}
/**
* Computes if the java service described in the message is accessible from the given file.
*
* @param file
* The file
* @param message
* The message describing the service
* @param marker
* The marker to use if the service is not accessible
* @throws JavaModelException
* In case of problem during the search of the service class.
* @throws CoreException
* In case of problem during the search of the service class.
*/
private static void computeAccessibleService(IFile file, String message, IMarker marker)
throws JavaModelException, CoreException {
boolean exported = false;
boolean found = false;
String projectName = ""; //$NON-NLS-1$
IProject project = file.getProject();
AcceleoProject acceleoProject = new AcceleoProject(project);
List<IProject> recursivelyAccessibleProjects = acceleoProject.getRecursivelyAccessibleProjects();
for (IProject iProject : recursivelyAccessibleProjects) {
if (iProject.isAccessible() && iProject.hasNature(JavaCore.NATURE_ID)) {
JavaProject javaProject = new JavaProject();
javaProject.setProject(iProject);
IType type = null;
IPackageFragment[] packageFragments = javaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
IType[] types = iCompilationUnit.getTypes();
for (IType iType : types) {
if (iType.getFullyQualifiedName().equals(
message.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()))) {
type = iType;
}
}
}
}
}
+ BundleDescription bundleDescription = null;
if (type != null && PluginRegistry.findModel(iProject) != null) {
found = true;
projectName = iProject.getName();
IPluginModelBase plugin = PluginRegistry.findModel(iProject);
- BundleDescription bundleDescription = plugin.getBundleDescription();
+ bundleDescription = plugin.getBundleDescription();
+ }
+ if (type != null && PluginRegistry.findModel(iProject) != null && bundleDescription != null) {
ExportPackageDescription[] exportPackages = bundleDescription.getExportPackages();
for (ExportPackageDescription exportPackageDescription : exportPackages) {
if (exportPackageDescription.getName().equals(
type.getPackageFragment().getElementName())) {
exported = true;
}
}
}
}
}
if (found && !exported) {
marker.setAttribute(IMarker.MESSAGE, AcceleoUIMessages.getString(
"AcceleoMarkerUtils.JavaServiceClassNotExported", message //$NON-NLS-1$
.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()), projectName));
} else {
marker.delete();
}
}
/**
* Creates the marker instance and associates it with the given file.
*
* @param markerId
* ID of the marker that's to be created.
* @param file
* File on which to create a marker.
* @param message
* Message of the data, it is the message displayed when you hover on the marker.
* @return The created marker.
* @throws CoreException
* This will be thrown if we couldn't set marker attributes.
*/
private static IMarker createMarker(String markerId, IFile file, String message) throws CoreException {
IMarker marker = null;
if (AcceleoMarkerUtils.PROBLEM_MARKER_ID.equals(markerId)
|| AcceleoMarkerUtils.WARNING_MARKER_ID.equals(markerId)) {
marker = file.createMarker(markerId);
} else if (AcceleoMarkerUtils.INFO_MARKER_ID.equals(markerId)) {
/*
* For 'info' markers we've positionned a tag at the beginning of the displayed message, we'll
* check these to create the different markers.
*/
if (message.startsWith(AcceleoParserInfo.TEMPLATE_OVERRIDE)) {
// Info markers that start with the template override message appears as a green arrow
marker = file.createMarker(AcceleoMarkerUtils.OVERRIDE_MARKER_ID);
} else if (message.startsWith(AcceleoParserInfo.TODO_COMMENT)) {
// Info markers that start with the todo comment appears as todo tasks
marker = file.createMarker(TASK_MARKER_ID);
} else if (message.startsWith(AcceleoParserInfo.FIXME_COMMENT)) {
// Info markers that start with the fixme comment appears as fixme tasks
marker = file.createMarker(TASK_MARKER_ID);
} else {
// otherwise info markers are created as info markers
marker = file.createMarker(AcceleoMarkerUtils.INFO_MARKER_ID);
}
}
return marker;
}
/**
* Some of our markers have different priorities, this will allow us to determine which it should be.
*
* @param markerId
* ID of the marker that's to be created.
* @param message
* Message of the data, it is the message displayed when you hover on the marker.
* @return Priority this particular marker should sport.
*/
private static int determinePriority(String markerId, String message) {
// Only information markers for 'TODO' tasks are not high priority
int priority = IMarker.PRIORITY_HIGH;
if (AcceleoMarkerUtils.INFO_MARKER_ID.equals(markerId)
&& message.startsWith(AcceleoParserInfo.TODO_COMMENT)) {
priority = IMarker.PRIORITY_NORMAL;
}
return priority;
}
}
| false | true | private static void computeAccessibleService(IFile file, String message, IMarker marker)
throws JavaModelException, CoreException {
boolean exported = false;
boolean found = false;
String projectName = ""; //$NON-NLS-1$
IProject project = file.getProject();
AcceleoProject acceleoProject = new AcceleoProject(project);
List<IProject> recursivelyAccessibleProjects = acceleoProject.getRecursivelyAccessibleProjects();
for (IProject iProject : recursivelyAccessibleProjects) {
if (iProject.isAccessible() && iProject.hasNature(JavaCore.NATURE_ID)) {
JavaProject javaProject = new JavaProject();
javaProject.setProject(iProject);
IType type = null;
IPackageFragment[] packageFragments = javaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
IType[] types = iCompilationUnit.getTypes();
for (IType iType : types) {
if (iType.getFullyQualifiedName().equals(
message.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()))) {
type = iType;
}
}
}
}
}
if (type != null && PluginRegistry.findModel(iProject) != null) {
found = true;
projectName = iProject.getName();
IPluginModelBase plugin = PluginRegistry.findModel(iProject);
BundleDescription bundleDescription = plugin.getBundleDescription();
ExportPackageDescription[] exportPackages = bundleDescription.getExportPackages();
for (ExportPackageDescription exportPackageDescription : exportPackages) {
if (exportPackageDescription.getName().equals(
type.getPackageFragment().getElementName())) {
exported = true;
}
}
}
}
}
if (found && !exported) {
marker.setAttribute(IMarker.MESSAGE, AcceleoUIMessages.getString(
"AcceleoMarkerUtils.JavaServiceClassNotExported", message //$NON-NLS-1$
.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()), projectName));
} else {
marker.delete();
}
}
| private static void computeAccessibleService(IFile file, String message, IMarker marker)
throws JavaModelException, CoreException {
boolean exported = false;
boolean found = false;
String projectName = ""; //$NON-NLS-1$
IProject project = file.getProject();
AcceleoProject acceleoProject = new AcceleoProject(project);
List<IProject> recursivelyAccessibleProjects = acceleoProject.getRecursivelyAccessibleProjects();
for (IProject iProject : recursivelyAccessibleProjects) {
if (iProject.isAccessible() && iProject.hasNature(JavaCore.NATURE_ID)) {
JavaProject javaProject = new JavaProject();
javaProject.setProject(iProject);
IType type = null;
IPackageFragment[] packageFragments = javaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
IType[] types = iCompilationUnit.getTypes();
for (IType iType : types) {
if (iType.getFullyQualifiedName().equals(
message.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()))) {
type = iType;
}
}
}
}
}
BundleDescription bundleDescription = null;
if (type != null && PluginRegistry.findModel(iProject) != null) {
found = true;
projectName = iProject.getName();
IPluginModelBase plugin = PluginRegistry.findModel(iProject);
bundleDescription = plugin.getBundleDescription();
}
if (type != null && PluginRegistry.findModel(iProject) != null && bundleDescription != null) {
ExportPackageDescription[] exportPackages = bundleDescription.getExportPackages();
for (ExportPackageDescription exportPackageDescription : exportPackages) {
if (exportPackageDescription.getName().equals(
type.getPackageFragment().getElementName())) {
exported = true;
}
}
}
}
}
if (found && !exported) {
marker.setAttribute(IMarker.MESSAGE, AcceleoUIMessages.getString(
"AcceleoMarkerUtils.JavaServiceClassNotExported", message //$NON-NLS-1$
.substring(AcceleoParserInfo.SERVICE_INVOCATION.length()), projectName));
} else {
marker.delete();
}
}
|
diff --git a/src/edu/jas/ufd/FactorInteger.java b/src/edu/jas/ufd/FactorInteger.java
index 6fbd4db9..d6752a87 100644
--- a/src/edu/jas/ufd/FactorInteger.java
+++ b/src/edu/jas/ufd/FactorInteger.java
@@ -1,976 +1,979 @@
/*
* $Id$
*/
package edu.jas.ufd;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import org.apache.log4j.Logger;
import edu.jas.arith.BigInteger;
import edu.jas.arith.ModIntegerRing;
import edu.jas.arith.ModLongRing;
import edu.jas.arith.Modular;
import edu.jas.arith.ModularRingFactory;
import edu.jas.arith.PrimeList;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.GenPolynomialRing;
import edu.jas.poly.PolyUtil;
import edu.jas.structure.GcdRingElem;
import edu.jas.structure.Power;
import edu.jas.structure.RingElem;
import edu.jas.structure.RingFactory;
import edu.jas.util.KsubSet;
/**
* Integer coefficients factorization algorithms. This class implements
* factorization methods for polynomials over integers.
* @author Heinz Kredel
*/
public class FactorInteger<MOD extends GcdRingElem<MOD> & Modular> extends FactorAbstract<BigInteger> {
private static final Logger logger = Logger.getLogger(FactorInteger.class);
private final boolean debug = true || logger.isDebugEnabled();
/**
* Factorization engine for modular base coefficients.
*/
protected final FactorAbstract<MOD> mfactor;
/**
* Gcd engine for modular base coefficients.
*/
protected final GreatestCommonDivisorAbstract<MOD> mengine;
/**
* No argument constructor.
*/
public FactorInteger() {
this(BigInteger.ONE);
}
/**
* Constructor.
* @param cfac coefficient ring factory.
*/
public FactorInteger(RingFactory<BigInteger> cfac) {
super(cfac);
ModularRingFactory<MOD> mcofac = (ModularRingFactory<MOD>) (Object) new ModLongRing(13, true); // hack
mfactor = FactorFactory.getImplementation(mcofac); //new FactorModular(mcofac);
mengine = GCDFactory.getImplementation(mcofac);
//mengine = GCDFactory.getProxy(mcofac);
}
/**
* GenPolynomial base factorization of a squarefree polynomial.
* @param P squarefree and primitive! GenPolynomial.
* @return [p_1,...,p_k] with P = prod_{i=1, ..., k} p_i.
*/
@SuppressWarnings("unchecked")
@Override
public List<GenPolynomial<BigInteger>> baseFactorsSquarefree(GenPolynomial<BigInteger> P) {
if (P == null) {
throw new IllegalArgumentException(this.getClass().getName() + " P == null");
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>();
if (P.isZERO()) {
return factors;
}
if (P.isONE()) {
factors.add(P);
return factors;
}
GenPolynomialRing<BigInteger> pfac = P.ring;
if (pfac.nvar > 1) {
throw new IllegalArgumentException(this.getClass().getName() + " only for univariate polynomials");
}
if (P.degree(0) <= 1L) {
factors.add(P);
return factors;
}
// compute norm
BigInteger an = P.maxNorm();
BigInteger ac = P.leadingBaseCoefficient();
//compute factor coefficient bounds
ExpVector degv = P.degreeVector();
int degi = (int) P.degree(0);
BigInteger M = an.multiply(PolyUtil.factorBound(degv));
M = M.multiply(ac.abs().multiply(ac.fromInteger(8)));
//System.out.println("M = " + M);
//M = M.multiply(M); // test
//initialize prime list and degree vector
PrimeList primes = new PrimeList(PrimeList.Range.small);
int pn = 30; //primes.size();
ModularRingFactory<MOD> cofac = null;
GenPolynomial<MOD> am = null;
GenPolynomialRing<MOD> mfac = null;
final int TT = 5; // 7
List<GenPolynomial<MOD>>[] modfac = new List[TT];
List<GenPolynomial<BigInteger>>[] intfac = new List[TT];
BigInteger[] plist = new BigInteger[TT];
List<GenPolynomial<MOD>> mlist = null;
List<GenPolynomial<BigInteger>> ilist = null;
int i = 0;
if (debug) {
logger.debug("an = " + an);
logger.debug("ac = " + ac);
logger.debug("M = " + M);
logger.info("degv = " + degv);
}
Iterator<java.math.BigInteger> pit = primes.iterator();
pit.next(); // skip p = 2
pit.next(); // skip p = 3
MOD nf = null;
for (int k = 0; k < TT; k++) {
if (k == TT - 1) { // -2
primes = new PrimeList(PrimeList.Range.medium);
pit = primes.iterator();
}
if (k == TT + 1) { // -1
primes = new PrimeList(PrimeList.Range.large);
pit = primes.iterator();
}
while (pit.hasNext()) {
java.math.BigInteger p = pit.next();
//System.out.println("next run ++++++++++++++++++++++++++++++++++");
if (++i >= pn) {
logger.error("prime list exhausted, pn = " + pn);
throw new ArithmeticException("prime list exhausted");
}
if (ModLongRing.MAX_LONG.compareTo(p) > 0) {
cofac = (ModularRingFactory) new ModLongRing(p, true);
} else {
cofac = (ModularRingFactory) new ModIntegerRing(p, true);
}
logger.info("prime = " + cofac);
nf = cofac.fromInteger(ac.getVal());
if (nf.isZERO()) {
logger.info("unlucky prime (nf) = " + p);
//System.out.println("unlucky prime (nf) = " + p);
continue;
}
// initialize polynomial factory and map polynomial
mfac = new GenPolynomialRing<MOD>(cofac, pfac);
am = PolyUtil.<MOD> fromIntegerCoefficients(mfac, P);
if (!am.degreeVector().equals(degv)) { // allways true
logger.info("unlucky prime (deg) = " + p);
//System.out.println("unlucky prime (deg) = " + p);
continue;
}
GenPolynomial<MOD> ap = PolyUtil.<MOD> baseDeriviative(am);
if (ap.isZERO()) {
logger.info("unlucky prime (a')= " + p);
//System.out.println("unlucky prime (a')= " + p);
continue;
}
GenPolynomial<MOD> g = mengine.baseGcd(am, ap);
if (g.isONE()) {
logger.info("**lucky prime = " + p);
//System.out.println("**lucky prime = " + p);
break;
}
}
// now am is squarefree mod p, make monic and factor mod p
if (!nf.isONE()) {
//System.out.println("nf = " + nf);
am = am.divide(nf); // make monic
}
mlist = mfactor.baseFactorsSquarefree(am);
if (logger.isInfoEnabled()) {
logger.info("modlist = " + mlist);
}
if (mlist.size() <= 1) {
factors.add(P);
return factors;
}
if (!nf.isONE()) {
GenPolynomial<MOD> mp = mfac.getONE(); //mlist.get(0);
//System.out.println("mp = " + mp);
mp = mp.multiply(nf);
//System.out.println("mp = " + mp);
mlist.add(0, mp); // set(0,mp);
}
modfac[k] = mlist;
plist[k] = cofac.getIntegerModul(); // p
}
// search shortest factor list
int min = Integer.MAX_VALUE;
BitSet AD = null;
for (int k = 0; k < TT; k++) {
List<ExpVector> ev = PolyUtil.<MOD> leadingExpVector(modfac[k]);
BitSet D = factorDegrees(ev, degi);
if (AD == null) {
AD = D;
} else {
AD.and(D);
}
int s = modfac[k].size();
logger.info("mod(" + plist[k] + ") #s = " + s + ", D = " + D /*+ ", lt = " + ev*/);
//System.out.println("mod s = " + s);
if (s < min) {
min = s;
mlist = modfac[k];
}
}
logger.info("min = " + min + ", AD = " + AD);
if (mlist.size() <= 1) {
logger.info("mlist.size() = 1");
factors.add(P);
return factors;
}
if (AD.cardinality() <= 2) { // only one possible factor
logger.info("degree set cardinality = " + AD.cardinality());
factors.add(P);
return factors;
}
boolean allLists = false; //true; //false;
if (allLists) {
// try each factor list
for (int k = 0; k < TT; k++) {
mlist = modfac[k];
if (debug) {
logger.info("lifting from " + mlist);
}
if (false && P.leadingBaseCoefficient().isONE()) {
factors = searchFactorsMonic(P, M, mlist, AD); // does now work in all cases
if (factors.size() == 1) {
factors = searchFactorsNonMonic(P, M, mlist, AD);
}
} else {
factors = searchFactorsNonMonic(P, M, mlist, AD);
}
intfac[k] = factors;
}
} else {
// try only shortest factor list
if (debug) {
logger.info("lifting shortest from " + mlist);
}
if (true && P.leadingBaseCoefficient().isONE()) {
long t = System.currentTimeMillis();
try {
mlist = PolyUtil.<MOD> monic(mlist);
factors = searchFactorsMonic(P, M, mlist, AD); // does now work in all cases
t = System.currentTimeMillis() - t;
//System.out.println("monic time = " + t);
if (false && debug) {
t = System.currentTimeMillis();
List<GenPolynomial<BigInteger>> fnm = searchFactorsNonMonic(P, M, mlist, AD);
t = System.currentTimeMillis() - t;
System.out.println("non monic time = " + t);
if (debug) {
if (!factors.equals(fnm)) {
System.out.println("monic factors = " + factors);
System.out.println("non monic factors = " + fnm);
}
}
}
} catch (RuntimeException e) {
t = System.currentTimeMillis();
factors = searchFactorsNonMonic(P, M, mlist, AD);
t = System.currentTimeMillis() - t;
//System.out.println("only non monic time = " + t);
}
} else {
long t = System.currentTimeMillis();
factors = searchFactorsNonMonic(P, M, mlist, AD);
t = System.currentTimeMillis() - t;
//System.out.println("non monic time = " + t);
}
return factors;
}
// search longest factor list
int max = 0;
for (int k = 0; k < TT; k++) {
int s = intfac[k].size();
logger.info("int s = " + s);
//System.out.println("int s = " + s);
if (s > max) {
max = s;
ilist = intfac[k];
}
}
factors = ilist;
return factors;
}
/**
* BitSet for factor degree list.
* @param E exponent vector list.
* @return b_0,...,b_k} a BitSet of possible factor degrees.
*/
public BitSet factorDegrees(List<ExpVector> E, int deg) {
BitSet D = new BitSet(deg + 1);
D.set(0); // constant factor
for (ExpVector e : E) {
int i = (int) e.getVal(0);
BitSet s = new BitSet(deg + 1);
for (int k = 0; k < deg + 1 - i; k++) { // shift by i places
s.set(i + k, D.get(k));
}
//System.out.println("s = " + s);
D.or(s);
//System.out.println("D = " + D);
}
return D;
}
/**
* Sum of all degrees.
* @param L univariate polynomial list.
* @return sum deg(p) for p in L.
*/
public static <C extends RingElem<C>> long degreeSum(List<GenPolynomial<C>> L) {
long s = 0L;
for (GenPolynomial<C> p : L) {
ExpVector e = p.leadingExpVector();
long d = e.getVal(0);
s += d;
}
return s;
}
/**
* Factor search with modular Hensel lifting algorithm. Let p =
* f_i.ring.coFac.modul() i = 0, ..., n-1 and assume C == prod_{0,...,n-1}
* f_i mod p with ggt(f_i,f_j) == 1 mod p for i != j
* @param C GenPolynomial.
* @param M bound on the coefficients of g_i as factors of C.
* @param F = [f_0,...,f_{n-1}] List<GenPolynomial>.
* @param D bit set of possible factor degrees.
* @return [g_0,...,g_{n-1}] = lift(C,F), with C = prod_{0,...,n-1} g_i mod
* p**e. <b>Note:</b> does not work in all cases.
*/
List<GenPolynomial<BigInteger>> searchFactorsMonic(GenPolynomial<BigInteger> C, BigInteger M,
List<GenPolynomial<MOD>> F, BitSet D) {
//System.out.println("*** monic factor combination ***");
if (C == null || C.isZERO() || F == null || F.size() == 0) {
throw new IllegalArgumentException("C must be nonzero and F must be nonempty");
}
GenPolynomialRing<BigInteger> pfac = C.ring;
if (pfac.nvar != 1) { // todo assert
throw new IllegalArgumentException("polynomial ring not univariate");
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>(F.size());
List<GenPolynomial<MOD>> mlist = F;
List<GenPolynomial<MOD>> lift;
//MOD nf = null;
GenPolynomial<MOD> ct = mlist.get(0);
if (ct.isConstant()) {
//nf = ct.leadingBaseCoefficient();
mlist.remove(ct);
//System.out.println("=== nf = " + nf);
if (mlist.size() <= 1) {
factors.add(C);
return factors;
}
} else {
//nf = ct.ring.coFac.getONE();
}
//System.out.println("modlist = " + mlist); // includes not ldcf
ModularRingFactory<MOD> mcfac = (ModularRingFactory<MOD>) ct.ring.coFac;
BigInteger m = mcfac.getIntegerModul();
long k = 1;
BigInteger pi = m;
while (pi.compareTo(M) < 0) {
k++;
pi = pi.multiply(m);
}
logger.info("p^k = " + m + "^" + k);
GenPolynomial<BigInteger> PP = C, P = C;
// lift via Hensel
try {
lift = HenselUtil.<MOD> liftHenselMonic(PP, mlist, k);
//System.out.println("lift = " + lift);
} catch (NoLiftingException e) {
throw new RuntimeException(e);
}
if (logger.isInfoEnabled()) {
logger.info("lifted modlist = " + lift);
}
GenPolynomialRing<MOD> mpfac = lift.get(0).ring;
// combine trial factors
int dl = (lift.size() + 1) / 2;
//System.out.println("dl = " + dl);
GenPolynomial<BigInteger> u = PP;
long deg = (u.degree(0) + 1L) / 2L;
//System.out.println("deg = " + deg);
//BigInteger ldcf = u.leadingBaseCoefficient();
//System.out.println("ldcf = " + ldcf);
for (int j = 1; j <= dl; j++) {
//System.out.println("j = " + j + ", dl = " + dl + ", lift = " + lift);
KsubSet<GenPolynomial<MOD>> ps = new KsubSet<GenPolynomial<MOD>>(lift, j);
for (List<GenPolynomial<MOD>> flist : ps) {
//System.out.println("degreeSum = " + degreeSum(flist));
if (!D.get((int) FactorInteger.<MOD> degreeSum(flist))) {
logger.info("skipped by degree set " + D + ", deg = " + degreeSum(flist));
continue;
}
GenPolynomial<MOD> mtrial = mpfac.getONE();
for (int kk = 0; kk < flist.size(); kk++) {
GenPolynomial<MOD> fk = flist.get(kk);
mtrial = mtrial.multiply(fk);
}
//System.out.println("+flist = " + flist + ", mtrial = " + mtrial);
if (mtrial.degree(0) > deg) { // this test is sometimes wrong
logger.info("degree " + mtrial.degree(0) + " > deg " + deg);
//continue;
}
//System.out.println("+flist = " + flist);
GenPolynomial<BigInteger> trial = PolyUtil.integerFromModularCoefficients(pfac, mtrial);
//System.out.println("+trial = " + trial);
//trial = engine.basePrimitivePart( trial.multiply(ldcf) );
trial = engine.basePrimitivePart(trial);
//System.out.println("pp(trial)= " + trial);
if (PolyUtil.<BigInteger> basePseudoRemainder(u, trial).isZERO()) {
logger.info("successful trial = " + trial);
//System.out.println("trial = " + trial);
//System.out.println("flist = " + flist);
//trial = engine.basePrimitivePart(trial);
//System.out.println("pp(trial)= " + trial);
factors.add(trial);
u = PolyUtil.<BigInteger> basePseudoDivide(u, trial); //u.divide( trial );
//System.out.println("u = " + u);
if (lift.removeAll(flist)) {
logger.info("new lift= " + lift);
dl = (lift.size() + 1) / 2;
//System.out.println("dl = " + dl);
j = 0; // since j++
break;
}
logger.error("error removing flist from lift = " + lift);
}
}
}
if (!u.isONE() && !u.equals(P)) {
logger.info("rest u = " + u);
//System.out.println("rest u = " + u);
factors.add(u);
}
if (factors.size() == 0) {
logger.info("irred u = " + u);
//System.out.println("irred u = " + u);
factors.add(PP);
}
return factors;
}
/**
* Factor search with modular Hensel lifting algorithm. Let p =
* f_i.ring.coFac.modul() i = 0, ..., n-1 and assume C == prod_{0,...,n-1}
* f_i mod p with ggt(f_i,f_j) == 1 mod p for i != j
* @param C GenPolynomial.
* @param M bound on the coefficients of g_i as factors of C.
* @param F = [f_0,...,f_{n-1}] List<GenPolynomial>.
* @param D bit set of possible factor degrees.
* @return [g_0,...,g_{n-1}] = lift(C,F), with C = prod_{0,...,n-1} g_i mod
* p**e.
*/
List<GenPolynomial<BigInteger>> searchFactorsNonMonic(GenPolynomial<BigInteger> C, BigInteger M,
List<GenPolynomial<MOD>> F, BitSet D) {
//System.out.println("*** non monic factor combination ***");
if (C == null || C.isZERO() || F == null || F.size() == 0) {
throw new IllegalArgumentException("C must be nonzero and F must be nonempty");
}
GenPolynomialRing<BigInteger> pfac = C.ring;
if (pfac.nvar != 1) { // todo assert
throw new IllegalArgumentException("polynomial ring not univariate");
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>(F.size());
List<GenPolynomial<MOD>> mlist = F;
MOD nf = null;
GenPolynomial<MOD> ct = mlist.get(0);
if (ct.isConstant()) {
nf = ct.leadingBaseCoefficient();
mlist.remove(ct);
//System.out.println("=== nf = " + nf);
//System.out.println("=== ldcf = " + C.leadingBaseCoefficient());
if (mlist.size() <= 1) {
factors.add(C);
return factors;
}
} else {
nf = ct.ring.coFac.getONE();
}
//System.out.println("modlist = " + mlist); // includes not ldcf
GenPolynomialRing<MOD> mfac = ct.ring;
GenPolynomial<MOD> Pm = PolyUtil.<MOD> fromIntegerCoefficients(mfac, C);
GenPolynomial<BigInteger> PP = C, P = C;
// combine trial factors
int dl = (mlist.size() + 1) / 2;
GenPolynomial<BigInteger> u = PP;
long deg = (u.degree(0) + 1L) / 2L;
GenPolynomial<MOD> um = Pm;
//BigInteger ldcf = u.leadingBaseCoefficient();
//System.out.println("ldcf = " + ldcf);
HenselApprox<MOD> ilist = null;
for (int j = 1; j <= dl; j++) {
//System.out.println("j = " + j + ", dl = " + dl + ", ilist = " + ilist);
KsubSet<GenPolynomial<MOD>> ps = new KsubSet<GenPolynomial<MOD>>(mlist, j);
for (List<GenPolynomial<MOD>> flist : ps) {
//System.out.println("degreeSum = " + degreeSum(flist));
if (!D.get((int) FactorInteger.<MOD> degreeSum(flist))) {
logger.info("skipped by degree set " + D + ", deg = " + degreeSum(flist));
continue;
}
GenPolynomial<MOD> trial = mfac.getONE().multiply(nf);
for (int kk = 0; kk < flist.size(); kk++) {
GenPolynomial<MOD> fk = flist.get(kk);
trial = trial.multiply(fk);
}
if (trial.degree(0) > deg) { // this test is sometimes wrong
logger.info("degree > deg " + deg + ", degree = " + trial.degree(0));
//continue;
}
GenPolynomial<MOD> cofactor = um.divide(trial);
//System.out.println("trial = " + trial);
//System.out.println("cofactor = " + cofactor);
// lift via Hensel
try {
// ilist = HenselUtil.liftHenselQuadraticFac(PP, M, trial, cofactor);
ilist = HenselUtil.<MOD> liftHenselQuadratic(PP, M, trial, cofactor);
//ilist = HenselUtil.<MOD> liftHensel(PP, M, trial, cofactor);
} catch (NoLiftingException e) {
// no liftable factors
if ( /*debug*/logger.isDebugEnabled()) {
logger.info("no liftable factors " + e);
e.printStackTrace();
}
continue;
}
GenPolynomial<BigInteger> itrial = ilist.A;
GenPolynomial<BigInteger> icofactor = ilist.B;
if (logger.isDebugEnabled()) {
logger.info(" modlist = " + trial + ", cofactor " + cofactor);
logger.info("lifted intlist = " + itrial + ", cofactor " + icofactor);
}
//System.out.println("lifted intlist = " + itrial + ", cofactor " + icofactor);
itrial = engine.basePrimitivePart(itrial);
//System.out.println("pp(trial)= " + itrial);
if (PolyUtil.<BigInteger> basePseudoRemainder(u, itrial).isZERO()) {
logger.info("successful trial = " + itrial);
//System.out.println("trial = " + itrial);
//System.out.println("cofactor = " + icofactor);
//System.out.println("flist = " + flist);
//itrial = engine.basePrimitivePart(itrial);
//System.out.println("pp(itrial)= " + itrial);
factors.add(itrial);
//u = PolyUtil.<BigInteger> basePseudoDivide(u, itrial); //u.divide( trial );
u = icofactor;
PP = u; // fixed finally on 2009-05-03
um = cofactor;
//System.out.println("u = " + u);
//System.out.println("um = " + um);
if (mlist.removeAll(flist)) {
logger.info("new mlist= " + mlist);
dl = (mlist.size() + 1) / 2;
j = 0; // since j++
break;
}
logger.error("error removing flist from ilist = " + mlist);
}
}
}
if (!u.isONE() && !u.equals(P)) {
logger.info("rest u = " + u);
//System.out.println("rest u = " + u);
factors.add(u);
}
if (factors.size() == 0) {
logger.info("irred u = " + u);
//System.out.println("irred u = " + u);
factors.add(PP);
}
return factors;
}
/**
* GenPolynomial factorization of a multivariate squarefree polynomial, using Hensel lifting.
* @param P squarefree and primitive! (respectively monic) multivariate GenPolynomial over the integers.
* @return [p_1,...,p_k] with P = prod_{i=1,...,r} p_i.
*/
public List<GenPolynomial<BigInteger>> factorsSquarefreeHensel(GenPolynomial<BigInteger> P) {
if (P == null) {
throw new IllegalArgumentException(this.getClass().getName() + " P != null");
}
GenPolynomialRing<BigInteger> pfac = P.ring;
System.out.println("pfac = " + pfac.toScript());
if (pfac.nvar == 1) {
return baseFactorsSquarefree(P);
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>();
if (P.isZERO()) {
return factors;
}
if (P.degreeVector().totalDeg() <= 1L) {
factors.add(P);
return factors;
}
GenPolynomial<BigInteger> pd = P;
System.out.println("pd = " + pd);
// ldcf(pd)
BigInteger ac = pd.leadingBaseCoefficient();
// factor leading coefficient as polynomial in the lowest variable
GenPolynomialRing<GenPolynomial<BigInteger>> rnfac = pfac.recursive(pfac.nvar-1);
GenPolynomial<GenPolynomial<BigInteger>> pr = PolyUtil.<BigInteger>recursive(rnfac,pd);
GenPolynomial<GenPolynomial<BigInteger>> prr = PolyUtil.<BigInteger>switchVariables(pr);
GenPolynomial<BigInteger> lprr = prr.leadingBaseCoefficient();
System.out.println("prr = " + prr);
System.out.println("lprr = " + lprr);
boolean isMonic = false;
if ( lprr.isConstant() ) {
isMonic = true;
}
SortedMap<GenPolynomial<BigInteger>,Long> lfactors = factors(lprr);
System.out.println("lfactors = " + lfactors);
List<GenPolynomial<BigInteger>> lfacs = new ArrayList<GenPolynomial<BigInteger>>(lfactors.keySet());
System.out.println("lfacs = " + lfacs);
// search evaluation point and evaluate
GenPolynomialRing<BigInteger> cpfac = pfac;
GenPolynomial<BigInteger> pe = pd;
GenPolynomial<BigInteger> pep;
GenPolynomialRing<BigInteger> ccpfac = lprr.ring;
List<GenPolynomial<BigInteger>> ce = lfacs;
List<GenPolynomial<BigInteger>> cep = null;
List<BigInteger> cei = null;
BigInteger pec = null;
BigInteger ped = null;
List<BigInteger> V = null;
long evStart = 0L; //3L * 5L;
boolean notLucky = true;
while ( notLucky ) { // for Wang's test
notLucky = false;
V = new ArrayList<BigInteger>();
cpfac = pfac;
pe = pd;
ccpfac = lprr.ring;
ce = lfacs;
cep = null;
cei = null;
pec = null;
ped = null;
long vi = 0L;
for ( int j = pfac.nvar; j > 1; j-- ) {
// evaluation up to univariate case
long degp = pe.degree(cpfac.nvar-2);
cpfac = cpfac.contract(1);
ccpfac = ccpfac.contract(1);
vi = evStart;//0L; //(long)(pfac.nvar-j); // 1L; 0 not so good for small p
BigInteger Vi;
// search evaluation point
while( true ) {
System.out.println("vi = " + vi);
Vi = new BigInteger(vi);
pep = PolyUtil.<BigInteger> evaluateMain(cpfac,pe,Vi);
System.out.println("pep = " + pep);
// check lucky evaluation point
if (degp == pep.degree(cpfac.nvar-1)) {
System.out.println("deg(pe) = " + degp + ", deg(pep) = " + pep.degree(cpfac.nvar-1));
// check squarefree
if ( sengine.isSquarefree(pep) ) {
System.out.println("squarefeee = " + pep);
break;
}
}
if ( vi > 0L ) {
vi = -vi;
} else {
vi = 1L - vi;
}
}
if ( !isMonic ) {
if ( ccpfac.nvar >= 1 ) {
cep = PolyUtil.<BigInteger> evaluateMain(ccpfac,ce,Vi);
} else {
cei = PolyUtil.<BigInteger> evaluateMain(ccpfac.coFac,ce,Vi);
}
}
V.add(Vi);
pe = pep;
ce = cep;
}
if ( !isMonic ) {
pec = engine.baseContent(pe);
System.out.println("cei = " + cei + ", pec = " + pec);
if ( lfacs.get(0).isConstant() ) {
ped = cei.remove(0);
- lfacs.remove(0);
+ //lfacs.remove(0);
} else {
ped = cei.get(0).getONE();
}
System.out.println("lfacs = " + lfacs + ", cei = " + cei + ", ped = " + ped);
// test Wang's condition
List<BigInteger> dei = new ArrayList<BigInteger>();
dei.add( pec.multiply(ped) );
int i = 1;
for ( BigInteger ci : cei ) {
BigInteger cii = ci;
for ( int ii = i-1; ii >= 0; ii-- ) {
BigInteger r = dei.get(ii) ;
do {
r = cii.gcd(r);
cii = cii.divide(r);
} while ( !r.isONE() );
}
if ( cii.isONE() ) {
System.out.println("condition not met");
notLucky = true;
evStart = vi + 1L;
}
dei.add(cii);
i++;
}
System.out.println("dei = " + dei);
}
} // end notLucky loop
logger.info("evaluation points = " + V);
System.out.println("pe = " + pe);
pe = pe.abs();
pe = engine.basePrimitivePart(pe);
System.out.println("pp(pe) = " + pe);
List<GenPolynomial<BigInteger>> ufactors = baseFactorsSquarefree(pe);
System.out.println("ufactors = " + ufactors + ", of " + pe);
System.out.println("lfacs = " + lfacs);
System.out.println("cei = " + cei);
if (ufactors.size() <= 1) {
factors.add(P);
return factors;
}
// determine leading coefficients for factors
List<GenPolynomial<BigInteger>> lf = new ArrayList<GenPolynomial<BigInteger>>();
GenPolynomial<BigInteger> lpx = lprr.ring.getONE();
for ( GenPolynomial<BigInteger> pp : ufactors) {
lf.add( lprr.ring.getONE() );
}
if ( !isMonic ) {
+ if ( lfacs.get(0).isConstant() ) {
+ GenPolynomial<BigInteger> xx = lfacs.remove(0);
+ }
int i = 0;
for ( GenPolynomial<BigInteger> pp : ufactors) {
BigInteger ppl = pp.leadingBaseCoefficient();
GenPolynomial<BigInteger> lfp = lf.get(i);
int ii = 0;
for ( BigInteger ci : cei ) {
while ( ppl.remainder(ci).isZERO() ) {
ppl = ppl.divide(ci);
lfp = lfp.multiply( lfacs.get(ii) );
}
ii++;
}
lfp = lfp.multiply(ppl);
lf.set(i,lfp);
lpx = lpx.multiply(lfp);
i++;
}
}
logger.info("ldcf factors = " + lf);
if ( !lprr.equals(lpx) ) { // something is wrong
- System.out.println("lpx = " + lpx + ", lprr == lpx: " + lprr.equals(lpx));
+ System.out.println("lprr = " + lprr + ", lpx = " + lpx + ", lprr == lpx: " + lprr.equals(lpx));
throw new RuntimeException("something is wrong");
}
GenPolynomialRing<BigInteger> ufac = pe.ring;
System.out.println("ufac = " + ufac.toScript());
//initialize prime list
PrimeList primes = new PrimeList(PrimeList.Range.medium); // PrimeList.Range.medium);
Iterator<java.math.BigInteger> primeIter = primes.iterator();
int pn = 50; //primes.size();
BigInteger ae = pe.leadingBaseCoefficient();
GenPolynomial<MOD> Pm = null;
ModularRingFactory<MOD> cofac = null;
GenPolynomialRing<MOD> mufac = null;
// search lucky prime
for ( int i = 0; i < 11; i++ ) { // meta loop
//for ( int i = 0; i < 1; i++ ) { // meta loop
java.math.BigInteger p = null; //new java.math.BigInteger("19"); //primes.next();
// 2 small, 5 medium and 4 large size primes
if ( i == 0 ) { // medium size
primes = new PrimeList(PrimeList.Range.medium);
primeIter = primes.iterator();
}
if ( i == 5 ) { // small size
primes = new PrimeList(PrimeList.Range.small);
primeIter = primes.iterator();
p = primeIter.next(); // 2
p = primeIter.next(); // 3
p = primeIter.next(); // 5
p = primeIter.next(); // 7
}
if ( i == 7 ) { // large size
primes = new PrimeList(PrimeList.Range.large);
primeIter = primes.iterator();
}
int pi = 0;
while ( pi < pn && primeIter.hasNext() ) {
p = primeIter.next();
//p = new java.math.BigInteger("19"); // test
logger.info("prime = " + p);
// initialize coefficient factory and map normalization factor and polynomials
ModularRingFactory<MOD> cf = null;
if (ModLongRing.MAX_LONG.compareTo(p) > 0) {
cf = (ModularRingFactory) new ModLongRing(p, true);
} else {
cf = (ModularRingFactory) new ModIntegerRing(p, true);
}
MOD nf = cf.fromInteger(ae.getVal());
if (nf.isZERO()) {
continue;
}
mufac = new GenPolynomialRing<MOD>(cf, ufac);
//System.out.println("mufac = " + mufac.toScript());
Pm = PolyUtil.<MOD> fromIntegerCoefficients(mufac, pe);
System.out.println("Pm = " + Pm);
if ( ! mfactor.isSquarefree(Pm) ) {
continue;
}
cofac = cf;
break;
}
if ( cofac != null ) {
break;
}
} // end meta loop
if ( cofac == null ) { // no lucky prime found
throw new RuntimeException("giving up on Hensel preparation");
}
logger.info("lucky prime = " + cofac.getIntegerModul());
List<GenPolynomial<MOD>> mufactors = PolyUtil.<MOD> fromIntegerCoefficients(mufac, ufactors);
System.out.println("mufactors = " + mufactors);
List<MOD> Vm = new ArrayList<MOD>(V.size());
for ( BigInteger v : V ) {
MOD vm = cofac.fromInteger(v.getVal());
Vm.add(vm);
}
System.out.println("Vm = " + Vm);
// coefficient bound
BigInteger an = pd.maxNorm();
BigInteger mn = an.multiply(ac.abs()).multiply(new BigInteger(2L));
long k = Power.logarithm(cofac.getIntegerModul(),mn) + 1L;
System.out.println("mn = " + mn);
System.out.println("k = " + k);
// Hensel lifting of factors
List<GenPolynomial<MOD>> mlift;
try {
mlift = HenselMultUtil.<MOD> liftHenselFull(pd,mufactors,Vm,k,lf);
logger.info("mlift = " + mlift);
} catch ( NoLiftingException nle ) {
System.out.println("exception : " + nle);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
} catch ( ArithmeticException aex ) {
System.out.println("exception : " + aex);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
}
if ( mlift.size() <= 1 ) { // irreducible mod I, p^k, can this happen?
factors.add(P);
return factors;
}
// combine trial factors
GenPolynomialRing<MOD> mfac = mlift.get(0).ring;
int dl = (mlift.size() + 1) / 2;
GenPolynomial<BigInteger> u = P;
long deg = (u.degree() + 1L) / 2L;
GenPolynomial<MOD> um = PolyUtil.<MOD> fromIntegerCoefficients(mfac, P);
GenPolynomial<BigInteger> ui = pd;
for (int j = 1; j <= dl; j++) {
System.out.println("j = " + j + ", dl = " + dl + ", mlift = " + mlift);
KsubSet<GenPolynomial<MOD>> subs = new KsubSet<GenPolynomial<MOD>>(mlift, j);
for (List<GenPolynomial<MOD>> flist : subs) {
//System.out.println("degreeSum = " + degreeSum(flist));
GenPolynomial<MOD> mtrial = mfac.getONE(); // .multiply(nf); // == 1, since primitive
for (int kk = 0; kk < flist.size(); kk++) {
GenPolynomial<MOD> fk = flist.get(kk);
mtrial = mtrial.multiply(fk);
}
if (mtrial.degree() > deg) { // this test is sometimes wrong
logger.info("degree > deg " + deg + ", degree = " + mtrial.degree());
//continue;
}
GenPolynomial<MOD> cofactor = um.divide(mtrial);
GenPolynomial<BigInteger> trial = PolyUtil.integerFromModularCoefficients(pfac, mtrial);
GenPolynomial<BigInteger> cotrial = PolyUtil.integerFromModularCoefficients(pfac, cofactor);
System.out.println("trial = " + trial); // + ", mtrial = " + mtrial);
//System.out.println("cotrial = " + cotrial + ", cofactor = " + cofactor);
if (trial.multiply(cotrial).equals(ui) ) {
factors.add(trial);
ui = cotrial; //PolyUtil.<BigInteger> basePseudoDivide(ui, trial); //u.divide( trial );
um = cofactor;
//System.out.println("ui = " + ui);
//System.out.println("um = " + um);
if (mlift.removeAll(flist)) {
logger.info("new mlift= " + mlift);
//System.out.println("dl = " + dl);
if ( mlift.size() > 1 ) {
dl = (mlift.size() + 1) / 2;
j = 0; // since j++
break;
} else {
logger.info("last ui = " + ui);
factors.add(ui);
return factors;
}
}
logger.error("error removing flist from mlift = " + mlift);
}
}
}
System.out.println("end combine, factors = " + factors);
if (!ui.isONE() && !ui.equals(pd)) {
logger.info("rest ui = " + ui);
//System.out.println("rest ui = " + ui);
factors.add(ui);
}
if (factors.size() == 0) {
logger.info("irred P = " + P);
factors.add(P);
}
return factors;
}
}
| false | true | public List<GenPolynomial<BigInteger>> factorsSquarefreeHensel(GenPolynomial<BigInteger> P) {
if (P == null) {
throw new IllegalArgumentException(this.getClass().getName() + " P != null");
}
GenPolynomialRing<BigInteger> pfac = P.ring;
System.out.println("pfac = " + pfac.toScript());
if (pfac.nvar == 1) {
return baseFactorsSquarefree(P);
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>();
if (P.isZERO()) {
return factors;
}
if (P.degreeVector().totalDeg() <= 1L) {
factors.add(P);
return factors;
}
GenPolynomial<BigInteger> pd = P;
System.out.println("pd = " + pd);
// ldcf(pd)
BigInteger ac = pd.leadingBaseCoefficient();
// factor leading coefficient as polynomial in the lowest variable
GenPolynomialRing<GenPolynomial<BigInteger>> rnfac = pfac.recursive(pfac.nvar-1);
GenPolynomial<GenPolynomial<BigInteger>> pr = PolyUtil.<BigInteger>recursive(rnfac,pd);
GenPolynomial<GenPolynomial<BigInteger>> prr = PolyUtil.<BigInteger>switchVariables(pr);
GenPolynomial<BigInteger> lprr = prr.leadingBaseCoefficient();
System.out.println("prr = " + prr);
System.out.println("lprr = " + lprr);
boolean isMonic = false;
if ( lprr.isConstant() ) {
isMonic = true;
}
SortedMap<GenPolynomial<BigInteger>,Long> lfactors = factors(lprr);
System.out.println("lfactors = " + lfactors);
List<GenPolynomial<BigInteger>> lfacs = new ArrayList<GenPolynomial<BigInteger>>(lfactors.keySet());
System.out.println("lfacs = " + lfacs);
// search evaluation point and evaluate
GenPolynomialRing<BigInteger> cpfac = pfac;
GenPolynomial<BigInteger> pe = pd;
GenPolynomial<BigInteger> pep;
GenPolynomialRing<BigInteger> ccpfac = lprr.ring;
List<GenPolynomial<BigInteger>> ce = lfacs;
List<GenPolynomial<BigInteger>> cep = null;
List<BigInteger> cei = null;
BigInteger pec = null;
BigInteger ped = null;
List<BigInteger> V = null;
long evStart = 0L; //3L * 5L;
boolean notLucky = true;
while ( notLucky ) { // for Wang's test
notLucky = false;
V = new ArrayList<BigInteger>();
cpfac = pfac;
pe = pd;
ccpfac = lprr.ring;
ce = lfacs;
cep = null;
cei = null;
pec = null;
ped = null;
long vi = 0L;
for ( int j = pfac.nvar; j > 1; j-- ) {
// evaluation up to univariate case
long degp = pe.degree(cpfac.nvar-2);
cpfac = cpfac.contract(1);
ccpfac = ccpfac.contract(1);
vi = evStart;//0L; //(long)(pfac.nvar-j); // 1L; 0 not so good for small p
BigInteger Vi;
// search evaluation point
while( true ) {
System.out.println("vi = " + vi);
Vi = new BigInteger(vi);
pep = PolyUtil.<BigInteger> evaluateMain(cpfac,pe,Vi);
System.out.println("pep = " + pep);
// check lucky evaluation point
if (degp == pep.degree(cpfac.nvar-1)) {
System.out.println("deg(pe) = " + degp + ", deg(pep) = " + pep.degree(cpfac.nvar-1));
// check squarefree
if ( sengine.isSquarefree(pep) ) {
System.out.println("squarefeee = " + pep);
break;
}
}
if ( vi > 0L ) {
vi = -vi;
} else {
vi = 1L - vi;
}
}
if ( !isMonic ) {
if ( ccpfac.nvar >= 1 ) {
cep = PolyUtil.<BigInteger> evaluateMain(ccpfac,ce,Vi);
} else {
cei = PolyUtil.<BigInteger> evaluateMain(ccpfac.coFac,ce,Vi);
}
}
V.add(Vi);
pe = pep;
ce = cep;
}
if ( !isMonic ) {
pec = engine.baseContent(pe);
System.out.println("cei = " + cei + ", pec = " + pec);
if ( lfacs.get(0).isConstant() ) {
ped = cei.remove(0);
lfacs.remove(0);
} else {
ped = cei.get(0).getONE();
}
System.out.println("lfacs = " + lfacs + ", cei = " + cei + ", ped = " + ped);
// test Wang's condition
List<BigInteger> dei = new ArrayList<BigInteger>();
dei.add( pec.multiply(ped) );
int i = 1;
for ( BigInteger ci : cei ) {
BigInteger cii = ci;
for ( int ii = i-1; ii >= 0; ii-- ) {
BigInteger r = dei.get(ii) ;
do {
r = cii.gcd(r);
cii = cii.divide(r);
} while ( !r.isONE() );
}
if ( cii.isONE() ) {
System.out.println("condition not met");
notLucky = true;
evStart = vi + 1L;
}
dei.add(cii);
i++;
}
System.out.println("dei = " + dei);
}
} // end notLucky loop
logger.info("evaluation points = " + V);
System.out.println("pe = " + pe);
pe = pe.abs();
pe = engine.basePrimitivePart(pe);
System.out.println("pp(pe) = " + pe);
List<GenPolynomial<BigInteger>> ufactors = baseFactorsSquarefree(pe);
System.out.println("ufactors = " + ufactors + ", of " + pe);
System.out.println("lfacs = " + lfacs);
System.out.println("cei = " + cei);
if (ufactors.size() <= 1) {
factors.add(P);
return factors;
}
// determine leading coefficients for factors
List<GenPolynomial<BigInteger>> lf = new ArrayList<GenPolynomial<BigInteger>>();
GenPolynomial<BigInteger> lpx = lprr.ring.getONE();
for ( GenPolynomial<BigInteger> pp : ufactors) {
lf.add( lprr.ring.getONE() );
}
if ( !isMonic ) {
int i = 0;
for ( GenPolynomial<BigInteger> pp : ufactors) {
BigInteger ppl = pp.leadingBaseCoefficient();
GenPolynomial<BigInteger> lfp = lf.get(i);
int ii = 0;
for ( BigInteger ci : cei ) {
while ( ppl.remainder(ci).isZERO() ) {
ppl = ppl.divide(ci);
lfp = lfp.multiply( lfacs.get(ii) );
}
ii++;
}
lfp = lfp.multiply(ppl);
lf.set(i,lfp);
lpx = lpx.multiply(lfp);
i++;
}
}
logger.info("ldcf factors = " + lf);
if ( !lprr.equals(lpx) ) { // something is wrong
System.out.println("lpx = " + lpx + ", lprr == lpx: " + lprr.equals(lpx));
throw new RuntimeException("something is wrong");
}
GenPolynomialRing<BigInteger> ufac = pe.ring;
System.out.println("ufac = " + ufac.toScript());
//initialize prime list
PrimeList primes = new PrimeList(PrimeList.Range.medium); // PrimeList.Range.medium);
Iterator<java.math.BigInteger> primeIter = primes.iterator();
int pn = 50; //primes.size();
BigInteger ae = pe.leadingBaseCoefficient();
GenPolynomial<MOD> Pm = null;
ModularRingFactory<MOD> cofac = null;
GenPolynomialRing<MOD> mufac = null;
// search lucky prime
for ( int i = 0; i < 11; i++ ) { // meta loop
//for ( int i = 0; i < 1; i++ ) { // meta loop
java.math.BigInteger p = null; //new java.math.BigInteger("19"); //primes.next();
// 2 small, 5 medium and 4 large size primes
if ( i == 0 ) { // medium size
primes = new PrimeList(PrimeList.Range.medium);
primeIter = primes.iterator();
}
if ( i == 5 ) { // small size
primes = new PrimeList(PrimeList.Range.small);
primeIter = primes.iterator();
p = primeIter.next(); // 2
p = primeIter.next(); // 3
p = primeIter.next(); // 5
p = primeIter.next(); // 7
}
if ( i == 7 ) { // large size
primes = new PrimeList(PrimeList.Range.large);
primeIter = primes.iterator();
}
int pi = 0;
while ( pi < pn && primeIter.hasNext() ) {
p = primeIter.next();
//p = new java.math.BigInteger("19"); // test
logger.info("prime = " + p);
// initialize coefficient factory and map normalization factor and polynomials
ModularRingFactory<MOD> cf = null;
if (ModLongRing.MAX_LONG.compareTo(p) > 0) {
cf = (ModularRingFactory) new ModLongRing(p, true);
} else {
cf = (ModularRingFactory) new ModIntegerRing(p, true);
}
MOD nf = cf.fromInteger(ae.getVal());
if (nf.isZERO()) {
continue;
}
mufac = new GenPolynomialRing<MOD>(cf, ufac);
//System.out.println("mufac = " + mufac.toScript());
Pm = PolyUtil.<MOD> fromIntegerCoefficients(mufac, pe);
System.out.println("Pm = " + Pm);
if ( ! mfactor.isSquarefree(Pm) ) {
continue;
}
cofac = cf;
break;
}
if ( cofac != null ) {
break;
}
} // end meta loop
if ( cofac == null ) { // no lucky prime found
throw new RuntimeException("giving up on Hensel preparation");
}
logger.info("lucky prime = " + cofac.getIntegerModul());
List<GenPolynomial<MOD>> mufactors = PolyUtil.<MOD> fromIntegerCoefficients(mufac, ufactors);
System.out.println("mufactors = " + mufactors);
List<MOD> Vm = new ArrayList<MOD>(V.size());
for ( BigInteger v : V ) {
MOD vm = cofac.fromInteger(v.getVal());
Vm.add(vm);
}
System.out.println("Vm = " + Vm);
// coefficient bound
BigInteger an = pd.maxNorm();
BigInteger mn = an.multiply(ac.abs()).multiply(new BigInteger(2L));
long k = Power.logarithm(cofac.getIntegerModul(),mn) + 1L;
System.out.println("mn = " + mn);
System.out.println("k = " + k);
// Hensel lifting of factors
List<GenPolynomial<MOD>> mlift;
try {
mlift = HenselMultUtil.<MOD> liftHenselFull(pd,mufactors,Vm,k,lf);
logger.info("mlift = " + mlift);
} catch ( NoLiftingException nle ) {
System.out.println("exception : " + nle);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
} catch ( ArithmeticException aex ) {
System.out.println("exception : " + aex);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
}
if ( mlift.size() <= 1 ) { // irreducible mod I, p^k, can this happen?
factors.add(P);
return factors;
}
// combine trial factors
GenPolynomialRing<MOD> mfac = mlift.get(0).ring;
int dl = (mlift.size() + 1) / 2;
GenPolynomial<BigInteger> u = P;
long deg = (u.degree() + 1L) / 2L;
GenPolynomial<MOD> um = PolyUtil.<MOD> fromIntegerCoefficients(mfac, P);
GenPolynomial<BigInteger> ui = pd;
for (int j = 1; j <= dl; j++) {
System.out.println("j = " + j + ", dl = " + dl + ", mlift = " + mlift);
KsubSet<GenPolynomial<MOD>> subs = new KsubSet<GenPolynomial<MOD>>(mlift, j);
for (List<GenPolynomial<MOD>> flist : subs) {
//System.out.println("degreeSum = " + degreeSum(flist));
GenPolynomial<MOD> mtrial = mfac.getONE(); // .multiply(nf); // == 1, since primitive
for (int kk = 0; kk < flist.size(); kk++) {
GenPolynomial<MOD> fk = flist.get(kk);
mtrial = mtrial.multiply(fk);
}
if (mtrial.degree() > deg) { // this test is sometimes wrong
logger.info("degree > deg " + deg + ", degree = " + mtrial.degree());
//continue;
}
GenPolynomial<MOD> cofactor = um.divide(mtrial);
GenPolynomial<BigInteger> trial = PolyUtil.integerFromModularCoefficients(pfac, mtrial);
GenPolynomial<BigInteger> cotrial = PolyUtil.integerFromModularCoefficients(pfac, cofactor);
System.out.println("trial = " + trial); // + ", mtrial = " + mtrial);
//System.out.println("cotrial = " + cotrial + ", cofactor = " + cofactor);
if (trial.multiply(cotrial).equals(ui) ) {
factors.add(trial);
ui = cotrial; //PolyUtil.<BigInteger> basePseudoDivide(ui, trial); //u.divide( trial );
um = cofactor;
//System.out.println("ui = " + ui);
//System.out.println("um = " + um);
if (mlift.removeAll(flist)) {
logger.info("new mlift= " + mlift);
//System.out.println("dl = " + dl);
if ( mlift.size() > 1 ) {
dl = (mlift.size() + 1) / 2;
j = 0; // since j++
break;
} else {
logger.info("last ui = " + ui);
factors.add(ui);
return factors;
}
}
logger.error("error removing flist from mlift = " + mlift);
}
}
}
System.out.println("end combine, factors = " + factors);
if (!ui.isONE() && !ui.equals(pd)) {
logger.info("rest ui = " + ui);
//System.out.println("rest ui = " + ui);
factors.add(ui);
}
if (factors.size() == 0) {
logger.info("irred P = " + P);
factors.add(P);
}
return factors;
}
| public List<GenPolynomial<BigInteger>> factorsSquarefreeHensel(GenPolynomial<BigInteger> P) {
if (P == null) {
throw new IllegalArgumentException(this.getClass().getName() + " P != null");
}
GenPolynomialRing<BigInteger> pfac = P.ring;
System.out.println("pfac = " + pfac.toScript());
if (pfac.nvar == 1) {
return baseFactorsSquarefree(P);
}
List<GenPolynomial<BigInteger>> factors = new ArrayList<GenPolynomial<BigInteger>>();
if (P.isZERO()) {
return factors;
}
if (P.degreeVector().totalDeg() <= 1L) {
factors.add(P);
return factors;
}
GenPolynomial<BigInteger> pd = P;
System.out.println("pd = " + pd);
// ldcf(pd)
BigInteger ac = pd.leadingBaseCoefficient();
// factor leading coefficient as polynomial in the lowest variable
GenPolynomialRing<GenPolynomial<BigInteger>> rnfac = pfac.recursive(pfac.nvar-1);
GenPolynomial<GenPolynomial<BigInteger>> pr = PolyUtil.<BigInteger>recursive(rnfac,pd);
GenPolynomial<GenPolynomial<BigInteger>> prr = PolyUtil.<BigInteger>switchVariables(pr);
GenPolynomial<BigInteger> lprr = prr.leadingBaseCoefficient();
System.out.println("prr = " + prr);
System.out.println("lprr = " + lprr);
boolean isMonic = false;
if ( lprr.isConstant() ) {
isMonic = true;
}
SortedMap<GenPolynomial<BigInteger>,Long> lfactors = factors(lprr);
System.out.println("lfactors = " + lfactors);
List<GenPolynomial<BigInteger>> lfacs = new ArrayList<GenPolynomial<BigInteger>>(lfactors.keySet());
System.out.println("lfacs = " + lfacs);
// search evaluation point and evaluate
GenPolynomialRing<BigInteger> cpfac = pfac;
GenPolynomial<BigInteger> pe = pd;
GenPolynomial<BigInteger> pep;
GenPolynomialRing<BigInteger> ccpfac = lprr.ring;
List<GenPolynomial<BigInteger>> ce = lfacs;
List<GenPolynomial<BigInteger>> cep = null;
List<BigInteger> cei = null;
BigInteger pec = null;
BigInteger ped = null;
List<BigInteger> V = null;
long evStart = 0L; //3L * 5L;
boolean notLucky = true;
while ( notLucky ) { // for Wang's test
notLucky = false;
V = new ArrayList<BigInteger>();
cpfac = pfac;
pe = pd;
ccpfac = lprr.ring;
ce = lfacs;
cep = null;
cei = null;
pec = null;
ped = null;
long vi = 0L;
for ( int j = pfac.nvar; j > 1; j-- ) {
// evaluation up to univariate case
long degp = pe.degree(cpfac.nvar-2);
cpfac = cpfac.contract(1);
ccpfac = ccpfac.contract(1);
vi = evStart;//0L; //(long)(pfac.nvar-j); // 1L; 0 not so good for small p
BigInteger Vi;
// search evaluation point
while( true ) {
System.out.println("vi = " + vi);
Vi = new BigInteger(vi);
pep = PolyUtil.<BigInteger> evaluateMain(cpfac,pe,Vi);
System.out.println("pep = " + pep);
// check lucky evaluation point
if (degp == pep.degree(cpfac.nvar-1)) {
System.out.println("deg(pe) = " + degp + ", deg(pep) = " + pep.degree(cpfac.nvar-1));
// check squarefree
if ( sengine.isSquarefree(pep) ) {
System.out.println("squarefeee = " + pep);
break;
}
}
if ( vi > 0L ) {
vi = -vi;
} else {
vi = 1L - vi;
}
}
if ( !isMonic ) {
if ( ccpfac.nvar >= 1 ) {
cep = PolyUtil.<BigInteger> evaluateMain(ccpfac,ce,Vi);
} else {
cei = PolyUtil.<BigInteger> evaluateMain(ccpfac.coFac,ce,Vi);
}
}
V.add(Vi);
pe = pep;
ce = cep;
}
if ( !isMonic ) {
pec = engine.baseContent(pe);
System.out.println("cei = " + cei + ", pec = " + pec);
if ( lfacs.get(0).isConstant() ) {
ped = cei.remove(0);
//lfacs.remove(0);
} else {
ped = cei.get(0).getONE();
}
System.out.println("lfacs = " + lfacs + ", cei = " + cei + ", ped = " + ped);
// test Wang's condition
List<BigInteger> dei = new ArrayList<BigInteger>();
dei.add( pec.multiply(ped) );
int i = 1;
for ( BigInteger ci : cei ) {
BigInteger cii = ci;
for ( int ii = i-1; ii >= 0; ii-- ) {
BigInteger r = dei.get(ii) ;
do {
r = cii.gcd(r);
cii = cii.divide(r);
} while ( !r.isONE() );
}
if ( cii.isONE() ) {
System.out.println("condition not met");
notLucky = true;
evStart = vi + 1L;
}
dei.add(cii);
i++;
}
System.out.println("dei = " + dei);
}
} // end notLucky loop
logger.info("evaluation points = " + V);
System.out.println("pe = " + pe);
pe = pe.abs();
pe = engine.basePrimitivePart(pe);
System.out.println("pp(pe) = " + pe);
List<GenPolynomial<BigInteger>> ufactors = baseFactorsSquarefree(pe);
System.out.println("ufactors = " + ufactors + ", of " + pe);
System.out.println("lfacs = " + lfacs);
System.out.println("cei = " + cei);
if (ufactors.size() <= 1) {
factors.add(P);
return factors;
}
// determine leading coefficients for factors
List<GenPolynomial<BigInteger>> lf = new ArrayList<GenPolynomial<BigInteger>>();
GenPolynomial<BigInteger> lpx = lprr.ring.getONE();
for ( GenPolynomial<BigInteger> pp : ufactors) {
lf.add( lprr.ring.getONE() );
}
if ( !isMonic ) {
if ( lfacs.get(0).isConstant() ) {
GenPolynomial<BigInteger> xx = lfacs.remove(0);
}
int i = 0;
for ( GenPolynomial<BigInteger> pp : ufactors) {
BigInteger ppl = pp.leadingBaseCoefficient();
GenPolynomial<BigInteger> lfp = lf.get(i);
int ii = 0;
for ( BigInteger ci : cei ) {
while ( ppl.remainder(ci).isZERO() ) {
ppl = ppl.divide(ci);
lfp = lfp.multiply( lfacs.get(ii) );
}
ii++;
}
lfp = lfp.multiply(ppl);
lf.set(i,lfp);
lpx = lpx.multiply(lfp);
i++;
}
}
logger.info("ldcf factors = " + lf);
if ( !lprr.equals(lpx) ) { // something is wrong
System.out.println("lprr = " + lprr + ", lpx = " + lpx + ", lprr == lpx: " + lprr.equals(lpx));
throw new RuntimeException("something is wrong");
}
GenPolynomialRing<BigInteger> ufac = pe.ring;
System.out.println("ufac = " + ufac.toScript());
//initialize prime list
PrimeList primes = new PrimeList(PrimeList.Range.medium); // PrimeList.Range.medium);
Iterator<java.math.BigInteger> primeIter = primes.iterator();
int pn = 50; //primes.size();
BigInteger ae = pe.leadingBaseCoefficient();
GenPolynomial<MOD> Pm = null;
ModularRingFactory<MOD> cofac = null;
GenPolynomialRing<MOD> mufac = null;
// search lucky prime
for ( int i = 0; i < 11; i++ ) { // meta loop
//for ( int i = 0; i < 1; i++ ) { // meta loop
java.math.BigInteger p = null; //new java.math.BigInteger("19"); //primes.next();
// 2 small, 5 medium and 4 large size primes
if ( i == 0 ) { // medium size
primes = new PrimeList(PrimeList.Range.medium);
primeIter = primes.iterator();
}
if ( i == 5 ) { // small size
primes = new PrimeList(PrimeList.Range.small);
primeIter = primes.iterator();
p = primeIter.next(); // 2
p = primeIter.next(); // 3
p = primeIter.next(); // 5
p = primeIter.next(); // 7
}
if ( i == 7 ) { // large size
primes = new PrimeList(PrimeList.Range.large);
primeIter = primes.iterator();
}
int pi = 0;
while ( pi < pn && primeIter.hasNext() ) {
p = primeIter.next();
//p = new java.math.BigInteger("19"); // test
logger.info("prime = " + p);
// initialize coefficient factory and map normalization factor and polynomials
ModularRingFactory<MOD> cf = null;
if (ModLongRing.MAX_LONG.compareTo(p) > 0) {
cf = (ModularRingFactory) new ModLongRing(p, true);
} else {
cf = (ModularRingFactory) new ModIntegerRing(p, true);
}
MOD nf = cf.fromInteger(ae.getVal());
if (nf.isZERO()) {
continue;
}
mufac = new GenPolynomialRing<MOD>(cf, ufac);
//System.out.println("mufac = " + mufac.toScript());
Pm = PolyUtil.<MOD> fromIntegerCoefficients(mufac, pe);
System.out.println("Pm = " + Pm);
if ( ! mfactor.isSquarefree(Pm) ) {
continue;
}
cofac = cf;
break;
}
if ( cofac != null ) {
break;
}
} // end meta loop
if ( cofac == null ) { // no lucky prime found
throw new RuntimeException("giving up on Hensel preparation");
}
logger.info("lucky prime = " + cofac.getIntegerModul());
List<GenPolynomial<MOD>> mufactors = PolyUtil.<MOD> fromIntegerCoefficients(mufac, ufactors);
System.out.println("mufactors = " + mufactors);
List<MOD> Vm = new ArrayList<MOD>(V.size());
for ( BigInteger v : V ) {
MOD vm = cofac.fromInteger(v.getVal());
Vm.add(vm);
}
System.out.println("Vm = " + Vm);
// coefficient bound
BigInteger an = pd.maxNorm();
BigInteger mn = an.multiply(ac.abs()).multiply(new BigInteger(2L));
long k = Power.logarithm(cofac.getIntegerModul(),mn) + 1L;
System.out.println("mn = " + mn);
System.out.println("k = " + k);
// Hensel lifting of factors
List<GenPolynomial<MOD>> mlift;
try {
mlift = HenselMultUtil.<MOD> liftHenselFull(pd,mufactors,Vm,k,lf);
logger.info("mlift = " + mlift);
} catch ( NoLiftingException nle ) {
System.out.println("exception : " + nle);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
} catch ( ArithmeticException aex ) {
System.out.println("exception : " + aex);
//continue;
mlift = new ArrayList<GenPolynomial<MOD>>();
}
if ( mlift.size() <= 1 ) { // irreducible mod I, p^k, can this happen?
factors.add(P);
return factors;
}
// combine trial factors
GenPolynomialRing<MOD> mfac = mlift.get(0).ring;
int dl = (mlift.size() + 1) / 2;
GenPolynomial<BigInteger> u = P;
long deg = (u.degree() + 1L) / 2L;
GenPolynomial<MOD> um = PolyUtil.<MOD> fromIntegerCoefficients(mfac, P);
GenPolynomial<BigInteger> ui = pd;
for (int j = 1; j <= dl; j++) {
System.out.println("j = " + j + ", dl = " + dl + ", mlift = " + mlift);
KsubSet<GenPolynomial<MOD>> subs = new KsubSet<GenPolynomial<MOD>>(mlift, j);
for (List<GenPolynomial<MOD>> flist : subs) {
//System.out.println("degreeSum = " + degreeSum(flist));
GenPolynomial<MOD> mtrial = mfac.getONE(); // .multiply(nf); // == 1, since primitive
for (int kk = 0; kk < flist.size(); kk++) {
GenPolynomial<MOD> fk = flist.get(kk);
mtrial = mtrial.multiply(fk);
}
if (mtrial.degree() > deg) { // this test is sometimes wrong
logger.info("degree > deg " + deg + ", degree = " + mtrial.degree());
//continue;
}
GenPolynomial<MOD> cofactor = um.divide(mtrial);
GenPolynomial<BigInteger> trial = PolyUtil.integerFromModularCoefficients(pfac, mtrial);
GenPolynomial<BigInteger> cotrial = PolyUtil.integerFromModularCoefficients(pfac, cofactor);
System.out.println("trial = " + trial); // + ", mtrial = " + mtrial);
//System.out.println("cotrial = " + cotrial + ", cofactor = " + cofactor);
if (trial.multiply(cotrial).equals(ui) ) {
factors.add(trial);
ui = cotrial; //PolyUtil.<BigInteger> basePseudoDivide(ui, trial); //u.divide( trial );
um = cofactor;
//System.out.println("ui = " + ui);
//System.out.println("um = " + um);
if (mlift.removeAll(flist)) {
logger.info("new mlift= " + mlift);
//System.out.println("dl = " + dl);
if ( mlift.size() > 1 ) {
dl = (mlift.size() + 1) / 2;
j = 0; // since j++
break;
} else {
logger.info("last ui = " + ui);
factors.add(ui);
return factors;
}
}
logger.error("error removing flist from mlift = " + mlift);
}
}
}
System.out.println("end combine, factors = " + factors);
if (!ui.isONE() && !ui.equals(pd)) {
logger.info("rest ui = " + ui);
//System.out.println("rest ui = " + ui);
factors.add(ui);
}
if (factors.size() == 0) {
logger.info("irred P = " + P);
factors.add(P);
}
return factors;
}
|
diff --git a/jvstm/src/jvstm/ProcessAtomicAnnotations.java b/jvstm/src/jvstm/ProcessAtomicAnnotations.java
index ae75f5f..36fbb52 100644
--- a/jvstm/src/jvstm/ProcessAtomicAnnotations.java
+++ b/jvstm/src/jvstm/ProcessAtomicAnnotations.java
@@ -1,351 +1,351 @@
/*
* JVSTM: a Java library for Software Transactional Memory
* Copyright (C) 2005 INESC-ID Software Engineering Group
* http://www.esw.inesc-id.pt
*
* 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.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author's contact:
* INESC-ID Software Engineering Group
* Rua Alves Redol 9
* 1000 - 029 Lisboa
* Portugal
*/
package jvstm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.*;
public class ProcessAtomicAnnotations {
private static final String ATOMIC_DESC = Type.getDescriptor(Atomic.class);
private String[] files;
ProcessAtomicAnnotations(String[] files) {
this.files = files;
}
public void start() {
for (String file : files) {
processFile(new File(file));
}
}
public void processFile(File file) {
if (file.isDirectory()) {
for (File subFile : file.listFiles()) {
processFile(subFile);
}
} else {
String fileName = file.getName();
if (fileName.endsWith(".class")) {
processClassFile(file);
}
}
}
protected void processClassFile(File classFile) {
AtomicMethodsInfo atomicMethods = collectAtomicMethods(classFile);
if (! atomicMethods.isEmpty()) {
transformClassFile(classFile, atomicMethods);
}
}
protected AtomicMethodsInfo collectAtomicMethods(File classFile) {
InputStream is = null;
try {
// get an input stream to read the bytecode of the class
is = new FileInputStream(classFile);
ClassReader cr = new ClassReader(is);
AtomicMethodCollector cv = new AtomicMethodCollector();
cr.accept(cv, false);
return cv.getAtomicMethods();
} catch (Exception e) {
e.printStackTrace();
throw new Error("Error processing class file: " + e);
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// intentionally empty
}
}
}
}
protected void transformClassFile(File classFile, AtomicMethodsInfo atomicMethods) {
InputStream is = null;
try {
// get an input stream to read the bytecode of the class
is = new FileInputStream(classFile);
ClassReader cr = new ClassReader(is);
ClassWriter cw = new ClassWriter(false);
AtomicMethodTransformer cv = new AtomicMethodTransformer(cw, atomicMethods);
cr.accept(cv, false);
writeNewClassFile(classFile, cw.toByteArray());
} catch (Exception e) {
e.printStackTrace();
throw new Error("Error processing class file: " + e);
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
// intentionally empty
}
}
}
}
protected void writeNewClassFile(File classFile, byte[] bytecode) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(classFile);
fos.write(bytecode);
} catch (Exception e) {
throw new Error("Couldn't rewrite class file: " + e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// intentionally empty
}
}
}
}
public static void main (final String args[]) throws Exception {
ProcessAtomicAnnotations processor = new ProcessAtomicAnnotations(args);
processor.start();
}
static class AtomicMethodCollector extends ClassAdapter {
private AtomicMethodsInfo atomicMethods = new AtomicMethodsInfo();
public AtomicMethodCollector() {
super(new EmptyVisitor());
}
public AtomicMethodsInfo getAtomicMethods() {
return atomicMethods;
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new MethodCollector(mv, name, desc);
}
class MethodCollector extends MethodAdapter {
private String methodName;
private String methodDesc;
MethodCollector(MethodVisitor mv, String name, String desc) {
super(mv);
this.methodName = name;
this.methodDesc = desc;
}
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (ATOMIC_DESC.equals(desc)) {
atomicMethods.addAtomicMethod(methodName, methodDesc);
}
return super.visitAnnotation(desc, visible);
}
}
}
protected static String getInternalMethodName(String name) {
return "atomic$" + name;
}
static class AtomicMethodTransformer extends ClassAdapter implements Opcodes {
private AtomicMethodsInfo atomicMethods;
private String className = null;
private boolean renameMethods = true;
private ArrayList<MethodWrapper> methods = new ArrayList<MethodWrapper>();
public AtomicMethodTransformer(ClassWriter cw, AtomicMethodsInfo atomicMethods) {
super(cw);
this.atomicMethods = atomicMethods;
}
public void visitEnd() {
renameMethods = false;
for (MethodWrapper mw : methods) {
Type returnType = Type.getReturnType(mw.desc);
Type[] argsType = Type.getArgumentTypes(mw.desc);
int argsSize = 0;
for (Type arg : argsType) {
argsSize += arg.getSize();
}
int boolVarPos = argsSize + 1;
int retSize = (returnType == Type.VOID_TYPE) ? 0 : returnType.getSize();
MethodVisitor mv = visitMethod(mw.access, mw.name, mw.desc, mw.signature, mw.exceptions);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "begin", "()Ljvstm/Transaction;");
mv.visitInsn(POP);
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitVarInsn(ALOAD, 0);
int stackPos = 1;
for (Type arg : argsType) {
mv.visitVarInsn(arg.getOpcode(ILOAD), stackPos);
stackPos += arg.getSize();
}
mv.visitMethodInsn(INVOKESPECIAL, className, getInternalMethodName(mw.name), mw.desc);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1);
}
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "commit", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1);
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1 + retSize);
}
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l3 = new Label();
mv.visitJumpInsn(IFNE, l3);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l3);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1 + retSize);
}
mv.visitInsn(returnType.getOpcode(IRETURN));
Label l4 = new Label();
mv.visitLabel(l4);
mv.visitVarInsn(ASTORE, boolVarPos + 1);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l5 = new Label();
mv.visitLabel(l5);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l6 = new Label();
mv.visitJumpInsn(IFNE, l6);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitJumpInsn(GOTO, l6);
Label l7 = new Label();
mv.visitLabel(l7);
mv.visitVarInsn(ASTORE, boolVarPos + 1 + (2 * retSize));
Label l8 = new Label();
mv.visitLabel(l8);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l9 = new Label();
mv.visitJumpInsn(IFNE, l9);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l9);
mv.visitVarInsn(ALOAD, boolVarPos + 1 + (2 * retSize));
mv.visitInsn(ATHROW);
mv.visitLabel(l6);
mv.visitJumpInsn(GOTO, l0);
mv.visitTryCatchBlock(l1, l2, l4, "jvstm/CommitException");
mv.visitTryCatchBlock(l1, l2, l7, null);
mv.visitTryCatchBlock(l4, l5, l7, null);
mv.visitTryCatchBlock(l7, l8, l7, null);
- mv.visitMaxs(boolVarPos, boolVarPos + 2 + (2 * retSize));
+ mv.visitMaxs(Math.max(boolVarPos, retSize), boolVarPos + 2 + (2 * retSize));
mv.visitEnd();
}
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
this.className = name;
super.visit(version, access, name, signature, superName, interfaces);
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (renameMethods && atomicMethods.isAtomicMethod(name, desc)) {
methods.add(new MethodWrapper(access, name, desc, signature, exceptions));
return super.visitMethod(ACC_PRIVATE, getInternalMethodName(name), desc, signature, exceptions);
} else {
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
static class MethodWrapper {
final int access;
final String name;
final String desc;
final String signature;
final String[] exceptions;
MethodWrapper(int access, String name, String desc, String signature, String[] exceptions) {
this.access = access;
this.name = name;
this.desc = desc;
this.signature = signature;
this.exceptions = exceptions;
}
}
}
static class AtomicMethodsInfo {
private Map<String,Set<String>> atomicMethods = new HashMap<String,Set<String>>();
public boolean isEmpty() {
return atomicMethods.isEmpty();
}
public void addAtomicMethod(String name, String desc) {
Set<String> methodDescs = atomicMethods.get(name);
if (methodDescs == null) {
methodDescs = new HashSet<String>();
atomicMethods.put(name, methodDescs);
}
methodDescs.add(desc);
}
public boolean isAtomicMethod(String name, String desc) {
Set<String> methodDescs = atomicMethods.get(name);
return (methodDescs != null) && methodDescs.contains(desc);
}
}
}
| true | true | public void visitEnd() {
renameMethods = false;
for (MethodWrapper mw : methods) {
Type returnType = Type.getReturnType(mw.desc);
Type[] argsType = Type.getArgumentTypes(mw.desc);
int argsSize = 0;
for (Type arg : argsType) {
argsSize += arg.getSize();
}
int boolVarPos = argsSize + 1;
int retSize = (returnType == Type.VOID_TYPE) ? 0 : returnType.getSize();
MethodVisitor mv = visitMethod(mw.access, mw.name, mw.desc, mw.signature, mw.exceptions);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "begin", "()Ljvstm/Transaction;");
mv.visitInsn(POP);
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitVarInsn(ALOAD, 0);
int stackPos = 1;
for (Type arg : argsType) {
mv.visitVarInsn(arg.getOpcode(ILOAD), stackPos);
stackPos += arg.getSize();
}
mv.visitMethodInsn(INVOKESPECIAL, className, getInternalMethodName(mw.name), mw.desc);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1);
}
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "commit", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1);
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1 + retSize);
}
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l3 = new Label();
mv.visitJumpInsn(IFNE, l3);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l3);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1 + retSize);
}
mv.visitInsn(returnType.getOpcode(IRETURN));
Label l4 = new Label();
mv.visitLabel(l4);
mv.visitVarInsn(ASTORE, boolVarPos + 1);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l5 = new Label();
mv.visitLabel(l5);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l6 = new Label();
mv.visitJumpInsn(IFNE, l6);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitJumpInsn(GOTO, l6);
Label l7 = new Label();
mv.visitLabel(l7);
mv.visitVarInsn(ASTORE, boolVarPos + 1 + (2 * retSize));
Label l8 = new Label();
mv.visitLabel(l8);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l9 = new Label();
mv.visitJumpInsn(IFNE, l9);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l9);
mv.visitVarInsn(ALOAD, boolVarPos + 1 + (2 * retSize));
mv.visitInsn(ATHROW);
mv.visitLabel(l6);
mv.visitJumpInsn(GOTO, l0);
mv.visitTryCatchBlock(l1, l2, l4, "jvstm/CommitException");
mv.visitTryCatchBlock(l1, l2, l7, null);
mv.visitTryCatchBlock(l4, l5, l7, null);
mv.visitTryCatchBlock(l7, l8, l7, null);
mv.visitMaxs(boolVarPos, boolVarPos + 2 + (2 * retSize));
mv.visitEnd();
}
}
| public void visitEnd() {
renameMethods = false;
for (MethodWrapper mw : methods) {
Type returnType = Type.getReturnType(mw.desc);
Type[] argsType = Type.getArgumentTypes(mw.desc);
int argsSize = 0;
for (Type arg : argsType) {
argsSize += arg.getSize();
}
int boolVarPos = argsSize + 1;
int retSize = (returnType == Type.VOID_TYPE) ? 0 : returnType.getSize();
MethodVisitor mv = visitMethod(mw.access, mw.name, mw.desc, mw.signature, mw.exceptions);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "begin", "()Ljvstm/Transaction;");
mv.visitInsn(POP);
mv.visitInsn(ICONST_0);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitVarInsn(ALOAD, 0);
int stackPos = 1;
for (Type arg : argsType) {
mv.visitVarInsn(arg.getOpcode(ILOAD), stackPos);
stackPos += arg.getSize();
}
mv.visitMethodInsn(INVOKESPECIAL, className, getInternalMethodName(mw.name), mw.desc);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1);
}
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "commit", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1);
mv.visitVarInsn(returnType.getOpcode(ISTORE), boolVarPos + 1 + retSize);
}
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l3 = new Label();
mv.visitJumpInsn(IFNE, l3);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l3);
if (returnType != Type.VOID_TYPE) {
mv.visitVarInsn(returnType.getOpcode(ILOAD), boolVarPos + 1 + retSize);
}
mv.visitInsn(returnType.getOpcode(IRETURN));
Label l4 = new Label();
mv.visitLabel(l4);
mv.visitVarInsn(ASTORE, boolVarPos + 1);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitInsn(ICONST_1);
mv.visitVarInsn(ISTORE, boolVarPos);
Label l5 = new Label();
mv.visitLabel(l5);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l6 = new Label();
mv.visitJumpInsn(IFNE, l6);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitJumpInsn(GOTO, l6);
Label l7 = new Label();
mv.visitLabel(l7);
mv.visitVarInsn(ASTORE, boolVarPos + 1 + (2 * retSize));
Label l8 = new Label();
mv.visitLabel(l8);
mv.visitVarInsn(ILOAD, boolVarPos);
Label l9 = new Label();
mv.visitJumpInsn(IFNE, l9);
mv.visitMethodInsn(INVOKESTATIC, "jvstm/Transaction", "abort", "()V");
mv.visitLabel(l9);
mv.visitVarInsn(ALOAD, boolVarPos + 1 + (2 * retSize));
mv.visitInsn(ATHROW);
mv.visitLabel(l6);
mv.visitJumpInsn(GOTO, l0);
mv.visitTryCatchBlock(l1, l2, l4, "jvstm/CommitException");
mv.visitTryCatchBlock(l1, l2, l7, null);
mv.visitTryCatchBlock(l4, l5, l7, null);
mv.visitTryCatchBlock(l7, l8, l7, null);
mv.visitMaxs(Math.max(boolVarPos, retSize), boolVarPos + 2 + (2 * retSize));
mv.visitEnd();
}
}
|
diff --git a/src/main/java/decentchat/api/DeCentInstance.java b/src/main/java/decentchat/api/DeCentInstance.java
index 89e96a4..4549e33 100644
--- a/src/main/java/decentchat/api/DeCentInstance.java
+++ b/src/main/java/decentchat/api/DeCentInstance.java
@@ -1,52 +1,52 @@
package decentchat.api;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import decentchat.internal.nodes.Node;
import decentchat.internal.nodes.NodeImpl;
public class DeCentInstance {
private String ip;
private int port;
private Registry reg = null;
private Node localNode = null;
/**
* The {@link DeCentInstance} is the main instance the client will be
* using when using the DeCentChat protocol. It defines the main
* public interface.
*
*/
public DeCentInstance() {
}
public boolean init(String bootstrap_ip, int port) {
this.port = port;
Node bootstrapNode = null;
try {
bootstrapNode = (Node)Naming.lookup("rmi://" + bootstrap_ip +":" +this.port+ "/node");
- ip = bootstrapNode.getIp();
+ ip = bootstrapNode.getIP();
// Now init registry
System.setProperty("java.rmi.server.hostname", ip);
reg = LocateRegistry.createRegistry(1099);
} catch (Exception e) {
System.err.println("Problem connecting to " + bootstrap_ip + ":" + port);
return false;
}
if(ip == null || reg == null) return false;
try {
localNode = new NodeImpl(); //TODO
} catch (RemoteException e) {
}
return true;
}
public int getPort() {
return this.port;
}
}
| true | true | public boolean init(String bootstrap_ip, int port) {
this.port = port;
Node bootstrapNode = null;
try {
bootstrapNode = (Node)Naming.lookup("rmi://" + bootstrap_ip +":" +this.port+ "/node");
ip = bootstrapNode.getIp();
// Now init registry
System.setProperty("java.rmi.server.hostname", ip);
reg = LocateRegistry.createRegistry(1099);
} catch (Exception e) {
System.err.println("Problem connecting to " + bootstrap_ip + ":" + port);
return false;
}
if(ip == null || reg == null) return false;
try {
localNode = new NodeImpl(); //TODO
} catch (RemoteException e) {
}
return true;
}
| public boolean init(String bootstrap_ip, int port) {
this.port = port;
Node bootstrapNode = null;
try {
bootstrapNode = (Node)Naming.lookup("rmi://" + bootstrap_ip +":" +this.port+ "/node");
ip = bootstrapNode.getIP();
// Now init registry
System.setProperty("java.rmi.server.hostname", ip);
reg = LocateRegistry.createRegistry(1099);
} catch (Exception e) {
System.err.println("Problem connecting to " + bootstrap_ip + ":" + port);
return false;
}
if(ip == null || reg == null) return false;
try {
localNode = new NodeImpl(); //TODO
} catch (RemoteException e) {
}
return true;
}
|
diff --git a/src/main/java/org/fcrepo/bench/BenchToolFC4.java b/src/main/java/org/fcrepo/bench/BenchToolFC4.java
index ba78da4..1760475 100644
--- a/src/main/java/org/fcrepo/bench/BenchToolFC4.java
+++ b/src/main/java/org/fcrepo/bench/BenchToolFC4.java
@@ -1,125 +1,127 @@
/**
*
*/
package org.fcrepo.bench;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.text.DecimalFormat;
import java.util.Random;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* @author frank asseg
*
*/
public class BenchToolFC4 {
private static final DecimalFormat FORMATTER = new DecimalFormat("000.00");
private static int numThreads = 0;
private static int maxThreads = 15;
public static void main(String[] args) {
String uri = args[0];
int numDatastreams = Integer.parseInt(args[1]);
int size = Integer.parseInt(args[2]);
maxThreads = Integer.parseInt(args[3]);
BenchToolFC4 bench = null;
System.out.println("generating " + numDatastreams +
" datastreams with size " + size);
FileOutputStream ingestOut = null;
try {
ingestOut = new FileOutputStream("ingest.log");
long start = System.currentTimeMillis();
for (int i = 0; i < numDatastreams; i++) {
while (numThreads >= maxThreads){
Thread.sleep(10);
}
Thread t = new Thread(new Ingester(uri, ingestOut, "benchfc4-" + (i+1), size));
t.start();
numThreads++;
float percent = (float) (i + 1) / (float) numDatastreams * 100f;
System.out.print("\r" + FORMATTER.format(percent) + "%");
}
while(numThreads > 0) {
Thread.sleep(100);
}
+ long duration = System.currentTimeMillis() - start;
System.out.println(" - ingest datastreams finished");
- System.out.println("Complete ingest of " + numDatastreams + " files took " + (System.currentTimeMillis() - start) + " ms\n");
+ System.out.println("Complete ingest of " + numDatastreams + " files took " + duration + " ms\n");
+ System.out.println("throughput was " + FORMATTER.format((double) numDatastreams * (double) size /1024d / duration) + " ms\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ingestOut);
}
}
private static class Ingester implements Runnable{
private final DefaultHttpClient client = new DefaultHttpClient();
private final URI fedoraUri;
private final OutputStream ingestOut;
private final int size;
private final String pid;
public Ingester(String fedoraUri, OutputStream out, String pid, int size) throws IOException {
super();
ingestOut = out;
if (fedoraUri.charAt(fedoraUri.length() - 1) == '/') {
fedoraUri = fedoraUri.substring(0, fedoraUri.length() - 1);
}
this.fedoraUri = URI.create(fedoraUri);
this.size = size;
this.pid = pid;
}
public void run() {
try {
this.ingestObject();
} catch (Exception e) {
e.printStackTrace();
}
}
private void ingestObject() throws Exception {
HttpPost post = new HttpPost(fedoraUri.toASCIIString() + "/rest/objects/" + pid + "/DS1/fcr:content");
post.setHeader("Content-Type", "application/octet-stream");
post.setEntity(new ByteArrayEntity(getRandomBytes(size)));
long start = System.currentTimeMillis();
HttpResponse resp = client.execute(post);
String answer = IOUtils.toString(resp.getEntity().getContent());
post.releaseConnection();
if (resp.getStatusLine().getStatusCode() != 201) {
System.out.println(answer);
BenchToolFC4.numThreads--;
throw new Exception("Unable to ingest object, fedora returned " +
resp.getStatusLine().getStatusCode());
}
IOUtils.write((System.currentTimeMillis() - start) + "\n", ingestOut);
BenchToolFC4.numThreads--;
}
private byte[] getRandomBytes(int size) {
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
return data;
}
}
}
| false | true | public static void main(String[] args) {
String uri = args[0];
int numDatastreams = Integer.parseInt(args[1]);
int size = Integer.parseInt(args[2]);
maxThreads = Integer.parseInt(args[3]);
BenchToolFC4 bench = null;
System.out.println("generating " + numDatastreams +
" datastreams with size " + size);
FileOutputStream ingestOut = null;
try {
ingestOut = new FileOutputStream("ingest.log");
long start = System.currentTimeMillis();
for (int i = 0; i < numDatastreams; i++) {
while (numThreads >= maxThreads){
Thread.sleep(10);
}
Thread t = new Thread(new Ingester(uri, ingestOut, "benchfc4-" + (i+1), size));
t.start();
numThreads++;
float percent = (float) (i + 1) / (float) numDatastreams * 100f;
System.out.print("\r" + FORMATTER.format(percent) + "%");
}
while(numThreads > 0) {
Thread.sleep(100);
}
System.out.println(" - ingest datastreams finished");
System.out.println("Complete ingest of " + numDatastreams + " files took " + (System.currentTimeMillis() - start) + " ms\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ingestOut);
}
}
| public static void main(String[] args) {
String uri = args[0];
int numDatastreams = Integer.parseInt(args[1]);
int size = Integer.parseInt(args[2]);
maxThreads = Integer.parseInt(args[3]);
BenchToolFC4 bench = null;
System.out.println("generating " + numDatastreams +
" datastreams with size " + size);
FileOutputStream ingestOut = null;
try {
ingestOut = new FileOutputStream("ingest.log");
long start = System.currentTimeMillis();
for (int i = 0; i < numDatastreams; i++) {
while (numThreads >= maxThreads){
Thread.sleep(10);
}
Thread t = new Thread(new Ingester(uri, ingestOut, "benchfc4-" + (i+1), size));
t.start();
numThreads++;
float percent = (float) (i + 1) / (float) numDatastreams * 100f;
System.out.print("\r" + FORMATTER.format(percent) + "%");
}
while(numThreads > 0) {
Thread.sleep(100);
}
long duration = System.currentTimeMillis() - start;
System.out.println(" - ingest datastreams finished");
System.out.println("Complete ingest of " + numDatastreams + " files took " + duration + " ms\n");
System.out.println("throughput was " + FORMATTER.format((double) numDatastreams * (double) size /1024d / duration) + " ms\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ingestOut);
}
}
|
diff --git a/src/forage/AddFoodLocationServlet.java b/src/forage/AddFoodLocationServlet.java
index 30f1f7f..edfa919 100644
--- a/src/forage/AddFoodLocationServlet.java
+++ b/src/forage/AddFoodLocationServlet.java
@@ -1,49 +1,48 @@
package forage;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
public class AddFoodLocationServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//get list of food items of the kind received in req and return as list
String kind = req.getParameter("kind");
String description = req.getParameter("description"); //Specific location description
String name = req.getParameter("name");
String lat = req.getParameter("lat");
String lng = req.getParameter("long");
String health = req.getParameter("health");
//query datastore for entity of kind FoodItem with name kind. Should actually only return one entity.
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
@SuppressWarnings("deprecation")
Query query = new Query("FoodItem").addFilter("name", Query.FilterOperator.EQUAL, kind);
Entity item = datastore.prepare(query).asSingleEntity();
- Key parentKey = null;
- parentKey = item.getKey();
+ Key parentKey = item.getKey();
// create itemLocation entity with selected foodItem as parentKey
Entity itemLocation = new Entity("Location", parentKey);
itemLocation.setProperty("description", description);
itemLocation.setProperty("name", name);
itemLocation.setProperty("lat", lat);
itemLocation.setProperty("long", lng);
itemLocation.setProperty("health", health);
datastore.put(itemLocation);
// send back to jsp
resp.sendRedirect("/addfoodlocations.jsp");
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//get list of food items of the kind received in req and return as list
String kind = req.getParameter("kind");
String description = req.getParameter("description"); //Specific location description
String name = req.getParameter("name");
String lat = req.getParameter("lat");
String lng = req.getParameter("long");
String health = req.getParameter("health");
//query datastore for entity of kind FoodItem with name kind. Should actually only return one entity.
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
@SuppressWarnings("deprecation")
Query query = new Query("FoodItem").addFilter("name", Query.FilterOperator.EQUAL, kind);
Entity item = datastore.prepare(query).asSingleEntity();
Key parentKey = null;
parentKey = item.getKey();
// create itemLocation entity with selected foodItem as parentKey
Entity itemLocation = new Entity("Location", parentKey);
itemLocation.setProperty("description", description);
itemLocation.setProperty("name", name);
itemLocation.setProperty("lat", lat);
itemLocation.setProperty("long", lng);
itemLocation.setProperty("health", health);
datastore.put(itemLocation);
// send back to jsp
resp.sendRedirect("/addfoodlocations.jsp");
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//get list of food items of the kind received in req and return as list
String kind = req.getParameter("kind");
String description = req.getParameter("description"); //Specific location description
String name = req.getParameter("name");
String lat = req.getParameter("lat");
String lng = req.getParameter("long");
String health = req.getParameter("health");
//query datastore for entity of kind FoodItem with name kind. Should actually only return one entity.
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
@SuppressWarnings("deprecation")
Query query = new Query("FoodItem").addFilter("name", Query.FilterOperator.EQUAL, kind);
Entity item = datastore.prepare(query).asSingleEntity();
Key parentKey = item.getKey();
// create itemLocation entity with selected foodItem as parentKey
Entity itemLocation = new Entity("Location", parentKey);
itemLocation.setProperty("description", description);
itemLocation.setProperty("name", name);
itemLocation.setProperty("lat", lat);
itemLocation.setProperty("long", lng);
itemLocation.setProperty("health", health);
datastore.put(itemLocation);
// send back to jsp
resp.sendRedirect("/addfoodlocations.jsp");
}
|
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus511/Nexus511MavenDeployTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus511/Nexus511MavenDeployTest.java
index ff62a5f74..6265e8f61 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus511/Nexus511MavenDeployTest.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus511/Nexus511MavenDeployTest.java
@@ -1,72 +1,71 @@
package org.sonatype.nexus.integrationtests.nexus511;
import java.io.File;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import org.junit.Before;
import org.junit.Test;
import org.sonatype.nexus.integrationtests.AbstractMavenNexusIT;
import org.sonatype.nexus.integrationtests.TestContainer;
/**
* Tests deploy to nexus using mvn deploy
*/
public class Nexus511MavenDeployTest
extends AbstractMavenNexusIT
{
static
{
TestContainer.getInstance().getTestContext().setSecureTest( true );
}
private Verifier verifier;
@Before
public void createVerifier()
throws Exception
{
File mavenProject = getTestFile( "maven-project" );
File settings = getTestFile( "server.xml" );
verifier = createVerifier( mavenProject, settings );
}
@Test
public void deploy()
throws Exception
{
try
{
verifier.executeGoal( "deploy" );
verifier.verifyErrorFreeLog();
}
catch ( VerificationException e )
{
failTest( verifier );
}
}
@SuppressWarnings("unchecked")
@Test
public void privateDeploy()
throws Exception
{
// try to deploy without servers authentication tokens
verifier.getCliOptions().clear();
verifier.getCliOptions().add("-X");
- verifier.getCliOptions().add("-DaltDeploymentRepository=\"\""); //
try
{
verifier.executeGoal( "deploy" );
verifier.verifyErrorFreeLog();
failTest( verifier );
}
catch ( VerificationException e )
{
// Expected exception
}
}
}
| true | true | public void privateDeploy()
throws Exception
{
// try to deploy without servers authentication tokens
verifier.getCliOptions().clear();
verifier.getCliOptions().add("-X");
verifier.getCliOptions().add("-DaltDeploymentRepository=\"\""); //
try
{
verifier.executeGoal( "deploy" );
verifier.verifyErrorFreeLog();
failTest( verifier );
}
catch ( VerificationException e )
{
// Expected exception
}
}
| public void privateDeploy()
throws Exception
{
// try to deploy without servers authentication tokens
verifier.getCliOptions().clear();
verifier.getCliOptions().add("-X");
try
{
verifier.executeGoal( "deploy" );
verifier.verifyErrorFreeLog();
failTest( verifier );
}
catch ( VerificationException e )
{
// Expected exception
}
}
|
diff --git a/src/share/classes/com/sun/javafx/runtime/sequence/CompositeSequence.java b/src/share/classes/com/sun/javafx/runtime/sequence/CompositeSequence.java
index 94518066e..3288cd5bc 100644
--- a/src/share/classes/com/sun/javafx/runtime/sequence/CompositeSequence.java
+++ b/src/share/classes/com/sun/javafx/runtime/sequence/CompositeSequence.java
@@ -1,80 +1,82 @@
/*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.javafx.runtime.sequence;
/**
* Intermediate (view) sequence implementation that represents the concatenation of zero or more other sequences of
* the same element type. Concatenating sequences should be done through the Sequences.concatenate() factory,
* not through the CompositeSequence constructor. O(nSeq) space and time construction costs.
*
* @author Brian Goetz
*/
class CompositeSequence<T> extends AbstractSequence<T> implements Sequence<T> {
private final Sequence<? extends T>[] sequences;
private final int[] startPositions;
private final int size, depth;
public CompositeSequence(Class<T> clazz, Sequence<? extends T>... sequences) {
super(clazz);
this.sequences = sequences.clone();
this.startPositions = new int[sequences.length];
int size = 0;
int depth = 0;
for (int i = 0, offset = 0; i < sequences.length; i++) {
- if (!sequences[i].getElementType().isAssignableFrom(clazz))
- throw new ClassCastException();
+ Class eClass = sequences[i].getElementType();
+ if (!clazz.isAssignableFrom(eClass))
+ throw new ClassCastException("cannot cast "+eClass.getName()
+ +" segment to "+clazz.getName()+" sequence");
startPositions[i] = offset;
size += sequences[i].size();
offset += sequences[i].size();
depth = Math.max(depth, sequences[i].getDepth());
}
this.size = size;
this.depth = depth + 1;
}
@Override
public int size() {
return size;
}
@Override
public int getDepth() {
return depth;
}
@Override
public T get(int position) {
if (position < 0 || position >= size || size == 0)
throw new IndexOutOfBoundsException(Integer.toString(position));
// Linear search should be good enough for now
int chunk = 0;
while (chunk < sequences.length - 1
&& (position >= startPositions[chunk+1] || sequences[chunk].size() == 0))
++chunk;
return sequences[chunk].get(position - startPositions[chunk]);
}
}
| true | true | public CompositeSequence(Class<T> clazz, Sequence<? extends T>... sequences) {
super(clazz);
this.sequences = sequences.clone();
this.startPositions = new int[sequences.length];
int size = 0;
int depth = 0;
for (int i = 0, offset = 0; i < sequences.length; i++) {
if (!sequences[i].getElementType().isAssignableFrom(clazz))
throw new ClassCastException();
startPositions[i] = offset;
size += sequences[i].size();
offset += sequences[i].size();
depth = Math.max(depth, sequences[i].getDepth());
}
this.size = size;
this.depth = depth + 1;
}
| public CompositeSequence(Class<T> clazz, Sequence<? extends T>... sequences) {
super(clazz);
this.sequences = sequences.clone();
this.startPositions = new int[sequences.length];
int size = 0;
int depth = 0;
for (int i = 0, offset = 0; i < sequences.length; i++) {
Class eClass = sequences[i].getElementType();
if (!clazz.isAssignableFrom(eClass))
throw new ClassCastException("cannot cast "+eClass.getName()
+" segment to "+clazz.getName()+" sequence");
startPositions[i] = offset;
size += sequences[i].size();
offset += sequences[i].size();
depth = Math.max(depth, sequences[i].getDepth());
}
this.size = size;
this.depth = depth + 1;
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/YUICompressor.java b/src/com/yahoo/platform/yui/compressor/YUICompressor.java
index 7fd1bd2..a1f96c3 100644
--- a/src/com/yahoo/platform/yui/compressor/YUICompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/YUICompressor.java
@@ -1,274 +1,275 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import jargs.gnu.CmdLineParser;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import java.io.*;
import java.nio.charset.Charset;
public class YUICompressor {
public static void main(String args[]) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option typeOpt = parser.addStringOption("type");
CmdLineParser.Option versionOpt = parser.addBooleanOption('V', "version");
CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
Reader in = null;
Writer out = null;
try {
parser.parse(args);
Boolean help = (Boolean) parser.getOptionValue(helpOpt);
if (help != null && help.booleanValue()) {
usage();
System.exit(0);
}
Boolean version = (Boolean) parser.getOptionValue(versionOpt);
if (version != null && version.booleanValue()) {
version();
System.exit(0);
}
boolean verbose = parser.getOptionValue(verboseOpt) != null;
String charset = (String) parser.getOptionValue(charsetOpt);
if (charset == null || !Charset.isSupported(charset)) {
// charset = System.getProperty("file.encoding");
// if (charset == null) {
// charset = "UTF-8";
// }
// UTF-8 seems to be a better choice than what the system is reporting
charset = "UTF-8";
if (verbose) {
System.err.println("\n[INFO] Using charset " + charset);
}
}
int linebreakpos = -1;
String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
if (linebreakstr != null) {
try {
linebreakpos = Integer.parseInt(linebreakstr, 10);
} catch (NumberFormatException e) {
usage();
System.exit(1);
}
}
String typeOverride = (String) parser.getOptionValue(typeOpt);
if (typeOverride != null && !typeOverride.equalsIgnoreCase("js") && !typeOverride.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
boolean munge = parser.getOptionValue(nomungeOpt) == null;
boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
String[] fileArgs = parser.getRemainingArgs();
java.util.List files = java.util.Arrays.asList(fileArgs);
if (files.isEmpty()) {
if (typeOverride == null) {
usage();
System.exit(1);
}
files = new java.util.ArrayList();
files.add("-"); // read from stdin
}
String output = (String) parser.getOptionValue(outputFilenameOpt);
String pattern[] = output != null ? output.split(":") : new String[0];
java.util.Iterator filenames = files.iterator();
while(filenames.hasNext()) {
String inputFilename = (String)filenames.next();
String type = null;
try {
if (inputFilename.equals("-")) {
in = new InputStreamReader(System.in, charset);
+ type = typeOverride;
} else {
if ( typeOverride != null ) {
type = typeOverride;
}
else {
int idx = inputFilename.lastIndexOf('.');
if (idx >= 0 && idx < inputFilename.length() - 1) {
type = inputFilename.substring(idx + 1);
}
}
if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
in = new InputStreamReader(new FileInputStream(inputFilename), charset);
}
String outputFilename = output;
// if a substitution pattern was passed in
if (pattern.length > 1 && files.size() > 0) {
outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
}
if (type.equalsIgnoreCase("js")) {
try {
final String localFilename = inputFilename;
JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
public void warning(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("\n[WARNING] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public void error(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("[ERROR] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
return new EvaluatorException(message);
}
});
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos, munge, verbose,
preserveAllSemiColons, disableOptimizations);
} catch (EvaluatorException e) {
e.printStackTrace();
// Return a special error code used specifically by the web front-end.
System.exit(2);
}
} else if (type.equalsIgnoreCase("css")) {
CssCompressor compressor = new CssCompressor(in);
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (CmdLineParser.OptionException e) {
usage();
System.exit(1);
}
}
private static void version() {
System.err.println("@VERSION@");
}
private static void usage() {
System.err.println(
"YUICompressor Version: @VERSION@\n"
+ "\nUsage: java -jar yuicompressor-@[email protected] [options] [input file]\n"
+ "\n"
+ "Global Options\n"
+ " -V, --version Print version information\n"
+ " -h, --help Displays this information\n"
+ " --type <js|css> Specifies the type of the input file\n"
+ " --charset <charset> Read the input file using <charset>\n"
+ " --line-break <column> Insert a line break after the specified column number\n"
+ " -v, --verbose Display informational messages and warnings\n"
+ " -o <file> Place the output into <file>. Defaults to stdout.\n"
+ " Multiple files can be processed using the following syntax:\n"
+ " java -jar yuicompressor.jar -o '.css$:-min.css' *.css\n"
+ " java -jar yuicompressor.jar -o '.js$:-min.js' *.js\n\n"
+ "JavaScript Options\n"
+ " --nomunge Minify only, do not obfuscate\n"
+ " --preserve-semi Preserve all semicolons\n"
+ " --disable-optimizations Disable all micro optimizations\n\n"
+ "If no input file is specified, it defaults to stdin. In this case, the 'type'\n"
+ "option is required. Otherwise, the 'type' option is required only if the input\n"
+ "file extension is neither 'js' nor 'css'.");
}
}
| true | true | public static void main(String args[]) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option typeOpt = parser.addStringOption("type");
CmdLineParser.Option versionOpt = parser.addBooleanOption('V', "version");
CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
Reader in = null;
Writer out = null;
try {
parser.parse(args);
Boolean help = (Boolean) parser.getOptionValue(helpOpt);
if (help != null && help.booleanValue()) {
usage();
System.exit(0);
}
Boolean version = (Boolean) parser.getOptionValue(versionOpt);
if (version != null && version.booleanValue()) {
version();
System.exit(0);
}
boolean verbose = parser.getOptionValue(verboseOpt) != null;
String charset = (String) parser.getOptionValue(charsetOpt);
if (charset == null || !Charset.isSupported(charset)) {
// charset = System.getProperty("file.encoding");
// if (charset == null) {
// charset = "UTF-8";
// }
// UTF-8 seems to be a better choice than what the system is reporting
charset = "UTF-8";
if (verbose) {
System.err.println("\n[INFO] Using charset " + charset);
}
}
int linebreakpos = -1;
String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
if (linebreakstr != null) {
try {
linebreakpos = Integer.parseInt(linebreakstr, 10);
} catch (NumberFormatException e) {
usage();
System.exit(1);
}
}
String typeOverride = (String) parser.getOptionValue(typeOpt);
if (typeOverride != null && !typeOverride.equalsIgnoreCase("js") && !typeOverride.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
boolean munge = parser.getOptionValue(nomungeOpt) == null;
boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
String[] fileArgs = parser.getRemainingArgs();
java.util.List files = java.util.Arrays.asList(fileArgs);
if (files.isEmpty()) {
if (typeOverride == null) {
usage();
System.exit(1);
}
files = new java.util.ArrayList();
files.add("-"); // read from stdin
}
String output = (String) parser.getOptionValue(outputFilenameOpt);
String pattern[] = output != null ? output.split(":") : new String[0];
java.util.Iterator filenames = files.iterator();
while(filenames.hasNext()) {
String inputFilename = (String)filenames.next();
String type = null;
try {
if (inputFilename.equals("-")) {
in = new InputStreamReader(System.in, charset);
} else {
if ( typeOverride != null ) {
type = typeOverride;
}
else {
int idx = inputFilename.lastIndexOf('.');
if (idx >= 0 && idx < inputFilename.length() - 1) {
type = inputFilename.substring(idx + 1);
}
}
if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
in = new InputStreamReader(new FileInputStream(inputFilename), charset);
}
String outputFilename = output;
// if a substitution pattern was passed in
if (pattern.length > 1 && files.size() > 0) {
outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
}
if (type.equalsIgnoreCase("js")) {
try {
final String localFilename = inputFilename;
JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
public void warning(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("\n[WARNING] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public void error(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("[ERROR] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
return new EvaluatorException(message);
}
});
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos, munge, verbose,
preserveAllSemiColons, disableOptimizations);
} catch (EvaluatorException e) {
e.printStackTrace();
// Return a special error code used specifically by the web front-end.
System.exit(2);
}
} else if (type.equalsIgnoreCase("css")) {
CssCompressor compressor = new CssCompressor(in);
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (CmdLineParser.OptionException e) {
usage();
System.exit(1);
}
}
| public static void main(String args[]) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option typeOpt = parser.addStringOption("type");
CmdLineParser.Option versionOpt = parser.addBooleanOption('V', "version");
CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
Reader in = null;
Writer out = null;
try {
parser.parse(args);
Boolean help = (Boolean) parser.getOptionValue(helpOpt);
if (help != null && help.booleanValue()) {
usage();
System.exit(0);
}
Boolean version = (Boolean) parser.getOptionValue(versionOpt);
if (version != null && version.booleanValue()) {
version();
System.exit(0);
}
boolean verbose = parser.getOptionValue(verboseOpt) != null;
String charset = (String) parser.getOptionValue(charsetOpt);
if (charset == null || !Charset.isSupported(charset)) {
// charset = System.getProperty("file.encoding");
// if (charset == null) {
// charset = "UTF-8";
// }
// UTF-8 seems to be a better choice than what the system is reporting
charset = "UTF-8";
if (verbose) {
System.err.println("\n[INFO] Using charset " + charset);
}
}
int linebreakpos = -1;
String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
if (linebreakstr != null) {
try {
linebreakpos = Integer.parseInt(linebreakstr, 10);
} catch (NumberFormatException e) {
usage();
System.exit(1);
}
}
String typeOverride = (String) parser.getOptionValue(typeOpt);
if (typeOverride != null && !typeOverride.equalsIgnoreCase("js") && !typeOverride.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
boolean munge = parser.getOptionValue(nomungeOpt) == null;
boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
String[] fileArgs = parser.getRemainingArgs();
java.util.List files = java.util.Arrays.asList(fileArgs);
if (files.isEmpty()) {
if (typeOverride == null) {
usage();
System.exit(1);
}
files = new java.util.ArrayList();
files.add("-"); // read from stdin
}
String output = (String) parser.getOptionValue(outputFilenameOpt);
String pattern[] = output != null ? output.split(":") : new String[0];
java.util.Iterator filenames = files.iterator();
while(filenames.hasNext()) {
String inputFilename = (String)filenames.next();
String type = null;
try {
if (inputFilename.equals("-")) {
in = new InputStreamReader(System.in, charset);
type = typeOverride;
} else {
if ( typeOverride != null ) {
type = typeOverride;
}
else {
int idx = inputFilename.lastIndexOf('.');
if (idx >= 0 && idx < inputFilename.length() - 1) {
type = inputFilename.substring(idx + 1);
}
}
if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
usage();
System.exit(1);
}
in = new InputStreamReader(new FileInputStream(inputFilename), charset);
}
String outputFilename = output;
// if a substitution pattern was passed in
if (pattern.length > 1 && files.size() > 0) {
outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
}
if (type.equalsIgnoreCase("js")) {
try {
final String localFilename = inputFilename;
JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {
public void warning(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("\n[WARNING] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public void error(String message, String sourceName,
int line, String lineSource, int lineOffset) {
System.err.println("[ERROR] in " + localFilename);
if (line < 0) {
System.err.println(" " + message);
} else {
System.err.println(" " + line + ':' + lineOffset + ':' + message);
}
}
public EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
return new EvaluatorException(message);
}
});
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos, munge, verbose,
preserveAllSemiColons, disableOptimizations);
} catch (EvaluatorException e) {
e.printStackTrace();
// Return a special error code used specifically by the web front-end.
System.exit(2);
}
} else if (type.equalsIgnoreCase("css")) {
CssCompressor compressor = new CssCompressor(in);
// Close the input stream first, and then open the output stream,
// in case the output file should override the input file.
in.close(); in = null;
if (outputFilename == null) {
out = new OutputStreamWriter(System.out, charset);
} else {
out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
}
compressor.compress(out, linebreakpos);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (CmdLineParser.OptionException e) {
usage();
System.exit(1);
}
}
|
diff --git a/src/java/com/idega/block/staff/business/StaffFinder.java b/src/java/com/idega/block/staff/business/StaffFinder.java
index cfdece4..72ee889 100644
--- a/src/java/com/idega/block/staff/business/StaffFinder.java
+++ b/src/java/com/idega/block/staff/business/StaffFinder.java
@@ -1,522 +1,522 @@
package com.idega.block.staff.business;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import com.idega.block.staff.data.StaffEntity;
import com.idega.block.staff.data.StaffInfo;
import com.idega.block.staff.data.StaffLocalized;
import com.idega.block.staff.data.StaffMeta;
import com.idega.block.staff.data.StaffMetaData;
import com.idega.core.business.UserGroupBusiness;
import com.idega.core.data.Email;
import com.idega.core.data.GenericGroup;
import com.idega.core.data.Phone;
import com.idega.core.localisation.business.ICLocaleBusiness;
import com.idega.core.user.business.UserBusiness;
import com.idega.core.user.data.User;
import com.idega.data.EntityFinder;
import com.idega.presentation.IWContext;
import com.idega.user.data.Group;
import com.idega.util.IWTimestamp;
/**
* Title: User
* Copyright: Copyright (c) 2000 idega.is All Rights Reserved
* Company: idega margmi�lun
* @author
* @version 1.0
*/
public class StaffFinder {
public static User getUser(int userID) {
try {
return ((com.idega.core.user.data.UserHome)com.idega.data.IDOLookup.getHomeLegacy(User.class)).findByPrimaryKeyLegacy(userID);
}
catch (SQLException e) {
return null;
}
}
public static StaffInfo getStaffInfo(int userId) {
try {
return ((com.idega.block.staff.data.StaffInfoHome)com.idega.data.IDOLookup.getHomeLegacy(StaffInfo.class)).findByPrimaryKeyLegacy(userId);
}
catch (SQLException e) {
return null;
}
}
public static StaffEntity getStaff(int userId) {
try {
return ((com.idega.block.staff.data.StaffEntityHome)com.idega.data.IDOLookup.getHomeLegacy(StaffEntity.class)).findByPrimaryKeyLegacy(userId);
}
catch (SQLException e) {
return null;
}
}
public static StaffMetaData[] getMetaData(int userId) {
try {
return (StaffMetaData[]) com.idega.block.staff.data.StaffMetaDataBMPBean.getStaticInstance().findAllByColumn(com.idega.block.staff.data.StaffMetaDataBMPBean.getColumnNameUserID(),Integer.toString(userId),"=");
}
catch (SQLException e) {
return null;
}
}
public static StaffMeta[] getMeta(int userID,int localeID) {
try {
return (StaffMeta[]) com.idega.block.staff.data.StaffMetaBMPBean.getStaticInstance(StaffMeta.class).findAllByColumn(com.idega.block.staff.data.StaffMetaBMPBean.getColumnNameUserID(),Integer.toString(userID),'=',com.idega.block.staff.data.StaffMetaBMPBean.getColumnNameLocaleId(),Integer.toString(localeID),'=');
}
catch (SQLException e) {
return null;
}
}
public static Email getUserEmail(User user) {
return UserBusiness.getUserMail(user);
}
public static List getGroups(IWContext iwc) {
try {
List allGroups = UserGroupBusiness.getAllGroups(iwc);
if ( allGroups != null ) {
allGroups.remove(iwc.getAccessController().getPermissionGroupAdministrator());
}
return allGroups;
}
catch (Exception e) {
return null;
}
}
public static List getAllUsers(IWContext iwc) {
try {
List allUsers = EntityFinder.findAll(com.idega.core.user.data.UserBMPBean.getStaticInstance());
/*if ( allUsers != null ) {
allUsers.remove(iwc.getAccessController().getAdministratorUser());
}*/
return allUsers;
}
catch (Exception e) {
return null;
}
}
public static List getAllUsersInGroup(Group group) {
return UserBusiness.getUsersInGroup(((Integer)group.getPrimaryKey()).intValue());
}
public static List getAllGroups(IWContext iwc) {
List groups = UserGroupBusiness.getAllGroups(iwc);
if ( groups != null ) {
try {
groups.remove(iwc.getAccessController().getPermissionGroupAdministrator());
}
catch (Exception e) {}
return groups;
}
return null;
}
public static List getUsersInPrimaryGroup(GenericGroup group) {
List users = UserBusiness.getUsersInPrimaryGroup(group);
if ( users != null )
return users;
return null;
}
public static List getAllUsersByLetter(IWContext iwc,String letter) {
try {
List allUsers = EntityFinder.findAllByColumn(com.idega.core.user.data.UserBMPBean.getStaticInstance(),com.idega.core.user.data.UserBMPBean.getColumnNameFirstName(),letter+"%");
if ( allUsers != null ) {
allUsers.remove(iwc.getAccessController().getAdministratorUser());
}
return allUsers;
}
catch (Exception e) {
return null;
}
}
public static List getUsersInNoGroups(GenericGroup group) {
try {
return UserBusiness.getUsersInGroup(group);
}
catch (Exception e) {
return null;
}
}
public static List getUsersInNoGroups() {
try {
return UserBusiness.getUsersInNoGroup();
}
catch (SQLException e) {
return null;
}
}
public static StaffLocalized getLocalizedStaff(StaffEntity entity, int iLocaleID){
try {
List list = null;
try {
list = EntityFinder.findRelated(entity,com.idega.block.staff.data.StaffLocalizedBMPBean.getStaticInstance(StaffLocalized.class));
}
catch (Exception e) {
list = null;
}
if ( list != null ) {
Iterator iter = list.iterator();
while (iter.hasNext()) {
StaffLocalized item = (StaffLocalized) iter.next();
if ( item.getLocaleId() == iLocaleID ) {
return item;
}
}
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static List getStaffHolders(List users,IWContext iwc) {
return getStaffHolders(users,ICLocaleBusiness.getLocaleId(iwc.getCurrentLocale()));
}
public static List getStaffHolders(List users,int localeID) {
Vector staffHolders = new Vector();
if ( users != null ) {
Iterator iter = users.iterator();
while (iter.hasNext()) {
staffHolders.add(getStaffHolder((User)iter.next(),localeID));
}
}
return staffHolders;
}
public static StaffHolder getStaffHolder(int userID,IWContext iwc) {
User user = StaffFinder.getUser(userID);
return getStaffHolder(user,ICLocaleBusiness.getLocaleId(iwc.getCurrentLocale()));
}
public static StaffHolder getStaffHolder(int userID,int localeID) {
User user = StaffFinder.getUser(userID);
return getStaffHolder(user,localeID);
}
public static StaffHolder getStaffHolder(User user,int localeID) {
StaffEntity staff = getStaff(user.getID());
StaffLocalized staffInfo = getLocalizedStaff(staff,localeID);
StaffMeta[] staffMeta = getMeta(user.getID(),localeID);
Phone workPhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.WORK_PHONE_ID);
Phone mobilePhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.MOBILE_PHONE_ID);
Email email = UserBusiness.getUserMail(user);
StaffHolder holder = new StaffHolder(user);
if ( user != null ) {
IWTimestamp stamp = null;
if ( user.getDateOfBirth() != null )
stamp = new IWTimestamp(user.getDateOfBirth());
IWTimestamp dateToday = new IWTimestamp();
int userAge = 0;
if ( stamp != null )
userAge = (new IWTimestamp().getDaysBetween(stamp,dateToday))/365;
/*
holder.setFirstName(user.getFirstName());
holder.setMiddleName(user.getMiddleName());
holder.setLastName(user.getLastName());
*/
holder.setAge(userAge);
// holder.setUserID(user.getID());
}
if ( staff != null ) {
if ( staff.getBeganWork() != null )
holder.setBeganWork(new IWTimestamp(staff.getBeganWork()));
holder.setImageID(staff.getImageID());
}
if ( staffInfo != null ) {
holder.setArea(staffInfo.getArea());
holder.setEducation(staffInfo.getEducation());
holder.setTitle(staffInfo.getTitle());
} else {//Legacy
try {
StaffInfo info = getStaffInfo(user.getID());
holder.setArea(info.getArea());
holder.setEducation(info.getEducation());
holder.setTitle(info.getTitle());
}
catch (Exception ex) {
//
}
}
if ( staffMeta != null ) {
String[] attributes = new String[staffMeta.length];
String[] values = new String[staffMeta.length];
for ( int a = 0; a < staffMeta.length; a++ ) {
attributes[a] = staffMeta[a].getAttribute();
values[a] = staffMeta[a].getValue();
}
holder.setMetaAttributes(attributes);
holder.setMetaValues(values);
}
if ( workPhone != null ) {
holder.setWorkPhone(workPhone.getNumber());
}
if ( mobilePhone != null ) {
- holder.setArea(mobilePhone.getNumber());
+ holder.setMobilePhone(mobilePhone.getNumber());
}
if ( email != null ) {
holder.setEmail(email.getEmailAddress());
}
return holder;
}
} // Class StaffFinder
| true | true | public static StaffHolder getStaffHolder(User user,int localeID) {
StaffEntity staff = getStaff(user.getID());
StaffLocalized staffInfo = getLocalizedStaff(staff,localeID);
StaffMeta[] staffMeta = getMeta(user.getID(),localeID);
Phone workPhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.WORK_PHONE_ID);
Phone mobilePhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.MOBILE_PHONE_ID);
Email email = UserBusiness.getUserMail(user);
StaffHolder holder = new StaffHolder(user);
if ( user != null ) {
IWTimestamp stamp = null;
if ( user.getDateOfBirth() != null )
stamp = new IWTimestamp(user.getDateOfBirth());
IWTimestamp dateToday = new IWTimestamp();
int userAge = 0;
if ( stamp != null )
userAge = (new IWTimestamp().getDaysBetween(stamp,dateToday))/365;
/*
holder.setFirstName(user.getFirstName());
holder.setMiddleName(user.getMiddleName());
holder.setLastName(user.getLastName());
*/
holder.setAge(userAge);
// holder.setUserID(user.getID());
}
if ( staff != null ) {
if ( staff.getBeganWork() != null )
holder.setBeganWork(new IWTimestamp(staff.getBeganWork()));
holder.setImageID(staff.getImageID());
}
if ( staffInfo != null ) {
holder.setArea(staffInfo.getArea());
holder.setEducation(staffInfo.getEducation());
holder.setTitle(staffInfo.getTitle());
} else {//Legacy
try {
StaffInfo info = getStaffInfo(user.getID());
holder.setArea(info.getArea());
holder.setEducation(info.getEducation());
holder.setTitle(info.getTitle());
}
catch (Exception ex) {
//
}
}
if ( staffMeta != null ) {
String[] attributes = new String[staffMeta.length];
String[] values = new String[staffMeta.length];
for ( int a = 0; a < staffMeta.length; a++ ) {
attributes[a] = staffMeta[a].getAttribute();
values[a] = staffMeta[a].getValue();
}
holder.setMetaAttributes(attributes);
holder.setMetaValues(values);
}
if ( workPhone != null ) {
holder.setWorkPhone(workPhone.getNumber());
}
if ( mobilePhone != null ) {
holder.setArea(mobilePhone.getNumber());
}
if ( email != null ) {
holder.setEmail(email.getEmailAddress());
}
return holder;
}
| public static StaffHolder getStaffHolder(User user,int localeID) {
StaffEntity staff = getStaff(user.getID());
StaffLocalized staffInfo = getLocalizedStaff(staff,localeID);
StaffMeta[] staffMeta = getMeta(user.getID(),localeID);
Phone workPhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.WORK_PHONE_ID);
Phone mobilePhone = UserBusiness.getUserPhone(user.getID(),com.idega.core.data.PhoneTypeBMPBean.MOBILE_PHONE_ID);
Email email = UserBusiness.getUserMail(user);
StaffHolder holder = new StaffHolder(user);
if ( user != null ) {
IWTimestamp stamp = null;
if ( user.getDateOfBirth() != null )
stamp = new IWTimestamp(user.getDateOfBirth());
IWTimestamp dateToday = new IWTimestamp();
int userAge = 0;
if ( stamp != null )
userAge = (new IWTimestamp().getDaysBetween(stamp,dateToday))/365;
/*
holder.setFirstName(user.getFirstName());
holder.setMiddleName(user.getMiddleName());
holder.setLastName(user.getLastName());
*/
holder.setAge(userAge);
// holder.setUserID(user.getID());
}
if ( staff != null ) {
if ( staff.getBeganWork() != null )
holder.setBeganWork(new IWTimestamp(staff.getBeganWork()));
holder.setImageID(staff.getImageID());
}
if ( staffInfo != null ) {
holder.setArea(staffInfo.getArea());
holder.setEducation(staffInfo.getEducation());
holder.setTitle(staffInfo.getTitle());
} else {//Legacy
try {
StaffInfo info = getStaffInfo(user.getID());
holder.setArea(info.getArea());
holder.setEducation(info.getEducation());
holder.setTitle(info.getTitle());
}
catch (Exception ex) {
//
}
}
if ( staffMeta != null ) {
String[] attributes = new String[staffMeta.length];
String[] values = new String[staffMeta.length];
for ( int a = 0; a < staffMeta.length; a++ ) {
attributes[a] = staffMeta[a].getAttribute();
values[a] = staffMeta[a].getValue();
}
holder.setMetaAttributes(attributes);
holder.setMetaValues(values);
}
if ( workPhone != null ) {
holder.setWorkPhone(workPhone.getNumber());
}
if ( mobilePhone != null ) {
holder.setMobilePhone(mobilePhone.getNumber());
}
if ( email != null ) {
holder.setEmail(email.getEmailAddress());
}
return holder;
}
|
diff --git a/src/jp/ac/titech/cs/de/ykstorage/service/cmm/CacheMemoryManager.java b/src/jp/ac/titech/cs/de/ykstorage/service/cmm/CacheMemoryManager.java
index 1290166..804dc70 100755
--- a/src/jp/ac/titech/cs/de/ykstorage/service/cmm/CacheMemoryManager.java
+++ b/src/jp/ac/titech/cs/de/ykstorage/service/cmm/CacheMemoryManager.java
@@ -1,205 +1,208 @@
package jp.ac.titech.cs.de.ykstorage.service.cmm;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;
import jp.ac.titech.cs.de.ykstorage.service.Value;
import jp.ac.titech.cs.de.ykstorage.util.StorageLogger;
public class CacheMemoryManager {
private Logger logger = StorageLogger.getLogger();
private ByteBuffer memBuffer;
private int max;
private int limit;
/**
* key: data key
* value: MemoryHeader object
*/
private Map<Integer, MemoryHeader> headerTable;
/**
* This map folds access time information for the LRU algorithm
* key: last accessed time of the value (nanosecond)
* value: data key
*/
private TreeMap<Long, Integer> lruKeys;
public CacheMemoryManager(int max, double threshold) {
if (threshold < 0 || threshold > 1.0)
throw new IllegalArgumentException("threshold must be in range 0 to 1.0.");
this.max = max;
this.limit = (int)Math.floor(max * threshold);
logger.info(String.format("cache memory max capacity : %d[Bytes]", this.max));
logger.info(String.format("cache memory threshold : %d[Bytes]", this.limit));
this.memBuffer = ByteBuffer.allocateDirect(max);
this.headerTable = new HashMap<Integer, MemoryHeader>();
this.lruKeys = new TreeMap<Long, Integer>();
}
public Value put(int key, Value value) {
int usage = memBuffer.capacity() - memBuffer.remaining();
int requireSize = value.getValue().length;
if (this.limit < usage + requireSize) {
logger.info(String.format(
"cache memory overflow. key id: %d, require size: %d[B], available: %d[B]",
key, requireSize, memBuffer.remaining()));
return Value.NULL;
}
long thisTime = System.nanoTime();
MemoryHeader header =
new MemoryHeader(memBuffer.position(), requireSize, thisTime);
headerTable.put(key, header);
memBuffer.put(value.getValue());
// update access time for LRU
updateLRUInfo(key);
logger.info(String.format(
"put on cache memory. key id: %d, val pos: %d, size: %d, time: %d",
key, header.getPosition(), requireSize, thisTime));
return value;
}
public Value get(int key) {
MemoryHeader header = headerTable.get(key);
if (header == null) {
return Value.NULL;
}
byte[] byteVal = new byte[header.getSize()];
int currentPos = memBuffer.position();
memBuffer.position(header.getPosition());
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.position(currentPos);
Value value = new Value(byteVal);
// update access time for LRU
updateLRUInfo(key);
long accessedTime = headerTable.get(key).getAccessedTime();
logger.info(String.format("get from cache memory. key id: %d, time: %d",
key, accessedTime));
return value;
}
public Value delete(int key) {
Value deleted = get(key);
if (!Value.NULL.equals(deleted)) {
MemoryHeader deletedHeader = headerTable.remove(key);
lruKeys.remove(deletedHeader.getAccessedTime());
logger.info(String.format("delete from cache memory. key id: %d", key));
}
return deleted;
}
public Set<Map.Entry<Integer,Value>> replace(int key, Value value) {
Map<Integer, Value> replacedMap = new HashMap<Integer, Value>();
while (true) {
compaction();
int usage = memBuffer.capacity() - memBuffer.remaining();
int requireSize = value.getValue().length;
if (this.limit < usage + requireSize) {
Map.Entry<Long, Integer> lruKey = lruKeys.firstEntry();
assert lruKey != null;
int replacedKey = lruKey.getValue();
Value deleted = delete(replacedKey);
if (!Value.NULL.equals(deleted))
replacedMap.put(replacedKey, deleted);
} else {
put(key, value);
break;
}
}
return replacedMap.entrySet();
}
private void updateLRUInfo(int key) {
MemoryHeader header = headerTable.get(key);
lruKeys.remove(header.getAccessedTime());
long thisTime = System.nanoTime();
header.setAccessedTime(thisTime);
lruKeys.put(thisTime, key);
}
public void compaction() {
boolean isFirst = true;
+ if(headerTable.isEmpty()) {
+ memBuffer.rewind();
+ }
for (MemoryHeader header : headerTable.values()) {
if (isFirst) {
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.rewind();
int newPosition = memBuffer.position();
memBuffer.put(byteVal);
header.setPosition(newPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, newPosition, header.getSize()));
isFirst = false;
continue;
}
int currentPosition = memBuffer.position();
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.position(currentPosition);
memBuffer.put(byteVal);
header.setPosition(currentPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, currentPosition, header.getSize()));
}
}
class MemoryHeader {
private int position;
private int size;
private long accessedTime;
public MemoryHeader(int position, int size, long accessedTime) {
this.position = position;
this.size = size;
this.accessedTime = accessedTime;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public long getAccessedTime() {
return accessedTime;
}
public void setAccessedTime(long accessedTime) {
this.accessedTime = accessedTime;
}
}
}
| true | true | public void compaction() {
boolean isFirst = true;
for (MemoryHeader header : headerTable.values()) {
if (isFirst) {
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.rewind();
int newPosition = memBuffer.position();
memBuffer.put(byteVal);
header.setPosition(newPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, newPosition, header.getSize()));
isFirst = false;
continue;
}
int currentPosition = memBuffer.position();
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.position(currentPosition);
memBuffer.put(byteVal);
header.setPosition(currentPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, currentPosition, header.getSize()));
}
}
| public void compaction() {
boolean isFirst = true;
if(headerTable.isEmpty()) {
memBuffer.rewind();
}
for (MemoryHeader header : headerTable.values()) {
if (isFirst) {
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.rewind();
int newPosition = memBuffer.position();
memBuffer.put(byteVal);
header.setPosition(newPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, newPosition, header.getSize()));
isFirst = false;
continue;
}
int currentPosition = memBuffer.position();
int oldPosition = header.getPosition();
byte[] byteVal = new byte[header.getSize()];
memBuffer.position(oldPosition);
memBuffer.get(byteVal, 0, header.getSize());
memBuffer.position(currentPosition);
memBuffer.put(byteVal);
header.setPosition(currentPosition);
logger.info(String.format(
"migrated. fromPos: %d, toPos: %d, size: %d",
oldPosition, currentPosition, header.getSize()));
}
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatTFileOutput.java b/src/main/java/org/agmip/translators/dssat/DssatTFileOutput.java
index c81fbb3..527fc0e 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatTFileOutput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatTFileOutput.java
@@ -1,181 +1,181 @@
package org.agmip.translators.dssat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import org.agmip.core.types.AdvancedHashMap;
import org.agmip.util.JSONAdapter;
/**
* DSSAT Observation Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatTFileOutput extends DssatCommonOutput {
private File outputFile;
/**
* Get output file object
*/
public File getOutputFile() {
return outputFile;
}
/**
* DSSAT Observation Data Output method
*
* @param arg0 file output path
* @param result data holder object
*/
@Override
public void writeFile(String arg0, AdvancedHashMap result) {
// Initial variables
JSONAdapter adapter = new JSONAdapter(); // JSON Adapter
AdvancedHashMap<String, Object> record; // Data holder for daily data
BufferedWriter bwT; // output object
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
HashMap altTitleList = new HashMap(); // Define alternative fields for the necessary observation data fields; key is necessary field
// TODO Add alternative fields here
LinkedHashMap titleOutput; // contain output data field id
DssatObservedData obvDataList = new DssatObservedData(); // Varibale list definition
try {
// Set default value for missing data
setDefVal();
// Get Data from input holder
- AdvancedHashMap obvFile = adapter.exportRecord((Map) result.getOr("time_course", result));
- AdvancedHashMap obvTFile = adapter.exportRecord((Map) obvFile.getOr("average", obvFile));
+ AdvancedHashMap obvFile = adapter.exportRecord((Map) result.getOr("observed", result));
+ AdvancedHashMap obvTFile = adapter.exportRecord((Map) obvFile.getOr("time_course", obvFile));
ArrayList observeRecordsSections = ((ArrayList) obvTFile.getOr("data", new ArrayList()));
// Initial BufferedWriter
String exName = getExName(obvTFile);
String fileName = exName;
if (fileName.equals("")) {
fileName = "a.tmp";
} else {
fileName = fileName.substring(0, fileName.length() - 2) + "." + fileName.substring(fileName.length() - 2) + "T";
}
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwT = new BufferedWriter(new FileWriter(outputFile));
// Output Observation File
// Titel Section
sbData.append(String.format("*EXP.DATA (T): %1$-10s %2$s\r\n\r\n", exName, obvTFile.getOr("local_name", defValC).toString()));
// Loop Data Sections
ArrayList observeRecords;
for (int id = 0; id < observeRecordsSections.size(); id++) {
observeRecords = (ArrayList) observeRecordsSections.get(id);
titleOutput = new LinkedHashMap();
// Get first record of observed data
AdvancedHashMap fstObvData;
if (observeRecords.isEmpty()) {
fstObvData = new AdvancedHashMap();
} else {
fstObvData = adapter.exportRecord((Map) observeRecords.get(0));
}
// Check if which field is available
for (Object key : fstObvData.keySet()) {
// check which optional data is exist, if not, remove from map
if (obvDataList.isTimeCourseData(key)) {
titleOutput.put(key, key);
} // check if the additional data is too long to output
else if (key.toString().length() <= 5) {
if (!key.equals("trno") && !key.equals("date")) {
titleOutput.put(key, key);
}
} // If it is too long for DSSAT, give a warning message
else {
sbError.append("! Waring: Unsuitable data for DSSAT observed data (too long): [").append(key).append("]\r\n");
}
}
// Check if all necessary field is available // TODO conrently unuseful
for (Object title : altTitleList.keySet()) {
// check which optional data is exist, if not, remove from map
if (!fstObvData.containsKey(title)) {
if (fstObvData.containsKey(altTitleList.get(title))) {
titleOutput.put(title, altTitleList.get(title));
} else {
// TODO throw new Exception("Incompleted record because missing data : [" + title + "]");
sbError.append("! Waring: Incompleted record because missing data : [").append(title).append("]\r\n");
}
} else {
}
}
// decompress observed data
decompressData(observeRecords);
// Observation Data Section
Object[] titleOutputId = titleOutput.keySet().toArray();
for (int i = 0; i < (titleOutputId.length / 39 + titleOutputId.length % 39 == 0 ? 0 : 1); i++) {
sbData.append("@TRNO DATE");
int limit = Math.min(titleOutputId.length, (i + 1) * 39);
for (int j = i * 39; j < limit; j++) {
sbData.append(String.format("%1$6s", titleOutput.get(titleOutputId[j]).toString().toUpperCase()));
}
sbData.append("\r\n");
for (int j = 0; j < observeRecords.size(); j++) {
record = adapter.exportRecord((Map) observeRecords.get(j));
sbData.append(String.format(" %1$5s", record.getOr("trno", 1).toString())); // TODO wait for confirmation that other model only have single treatment in one file
sbData.append(String.format(" %1$5d", Integer.parseInt(formatDateStr(record.getOr("date", defValI).toString()))));
for (int k = i * 39; k < limit; k++) {
if (obvDataList.isDapDateType(titleOutputId[k], titleOutput.get(titleOutputId[k]))) {
String pdate = (String) ((AdvancedHashMap) result.getOr("experiment", new AdvancedHashMap())).getOr("pdate", defValD); // TODO need be updated after ear;y version
sbData.append(String.format("%1$6s", formatDateStr(pdate, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else if (obvDataList.isDateType(titleOutputId[k])) {
sbData.append(String.format("%1$6s", formatDateStr(record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else {
sbData.append(" ").append(formatNumStr(5, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString()));
}
}
sbData.append("\r\n");
}
}
// Add section deviding line
sbData.append("\r\n");
}
// Output finish
bwT.write(sbError.toString());
bwT.write(sbData.toString());
bwT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Set default value for missing data
*
* @version 1.0
*/
private void setDefVal() {
// defValD = ""; No need to set default value for Date type in Observation file
defValR = "-99";
defValC = "-99"; // TODO wait for confirmation
defValI = "-99";
}
}
| true | true | public void writeFile(String arg0, AdvancedHashMap result) {
// Initial variables
JSONAdapter adapter = new JSONAdapter(); // JSON Adapter
AdvancedHashMap<String, Object> record; // Data holder for daily data
BufferedWriter bwT; // output object
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
HashMap altTitleList = new HashMap(); // Define alternative fields for the necessary observation data fields; key is necessary field
// TODO Add alternative fields here
LinkedHashMap titleOutput; // contain output data field id
DssatObservedData obvDataList = new DssatObservedData(); // Varibale list definition
try {
// Set default value for missing data
setDefVal();
// Get Data from input holder
AdvancedHashMap obvFile = adapter.exportRecord((Map) result.getOr("time_course", result));
AdvancedHashMap obvTFile = adapter.exportRecord((Map) obvFile.getOr("average", obvFile));
ArrayList observeRecordsSections = ((ArrayList) obvTFile.getOr("data", new ArrayList()));
// Initial BufferedWriter
String exName = getExName(obvTFile);
String fileName = exName;
if (fileName.equals("")) {
fileName = "a.tmp";
} else {
fileName = fileName.substring(0, fileName.length() - 2) + "." + fileName.substring(fileName.length() - 2) + "T";
}
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwT = new BufferedWriter(new FileWriter(outputFile));
// Output Observation File
// Titel Section
sbData.append(String.format("*EXP.DATA (T): %1$-10s %2$s\r\n\r\n", exName, obvTFile.getOr("local_name", defValC).toString()));
// Loop Data Sections
ArrayList observeRecords;
for (int id = 0; id < observeRecordsSections.size(); id++) {
observeRecords = (ArrayList) observeRecordsSections.get(id);
titleOutput = new LinkedHashMap();
// Get first record of observed data
AdvancedHashMap fstObvData;
if (observeRecords.isEmpty()) {
fstObvData = new AdvancedHashMap();
} else {
fstObvData = adapter.exportRecord((Map) observeRecords.get(0));
}
// Check if which field is available
for (Object key : fstObvData.keySet()) {
// check which optional data is exist, if not, remove from map
if (obvDataList.isTimeCourseData(key)) {
titleOutput.put(key, key);
} // check if the additional data is too long to output
else if (key.toString().length() <= 5) {
if (!key.equals("trno") && !key.equals("date")) {
titleOutput.put(key, key);
}
} // If it is too long for DSSAT, give a warning message
else {
sbError.append("! Waring: Unsuitable data for DSSAT observed data (too long): [").append(key).append("]\r\n");
}
}
// Check if all necessary field is available // TODO conrently unuseful
for (Object title : altTitleList.keySet()) {
// check which optional data is exist, if not, remove from map
if (!fstObvData.containsKey(title)) {
if (fstObvData.containsKey(altTitleList.get(title))) {
titleOutput.put(title, altTitleList.get(title));
} else {
// TODO throw new Exception("Incompleted record because missing data : [" + title + "]");
sbError.append("! Waring: Incompleted record because missing data : [").append(title).append("]\r\n");
}
} else {
}
}
// decompress observed data
decompressData(observeRecords);
// Observation Data Section
Object[] titleOutputId = titleOutput.keySet().toArray();
for (int i = 0; i < (titleOutputId.length / 39 + titleOutputId.length % 39 == 0 ? 0 : 1); i++) {
sbData.append("@TRNO DATE");
int limit = Math.min(titleOutputId.length, (i + 1) * 39);
for (int j = i * 39; j < limit; j++) {
sbData.append(String.format("%1$6s", titleOutput.get(titleOutputId[j]).toString().toUpperCase()));
}
sbData.append("\r\n");
for (int j = 0; j < observeRecords.size(); j++) {
record = adapter.exportRecord((Map) observeRecords.get(j));
sbData.append(String.format(" %1$5s", record.getOr("trno", 1).toString())); // TODO wait for confirmation that other model only have single treatment in one file
sbData.append(String.format(" %1$5d", Integer.parseInt(formatDateStr(record.getOr("date", defValI).toString()))));
for (int k = i * 39; k < limit; k++) {
if (obvDataList.isDapDateType(titleOutputId[k], titleOutput.get(titleOutputId[k]))) {
String pdate = (String) ((AdvancedHashMap) result.getOr("experiment", new AdvancedHashMap())).getOr("pdate", defValD); // TODO need be updated after ear;y version
sbData.append(String.format("%1$6s", formatDateStr(pdate, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else if (obvDataList.isDateType(titleOutputId[k])) {
sbData.append(String.format("%1$6s", formatDateStr(record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else {
sbData.append(" ").append(formatNumStr(5, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString()));
}
}
sbData.append("\r\n");
}
}
// Add section deviding line
sbData.append("\r\n");
}
// Output finish
bwT.write(sbError.toString());
bwT.write(sbData.toString());
bwT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void writeFile(String arg0, AdvancedHashMap result) {
// Initial variables
JSONAdapter adapter = new JSONAdapter(); // JSON Adapter
AdvancedHashMap<String, Object> record; // Data holder for daily data
BufferedWriter bwT; // output object
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
HashMap altTitleList = new HashMap(); // Define alternative fields for the necessary observation data fields; key is necessary field
// TODO Add alternative fields here
LinkedHashMap titleOutput; // contain output data field id
DssatObservedData obvDataList = new DssatObservedData(); // Varibale list definition
try {
// Set default value for missing data
setDefVal();
// Get Data from input holder
AdvancedHashMap obvFile = adapter.exportRecord((Map) result.getOr("observed", result));
AdvancedHashMap obvTFile = adapter.exportRecord((Map) obvFile.getOr("time_course", obvFile));
ArrayList observeRecordsSections = ((ArrayList) obvTFile.getOr("data", new ArrayList()));
// Initial BufferedWriter
String exName = getExName(obvTFile);
String fileName = exName;
if (fileName.equals("")) {
fileName = "a.tmp";
} else {
fileName = fileName.substring(0, fileName.length() - 2) + "." + fileName.substring(fileName.length() - 2) + "T";
}
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwT = new BufferedWriter(new FileWriter(outputFile));
// Output Observation File
// Titel Section
sbData.append(String.format("*EXP.DATA (T): %1$-10s %2$s\r\n\r\n", exName, obvTFile.getOr("local_name", defValC).toString()));
// Loop Data Sections
ArrayList observeRecords;
for (int id = 0; id < observeRecordsSections.size(); id++) {
observeRecords = (ArrayList) observeRecordsSections.get(id);
titleOutput = new LinkedHashMap();
// Get first record of observed data
AdvancedHashMap fstObvData;
if (observeRecords.isEmpty()) {
fstObvData = new AdvancedHashMap();
} else {
fstObvData = adapter.exportRecord((Map) observeRecords.get(0));
}
// Check if which field is available
for (Object key : fstObvData.keySet()) {
// check which optional data is exist, if not, remove from map
if (obvDataList.isTimeCourseData(key)) {
titleOutput.put(key, key);
} // check if the additional data is too long to output
else if (key.toString().length() <= 5) {
if (!key.equals("trno") && !key.equals("date")) {
titleOutput.put(key, key);
}
} // If it is too long for DSSAT, give a warning message
else {
sbError.append("! Waring: Unsuitable data for DSSAT observed data (too long): [").append(key).append("]\r\n");
}
}
// Check if all necessary field is available // TODO conrently unuseful
for (Object title : altTitleList.keySet()) {
// check which optional data is exist, if not, remove from map
if (!fstObvData.containsKey(title)) {
if (fstObvData.containsKey(altTitleList.get(title))) {
titleOutput.put(title, altTitleList.get(title));
} else {
// TODO throw new Exception("Incompleted record because missing data : [" + title + "]");
sbError.append("! Waring: Incompleted record because missing data : [").append(title).append("]\r\n");
}
} else {
}
}
// decompress observed data
decompressData(observeRecords);
// Observation Data Section
Object[] titleOutputId = titleOutput.keySet().toArray();
for (int i = 0; i < (titleOutputId.length / 39 + titleOutputId.length % 39 == 0 ? 0 : 1); i++) {
sbData.append("@TRNO DATE");
int limit = Math.min(titleOutputId.length, (i + 1) * 39);
for (int j = i * 39; j < limit; j++) {
sbData.append(String.format("%1$6s", titleOutput.get(titleOutputId[j]).toString().toUpperCase()));
}
sbData.append("\r\n");
for (int j = 0; j < observeRecords.size(); j++) {
record = adapter.exportRecord((Map) observeRecords.get(j));
sbData.append(String.format(" %1$5s", record.getOr("trno", 1).toString())); // TODO wait for confirmation that other model only have single treatment in one file
sbData.append(String.format(" %1$5d", Integer.parseInt(formatDateStr(record.getOr("date", defValI).toString()))));
for (int k = i * 39; k < limit; k++) {
if (obvDataList.isDapDateType(titleOutputId[k], titleOutput.get(titleOutputId[k]))) {
String pdate = (String) ((AdvancedHashMap) result.getOr("experiment", new AdvancedHashMap())).getOr("pdate", defValD); // TODO need be updated after ear;y version
sbData.append(String.format("%1$6s", formatDateStr(pdate, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else if (obvDataList.isDateType(titleOutputId[k])) {
sbData.append(String.format("%1$6s", formatDateStr(record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString())));
} else {
sbData.append(" ").append(formatNumStr(5, record.getOr(titleOutput.get(titleOutputId[k]).toString(), defValI).toString()));
}
}
sbData.append("\r\n");
}
}
// Add section deviding line
sbData.append("\r\n");
}
// Output finish
bwT.write(sbError.toString());
bwT.write(sbData.toString());
bwT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java b/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
index 8b35853f..77957b00 100644
--- a/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
+++ b/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
@@ -1,243 +1,246 @@
package org.motechproject.server.omod.tasks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.motechproject.server.model.Message;
import org.motechproject.server.model.MessageDefinition;
import org.motechproject.server.model.MessageProgramEnrollment;
import org.motechproject.server.model.MessageStatus;
import org.motechproject.server.model.MessageType;
import org.motechproject.server.model.ScheduledMessage;
import org.motechproject.server.omod.MotechModuleActivator;
import org.motechproject.server.omod.MotechService;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.ContactNumberType;
import org.motechproject.ws.DayOfWeek;
import org.motechproject.ws.Gender;
import org.motechproject.ws.HowLearned;
import org.motechproject.ws.InterestReason;
import org.motechproject.ws.MediaType;
import org.motechproject.ws.RegistrantType;
import org.motechproject.ws.RegistrationMode;
import org.openmrs.Concept;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.scheduler.TaskDefinition;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;
/**
* BaseModuleContextSensitiveTest loads both the OpenMRS core and module spring
* contexts and hibernate mappings, providing the OpenMRS Context for both
* OpenMRS core and module services.
*/
public class MessageProgramUpdateTaskTest extends
BaseModuleContextSensitiveTest {
static MotechModuleActivator activator;
Log log = LogFactory.getLog(MessageProgramUpdateTaskTest.class);
@BeforeClass
public static void setUpClass() throws Exception {
activator = new MotechModuleActivator(false);
}
@AfterClass
public static void tearDownClass() throws Exception {
activator = null;
}
@Before
public void setup() throws Exception {
// Perform same steps as BaseSetup (initializeInMemoryDatabase,
// executeDataSet, authenticate), except load custom XML dataset
initializeInMemoryDatabase();
// Created from org.openmrs.test.CreateInitialDataSet
// without line for "concept_synonym" table (not exist)
// using 1.4.4-createdb-from-scratch-with-demo-data.sql
// Removed all empty short_name="" from concepts
// Added missing description to relationship_type
// Removed all patients and related patient/person info (id 2-500)
executeDataSet("initial-openmrs-dataset.xml");
authenticate();
activator.startup();
}
@After
public void tearDown() throws Exception {
activator.shutdown();
}
@Test
@SkipBaseSetup
public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
+ Context.getService(MotechService.class).saveMessageDefinition(
+ new MessageDefinition("pregnancy.week.8", 21L,
+ MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
- int slush = 2;
+ int slush = 4;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
- .equals("pregnancy.week.7")) {
+ .equals("pregnancy.week.8")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
}
| false | true | public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int slush = 2;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
.equals("pregnancy.week.7")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
| public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.8", 21L,
MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int slush = 4;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
.equals("pregnancy.week.8")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
|
diff --git a/src/com/kurento/kas/mscontrol/join/AudioJoinableStreamImpl.java b/src/com/kurento/kas/mscontrol/join/AudioJoinableStreamImpl.java
index 045e62a..8e804fb 100644
--- a/src/com/kurento/kas/mscontrol/join/AudioJoinableStreamImpl.java
+++ b/src/com/kurento/kas/mscontrol/join/AudioJoinableStreamImpl.java
@@ -1,117 +1,117 @@
package com.kurento.kas.mscontrol.join;
import java.util.Map;
import android.util.Log;
import com.kurento.commons.media.format.SessionSpec;
import com.kurento.commons.media.format.SpecTools;
import com.kurento.commons.mscontrol.MsControlException;
import com.kurento.commons.mscontrol.join.Joinable;
import com.kurento.commons.mscontrol.join.JoinableContainer;
import com.kurento.commons.sdp.enums.MediaType;
import com.kurento.commons.sdp.enums.Mode;
import com.kurento.kas.media.codecs.AudioCodecType;
import com.kurento.kas.media.profiles.AudioProfile;
import com.kurento.kas.media.rx.AudioRx;
import com.kurento.kas.media.rx.MediaRx;
import com.kurento.kas.media.tx.AudioInfoTx;
import com.kurento.kas.media.tx.MediaTx;
import com.kurento.kas.mscontrol.mediacomponent.internal.AudioSink;
import com.kurento.kas.mscontrol.networkconnection.internal.RTPInfo;
public class AudioJoinableStreamImpl extends JoinableStreamBase implements
AudioSink, AudioRx {
public final static String LOG_TAG = "AudioJoinableStream";
private AudioInfoTx audioInfo;
private SessionSpec localSessionSpec;
private AudioRxThread audioRxThread = null;
public AudioInfoTx getAudioInfoTx() {
return audioInfo;
}
public AudioJoinableStreamImpl(JoinableContainer container,
StreamType type, SessionSpec remoteSessionSpec,
SessionSpec localSessionSpec) {
super(container, type);
this.localSessionSpec = localSessionSpec;
Map<MediaType, Mode> mediaTypesModes = SpecTools
.getModesOfFirstMediaTypes(localSessionSpec);
Mode audioMode = mediaTypesModes.get(MediaType.AUDIO);
RTPInfo remoteRTPInfo = new RTPInfo(remoteSessionSpec);
if (audioMode != null) {
AudioCodecType audioCodecType = remoteRTPInfo.getAudioCodecType();
AudioProfile audioProfile = AudioProfile
.getAudioProfileFromAudioCodecType(audioCodecType);
if ((Mode.SENDRECV.equals(audioMode) || Mode.SENDONLY
.equals(audioMode)) && audioProfile != null) {
AudioInfoTx audioInfo = new AudioInfoTx(audioProfile);
audioInfo.setOut(remoteRTPInfo.getAudioRTPDir());
audioInfo.setPayloadType(remoteRTPInfo.getAudioPayloadType());
audioInfo.setFrameSize(MediaTx.initAudio(audioInfo));
if (audioInfo.getFrameSize() < 0) {
- Log.d(LOG_TAG, "Error in initAudio");
+ Log.e(LOG_TAG, "Error in initAudio");
MediaTx.finishAudio();
return;
}
this.audioInfo = audioInfo;
}
if ((Mode.SENDRECV.equals(audioMode) || Mode.RECVONLY
.equals(audioMode))) {
this.audioRxThread = new AudioRxThread(this);
this.audioRxThread.start();
}
}
}
@Override
public void putAudioSamples(short[] in_buffer, int in_size) {
MediaTx.putAudioSamples(in_buffer, in_size);
}
@Override
public void putAudioSamplesRx(byte[] audio, int length) {
try {
for (Joinable j : getJoinees(Direction.SEND))
if (j instanceof AudioRx)
((AudioRx) j).putAudioSamplesRx(audio, length);
} catch (MsControlException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
Log.d(LOG_TAG, "finishAudio");
MediaTx.finishAudio();
Log.d(LOG_TAG, "stopAudioRx");
MediaRx.stopAudioRx();
}
private class AudioRxThread extends Thread {
private AudioRx audioRx;
public AudioRxThread(AudioRx audioRx) {
this.audioRx = audioRx;
}
@Override
public void run() {
Log.d(LOG_TAG, "startVideoRx");
if (!SpecTools.filterMediaByType(localSessionSpec, "audio")
.getMediaSpec().isEmpty()) {
String sdpAudio = SpecTools.filterMediaByType(localSessionSpec,
"audio").toString();
MediaRx.startAudioRx(sdpAudio, this.audioRx);
}
}
}
}
| true | true | public AudioJoinableStreamImpl(JoinableContainer container,
StreamType type, SessionSpec remoteSessionSpec,
SessionSpec localSessionSpec) {
super(container, type);
this.localSessionSpec = localSessionSpec;
Map<MediaType, Mode> mediaTypesModes = SpecTools
.getModesOfFirstMediaTypes(localSessionSpec);
Mode audioMode = mediaTypesModes.get(MediaType.AUDIO);
RTPInfo remoteRTPInfo = new RTPInfo(remoteSessionSpec);
if (audioMode != null) {
AudioCodecType audioCodecType = remoteRTPInfo.getAudioCodecType();
AudioProfile audioProfile = AudioProfile
.getAudioProfileFromAudioCodecType(audioCodecType);
if ((Mode.SENDRECV.equals(audioMode) || Mode.SENDONLY
.equals(audioMode)) && audioProfile != null) {
AudioInfoTx audioInfo = new AudioInfoTx(audioProfile);
audioInfo.setOut(remoteRTPInfo.getAudioRTPDir());
audioInfo.setPayloadType(remoteRTPInfo.getAudioPayloadType());
audioInfo.setFrameSize(MediaTx.initAudio(audioInfo));
if (audioInfo.getFrameSize() < 0) {
Log.d(LOG_TAG, "Error in initAudio");
MediaTx.finishAudio();
return;
}
this.audioInfo = audioInfo;
}
if ((Mode.SENDRECV.equals(audioMode) || Mode.RECVONLY
.equals(audioMode))) {
this.audioRxThread = new AudioRxThread(this);
this.audioRxThread.start();
}
}
}
| public AudioJoinableStreamImpl(JoinableContainer container,
StreamType type, SessionSpec remoteSessionSpec,
SessionSpec localSessionSpec) {
super(container, type);
this.localSessionSpec = localSessionSpec;
Map<MediaType, Mode> mediaTypesModes = SpecTools
.getModesOfFirstMediaTypes(localSessionSpec);
Mode audioMode = mediaTypesModes.get(MediaType.AUDIO);
RTPInfo remoteRTPInfo = new RTPInfo(remoteSessionSpec);
if (audioMode != null) {
AudioCodecType audioCodecType = remoteRTPInfo.getAudioCodecType();
AudioProfile audioProfile = AudioProfile
.getAudioProfileFromAudioCodecType(audioCodecType);
if ((Mode.SENDRECV.equals(audioMode) || Mode.SENDONLY
.equals(audioMode)) && audioProfile != null) {
AudioInfoTx audioInfo = new AudioInfoTx(audioProfile);
audioInfo.setOut(remoteRTPInfo.getAudioRTPDir());
audioInfo.setPayloadType(remoteRTPInfo.getAudioPayloadType());
audioInfo.setFrameSize(MediaTx.initAudio(audioInfo));
if (audioInfo.getFrameSize() < 0) {
Log.e(LOG_TAG, "Error in initAudio");
MediaTx.finishAudio();
return;
}
this.audioInfo = audioInfo;
}
if ((Mode.SENDRECV.equals(audioMode) || Mode.RECVONLY
.equals(audioMode))) {
this.audioRxThread = new AudioRxThread(this);
this.audioRxThread.start();
}
}
}
|
diff --git a/container/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/host/DeleteHostAction.java b/container/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/host/DeleteHostAction.java
index d9b7564f..fb6e893f 100644
--- a/container/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/host/DeleteHostAction.java
+++ b/container/webapps/admin/WEB-INF/classes/org/apache/webapp/admin/host/DeleteHostAction.java
@@ -1,154 +1,154 @@
/*
* 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.webapp.admin.host;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.struts.util.MessageResources;
import org.apache.webapp.admin.ApplicationServlet;
import org.apache.webapp.admin.Lists;
import org.apache.webapp.admin.TomcatTreeBuilder;
/**
* The <code>Action</code> that sets up <em>Delete Hosts</em> transactions.
*
* @author Manveen Kaur
* @version $Revision$ $Date$
*/
public class DeleteHostAction extends Action {
/**
* The MBeanServer we will be interacting with.
*/
private MBeanServer mBServer = null;
// --------------------------------------------------------- Public Methods
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Acquire the resources that we need
Locale locale = getLocale(request);
MessageResources resources = getResources(request);
// Acquire a reference to the MBeanServer containing our MBeans
try {
mBServer = ((ApplicationServlet) getServlet()).getServer();
} catch (Throwable t) {
throw new ServletException
("Cannot acquire MBeanServer reference", t);
}
// Set up a form bean containing the currently selected
// objects to be deleted
HostsForm hostsForm = new HostsForm();
String select = request.getParameter("select");
String domain = null;
if (select != null) {
String hosts[] = new String[1];
hosts[0] = select;
hostsForm.setHosts(hosts);
try {
domain = (new ObjectName(select)).getDomain();
} catch (Exception e) {
throw new ServletException
("Error extracting service name from the host to be deleted", e);
}
}
String adminHost = null;
// Get the host name the admin app runs on
// this host cannot be deleted from the admin tool
try {
adminHost = Lists.getAdminAppHost(
- mBServer, "domain" ,request);
+ mBServer, domain ,request);
} catch (Exception e) {
String message =
resources.getMessage(locale, "error.hostName.bad",
adminHost);
getServlet().log(message);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
return (null);
}
request.setAttribute("adminAppHost", adminHost);
request.setAttribute("hostsForm", hostsForm);
// Accumulate a list of all available hosts
ArrayList list = new ArrayList();
try {
String pattern = domain + TomcatTreeBuilder.HOST_TYPE +
TomcatTreeBuilder.WILDCARD;
Iterator items =
mBServer.queryNames(new ObjectName(pattern), null).iterator();
while (items.hasNext()) {
list.add(items.next().toString());
}
} catch (Exception e) {
getServlet().log
(resources.getMessage(locale, "users.error.select"));
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
resources.getMessage(locale, "users.error.select"));
return (null);
}
Collections.sort(list);
request.setAttribute("hostsList", list);
// Forward to the list display page
return (mapping.findForward("Hosts"));
}
}
| true | true | public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Acquire the resources that we need
Locale locale = getLocale(request);
MessageResources resources = getResources(request);
// Acquire a reference to the MBeanServer containing our MBeans
try {
mBServer = ((ApplicationServlet) getServlet()).getServer();
} catch (Throwable t) {
throw new ServletException
("Cannot acquire MBeanServer reference", t);
}
// Set up a form bean containing the currently selected
// objects to be deleted
HostsForm hostsForm = new HostsForm();
String select = request.getParameter("select");
String domain = null;
if (select != null) {
String hosts[] = new String[1];
hosts[0] = select;
hostsForm.setHosts(hosts);
try {
domain = (new ObjectName(select)).getDomain();
} catch (Exception e) {
throw new ServletException
("Error extracting service name from the host to be deleted", e);
}
}
String adminHost = null;
// Get the host name the admin app runs on
// this host cannot be deleted from the admin tool
try {
adminHost = Lists.getAdminAppHost(
mBServer, "domain" ,request);
} catch (Exception e) {
String message =
resources.getMessage(locale, "error.hostName.bad",
adminHost);
getServlet().log(message);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
return (null);
}
request.setAttribute("adminAppHost", adminHost);
request.setAttribute("hostsForm", hostsForm);
// Accumulate a list of all available hosts
ArrayList list = new ArrayList();
try {
String pattern = domain + TomcatTreeBuilder.HOST_TYPE +
TomcatTreeBuilder.WILDCARD;
Iterator items =
mBServer.queryNames(new ObjectName(pattern), null).iterator();
while (items.hasNext()) {
list.add(items.next().toString());
}
} catch (Exception e) {
getServlet().log
(resources.getMessage(locale, "users.error.select"));
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
resources.getMessage(locale, "users.error.select"));
return (null);
}
Collections.sort(list);
request.setAttribute("hostsList", list);
// Forward to the list display page
return (mapping.findForward("Hosts"));
}
| public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Acquire the resources that we need
Locale locale = getLocale(request);
MessageResources resources = getResources(request);
// Acquire a reference to the MBeanServer containing our MBeans
try {
mBServer = ((ApplicationServlet) getServlet()).getServer();
} catch (Throwable t) {
throw new ServletException
("Cannot acquire MBeanServer reference", t);
}
// Set up a form bean containing the currently selected
// objects to be deleted
HostsForm hostsForm = new HostsForm();
String select = request.getParameter("select");
String domain = null;
if (select != null) {
String hosts[] = new String[1];
hosts[0] = select;
hostsForm.setHosts(hosts);
try {
domain = (new ObjectName(select)).getDomain();
} catch (Exception e) {
throw new ServletException
("Error extracting service name from the host to be deleted", e);
}
}
String adminHost = null;
// Get the host name the admin app runs on
// this host cannot be deleted from the admin tool
try {
adminHost = Lists.getAdminAppHost(
mBServer, domain ,request);
} catch (Exception e) {
String message =
resources.getMessage(locale, "error.hostName.bad",
adminHost);
getServlet().log(message);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
return (null);
}
request.setAttribute("adminAppHost", adminHost);
request.setAttribute("hostsForm", hostsForm);
// Accumulate a list of all available hosts
ArrayList list = new ArrayList();
try {
String pattern = domain + TomcatTreeBuilder.HOST_TYPE +
TomcatTreeBuilder.WILDCARD;
Iterator items =
mBServer.queryNames(new ObjectName(pattern), null).iterator();
while (items.hasNext()) {
list.add(items.next().toString());
}
} catch (Exception e) {
getServlet().log
(resources.getMessage(locale, "users.error.select"));
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
resources.getMessage(locale, "users.error.select"));
return (null);
}
Collections.sort(list);
request.setAttribute("hostsList", list);
// Forward to the list display page
return (mapping.findForward("Hosts"));
}
|
diff --git a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
index 8cc7f4e2..73701d82 100644
--- a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
+++ b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
@@ -1,56 +1,56 @@
package org.apache.ode.bpel.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Matthieu Riou <mriou at apache dot org>
*/
public class CountLRUDehydrationPolicy implements DehydrationPolicy {
/** Maximum age of a process before it is quiesced */
private long _processMaxAge = 20 * 60 * 1000;
/** Maximum process count before oldest ones get quiesced */
private int _processMaxCount = 1000;
public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
- if (p1.getLastUsed() > p2.getLastUsed()) return 1;
- if (p1.getLastUsed() < p2.getLastUsed()) return -1;
+ if (p1.getLastUsed() > p2.getLastUsed()) return -1;
+ if (p1.getLastUsed() < p2.getLastUsed()) return 1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
public void setProcessMaxAge(long processMaxAge) {
_processMaxAge = processMaxAge;
}
public void setProcessMaxCount(int processMaxCount) {
_processMaxCount = processMaxCount;
}
}
| true | true | public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
if (p1.getLastUsed() > p2.getLastUsed()) return 1;
if (p1.getLastUsed() < p2.getLastUsed()) return -1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
| public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
if (p1.getLastUsed() > p2.getLastUsed()) return -1;
if (p1.getLastUsed() < p2.getLastUsed()) return 1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
|
diff --git a/src/com/android/settings/ProgressCategory.java b/src/com/android/settings/ProgressCategory.java
index e854a0038..c1b25d83b 100644
--- a/src/com/android/settings/ProgressCategory.java
+++ b/src/com/android/settings/ProgressCategory.java
@@ -1,72 +1,72 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class ProgressCategory extends ProgressCategoryBase {
private boolean mProgress = false;
private Preference mNoDeviceFoundPreference;
private boolean mNoDeviceFoundAdded;
public ProgressCategory(Context context, AttributeSet attrs) {
super(context, attrs);
setLayoutResource(R.layout.preference_progress_category);
}
@Override
public void onBindView(View view) {
super.onBindView(view);
- final TextView textView = (TextView) view.findViewById(R.id.scanning_text);
+ final TextView scanning = (TextView) view.findViewById(R.id.scanning_text);
final View progressBar = view.findViewById(R.id.scanning_progress);
- textView.setText(mProgress ? R.string.progress_scanning : R.string.progress_tap_to_pair);
+ scanning.setText(mProgress ? R.string.progress_scanning : R.string.progress_tap_to_pair);
boolean noDeviceFound = (getPreferenceCount() == 0 ||
(getPreferenceCount() == 1 && getPreference(0) == mNoDeviceFoundPreference));
- textView.setVisibility(noDeviceFound ? View.INVISIBLE : View.VISIBLE);
- progressBar.setVisibility(mProgress ? View.VISIBLE : View.INVISIBLE);
+ scanning.setVisibility(noDeviceFound ? View.GONE : View.VISIBLE);
+ progressBar.setVisibility(mProgress ? View.VISIBLE : View.GONE);
if (mProgress || !noDeviceFound) {
if (mNoDeviceFoundAdded) {
removePreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = false;
}
} else {
if (!mNoDeviceFoundAdded) {
if (mNoDeviceFoundPreference == null) {
mNoDeviceFoundPreference = new Preference(getContext());
mNoDeviceFoundPreference.setLayoutResource(R.layout.preference_empty_list);
mNoDeviceFoundPreference.setTitle(R.string.bluetooth_no_devices_found);
mNoDeviceFoundPreference.setSelectable(false);
}
addPreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = true;
}
}
}
@Override
public void setProgress(boolean progressOn) {
mProgress = progressOn;
notifyChanged();
}
}
| false | true | public void onBindView(View view) {
super.onBindView(view);
final TextView textView = (TextView) view.findViewById(R.id.scanning_text);
final View progressBar = view.findViewById(R.id.scanning_progress);
textView.setText(mProgress ? R.string.progress_scanning : R.string.progress_tap_to_pair);
boolean noDeviceFound = (getPreferenceCount() == 0 ||
(getPreferenceCount() == 1 && getPreference(0) == mNoDeviceFoundPreference));
textView.setVisibility(noDeviceFound ? View.INVISIBLE : View.VISIBLE);
progressBar.setVisibility(mProgress ? View.VISIBLE : View.INVISIBLE);
if (mProgress || !noDeviceFound) {
if (mNoDeviceFoundAdded) {
removePreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = false;
}
} else {
if (!mNoDeviceFoundAdded) {
if (mNoDeviceFoundPreference == null) {
mNoDeviceFoundPreference = new Preference(getContext());
mNoDeviceFoundPreference.setLayoutResource(R.layout.preference_empty_list);
mNoDeviceFoundPreference.setTitle(R.string.bluetooth_no_devices_found);
mNoDeviceFoundPreference.setSelectable(false);
}
addPreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = true;
}
}
}
| public void onBindView(View view) {
super.onBindView(view);
final TextView scanning = (TextView) view.findViewById(R.id.scanning_text);
final View progressBar = view.findViewById(R.id.scanning_progress);
scanning.setText(mProgress ? R.string.progress_scanning : R.string.progress_tap_to_pair);
boolean noDeviceFound = (getPreferenceCount() == 0 ||
(getPreferenceCount() == 1 && getPreference(0) == mNoDeviceFoundPreference));
scanning.setVisibility(noDeviceFound ? View.GONE : View.VISIBLE);
progressBar.setVisibility(mProgress ? View.VISIBLE : View.GONE);
if (mProgress || !noDeviceFound) {
if (mNoDeviceFoundAdded) {
removePreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = false;
}
} else {
if (!mNoDeviceFoundAdded) {
if (mNoDeviceFoundPreference == null) {
mNoDeviceFoundPreference = new Preference(getContext());
mNoDeviceFoundPreference.setLayoutResource(R.layout.preference_empty_list);
mNoDeviceFoundPreference.setTitle(R.string.bluetooth_no_devices_found);
mNoDeviceFoundPreference.setSelectable(false);
}
addPreference(mNoDeviceFoundPreference);
mNoDeviceFoundAdded = true;
}
}
}
|
diff --git a/test/src/test/java/hudson/tasks/MailerTest.java b/test/src/test/java/hudson/tasks/MailerTest.java
index bbde7bed8..4cfbb166b 100644
--- a/test/src/test/java/hudson/tasks/MailerTest.java
+++ b/test/src/test/java/hudson/tasks/MailerTest.java
@@ -1,128 +1,128 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import hudson.model.FreeStyleProject;
import hudson.tasks.Mailer.DescriptorImpl;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.Email;
import org.jvnet.mock_javamail.Mailbox;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
/**
* @author Kohsuke Kawaguchi
*/
public class MailerTest extends HudsonTestCase {
@Bug(1566)
public void testSenderAddress() throws Exception {
// intentionally give the whole thin in a double quote
Mailer.descriptor().setAdminAddress("\"me <[email protected]>\"");
String recipient = "you <[email protected]>";
Mailbox yourInbox = Mailbox.get(new InternetAddress(recipient));
yourInbox.clear();
// create a project to simulate a build failure
FreeStyleProject project = createFreeStyleProject();
project.getBuildersList().add(new FailureBuilder());
Mailer m = new Mailer();
m.recipients = recipient;
project.getPublishersList().add(m);
project.scheduleBuild2(0).get();
assertEquals(1,yourInbox.size());
Address[] senders = yourInbox.get(0).getFrom();
assertEquals(1,senders.length);
assertEquals("me <[email protected]>",senders[0].toString());
}
/**
* Makes sure the use of "localhost" in the Hudson URL reports a warning.
*/
public void testLocalHostWarning() throws Exception {
HtmlPage p = new WebClient().goTo("configure");
HtmlInput url = p.getFormByName("config").getInputByName("_.url");
url.setValueAttribute("http://localhost:1234/");
assertTrue(p.getDocumentElement().getTextContent().contains("instead of localhost"));
}
@Email("http://www.nabble.com/email-recipients-disappear-from-freestyle-job-config-on-save-to25479293.html")
public void testConfigRoundtrip() throws Exception {
Mailer m = new Mailer();
m.recipients = "[email protected]";
m.dontNotifyEveryUnstableBuild = true;
m.sendToIndividuals = true;
verifyRoundtrip(m);
m = new Mailer();
m.recipients = "";
m.dontNotifyEveryUnstableBuild = false;
m.sendToIndividuals = false;
verifyRoundtrip(m);
}
private void verifyRoundtrip(Mailer m) throws Exception {
FreeStyleProject p = createFreeStyleProject();
p.getPublishersList().add(m);
submit(new WebClient().getPage(p,"configure").getFormByName("config"));
assertEqualBeans(m,p.getPublishersList().get(Mailer.class),"recipients,dontNotifyEveryUnstableBuild,sendToIndividuals");
}
public void testGlobalConfigRoundtrip() throws Exception {
DescriptorImpl d = Mailer.descriptor();
d.setAdminAddress("admin@me");
d.setDefaultSuffix("default-suffix");
d.setHudsonUrl("http://nowhere/");
d.setSmtpHost("smtp.host");
d.setSmtpPort("1025");
d.setUseSsl(true);
d.setSmtpAuth("user","pass");
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals("admin@me",d.getAdminAddress());
assertEquals("default-suffix",d.getDefaultSuffix());
assertEquals("http://nowhere/",d.getUrl());
assertEquals("smtp.host",d.getSmtpServer());
assertEquals("1025",d.getSmtpPort());
assertEquals(true,d.getUseSsl());
assertEquals("user",d.getSmtpAuthUserName());
assertEquals("pass",d.getSmtpAuthPassword());
d.setUseSsl(false);
d.setSmtpAuth(null,null);
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals(false,d.getUseSsl());
assertNull("expected null, got: " + d.getSmtpAuthUserName(), d.getSmtpAuthUserName());
- assertEquals("", d.getSmtpAuthPassword());
+ assertNull("expected null, got: " + d.getSmtpAuthPassword(), d.getSmtpAuthPassword());
}
}
| true | true | public void testGlobalConfigRoundtrip() throws Exception {
DescriptorImpl d = Mailer.descriptor();
d.setAdminAddress("admin@me");
d.setDefaultSuffix("default-suffix");
d.setHudsonUrl("http://nowhere/");
d.setSmtpHost("smtp.host");
d.setSmtpPort("1025");
d.setUseSsl(true);
d.setSmtpAuth("user","pass");
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals("admin@me",d.getAdminAddress());
assertEquals("default-suffix",d.getDefaultSuffix());
assertEquals("http://nowhere/",d.getUrl());
assertEquals("smtp.host",d.getSmtpServer());
assertEquals("1025",d.getSmtpPort());
assertEquals(true,d.getUseSsl());
assertEquals("user",d.getSmtpAuthUserName());
assertEquals("pass",d.getSmtpAuthPassword());
d.setUseSsl(false);
d.setSmtpAuth(null,null);
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals(false,d.getUseSsl());
assertNull("expected null, got: " + d.getSmtpAuthUserName(), d.getSmtpAuthUserName());
assertEquals("", d.getSmtpAuthPassword());
}
| public void testGlobalConfigRoundtrip() throws Exception {
DescriptorImpl d = Mailer.descriptor();
d.setAdminAddress("admin@me");
d.setDefaultSuffix("default-suffix");
d.setHudsonUrl("http://nowhere/");
d.setSmtpHost("smtp.host");
d.setSmtpPort("1025");
d.setUseSsl(true);
d.setSmtpAuth("user","pass");
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals("admin@me",d.getAdminAddress());
assertEquals("default-suffix",d.getDefaultSuffix());
assertEquals("http://nowhere/",d.getUrl());
assertEquals("smtp.host",d.getSmtpServer());
assertEquals("1025",d.getSmtpPort());
assertEquals(true,d.getUseSsl());
assertEquals("user",d.getSmtpAuthUserName());
assertEquals("pass",d.getSmtpAuthPassword());
d.setUseSsl(false);
d.setSmtpAuth(null,null);
submit(new WebClient().goTo("configure").getFormByName("config"));
assertEquals(false,d.getUseSsl());
assertNull("expected null, got: " + d.getSmtpAuthUserName(), d.getSmtpAuthUserName());
assertNull("expected null, got: " + d.getSmtpAuthPassword(), d.getSmtpAuthPassword());
}
|
diff --git a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java
index 7eab80cdd..89b0b0648 100644
--- a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java
+++ b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java
@@ -1,122 +1,121 @@
/*******************************************************************************
* Copyright (c) 2010 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.core;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.jboss.tools.cdi.internal.core.impl.EventBean;
public class CDIImages {
private static CDIImages INSTANCE;
static {
try {
INSTANCE = new CDIImages(new URL(CDICorePlugin.getDefault().getBundle().getEntry("/"), "images/")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (MalformedURLException e) {
CDICorePlugin.getDefault().logError(e);
}
}
public static final Image CDI_BEAN_IMAGE = getImage("search/cdi_bean.gif"); //$NON-NLS-1$
public static final Image WELD_IMAGE = getImage("search/weld_icon_16x.gif"); //$NON-NLS-1$
public static final Image BEAN_CLASS_IMAGE = getImage("bean_class.png"); //$NON-NLS-1$
public static final Image BEAN_METHOD_IMAGE = getImage("bean_method.png"); //$NON-NLS-1$
public static final Image BEAN_FIELD_IMAGE = getImage("bean_field.png"); //$NON-NLS-1$
public static final Image INJECTION_POINT_IMAGE = getImage("injection_point.png"); //$NON-NLS-1$
public static final Image ANNOTATION_IMAGE = getImage("annotation.png"); //$NON-NLS-1$
public static final Image CDI_EVENT_IMAGE = getImage("event.png"); //$NON-NLS-1$
public static final Image QUICKFIX_ADD = getImage("quickfixes/cdi_add.png"); //$NON-NLS-1$
public static final Image QUICKFIX_REMOVE = getImage("quickfixes/cdi_remove.png"); //$NON-NLS-1$
public static final Image QUICKFIX_EDIT = getImage("quickfixes/cdi_edit.png"); //$NON-NLS-1$
public static final Image QUICKFIX_CHANGE = getImage("quickfixes/cdi_change.png"); //$NON-NLS-1$
public static final String WELD_WIZARD_IMAGE_PATH = "wizard/WeldWizBan.gif"; //$NON-NLS-1$
public static Image getImage(String key) {
return INSTANCE.createImageDescriptor(key).createImage();
}
public static ImageDescriptor getImageDescriptor(String key) {
return INSTANCE.createImageDescriptor(key);
}
public static void setImageDescriptors(IAction action, String iconName) {
action.setImageDescriptor(INSTANCE.createImageDescriptor(iconName));
}
public static CDIImages getInstance() {
return INSTANCE;
}
private URL baseUrl;
private CDIImages parentRegistry;
protected CDIImages(URL registryUrl, CDIImages parent){
if(registryUrl == null) throw new IllegalArgumentException(CDICoreMessages.CDI_IMAGESBASE_URL_FOR_IMAGE_REGISTRY_CANNOT_BE_NULL);
baseUrl = registryUrl;
parentRegistry = parent;
}
protected CDIImages(URL url){
this(url,null);
}
public Image getImageByFileName(String key) {
return createImageDescriptor(key).createImage();
}
public ImageDescriptor createImageDescriptor(String key) {
try {
return ImageDescriptor.createFromURL(makeIconFileURL(key));
} catch (MalformedURLException e) {
if(parentRegistry == null) {
return ImageDescriptor.getMissingImageDescriptor();
} else {
return parentRegistry.createImageDescriptor(key);
}
}
}
private URL makeIconFileURL(String name) throws MalformedURLException {
if (name == null) throw new MalformedURLException(CDICoreMessages.CDI_IMAGESIMAGE_NAME_CANNOT_BE_NULL);
return new URL(baseUrl, name);
}
public static Image getImageByElement(ICDIElement element){
if(element instanceof IClassBean){
return BEAN_CLASS_IMAGE;
}else if(element instanceof IInjectionPoint){
return INJECTION_POINT_IMAGE;
}else if(element instanceof ICDIAnnotation){
return ANNOTATION_IMAGE;
}else if(element instanceof EventBean){
return CDI_EVENT_IMAGE;
}else if(element instanceof IBeanMethod){
return BEAN_METHOD_IMAGE;
}else if(element instanceof IBeanField){
return BEAN_FIELD_IMAGE;
}
- System.out.println("NO IMAGE for - "+element.getClass());
return WELD_IMAGE;
}
}
| true | true | public static Image getImageByElement(ICDIElement element){
if(element instanceof IClassBean){
return BEAN_CLASS_IMAGE;
}else if(element instanceof IInjectionPoint){
return INJECTION_POINT_IMAGE;
}else if(element instanceof ICDIAnnotation){
return ANNOTATION_IMAGE;
}else if(element instanceof EventBean){
return CDI_EVENT_IMAGE;
}else if(element instanceof IBeanMethod){
return BEAN_METHOD_IMAGE;
}else if(element instanceof IBeanField){
return BEAN_FIELD_IMAGE;
}
System.out.println("NO IMAGE for - "+element.getClass());
return WELD_IMAGE;
}
| public static Image getImageByElement(ICDIElement element){
if(element instanceof IClassBean){
return BEAN_CLASS_IMAGE;
}else if(element instanceof IInjectionPoint){
return INJECTION_POINT_IMAGE;
}else if(element instanceof ICDIAnnotation){
return ANNOTATION_IMAGE;
}else if(element instanceof EventBean){
return CDI_EVENT_IMAGE;
}else if(element instanceof IBeanMethod){
return BEAN_METHOD_IMAGE;
}else if(element instanceof IBeanField){
return BEAN_FIELD_IMAGE;
}
return WELD_IMAGE;
}
|
diff --git a/src/com/oresomecraft/BattleMaps/maps/ClashOfClayII.java b/src/com/oresomecraft/BattleMaps/maps/ClashOfClayII.java
index 86eb06b..82306a6 100644
--- a/src/com/oresomecraft/BattleMaps/maps/ClashOfClayII.java
+++ b/src/com/oresomecraft/BattleMaps/maps/ClashOfClayII.java
@@ -1,129 +1,129 @@
package com.oresomecraft.BattleMaps.maps;
import java.util.List;
import com.oresomecraft.BattleMaps.IBattleMap;
import com.oresomecraft.BattleMaps.api.InvUtils;
import com.oresomecraft.OresomeBattles.BattlePlayer;
import com.oresomecraft.OresomeBattles.gamemodes.TDM;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.oresomecraft.BattleMaps.BattleMap;
import com.oresomecraft.OresomeBattles.Gamemode;
import com.oresomecraft.OresomeBattles.events.InventoryEvent;
public class ClashOfClayII extends BattleMap implements IBattleMap, Listener {
public ClashOfClayII() {
super.initiate(this);
setDetails(name, fullName, creators, modes);
}
String name = "clashofclayii";
String fullName = "Clash Of Clay II";
String creators = "_Moist and R3creat3";
Gamemode[] modes = {Gamemode.TDM};
public void readyTDMSpawns() {
World w = Bukkit.getServer().getWorld(name);
Location redSpawn = new Location(w, 20, 77, -25);
Location blueSpawn = new Location(w, 250, 77, -27);
redSpawns.add(redSpawn);
blueSpawns.add(blueSpawn);
setRedSpawns(name, redSpawns);
setBlueSpawns(name, blueSpawns);
}
public void readyFFASpawns() {
World w = Bukkit.getServer().getWorld(name);
Location redSpawn = new Location(w, 20, 77, -25);
Location blueSpawn = new Location(w, 250, 77, -27);
FFASpawns.add(blueSpawn);
FFASpawns.add(redSpawn);
setFFASpawns(name, FFASpawns);
}
@EventHandler(priority = EventPriority.NORMAL)
public void applyInventory(InventoryEvent event) {
if (event.getMessage().equalsIgnoreCase(name)) {
final BattlePlayer p = event.getPlayer();
Inventory i = p.getInventory();
clearInv(p);
ItemStack WOODEN_SWORD = new ItemStack(Material.WOOD_SWORD, 1, (short) -16373);
ItemStack BOW = new ItemStack(Material.BOW, 1);
ItemStack IRON_PICKAXE = new ItemStack(Material.IRON_PICKAXE, 1, (short) -1400);
ItemStack PUMPKIN_PIE = new ItemStack(Material.PUMPKIN_PIE, 5);
ItemStack APPLE = new ItemStack(Material.GOLDEN_APPLE, 2);
ItemStack BLUE_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 11);
ItemStack RED_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 14);
ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
LEATHER_CHESTPLATE.addEnchantment(Enchantment.PROTECTION_PROJECTILE, 2);
ItemStack DIAMOND_HELMET = new ItemStack(Material.DIAMOND_HELMET, 1);
ItemStack TORCH = new ItemStack(Material.TORCH, 16);
ItemStack ARROW = new ItemStack(Material.ARROW, 1);
- p.getInventory().setChestplate(LEATHER_CHESTPLATE);
p.getInventory().setHelmet(DIAMOND_HELMET);
BOW.addEnchantment(Enchantment.ARROW_INFINITE, 1);
InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE});
+ p.getInventory().setChestplate(LEATHER_CHESTPLATE);
i.setItem(0, WOODEN_SWORD);
i.setItem(1, BOW);
i.setItem(2, IRON_PICKAXE);
i.setItem(3, PUMPKIN_PIE);
i.setItem(4, APPLE);
if (TDM.isRed(p.getName())) {
i.setItem(5, RED_STAINED_CLAY);
}
if (TDM.isBlue(p.getName())) {
i.setItem(5, BLUE_STAINED_CLAY);
}
i.setItem(6, TORCH);
i.setItem(27, ARROW);
}
}
// Region. (Top corner block and bottom corner block.
// Top left corner.
public int x1 = -100;
public int y1 = 160;
public int z1 = -70;
//Bottom right corner.
public int x2 = -70;
public int y2 = 30;
public int z2 = 50;
@EventHandler
public void death(org.bukkit.event.entity.PlayerDeathEvent event) {
Player p = event.getEntity();
List<ItemStack> drops = event.getDrops();
for (ItemStack item : drops) {
Material mat = item.getType();
if (mat == Material.DIAMOND_HELMET || mat == Material.WOOD_SWORD) {
item.setType(Material.AIR);
}
}
}
}
| false | true | public void applyInventory(InventoryEvent event) {
if (event.getMessage().equalsIgnoreCase(name)) {
final BattlePlayer p = event.getPlayer();
Inventory i = p.getInventory();
clearInv(p);
ItemStack WOODEN_SWORD = new ItemStack(Material.WOOD_SWORD, 1, (short) -16373);
ItemStack BOW = new ItemStack(Material.BOW, 1);
ItemStack IRON_PICKAXE = new ItemStack(Material.IRON_PICKAXE, 1, (short) -1400);
ItemStack PUMPKIN_PIE = new ItemStack(Material.PUMPKIN_PIE, 5);
ItemStack APPLE = new ItemStack(Material.GOLDEN_APPLE, 2);
ItemStack BLUE_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 11);
ItemStack RED_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 14);
ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
LEATHER_CHESTPLATE.addEnchantment(Enchantment.PROTECTION_PROJECTILE, 2);
ItemStack DIAMOND_HELMET = new ItemStack(Material.DIAMOND_HELMET, 1);
ItemStack TORCH = new ItemStack(Material.TORCH, 16);
ItemStack ARROW = new ItemStack(Material.ARROW, 1);
p.getInventory().setChestplate(LEATHER_CHESTPLATE);
p.getInventory().setHelmet(DIAMOND_HELMET);
BOW.addEnchantment(Enchantment.ARROW_INFINITE, 1);
InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE});
i.setItem(0, WOODEN_SWORD);
i.setItem(1, BOW);
i.setItem(2, IRON_PICKAXE);
i.setItem(3, PUMPKIN_PIE);
i.setItem(4, APPLE);
if (TDM.isRed(p.getName())) {
i.setItem(5, RED_STAINED_CLAY);
}
if (TDM.isBlue(p.getName())) {
i.setItem(5, BLUE_STAINED_CLAY);
}
i.setItem(6, TORCH);
i.setItem(27, ARROW);
}
}
| public void applyInventory(InventoryEvent event) {
if (event.getMessage().equalsIgnoreCase(name)) {
final BattlePlayer p = event.getPlayer();
Inventory i = p.getInventory();
clearInv(p);
ItemStack WOODEN_SWORD = new ItemStack(Material.WOOD_SWORD, 1, (short) -16373);
ItemStack BOW = new ItemStack(Material.BOW, 1);
ItemStack IRON_PICKAXE = new ItemStack(Material.IRON_PICKAXE, 1, (short) -1400);
ItemStack PUMPKIN_PIE = new ItemStack(Material.PUMPKIN_PIE, 5);
ItemStack APPLE = new ItemStack(Material.GOLDEN_APPLE, 2);
ItemStack BLUE_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 11);
ItemStack RED_STAINED_CLAY = new ItemStack(Material.STAINED_CLAY, 48, (short) 14);
ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
LEATHER_CHESTPLATE.addEnchantment(Enchantment.PROTECTION_PROJECTILE, 2);
ItemStack DIAMOND_HELMET = new ItemStack(Material.DIAMOND_HELMET, 1);
ItemStack TORCH = new ItemStack(Material.TORCH, 16);
ItemStack ARROW = new ItemStack(Material.ARROW, 1);
p.getInventory().setHelmet(DIAMOND_HELMET);
BOW.addEnchantment(Enchantment.ARROW_INFINITE, 1);
InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE});
p.getInventory().setChestplate(LEATHER_CHESTPLATE);
i.setItem(0, WOODEN_SWORD);
i.setItem(1, BOW);
i.setItem(2, IRON_PICKAXE);
i.setItem(3, PUMPKIN_PIE);
i.setItem(4, APPLE);
if (TDM.isRed(p.getName())) {
i.setItem(5, RED_STAINED_CLAY);
}
if (TDM.isBlue(p.getName())) {
i.setItem(5, BLUE_STAINED_CLAY);
}
i.setItem(6, TORCH);
i.setItem(27, ARROW);
}
}
|
diff --git a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/DistroPkgFinder/DebianPkgFinderJsoupRunner.java b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/DistroPkgFinder/DebianPkgFinderJsoupRunner.java
index 59a8262..b2f9f06 100644
--- a/ManalithBot/src/main/java/org/manalith/ircbot/plugin/DistroPkgFinder/DebianPkgFinderJsoupRunner.java
+++ b/ManalithBot/src/main/java/org/manalith/ircbot/plugin/DistroPkgFinder/DebianPkgFinderJsoupRunner.java
@@ -1,99 +1,100 @@
package org.manalith.ircbot.plugin.DistroPkgFinder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class DebianPkgFinderJsoupRunner {
private String keyword;
public DebianPkgFinderJsoupRunner ( )
{
this.setKeyword( "" );
}
public DebianPkgFinderJsoupRunner ( String newKeyword )
{
this.setKeyword(newKeyword);
}
public void setKeyword ( String newKeyword )
{
this.keyword = newKeyword;
}
public String getKeyword ( )
{
return this.keyword;
}
public String run ( )
{
String result = "";
String url = "http://packages.debian.org/search?keywords=" + this.getKeyword() + "&searchon=names&suite=all§ion=all";
boolean hasExacthits = false;
String pkgname = "";
String version = "";
String description = "";
try
{
Document doc = Jsoup.connect(url).get();
if ( doc.select("#psearchres").size() == 0 )
{
result = "There is no result";
return result;
}
Elements hits = doc.select("#psearchres").select("h2");
int hsize = hits.size();
if ( hsize == 0 )
result = "There is no result";
for ( int i = 0 ; i < hsize ; i++ )
{
if ( hits.get(i).text().equals("Exact hits") )
{
hasExacthits = true;
break;
}
}
if ( !hasExacthits )
{
result = "There is no result";
return result;
}
pkgname = doc.select("#psearchres").select("h3").get(0).text().split("\\s")[1];
result = pkgname + "-";
Elements ExactHits = doc.select("#psearchres").select("ul").get(0).select("li");
int elemCnt = ExactHits.size();
+ if ( ExactHits.get(elemCnt - 1).select("a").text().contains("experimental")) elemCnt--;
Element latestElement = ExactHits.get(elemCnt - 1);
String [] verSplit = latestElement.toString().split("\\<br\\s\\/>")[1].split("\\:");
if ( verSplit.length == 2 )
version = verSplit[0];
else if ( verSplit.length == 3)
version = verSplit[1];
result += version + " : ";
description = latestElement.toString().split("\\<br\\s\\/>")[0].split("\\:")[1].trim();
result += description;
}
catch ( Exception e )
{
result = e.getMessage();
return result;
}
return result;
}
}
| true | true | public String run ( )
{
String result = "";
String url = "http://packages.debian.org/search?keywords=" + this.getKeyword() + "&searchon=names&suite=all§ion=all";
boolean hasExacthits = false;
String pkgname = "";
String version = "";
String description = "";
try
{
Document doc = Jsoup.connect(url).get();
if ( doc.select("#psearchres").size() == 0 )
{
result = "There is no result";
return result;
}
Elements hits = doc.select("#psearchres").select("h2");
int hsize = hits.size();
if ( hsize == 0 )
result = "There is no result";
for ( int i = 0 ; i < hsize ; i++ )
{
if ( hits.get(i).text().equals("Exact hits") )
{
hasExacthits = true;
break;
}
}
if ( !hasExacthits )
{
result = "There is no result";
return result;
}
pkgname = doc.select("#psearchres").select("h3").get(0).text().split("\\s")[1];
result = pkgname + "-";
Elements ExactHits = doc.select("#psearchres").select("ul").get(0).select("li");
int elemCnt = ExactHits.size();
Element latestElement = ExactHits.get(elemCnt - 1);
String [] verSplit = latestElement.toString().split("\\<br\\s\\/>")[1].split("\\:");
if ( verSplit.length == 2 )
version = verSplit[0];
else if ( verSplit.length == 3)
version = verSplit[1];
result += version + " : ";
description = latestElement.toString().split("\\<br\\s\\/>")[0].split("\\:")[1].trim();
result += description;
}
catch ( Exception e )
{
result = e.getMessage();
return result;
}
return result;
}
| public String run ( )
{
String result = "";
String url = "http://packages.debian.org/search?keywords=" + this.getKeyword() + "&searchon=names&suite=all§ion=all";
boolean hasExacthits = false;
String pkgname = "";
String version = "";
String description = "";
try
{
Document doc = Jsoup.connect(url).get();
if ( doc.select("#psearchres").size() == 0 )
{
result = "There is no result";
return result;
}
Elements hits = doc.select("#psearchres").select("h2");
int hsize = hits.size();
if ( hsize == 0 )
result = "There is no result";
for ( int i = 0 ; i < hsize ; i++ )
{
if ( hits.get(i).text().equals("Exact hits") )
{
hasExacthits = true;
break;
}
}
if ( !hasExacthits )
{
result = "There is no result";
return result;
}
pkgname = doc.select("#psearchres").select("h3").get(0).text().split("\\s")[1];
result = pkgname + "-";
Elements ExactHits = doc.select("#psearchres").select("ul").get(0).select("li");
int elemCnt = ExactHits.size();
if ( ExactHits.get(elemCnt - 1).select("a").text().contains("experimental")) elemCnt--;
Element latestElement = ExactHits.get(elemCnt - 1);
String [] verSplit = latestElement.toString().split("\\<br\\s\\/>")[1].split("\\:");
if ( verSplit.length == 2 )
version = verSplit[0];
else if ( verSplit.length == 3)
version = verSplit[1];
result += version + " : ";
description = latestElement.toString().split("\\<br\\s\\/>")[0].split("\\:")[1].trim();
result += description;
}
catch ( Exception e )
{
result = e.getMessage();
return result;
}
return result;
}
|
diff --git a/beam-gpf/src/main/java/org/esa/beam/framework/gpf/annotations/ParameterDefinitionFactory.java b/beam-gpf/src/main/java/org/esa/beam/framework/gpf/annotations/ParameterDefinitionFactory.java
index fa318ce36..a9003a1e8 100644
--- a/beam-gpf/src/main/java/org/esa/beam/framework/gpf/annotations/ParameterDefinitionFactory.java
+++ b/beam-gpf/src/main/java/org/esa/beam/framework/gpf/annotations/ParameterDefinitionFactory.java
@@ -1,138 +1,138 @@
package org.esa.beam.framework.gpf.annotations;
import com.bc.ceres.binding.*;
import org.esa.beam.framework.gpf.GPF;
import org.esa.beam.framework.gpf.Operator;
import org.esa.beam.framework.gpf.OperatorSpi;
import org.esa.beam.framework.gpf.OperatorSpiRegistry;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.regex.Pattern;
public class ParameterDefinitionFactory implements ValueDefinitionFactory {
public ParameterDefinitionFactory() {
}
public ValueDefinition createValueDefinition(Field field) {
try {
return createValueDefinitionImpl(field);
} catch (ConversionException e) {
throw new IllegalArgumentException("field", e);
}
}
private ValueDefinition createValueDefinitionImpl(Field field) throws ConversionException {
final boolean operatorDetected = Operator.class.isAssignableFrom(field.getDeclaringClass());
Parameter parameter = field.getAnnotation(Parameter.class);
if (operatorDetected && parameter == null) {
return null;
}
ValueDefinition valueDefinition = new ValueDefinition(field.getName(), field.getType());
if (parameter == null) {
return valueDefinition;
}
if (parameter.validator() != Validator.class) {
final Validator validator;
try {
validator = parameter.validator().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create validator.", t);
}
valueDefinition.setValidator(validator);
}
if (parameter.converter() != Converter.class) {
Converter converter;
try {
converter = parameter.converter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create converter.", t);
}
valueDefinition.setConverter(converter);
}
if (valueDefinition.getConverter() == null) {
valueDefinition.setConverter(ConverterRegistry.getInstance().getConverter(valueDefinition.getType()));
}
if (parameter.itemConverter() != Converter.class) {
Converter converter;
try {
converter = parameter.itemConverter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create item converter.", t);
}
valueDefinition.setItemConverter(converter);
}
if (ParameterDefinitionFactory.isSet(parameter.label())) {
valueDefinition.setDisplayName(parameter.label());
} else {
valueDefinition.setDisplayName(field.getName());
}
if (ParameterDefinitionFactory.isSet(parameter.alias())) {
valueDefinition.setAlias(parameter.alias());
}
if (ParameterDefinitionFactory.isSet(parameter.itemAlias())) {
- valueDefinition.setItemAlias(parameter.alias());
+ valueDefinition.setItemAlias(parameter.itemAlias());
}
valueDefinition.setItemsInlined(parameter.itemsInlined());
valueDefinition.setUnit(parameter.unit());
valueDefinition.setDescription(parameter.description());
valueDefinition.setNotNull(parameter.notNull());
valueDefinition.setNotEmpty(parameter.notEmpty());
if (isSet(parameter.pattern())) {
Pattern pattern = Pattern.compile(parameter.pattern());
valueDefinition.setPattern(pattern);
}
if (isSet(parameter.interval())) {
Interval interval = Interval.parseInterval(parameter.interval());
valueDefinition.setInterval(interval);
}
if (isSet(parameter.format())) {
valueDefinition.setFormat(parameter.format());
}
if (isSet(parameter.valueSet())) {
Converter converter = valueDefinition.getConverter();
ValueSet valueSet = ValueSet.parseValueSet(parameter.valueSet(), converter);
valueDefinition.setValueSet(valueSet);
}
if (isSet(parameter.defaultValue())) {
Converter converter = valueDefinition.getConverter();
valueDefinition.setDefaultValue(converter.parse(parameter.defaultValue()));
}
return valueDefinition;
}
public static ValueContainer createMapBackedOperatorValueContainer(String operatorName, Map<String, Object> operatorParameters) {
final OperatorSpiRegistry registry = GPF.getDefaultInstance().getOperatorSpiRegistry();
registry.loadOperatorSpis();
OperatorSpi operatorSpi = registry.getOperatorSpi(operatorName);
if (operatorSpi == null) {
throw new IllegalStateException("Operator SPI not found for operator [" + operatorName + "]");
}
Class<? extends Operator> operatorClass = operatorSpi.getOperatorClass();
ValueContainerFactory factory = new ValueContainerFactory(new ParameterDefinitionFactory());
return factory.createMapBackedValueContainer(operatorClass, operatorParameters);
}
private static boolean isNull(Object value) {
return value == null;
}
private static boolean isEmpty(String value) {
return value.isEmpty();
}
private static boolean isEmpty(String[] value) {
return value.length == 0;
}
private static boolean isSet(String value) {
return !ParameterDefinitionFactory.isNull(value) && !ParameterDefinitionFactory.isEmpty(value);
}
private static boolean isSet(String[] value) {
return !ParameterDefinitionFactory.isNull(value) && !ParameterDefinitionFactory.isEmpty(value);
}
}
| true | true | private ValueDefinition createValueDefinitionImpl(Field field) throws ConversionException {
final boolean operatorDetected = Operator.class.isAssignableFrom(field.getDeclaringClass());
Parameter parameter = field.getAnnotation(Parameter.class);
if (operatorDetected && parameter == null) {
return null;
}
ValueDefinition valueDefinition = new ValueDefinition(field.getName(), field.getType());
if (parameter == null) {
return valueDefinition;
}
if (parameter.validator() != Validator.class) {
final Validator validator;
try {
validator = parameter.validator().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create validator.", t);
}
valueDefinition.setValidator(validator);
}
if (parameter.converter() != Converter.class) {
Converter converter;
try {
converter = parameter.converter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create converter.", t);
}
valueDefinition.setConverter(converter);
}
if (valueDefinition.getConverter() == null) {
valueDefinition.setConverter(ConverterRegistry.getInstance().getConverter(valueDefinition.getType()));
}
if (parameter.itemConverter() != Converter.class) {
Converter converter;
try {
converter = parameter.itemConverter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create item converter.", t);
}
valueDefinition.setItemConverter(converter);
}
if (ParameterDefinitionFactory.isSet(parameter.label())) {
valueDefinition.setDisplayName(parameter.label());
} else {
valueDefinition.setDisplayName(field.getName());
}
if (ParameterDefinitionFactory.isSet(parameter.alias())) {
valueDefinition.setAlias(parameter.alias());
}
if (ParameterDefinitionFactory.isSet(parameter.itemAlias())) {
valueDefinition.setItemAlias(parameter.alias());
}
valueDefinition.setItemsInlined(parameter.itemsInlined());
valueDefinition.setUnit(parameter.unit());
valueDefinition.setDescription(parameter.description());
valueDefinition.setNotNull(parameter.notNull());
valueDefinition.setNotEmpty(parameter.notEmpty());
if (isSet(parameter.pattern())) {
Pattern pattern = Pattern.compile(parameter.pattern());
valueDefinition.setPattern(pattern);
}
if (isSet(parameter.interval())) {
Interval interval = Interval.parseInterval(parameter.interval());
valueDefinition.setInterval(interval);
}
if (isSet(parameter.format())) {
valueDefinition.setFormat(parameter.format());
}
if (isSet(parameter.valueSet())) {
Converter converter = valueDefinition.getConverter();
ValueSet valueSet = ValueSet.parseValueSet(parameter.valueSet(), converter);
valueDefinition.setValueSet(valueSet);
}
if (isSet(parameter.defaultValue())) {
Converter converter = valueDefinition.getConverter();
valueDefinition.setDefaultValue(converter.parse(parameter.defaultValue()));
}
return valueDefinition;
}
| private ValueDefinition createValueDefinitionImpl(Field field) throws ConversionException {
final boolean operatorDetected = Operator.class.isAssignableFrom(field.getDeclaringClass());
Parameter parameter = field.getAnnotation(Parameter.class);
if (operatorDetected && parameter == null) {
return null;
}
ValueDefinition valueDefinition = new ValueDefinition(field.getName(), field.getType());
if (parameter == null) {
return valueDefinition;
}
if (parameter.validator() != Validator.class) {
final Validator validator;
try {
validator = parameter.validator().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create validator.", t);
}
valueDefinition.setValidator(validator);
}
if (parameter.converter() != Converter.class) {
Converter converter;
try {
converter = parameter.converter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create converter.", t);
}
valueDefinition.setConverter(converter);
}
if (valueDefinition.getConverter() == null) {
valueDefinition.setConverter(ConverterRegistry.getInstance().getConverter(valueDefinition.getType()));
}
if (parameter.itemConverter() != Converter.class) {
Converter converter;
try {
converter = parameter.itemConverter().newInstance();
} catch (Throwable t) {
throw new ConversionException("Failed to create item converter.", t);
}
valueDefinition.setItemConverter(converter);
}
if (ParameterDefinitionFactory.isSet(parameter.label())) {
valueDefinition.setDisplayName(parameter.label());
} else {
valueDefinition.setDisplayName(field.getName());
}
if (ParameterDefinitionFactory.isSet(parameter.alias())) {
valueDefinition.setAlias(parameter.alias());
}
if (ParameterDefinitionFactory.isSet(parameter.itemAlias())) {
valueDefinition.setItemAlias(parameter.itemAlias());
}
valueDefinition.setItemsInlined(parameter.itemsInlined());
valueDefinition.setUnit(parameter.unit());
valueDefinition.setDescription(parameter.description());
valueDefinition.setNotNull(parameter.notNull());
valueDefinition.setNotEmpty(parameter.notEmpty());
if (isSet(parameter.pattern())) {
Pattern pattern = Pattern.compile(parameter.pattern());
valueDefinition.setPattern(pattern);
}
if (isSet(parameter.interval())) {
Interval interval = Interval.parseInterval(parameter.interval());
valueDefinition.setInterval(interval);
}
if (isSet(parameter.format())) {
valueDefinition.setFormat(parameter.format());
}
if (isSet(parameter.valueSet())) {
Converter converter = valueDefinition.getConverter();
ValueSet valueSet = ValueSet.parseValueSet(parameter.valueSet(), converter);
valueDefinition.setValueSet(valueSet);
}
if (isSet(parameter.defaultValue())) {
Converter converter = valueDefinition.getConverter();
valueDefinition.setDefaultValue(converter.parse(parameter.defaultValue()));
}
return valueDefinition;
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/BaseClientHelper.java b/modules/org.restlet/src/org/restlet/engine/http/connector/BaseClientHelper.java
index 2aa2ec339..7d553d78b 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/connector/BaseClientHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/connector/BaseClientHelper.java
@@ -1,653 +1,654 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.http.connector;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Reference;
import org.restlet.data.Status;
/**
* Base client helper based on NIO blocking sockets. Here is the list of
* parameters that are supported. They should be set in the Client's context
* before it is started:
* <table>
* <tr>
* <th>Parameter name</th>
* <th>Value type</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tcpNoDelay</td>
* <td>boolean</td>
* <td>false</td>
* <td>Indicate if Nagle's TCP_NODELAY algorithm should be used.</td>
* </tr>
* <td>keystorePath</td>
* <td>String</td>
* <td>${user.home}/.keystore</td>
* <td>SSL keystore path.</td>
* </tr>
* <tr>
* <td>keystorePassword</td>
* <td>String</td>
* <td>System property "javax.net.ssl.keyStorePassword"</td>
* <td>SSL keystore password.</td>
* </tr>
* <tr>
* <td>keystoreType</td>
* <td>String</td>
* <td>JKS</td>
* <td>SSL keystore type</td>
* </tr>
* <tr>
* <td>keyPassword</td>
* <td>String</td>
* <td>System property "javax.net.ssl.keyStorePassword"</td>
* <td>SSL key password.</td>
* </tr>
* <tr>
* <td>certAlgorithm</td>
* <td>String</td>
* <td>SunX509</td>
* <td>SSL certificate algorithm.</td>
* </tr>
* <tr>
* <td>secureRandomAlgorithm</td>
* <td>String</td>
* <td>null (see java.security.SecureRandom)</td>
* <td>Name of the RNG algorithm. (see java.security.SecureRandom class).</td>
* </tr>
* <tr>
* <td>securityProvider</td>
* <td>String</td>
* <td>null (see javax.net.ssl.SSLContext)</td>
* <td>Java security provider name (see java.security.Provider class).</td>
* </tr>
* <tr>
* <td>sslProtocol</td>
* <td>String</td>
* <td>TLS</td>
* <td>SSL protocol.</td>
* </tr>
* <tr>
* <td>truststoreType</td>
* <td>String</td>
* <td>System property "javax.net.ssl.trustStoreType"</td>
* <td>Trust store type</td>
* </tr>
* <tr>
* <td>truststorePath</td>
* <td>String</td>
* <td>null</td>
* <td>Path to trust store</td>
* </tr>
* <tr>
* <td>truststorePassword</td>
* <td>String</td>
* <td>System property "javax.net.ssl.trustStorePassword"</td>
* <td>Trust store password</td>
* </tr>
* </table>
*
* @author Jerome Louvel
*/
public class BaseClientHelper extends BaseHelper<Client> {
/** The regular socket factory. */
private volatile SocketFactory regularSocketFactory;
/** The secure socket factory. */
private volatile SocketFactory secureSocketFactory;
/**
* Constructor.
*
* @param connector
* The helped client connector.
*/
public BaseClientHelper(Client connector) {
super(connector, true);
this.regularSocketFactory = null;
this.secureSocketFactory = null;
}
@Override
protected Connection<Client> createConnection(BaseHelper<Client> helper,
Socket socket, SocketChannel socketChannel) throws IOException {
return new ClientConnection(helper, socket, socketChannel);
}
/**
* Creates a properly configured secure socket factory.
*
* @return Properly configured secure socket factory.
* @throws IOException
* @throws GeneralSecurityException
*/
protected SocketFactory createSecureSocketFactory() throws IOException,
GeneralSecurityException {
// Retrieve the configuration variables
String certAlgorithm = getCertAlgorithm();
String keystorePath = getKeystorePath();
String keystorePassword = getKeystorePassword();
String keyPassword = getKeyPassword();
String truststoreType = getTruststoreType();
String truststorePath = getTruststorePath();
String truststorePassword = getTruststorePassword();
String secureRandomAlgorithm = getSecureRandomAlgorithm();
String securityProvider = getSecurityProvider();
// Initialize a key store
InputStream keystoreInputStream = null;
if ((keystorePath != null) && (new File(keystorePath).exists())) {
keystoreInputStream = new FileInputStream(keystorePath);
}
KeyStore keystore = null;
if (keystoreInputStream != null) {
try {
keystore = KeyStore.getInstance(getKeystoreType());
keystore.load(keystoreInputStream,
keystorePassword == null ? null : keystorePassword
.toCharArray());
} catch (IOException ioe) {
getLogger().log(Level.WARNING, "Unable to load the key store",
ioe);
keystore = null;
}
}
KeyManager[] keyManagers = null;
if ((keystore != null) && (keyPassword != null)) {
// Initialize a key manager
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(certAlgorithm);
keyManagerFactory.init(keystore, keyPassword.toCharArray());
keyManagers = keyManagerFactory.getKeyManagers();
}
// Initialize the trust store
InputStream truststoreInputStream = null;
if ((truststorePath != null) && (new File(truststorePath).exists())) {
truststoreInputStream = new FileInputStream(truststorePath);
}
KeyStore truststore = null;
if ((truststoreType != null) && (truststoreInputStream != null)) {
try {
truststore = KeyStore.getInstance(truststoreType);
truststore.load(truststoreInputStream,
truststorePassword == null ? null : truststorePassword
.toCharArray());
} catch (IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to load the trust store", ioe);
truststore = null;
}
}
TrustManager[] trustManagers = null;
if (truststore != null) {
// Initialize the trust manager
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(certAlgorithm);
trustManagerFactory.init(truststore);
trustManagers = trustManagerFactory.getTrustManagers();
}
// Initialize the SSL context
SecureRandom secureRandom = secureRandomAlgorithm == null ? null
: SecureRandom.getInstance(secureRandomAlgorithm);
SSLContext context = securityProvider == null ? SSLContext
.getInstance(getSslProtocol()) : SSLContext.getInstance(
getSslProtocol(), securityProvider);
context.init(keyManagers, trustManagers, secureRandom);
// Return the SSL socket factory
return context.getSocketFactory();
}
/**
* Creates the socket that will be used to send the request and get the
* response.
*
* @param hostDomain
* The target host domain name.
* @param hostPort
* The target host port.
* @return The created socket.
* @throws UnknownHostException
* @throws IOException
*/
public Socket createSocket(boolean secure, String hostDomain, int hostPort)
throws UnknownHostException, IOException {
Socket result = null;
SocketFactory factory = getSocketFactory(secure);
if (factory != null) {
result = factory.createSocket();
InetSocketAddress address = new InetSocketAddress(hostDomain,
hostPort);
result.connect(address, getConnectTimeout());
result.setTcpNoDelay(getTcpNoDelay());
}
return result;
}
/**
* Creates a normal or secure socket factory.
*
* @param secure
* Indicates if the sockets should be secured.
* @return A normal or secure socket factory.
*/
protected SocketFactory createSocketFactory(boolean secure) {
SocketFactory result = null;
if (secure) {
try {
return createSecureSocketFactory();
} catch (IOException ex) {
getLogger().log(
Level.SEVERE,
"Could not create secure socket factory: "
+ ex.getMessage(), ex);
} catch (GeneralSecurityException ex) {
getLogger().log(
Level.SEVERE,
"Could not create secure socket factory: "
+ ex.getMessage(), ex);
}
} else {
result = SocketFactory.getDefault();
}
return result;
}
/**
* Returns the SSL certificate algorithm.
*
* @return The SSL certificate algorithm.
*/
public String getCertAlgorithm() {
return getHelpedParameters().getFirstValue("certAlgorithm", "SunX509");
}
/**
* Returns the connection timeout.
*
* @return The connection timeout.
*/
public int getConnectTimeout() {
return getHelped().getConnectTimeout();
}
/**
* Returns the SSL key password.
*
* @return The SSL key password.
*/
public String getKeyPassword() {
return getHelpedParameters().getFirstValue("keyPassword",
System.getProperty("javax.net.ssl.keyStorePassword"));
}
/**
* Returns the SSL keystore password.
*
* @return The SSL keystore password.
*/
public String getKeystorePassword() {
return getHelpedParameters().getFirstValue("keystorePassword",
System.getProperty("javax.net.ssl.keyStorePassword"));
}
/**
* Returns the SSL keystore path.
*
* @return The SSL keystore path.
*/
public String getKeystorePath() {
return getHelpedParameters().getFirstValue("keystorePath",
System.getProperty("user.home") + File.separator + ".keystore");
}
/**
* Returns the SSL keystore type.
*
* @return The SSL keystore type.
*/
public String getKeystoreType() {
return getHelpedParameters().getFirstValue("keystoreType", "JKS");
}
/**
* Returns the regular socket factory.
*
* @return The regular socket factory.
*/
public SocketFactory getRegularSocketFactory() {
return regularSocketFactory;
}
/**
* Returns the name of the RNG algorithm.
*
* @return The name of the RNG algorithm.
*/
public String getSecureRandomAlgorithm() {
return getHelpedParameters().getFirstValue("secureRandomAlgorithm",
null);
}
/**
* Returns the secure socket factory.
*
* @return The secure socket factory.
*/
public SocketFactory getSecureSocketFactory() {
return secureSocketFactory;
}
/**
* Returns the Java security provider name.
*
* @return The Java security provider name.
*/
public String getSecurityProvider() {
return getHelpedParameters().getFirstValue("securityProvider", null);
}
/**
* Returns the socket factory.
*
* @param secure
* Indicates if a factory for secure sockets is expected.
* @return The socket factory.
*/
public SocketFactory getSocketFactory(boolean secure) {
return secure ? getSecureSocketFactory() : getRegularSocketFactory();
}
/**
* Returns the SSL keystore type.
*
* @return The SSL keystore type.
*/
public String getSslProtocol() {
return getHelpedParameters().getFirstValue("sslProtocol", "TLS");
}
/**
* Indicates if the protocol will use Nagle's algorithm
*
* @return True to enable TCP_NODELAY, false to disable.
* @see java.net.Socket#setTcpNoDelay(boolean)
*/
public boolean getTcpNoDelay() {
return Boolean.parseBoolean(getHelpedParameters().getFirstValue(
"tcpNoDelay", "false"));
}
/**
* Returns the SSL trust store password.
*
* @return The SSL trust store password.
*/
public String getTruststorePassword() {
return getHelpedParameters().getFirstValue("truststorePassword",
System.getProperty("javax.net.ssl.keyStorePassword"));
}
/**
* Returns the SSL trust store path.
*
* @return The SSL trust store path.
*/
public String getTruststorePath() {
return getHelpedParameters().getFirstValue("truststorePath", null);
}
/**
* Returns the SSL trust store type.
*
* @return The SSL trust store type.
*/
public String getTruststoreType() {
return getHelpedParameters().getFirstValue("truststoreType",
System.getProperty("javax.net.ssl.trustStoreType"));
}
@Override
public void handle(Request request, Response response) {
try {
if (request.getOnResponse() == null) {
// Synchronous mode
CountDownLatch latch = new CountDownLatch(1);
request.getAttributes().put(
"org.restlet.engine.http.connector.latch", latch);
// Add the message to the outbound queue for processing
getOutboundMessages().add(response);
// Await on the latch
latch.await();
} else {
// Add the message to the outbound queue for processing
getOutboundMessages().add(response);
}
} catch (Exception e) {
getLogger().log(
Level.INFO,
"Error while handling a " + request.getProtocol().getName()
+ " client request", e);
response.setStatus(Status.CONNECTOR_ERROR_INTERNAL, e);
}
}
@Override
public void handleInbound(Response response) {
if (response != null) {
if (response.getRequest().getOnResponse() != null) {
response.getRequest().getOnResponse().handle(
response.getRequest(), response);
}
if (!response.getStatus().isInformational()) {
CountDownLatch latch = (CountDownLatch) response.getRequest()
.getAttributes().get(
"org.restlet.engine.http.connector.latch");
if (latch != null) {
latch.countDown();
}
}
}
}
@Override
public void handleOutbound(Response response) {
if ((response != null) && (response.getRequest() != null)) {
Request request = response.getRequest();
// Resolve relative references
Reference resourceRef = request.getResourceRef().isRelative() ? request
.getResourceRef().getTargetRef()
: request.getResourceRef();
// Extract the host info
String hostDomain = resourceRef.getHostDomain();
int hostPort = resourceRef.getHostPort();
if (hostPort == -1) {
if (resourceRef.getSchemeProtocol() != null) {
hostPort = resourceRef.getSchemeProtocol().getDefaultPort();
} else {
hostPort = getProtocols().get(0).getDefaultPort();
}
}
try {
// Create the client socket
Socket socket = createSocket(request.isConfidential(),
hostDomain, hostPort);
InetAddress socketAddress = socket.getInetAddress();
int hostConnectionCount = 0;
int bestCount = 0;
Connection<Client> bestConn = null;
boolean foundConn = false;
// Try to reuse an existing connection
for (Connection<Client> currConn : getConnections()) {
if (currConn.getSocket().getInetAddress().equals(
socketAddress)) {
hostConnectionCount++;
if (currConn.getState().equals(ConnectionState.OPEN)
&& !currConn.isOutboundBusy()) {
bestConn = currConn;
foundConn = true;
continue;
}
int currCount = currConn.getOutboundMessages().size();
if (bestCount > currCount) {
bestCount = currCount;
bestConn = currConn;
}
}
}
if (!foundConn
&& ((getMaxTotalConnections() == -1) || (getConnections()
.size() < getMaxTotalConnections()))
&& ((getMaxConnectionsPerHost() == -1) || (hostConnectionCount < getMaxConnectionsPerHost()))) {
// Create a new connection
bestConn = createConnection(this, socket, null);
bestConn.open();
bestCount = 0;
}
if (bestConn != null) {
bestConn.getOutboundMessages().add(response);
getConnections().add(bestConn);
if (!request.isExpectingResponse()) {
// Attempt to directly write the response, preventing a
// thread context switch
bestConn.writeMessages();
- // Unblock the possibly waiting thread.
- // NB : the request may not be written at this time.
- CountDownLatch latch = (CountDownLatch) response
- .getRequest().getAttributes()
- .get("org.restlet.engine.http.connector.latch");
- if (latch != null) {
- latch.countDown();
- }
}
} else {
getLogger().warning(
"Unable to find a connection to send the request");
}
} catch (IOException ioe) {
getLogger()
.log(
Level.FINE,
"An error occured during the communication with the remote server.",
ioe);
response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
+ } finally {
+ // Unblock the possibly waiting thread.
+ // NB : the request may not be written at this time.
+ CountDownLatch latch = (CountDownLatch) response
+ .getRequest().getAttributes()
+ .get("org.restlet.engine.http.connector.latch");
+ if (latch != null) {
+ latch.countDown();
+ }
}
}
}
/**
* Sets the regular socket factory.
*
* @param regularSocketFactory
* The regular socket factory.
*/
public void setRegularSocketFactory(SocketFactory regularSocketFactory) {
this.regularSocketFactory = regularSocketFactory;
}
/**
* Sets the secure socket factory.
*
* @param secureSocketFactory
* The secure socket factory.
*/
public void setSecureSocketFactory(SocketFactory secureSocketFactory) {
this.secureSocketFactory = secureSocketFactory;
}
@Override
public synchronized void start() throws Exception {
setRegularSocketFactory(createSocketFactory(false));
setSecureSocketFactory(createSocketFactory(true));
super.start();
}
@Override
public synchronized void stop() throws Exception {
setRegularSocketFactory(null);
setSecureSocketFactory(null);
super.stop();
}
}
| false | true | public void handleOutbound(Response response) {
if ((response != null) && (response.getRequest() != null)) {
Request request = response.getRequest();
// Resolve relative references
Reference resourceRef = request.getResourceRef().isRelative() ? request
.getResourceRef().getTargetRef()
: request.getResourceRef();
// Extract the host info
String hostDomain = resourceRef.getHostDomain();
int hostPort = resourceRef.getHostPort();
if (hostPort == -1) {
if (resourceRef.getSchemeProtocol() != null) {
hostPort = resourceRef.getSchemeProtocol().getDefaultPort();
} else {
hostPort = getProtocols().get(0).getDefaultPort();
}
}
try {
// Create the client socket
Socket socket = createSocket(request.isConfidential(),
hostDomain, hostPort);
InetAddress socketAddress = socket.getInetAddress();
int hostConnectionCount = 0;
int bestCount = 0;
Connection<Client> bestConn = null;
boolean foundConn = false;
// Try to reuse an existing connection
for (Connection<Client> currConn : getConnections()) {
if (currConn.getSocket().getInetAddress().equals(
socketAddress)) {
hostConnectionCount++;
if (currConn.getState().equals(ConnectionState.OPEN)
&& !currConn.isOutboundBusy()) {
bestConn = currConn;
foundConn = true;
continue;
}
int currCount = currConn.getOutboundMessages().size();
if (bestCount > currCount) {
bestCount = currCount;
bestConn = currConn;
}
}
}
if (!foundConn
&& ((getMaxTotalConnections() == -1) || (getConnections()
.size() < getMaxTotalConnections()))
&& ((getMaxConnectionsPerHost() == -1) || (hostConnectionCount < getMaxConnectionsPerHost()))) {
// Create a new connection
bestConn = createConnection(this, socket, null);
bestConn.open();
bestCount = 0;
}
if (bestConn != null) {
bestConn.getOutboundMessages().add(response);
getConnections().add(bestConn);
if (!request.isExpectingResponse()) {
// Attempt to directly write the response, preventing a
// thread context switch
bestConn.writeMessages();
// Unblock the possibly waiting thread.
// NB : the request may not be written at this time.
CountDownLatch latch = (CountDownLatch) response
.getRequest().getAttributes()
.get("org.restlet.engine.http.connector.latch");
if (latch != null) {
latch.countDown();
}
}
} else {
getLogger().warning(
"Unable to find a connection to send the request");
}
} catch (IOException ioe) {
getLogger()
.log(
Level.FINE,
"An error occured during the communication with the remote server.",
ioe);
response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
}
}
}
| public void handleOutbound(Response response) {
if ((response != null) && (response.getRequest() != null)) {
Request request = response.getRequest();
// Resolve relative references
Reference resourceRef = request.getResourceRef().isRelative() ? request
.getResourceRef().getTargetRef()
: request.getResourceRef();
// Extract the host info
String hostDomain = resourceRef.getHostDomain();
int hostPort = resourceRef.getHostPort();
if (hostPort == -1) {
if (resourceRef.getSchemeProtocol() != null) {
hostPort = resourceRef.getSchemeProtocol().getDefaultPort();
} else {
hostPort = getProtocols().get(0).getDefaultPort();
}
}
try {
// Create the client socket
Socket socket = createSocket(request.isConfidential(),
hostDomain, hostPort);
InetAddress socketAddress = socket.getInetAddress();
int hostConnectionCount = 0;
int bestCount = 0;
Connection<Client> bestConn = null;
boolean foundConn = false;
// Try to reuse an existing connection
for (Connection<Client> currConn : getConnections()) {
if (currConn.getSocket().getInetAddress().equals(
socketAddress)) {
hostConnectionCount++;
if (currConn.getState().equals(ConnectionState.OPEN)
&& !currConn.isOutboundBusy()) {
bestConn = currConn;
foundConn = true;
continue;
}
int currCount = currConn.getOutboundMessages().size();
if (bestCount > currCount) {
bestCount = currCount;
bestConn = currConn;
}
}
}
if (!foundConn
&& ((getMaxTotalConnections() == -1) || (getConnections()
.size() < getMaxTotalConnections()))
&& ((getMaxConnectionsPerHost() == -1) || (hostConnectionCount < getMaxConnectionsPerHost()))) {
// Create a new connection
bestConn = createConnection(this, socket, null);
bestConn.open();
bestCount = 0;
}
if (bestConn != null) {
bestConn.getOutboundMessages().add(response);
getConnections().add(bestConn);
if (!request.isExpectingResponse()) {
// Attempt to directly write the response, preventing a
// thread context switch
bestConn.writeMessages();
}
} else {
getLogger().warning(
"Unable to find a connection to send the request");
}
} catch (IOException ioe) {
getLogger()
.log(
Level.FINE,
"An error occured during the communication with the remote server.",
ioe);
response.setStatus(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
} finally {
// Unblock the possibly waiting thread.
// NB : the request may not be written at this time.
CountDownLatch latch = (CountDownLatch) response
.getRequest().getAttributes()
.get("org.restlet.engine.http.connector.latch");
if (latch != null) {
latch.countDown();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.