gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2015 Duanze
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.duanze.litepreferences.rawmaterial;
import android.content.Context;
import com.duanze.litepreferences.ActualUtil;
import com.duanze.litepreferences.LiteInterface;
import com.duanze.litepreferences.model.Pref;
import com.duanze.litepreferences.parser.ParsePrefsXml;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Map;
/**
* Created by Duanze on 2015/11/20.
*/
public class BaseLitePrefs implements LiteInterface {
protected static BaseLitePrefs sMe;
protected Context mContext;
protected ActualUtil mUtil;
protected boolean valid = false;
protected BaseLitePrefs() {
}
@Override
public LiteInterface getImpl() {
return this;
}
public static LiteInterface getLiteInterface() {
if (null == sMe) {
sMe = new BaseLitePrefs();
}
return sMe.getImpl();
}
/**
* Must call this method before use LitePrefs.
* Pass the **Application Context** or **Main Activity**
* as parameter to avoid your activity
* cannot be recycled by GC.
*
* @param context should pass a **Application Context** or **Main Activity**
* @param res the xml file resource id
* @see #initFromMap(Context, String, Map)
*/
public static void initFromXml(Context context, int res) throws IOException, XmlPullParserException {
getLiteInterface().initFromXmlLite(context, res);
}
/**
* Must call this method before use LitePrefs.
* Pass the **Application Context** or **Main Activity**
* as parameter to avoid your activity
* cannot be recycled by GC.
*
* @param context should pass a **Application Context** or **Main Activity**
* @param res the xml file resource id
* @see #initFromMapLite(Context, String, Map)
*/
public void initFromXmlLite(Context context, int res) throws IOException, XmlPullParserException {
mContext = context;
mUtil = ParsePrefsXml.parse(context.getResources().getXml(res));
mUtil.init(context);
valid = true;
}
/**
* Must call this method before use LitePrefs.
* Pass the **Application Context** or **Main Activity**
* as parameter to avoid your activity
* cannot be recycled by GC.
*
* @param context should pass a **Application Context** or **Main Activity**
* @param name the name of the SharedPreferences you use
* @param map the core data map
* @see #initFromXml(Context, int)
*/
public static void initFromMap(Context context, String name, Map<String, Pref> map) {
getLiteInterface().initFromMapLite(context, name, map);
}
/**
* Must call this method before use LitePrefs.
* Pass the **Application Context** or **Main Activity**
* as parameter to avoid your activity
* cannot be recycled by GC.
*
* @param context should pass a **Application Context** or **Main Activity**
* @param name the name of the SharedPreferences you use
* @param map the core data map
* @see #initFromXmlLite(Context, int)
*/
public void initFromMapLite(Context context, String name, Map<String, Pref> map) {
mContext = context;
mUtil = new ActualUtil(name, map);
mUtil.init(context);
valid = true;
}
/**
* Return the core data map,
* the **key** of the map is just **Pref.key**
*
* @return the core data map
* @see Pref
*/
public static Map<String, Pref> getPrefsMap() {
return getLiteInterface().getPrefsMapLite();
}
/**
* Return the core data map,
* the **key** of the map is just **Pref.key**
*
* @return the core data map
* @see Pref
*/
public Map<String, Pref> getPrefsMapLite() {
checkValid();
return mUtil.getPrefsMap();
}
/**
* Add one key-value pair to the core data map.
* <p/>
* Be sure call it after LitePrefs is initialized.
*
* @param key
* @param pref
*/
public static void putToMap(String key, Pref pref) {
getLiteInterface().putToMapLite(key, pref);
}
/**
* Add one key-value pair to the core data map.
* <p/>
* Be sure call it after LitePrefs is initialized.
*
* @param key
* @param pref
*/
public void putToMapLite(String key, Pref pref) {
checkValid();
mUtil.putToMap(key, pref);
}
private void checkValid() {
if (!valid) {
throw new IllegalStateException("this should only be called when LitePrefs didn't initialize once");
}
}
public static int getInt(int keyRes) {
return getLiteInterface().getIntLite(keyRes);
}
public static int getInt(String key) {
return getLiteInterface().getIntLite(key);
}
public int getIntLite(String key) {
checkValid();
return mUtil.getInt(key);
}
public int getIntLite(int keyRes) {
checkValid();
return mUtil.getInt(mContext.getString(keyRes));
}
public static long getLong(int keyRes) {
return getLiteInterface().getLongLite(keyRes);
}
public static long getLong(String key) {
return getLiteInterface().getLongLite(key);
}
public long getLongLite(String key) {
checkValid();
return mUtil.getLong(key);
}
public long getLongLite(int keyRes) {
checkValid();
return mUtil.getLong(mContext.getString(keyRes));
}
public static float getFloat(int keyRes) {
return getLiteInterface().getFloatLite(keyRes);
}
public static float getFloat(String key) {
return getLiteInterface().getFloatLite(key);
}
public float getFloatLite(String key) {
checkValid();
return mUtil.getFloat(key);
}
public float getFloatLite(int keyRes) {
checkValid();
return mUtil.getFloat(mContext.getString(keyRes));
}
public static boolean getBoolean(int keyRes) {
return getLiteInterface().getBooleanLite(keyRes);
}
public static boolean getBoolean(String key) {
return getLiteInterface().getBooleanLite(key);
}
public boolean getBooleanLite(String key) {
checkValid();
return mUtil.getBoolean(key);
}
public boolean getBooleanLite(int keyRes) {
checkValid();
return mUtil.getBoolean(mContext.getString(keyRes));
}
public static String getString(int keyRes) {
return getLiteInterface().getStringLite(keyRes);
}
public static String getString(String key) {
return getLiteInterface().getStringLite(key);
}
public String getStringLite(String key) {
checkValid();
return mUtil.getString(key);
}
public String getStringLite(int keyRes) {
checkValid();
return mUtil.getString(mContext.getString(keyRes));
}
public static boolean putInt(int keyRes, int value) {
return getLiteInterface().putIntLite(keyRes, value);
}
public static boolean putInt(String key, int value) {
return getLiteInterface().putIntLite(key, value);
}
public boolean putIntLite(String key, int value) {
checkValid();
return mUtil.putInt(key, value);
}
public boolean putIntLite(int keyRes, int value) {
checkValid();
return mUtil.putInt(mContext.getString(keyRes), value);
}
public static boolean putLong(int keyRes, long value) {
return getLiteInterface().putLongLite(keyRes, value);
}
public static boolean putLong(String key, long value) {
return getLiteInterface().putLongLite(key, value);
}
public boolean putLongLite(String key, long value) {
checkValid();
return mUtil.putLong(key, value);
}
public boolean putLongLite(int keyRes, long value) {
checkValid();
return mUtil.putLong(mContext.getString(keyRes), value);
}
public static boolean putFloat(int keyRes, float value) {
return getLiteInterface().putFloatLite(keyRes, value);
}
public static boolean putFloat(String key, float value) {
return getLiteInterface().putFloatLite(key, value);
}
public boolean putFloatLite(String key, float value) {
checkValid();
return mUtil.putFloat(key, value);
}
public boolean putFloatLite(int keyRes, float value) {
checkValid();
return mUtil.putFloat(mContext.getString(keyRes), value);
}
public static boolean putBoolean(int keyRes, boolean value) {
return getLiteInterface().putBooleanLite(keyRes, value);
}
public static boolean putBoolean(String key, boolean value) {
return getLiteInterface().putBooleanLite(key, value);
}
public boolean putBooleanLite(String key, boolean value) {
checkValid();
return mUtil.putBoolean(key, value);
}
public boolean putBooleanLite(int keyRes, boolean value) {
checkValid();
return mUtil.putBoolean(mContext.getString(keyRes), value);
}
public static boolean putString(int keyRes, String value) {
return getLiteInterface().putStringLite(keyRes, value);
}
public static boolean putString(String key, String value) {
return getLiteInterface().putStringLite(key, value);
}
public boolean putStringLite(String key, String value) {
checkValid();
return mUtil.putString(key, value);
}
public boolean putStringLite(int keyRes, String value) {
checkValid();
return mUtil.putString(mContext.getString(keyRes), value);
}
public static boolean remove(int keyRes) {
return getLiteInterface().removeLite(keyRes);
}
public static boolean remove(String key) {
return getLiteInterface().removeLite(key);
}
public boolean removeLite(String key) {
checkValid();
return mUtil.remove(key);
}
public boolean removeLite(int keyRes) {
checkValid();
return mUtil.remove(mContext.getString(keyRes));
}
public static boolean clear() {
return getLiteInterface().clearLite();
}
public boolean clearLite() {
checkValid();
return mUtil.clear();
}
}
| |
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/site/tags/sakai-10.6/mergedlist-util/util/src/java/org/sakaiproject/util/MergedList.java $
* $Id: MergedList.java 120414 2013-02-23 01:14:36Z botimer@umich.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The 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.opensource.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.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
/**
* Contains the list of merged/non-merged channels
*/
public class MergedList extends ArrayList
{
/**
* Used to create a reference. This is unique to each caller, so we
* need an interface.
*/
public interface ChannelReferenceMaker
{
String makeReference(String siteId);
}
/**
* channel entry used to communicate with the Velocity templates when dealing with merged channels.
*/
public interface MergedEntry extends Comparable
{
/**
* Returns the display string for the channel.
*/
public String getDisplayName();
/**
* Returns the ID of the group. (The ID is used as a key.)
*/
public String getReference();
/**
* Returns true if this channel is currently being merged.
*/
public boolean isMerged();
/**
* Marks this channel as being merged or not.
*/
public void setMerged(boolean b);
/**
* This returns true if this list item should be visible to the user.
*/
public boolean isVisible();
/**
* Implemented so that we can order by the group full name.
*/
public int compareTo(Object arg0);
}
/**
* This interface is used to describe a generic list entry provider so that
* a variety of list entries can be used. This currently serves merged sites
* for the schedule and merged channels for announcements.
*/
public interface EntryProvider
{
/**
* Gets an iterator for the channels, calendars, etc.
*/
public Iterator getIterator();
/**
* See if we can do a "get" on the calendar, channel, etc.
*/
public boolean allowGet(String ref);
/**
* Generically access the context of the resource provided
* by the getIterator() call.
* @return The context.
*/
public String getContext(Object obj);
/**
* Generically access the reference of the resource provided
* by the getIterator() call.
*/
public String getReference(Object obj);
/**
* Generically access the resource's properties.
* @return The resource's properties.
*/
public ResourceProperties getProperties(Object obj);
public boolean isUserChannel(Object channel);
public boolean isSpecialSite(Object channel);
public String getSiteUserId(Object channel);
public Site getSite(Object channel);
}
/** This is used to separate group names in the config parameter. */
static private final String ID_DELIMITER = "_,_";
/**
* Implementation of channel entry used for rendering the list of merged channels
*/
private class MergedChannelEntryImpl implements MergedEntry
{
final private String channelReference;
final private String channelFullName;
private boolean merged;
private boolean visible;
public MergedChannelEntryImpl(
String channelReference,
String channelFullName,
boolean merged,
boolean visible)
{
this.channelReference = channelReference;
this.channelFullName = channelFullName;
this.merged = merged;
this.visible = visible;
}
/* (non-Javadoc)
* @see org.chefproject.actions.channelAction.MergedCalenderEntry#getchannelDisplayName()
*/
public String getDisplayName()
{
return channelFullName;
}
/* (non-Javadoc)
* @see org.chefproject.actions.channelAction.MergedCalenderEntry#getchannelReference()
*/
public String getReference()
{
return channelReference;
}
/* (non-Javadoc)
* @see org.chefproject.actions.channelAction.MergedCalenderEntry#isMerged()
*/
public boolean isMerged()
{
return merged;
}
/* (non-Javadoc)
* @see org.chefproject.actions.channelAction.MergedCalenderEntry#setMerged(boolean)
*/
public void setMerged(boolean b)
{
merged = b;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object arg0)
{
MergedChannelEntryImpl compObj = (MergedChannelEntryImpl) arg0;
return this.getDisplayName().compareTo(compObj.getDisplayName());
}
/* (non-Javadoc)
* @see org.chefproject.actions.channelAction.MergedCalenderEntry#isVisible()
*/
public boolean isVisible()
{
return visible;
}
}
/**
* loadChannelsFromDelimitedString
*
* Selects and loads channels from a list provided by the entryProvider
* parameter. The algorithm for loading channels is a bit complex, and
* depends on whether or not the user is currently in their "My Workspace", etc.
*
* This function formerly filtered through a list of all sites. It still
* goes through the motions of filtering, and deciding how to flag the channels
* as to whether or not they are merged, hidden, etc. However, it has been
* modified to take all of its information from an EntryProvider parameter,
* This list is now customized and is no longer "all sites in existence".
* When sites are being selected for merging, this list can be quite long.
* This function is more often called just to display merged events, so
* passing a more restricted list makes for better performance.
*
* At some point we could condense redundant logic, but this modification
* was performed under the time constraints of a release. So, an effort was
* made not to tinker with the logic, so much as to reduce the set of data
* that the function had to process.
*
* @param isOnWorkspaceTab - true if this is the user's my workspace
* @param entryProvider - provides available channels for load/merge
* @param userId - current userId
* @param channelArray - array of selected channels for load/merge
* @param isSuperUser - if true, then don't merge all available channels
* @param currentSiteId - current worksite
*/
public void loadChannelsFromDelimitedString(
boolean isOnWorkspaceTab,
EntryProvider entryProvider, String userId, String[] channelArray,
boolean isSuperUser, String currentSiteId)
{
loadChannelsFromDelimitedString( isOnWorkspaceTab, true, entryProvider,
userId, channelArray, isSuperUser, currentSiteId );
}
/**
* loadChannelsFromDelimitedString
*
* (see description on above method)
*
* @param isOnWorkspaceTab - true if this is the user's my workspace
* @param mergeAllOnWorkspaceTab - if true, merge all channels in channelArray
* @param entryProvider - provides available channels for load/merge
* @param userId - current userId
* @param channelArray - array of selected channels for load/merge
* @param isSuperUser - if true, then don't merge all available channels
* @param currentSiteId - current worksite
*/
public void loadChannelsFromDelimitedString(
boolean isOnWorkspaceTab,
boolean mergeAllOnWorkspaceTab,
EntryProvider entryProvider, String userId, String[] channelArray,
boolean isSuperUser, String currentSiteId)
{
// Remove any initial list contents.
this.clear();
// We'll need a map since we want to test for the
// presence of channels without searching through a list.
Map currentlyMergedchannels = makeChannelMap(channelArray);
// Loop through the channels that the EntryProvider gives us.
Iterator it = entryProvider.getIterator();
while (it.hasNext())
{
Object channel = it.next();
// Watch out for null channels. Ignore them if they are there.
if ( channel == null )
{
continue;
}
// If true, this channel will be added to the list of
// channels that may be merged.
boolean addThisChannel = false;
// If true, this channel will be marked as "merged".
boolean merged = false;
// If true, then this channel will be in the list, but will not
// be shown to the user.
boolean hidden = false;
// If true, this is a user channel.
boolean thisIsUserChannel = entryProvider.isUserChannel(channel);
// If true, this is a "special" site.
boolean isSpecialSite = entryProvider.isSpecialSite(channel);
// If true, this is the channel associated with the current
// user.
boolean thisIsTheUsersMyWorkspaceChannel = false;
if ( thisIsUserChannel
&& userId.equals(
entryProvider.getSiteUserId(channel)) )
{
thisIsTheUsersMyWorkspaceChannel = true;
}
//
// Don't put the channels of other users in the merge list.
// Go to the next item in the loop.
//
if (thisIsUserChannel && !thisIsTheUsersMyWorkspaceChannel)
{
continue;
}
// Only add to the list if the user can access this channel.
if (entryProvider.allowGet(entryProvider.getReference(channel)))
{
// Merge *almost* everything the user can access.
if (thisIsTheUsersMyWorkspaceChannel)
{
// Don't merge the user's channel in with a
// group channel. If we're on the "My Workspace"
// tab, then it's okay to merge.
if (isOnWorkspaceTab)
{
merged = true;
}
else
{
merged = false;
}
}
else
{
//
// If we're the admin, and we're on our "My Workspace" tab, then only
// use our channel (handled above). We'd be overloaded if we could
// see everyone's events.
//
if (isSuperUser && isOnWorkspaceTab)
{
merged = false;
}
else
{
// merge all sites if onWorkspaceTab and mergeAll is enabled
if (isOnWorkspaceTab && mergeAllOnWorkspaceTab)
{
merged = true;
}
// Set it to merged if the channel was specified in the merged
// channel list that we got from the portlet configuration.
else
{
merged =
currentlyMergedchannels.containsKey(
entryProvider.getReference(channel));
}
}
}
addThisChannel = true;
// Hide user or "special" sites from the user interface merge list.
if (thisIsUserChannel || isSpecialSite)
{
// Hide the user's own channel from them.
hidden = true;
}
}
if (addThisChannel)
{
String siteDisplayName = "";
// There is no point in getting the display name for hidden items
if (!hidden)
{
String displayNameProperty = entryProvider.getProperties(
channel).getProperty(
entryProvider.getProperties(channel)
.getNamePropDisplayName());
// If the channel has a displayName property and use that
// instead.
if (displayNameProperty != null
&& displayNameProperty.length() != 0)
{
siteDisplayName = displayNameProperty;
}
else
{
String channelName = "";
Site site = entryProvider.getSite(channel);
if (site != null)
{
boolean isCurrentSite = currentSiteId.equals(site.getId());
//
// Hide and force the current site to be merged.
//
if (isCurrentSite)
{
hidden = true;
merged = true;
}
else
{
// Else just get the name.
channelName = site.getTitle();
siteDisplayName = channelName + " ("
+ site.getId() + ") ";
}
}
}
}
this.add(
new MergedChannelEntryImpl(
entryProvider.getReference(channel),
siteDisplayName,
merged,
!hidden));
}
}
// MergedchannelEntry implements Comparable, so the sort will work correctly.
Collections.sort(this);
} // loadFromPortletConfig
/**
* Forms an array of all channel references to which the user has read access.
*/
public String[] getAllPermittedChannels(ChannelReferenceMaker refMaker)
{
List finalList = new ArrayList();
String [] returnArray = null;
// Get all accessible sites for the current user, not requiring descriptions
List siteList = SiteService.getUserSites(false);
Iterator it = siteList.iterator();
// Add all the references to the list.
while ( it.hasNext() )
{
Site site = (Site) it.next();
finalList.add(refMaker.makeReference(site.getId()));
}
// Make the array that we'll return
returnArray = new String[finalList.size()];
for ( int i=0; i < finalList.size(); i++ )
{
returnArray[i] = (String) finalList.get(i);
}
return returnArray;
}
/**
* This gets a list of channels from the portlet configuration information.
* Channels here can really be a channel or a schedule from a site.
*/
public String[] getChannelReferenceArrayFromDelimitedString(
String primarychannelReference,
String mergedInitParameterValue)
{
String mergedChannels = null;
// Get a list of the currently merged channels. This is a delimited list.
mergedChannels =
StringUtil.trimToNull(
mergedInitParameterValue);
String[] mergedChannelArray = null;
// Split the configuration string into an array of channel references.
if (mergedChannels != null)
{
mergedChannelArray = mergedChannels.split(ID_DELIMITER);
}
else
{
// If there are no merged channels, default to the primary channel.
mergedChannelArray = new String[1];
mergedChannelArray[0] = primarychannelReference;
}
return mergedChannelArray;
} // getChannelReferenceArrayFromDelimitedString
/**
* Create a channel reference map from an array of channel references.
*/
private Map makeChannelMap(String[] mergedChannelArray)
{
// Make a map of those channels that are currently merged.
Map currentlyMergedchannels = new HashMap();
if (mergedChannelArray != null)
{
for (int i = 0; i < mergedChannelArray.length; i++)
{
currentlyMergedchannels.put(
mergedChannelArray[i],
Boolean.valueOf(true));
}
}
return currentlyMergedchannels;
}
/**
* Loads data input by the user into this list and then saves the list to
* the portlet config information. The initContextForMergeOptions() function
* must have previously been called.
*/
public void loadFromRunData(ParameterParser params)
{
Iterator it = this.iterator();
while (it.hasNext())
{
MergedEntry entry = (MergedEntry) it.next();
// If the group is even mentioned in the parameters, then
// it means that the checkbox was selected. Deselected checkboxes
// will not be present in the parameter list.
if (params.getString(entry.getReference())
!= null)
{
entry.setMerged(true);
}
else
{
//
// If the entry isn't visible, then we can't "unmerge" it due to
// the lack of a checkbox in the user interface.
//
if (entry.isVisible())
{
entry.setMerged(false);
}
}
}
}
/**
* Loads data input by the user into this list and then saves the list to
* the portlet config information. The initContextForMergeOptions() function
* must have previously been called.
*/
public String getDelimitedChannelReferenceString()
{
StringBuilder mergedReferences = new StringBuilder("");
Iterator it = this.iterator();
boolean firstEntry = true;
while (it.hasNext())
{
MergedEntry entry = (MergedEntry) it.next();
if (entry.isMerged())
{
// Add a delimiter, if appropriate.
if ( !firstEntry )
{
mergedReferences.append(ID_DELIMITER);
}
else
{
firstEntry = false;
}
// Add to our list
mergedReferences.append(entry.getReference());
}
}
// Return the delimited list of merged references
return mergedReferences.toString();
}
/**
* Returns an array of merged references.
*/
public List getReferenceList()
{
List references = new ArrayList();
Iterator it = this.iterator();
while (it.hasNext())
{
MergedEntry mergedEntry = (MergedEntry) it.next();
// Only add it to the list if it has been merged.
if (mergedEntry.isMerged())
{
references.add(mergedEntry.getReference());
}
}
return references;
}
}
| |
/*
* 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.ambari.server.controller.metrics;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.AmbariServer;
import org.apache.ambari.server.controller.internal.PropertyInfo;
import org.apache.ambari.server.controller.internal.ResourceImpl;
import org.apache.ambari.server.controller.internal.StackDefinedPropertyProvider;
import org.apache.ambari.server.controller.jmx.JMXPropertyProvider;
import org.apache.ambari.server.controller.jmx.TestStreamProvider;
import org.apache.ambari.server.controller.metrics.MetricsServiceProvider.MetricsService;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.TemporalInfo;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.controller.utilities.StreamProvider;
import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
import org.apache.ambari.server.orm.dao.StackDAO;
import org.apache.ambari.server.orm.entities.StackEntity;
import org.apache.ambari.server.security.TestAuthenticationFactory;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.ConfigHelper;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.services.MetricsRetrievalService;
import org.apache.ambari.server.state.stack.Metric;
import org.apache.ambari.server.state.stack.MetricDefinition;
import org.apache.ambari.server.utils.SynchronousThreadPoolExecutor;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.security.core.context.SecurityContextHolder;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Rest metrics property provider tests.
*/
public class RestMetricsPropertyProviderTest {
public static final String WRAPPED_METRICS_KEY = "WRAPPED_METRICS_KEY";
protected static final String HOST_COMPONENT_HOST_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("HostRoles", "host_name");
protected static final String HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("HostRoles", "component_name");
protected static final String HOST_COMPONENT_STATE_PROPERTY_ID = PropertyHelper.getPropertyId("HostRoles", "state");
protected static final Map<String, String> metricsProperties = new HashMap<>();
protected static final Map<String, Metric> componentMetrics = new HashMap<>();
private static final String CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("HostRoles", "cluster_name");
private static final String DEFAULT_STORM_UI_PORT = "8745";
public static final int NUMBER_OF_RESOURCES = 400;
private static final int METRICS_SERVICE_TIMEOUT = 10;
private static Injector injector;
private static Clusters clusters;
private static Cluster c1;
private static AmbariManagementController amc;
private static MetricsRetrievalService metricsRetrievalService;
{
metricsProperties.put("default_port", DEFAULT_STORM_UI_PORT);
metricsProperties.put("port_config_type", "storm-site");
metricsProperties.put("port_property_name", "ui.port");
metricsProperties.put("protocol", "http");
componentMetrics.put("metrics/api/cluster/summary/tasks.total", new Metric("/api/cluster/summary##tasks.total", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/slots.total", new Metric("/api/cluster/summary##slots.total", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/slots.free", new Metric("/api/cluster/summary##slots.free", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/supervisors", new Metric("/api/cluster/summary##supervisors", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/executors.total", new Metric("/api/cluster/summary##executors.total", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/slots.used", new Metric("/api/cluster/summary##slots.used", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/topologies", new Metric("/api/cluster/summary##topologies", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/nimbus.uptime", new Metric("/api/cluster/summary##nimbus.uptime", false, false, false, "unitless"));
componentMetrics.put("metrics/api/cluster/summary/wrong.metric", new Metric(null, false, false, false, "unitless"));
}
@BeforeClass
public static void setup() throws Exception {
injector = Guice.createInjector(new InMemoryDefaultTestModule());
injector.getInstance(GuiceJpaInitializer.class);
clusters = injector.getInstance(Clusters.class);
StackDAO stackDAO = injector.getInstance(StackDAO.class);
StackEntity stackEntity = new StackEntity();
stackEntity.setStackName("HDP");
stackEntity.setStackVersion("2.1.1");
stackDAO.create(stackEntity);
clusters.addCluster("c1", new StackId("HDP-2.1.1"));
c1 = clusters.getCluster("c1");
// disable request TTL for these tests
Configuration configuration = injector.getInstance(Configuration.class);
configuration.setProperty(Configuration.METRIC_RETRIEVAL_SERVICE_REQUEST_TTL_ENABLED.getKey(),
"false");
JMXPropertyProvider.init(configuration);
metricsRetrievalService = injector.getInstance(
MetricsRetrievalService.class);
metricsRetrievalService.startAsync();
metricsRetrievalService.awaitRunning(METRICS_SERVICE_TIMEOUT, TimeUnit.SECONDS);
metricsRetrievalService.setThreadPoolExecutor(new SynchronousThreadPoolExecutor());
// Setting up Mocks for Controller, Clusters etc, queried as part of user's Role context
// while fetching Metrics.
amc = createNiceMock(AmbariManagementController.class);
Field field = AmbariServer.class.getDeclaredField("clusterController");
field.setAccessible(true);
field.set(null, amc);
ConfigHelper configHelperMock = createNiceMock(ConfigHelper.class);
expect(amc.getClusters()).andReturn(clusters).anyTimes();
expect(amc.getAmbariEventPublisher()).andReturn(createNiceMock(AmbariEventPublisher.class)).anyTimes();
expect(amc.findConfigurationTagsWithOverrides(eq(c1), anyString())).andReturn(Collections.singletonMap("storm-site",
Collections.singletonMap("tag", "version1"))).anyTimes();
expect(amc.getConfigHelper()).andReturn(configHelperMock).anyTimes();
expect(configHelperMock.getEffectiveConfigProperties(eq(c1),
EasyMock.anyObject())).andReturn(Collections.singletonMap("storm-site",
Collections.singletonMap("ui.port", DEFAULT_STORM_UI_PORT))).anyTimes();
replay(amc, configHelperMock);
}
@AfterClass
public static void after() throws AmbariException, SQLException, TimeoutException {
if (metricsRetrievalService != null && metricsRetrievalService.isRunning()) {
metricsRetrievalService.stopAsync();
metricsRetrievalService.awaitTerminated(METRICS_SERVICE_TIMEOUT, TimeUnit.SECONDS);
}
H2DatabaseCleaner.clearDatabaseAndStopPersistenceService(injector);
}
private RestMetricsPropertyProvider createRestMetricsPropertyProvider(MetricDefinition metricDefinition,
HashMap<String, Map<String, PropertyInfo>> componentMetrics, StreamProvider streamProvider,
TestMetricsHostProvider metricsHostProvider) throws Exception {
MetricPropertyProviderFactory factory = injector.getInstance(MetricPropertyProviderFactory.class);
RestMetricsPropertyProvider restMetricsPropertyProvider = factory.createRESTMetricsPropertyProvider(
metricDefinition.getProperties(),
componentMetrics,
streamProvider,
metricsHostProvider,
PropertyHelper.getPropertyId("HostRoles", "cluster_name"),
PropertyHelper.getPropertyId("HostRoles", "host_name"),
PropertyHelper.getPropertyId("HostRoles", "component_name"),
PropertyHelper.getPropertyId("HostRoles", "state"),
"STORM_REST_API"
);
Field field = RestMetricsPropertyProvider.class.getDeclaredField("amc");
field.setAccessible(true);
field.set(restMetricsPropertyProvider, amc);
return restMetricsPropertyProvider;
}
@After
public void clearAuthentication() {
SecurityContextHolder.getContext().setAuthentication(null);
}
@Test
public void testRestMetricsPropertyProviderAsClusterAdministrator() throws Exception {
//Setup user with Role 'ClusterAdministrator'.
SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createClusterAdministrator("ClusterAdmin", 2L));
testPopulateResources();
testPopulateResources_singleProperty();
testPopulateResources_category();
testPopulateResourcesUnhealthyResource();
testPopulateResourcesMany();
testPopulateResourcesTimeout();
}
@Test
public void testRestMetricsPropertyProviderAsAdministrator() throws Exception {
//Setup user with Role 'Administrator'
SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createAdministrator("Admin"));
testPopulateResources();
testPopulateResources_singleProperty();
testPopulateResources_category();
testPopulateResourcesUnhealthyResource();
testPopulateResourcesMany();
testPopulateResourcesTimeout();
}
@Test
public void testRestMetricsPropertyProviderAsServiceAdministrator() throws Exception {
//Setup user with 'ServiceAdministrator'
SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createServiceAdministrator("ServiceAdmin", 2L));
testPopulateResources();
testPopulateResources_singleProperty();
testPopulateResources_category();
testPopulateResourcesUnhealthyResource();
testPopulateResourcesMany();
testPopulateResourcesTimeout();
}
@Test(expected = AuthorizationException.class)
public void testRestMetricsPropertyProviderAsViewUser() throws Exception {
// Setup user with 'ViewUser'
// ViewUser doesn't have the 'CLUSTER_VIEW_METRICS', 'HOST_VIEW_METRICS' and 'SERVICE_VIEW_METRICS', thus
// can't retrieve the Metrics.
SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createViewUser("ViewUser", 2L));
testPopulateResources();
testPopulateResources_singleProperty();
testPopulateResources_category();
testPopulateResourcesUnhealthyResource();
testPopulateResourcesMany();
testPopulateResourcesTimeout();
}
@Test
public void testResolvePort() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
// a property with a port doesn't exist, should return a default
Map<String, String> customMetricsProperties = new HashMap<>(metricsProperties);
customMetricsProperties.put("port_property_name", "wrong_property");
String resolvedPort = restMetricsPropertyProvider.resolvePort(c1, "domu-12-31-39-0e-34-e1.compute-1.internal",
"STORM_REST_API", customMetricsProperties, "http");
Assert.assertEquals(DEFAULT_STORM_UI_PORT, resolvedPort);
// a port property exists (8745). Should return it, not a default_port (8746)
customMetricsProperties = new HashMap<>(metricsProperties);
// custom default
customMetricsProperties.put("default_port", "8746");
resolvedPort = restMetricsPropertyProvider.resolvePort(c1, "domu-12-31-39-0e-34-e1.compute-1.internal",
"STORM_REST_API", customMetricsProperties, "http");
Assert.assertEquals(DEFAULT_STORM_UI_PORT, resolvedPort);
}
public void testPopulateResources() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, "STARTED");
// request with an empty set should get all supported properties
Request request = PropertyHelper.getReadRequest(Collections.emptySet());
Assert.assertEquals(1, restMetricsPropertyProvider.populateResources(Collections.singleton(resource), request, null).size());
Assert.assertNull(resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "wrong.metric")));
//STORM_REST_API
Assert.assertEquals(28.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "tasks.total")));
Assert.assertEquals(8.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "slots.total")));
Assert.assertEquals(5.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "slots.free")));
Assert.assertEquals(2.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "supervisors")));
Assert.assertEquals(28.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "executors.total")));
Assert.assertEquals(3.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "slots.used")));
Assert.assertEquals(1.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "topologies")));
Assert.assertEquals(4637.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "nimbus.uptime")));
}
public void testPopulateResources_singleProperty() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, "STARTED");
// request with an empty set should get all supported properties
Request request = PropertyHelper.getReadRequest(Collections.emptySet());
Assert.assertEquals(1, restMetricsPropertyProvider.populateResources(Collections.singleton(resource), request, null).size());
Assert.assertEquals(28.0, resource.getPropertyValue("metrics/api/cluster/summary/tasks.total"));
Assert.assertNull(resource.getPropertyValue("metrics/api/cluster/summary/taskstotal"));
}
public void testPopulateResources_category() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, "STARTED");
// request with an empty set should get all supported properties
// only ask for one property
Map<String, TemporalInfo> temporalInfoMap = new HashMap<>();
Request request = PropertyHelper.getReadRequest(Collections.singleton("metrics/api/cluster"), temporalInfoMap);
Assert.assertEquals(1, restMetricsPropertyProvider.populateResources(Collections.singleton(resource), request, null).size());
// see test/resources/hdfs_namenode_jmx.json for values
Assert.assertEquals(28.0, resource.getPropertyValue("metrics/api/cluster/summary/tasks.total"));
Assert.assertEquals(2.0, resource.getPropertyValue("metrics/api/cluster/summary/supervisors"));
Assert.assertNull(resource.getPropertyValue("metrics/api/cluster/summary/taskstotal"));
}
public void testPopulateResourcesUnhealthyResource() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, "INSTALLED");
// request with an empty set should get all supported properties
Request request = PropertyHelper.getReadRequest(Collections.emptySet());
Assert.assertEquals(1, restMetricsPropertyProvider.populateResources(Collections.singleton(resource), request, null).size());
// Assert that the stream provider was never called.
Assert.assertNull(streamProvider.getLastSpec());
}
public void testPopulateResourcesMany() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider();
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
Set<Resource> resources = new HashSet<>();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
for (int i = 0; i < NUMBER_OF_RESOURCES; ++i) {
// strom_rest_api
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resource.setProperty(HOST_COMPONENT_STATE_PROPERTY_ID, "STARTED");
resource.setProperty("unique_id", i);
resources.add(resource);
}
// request with an empty set should get all supported properties
Request request = PropertyHelper.getReadRequest(Collections.emptySet());
Set<Resource> resourceSet = restMetricsPropertyProvider.populateResources(resources, request, null);
Assert.assertEquals(NUMBER_OF_RESOURCES, resourceSet.size());
for (Resource resource : resourceSet) {
Assert.assertEquals(28.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "tasks.total")));
Assert.assertEquals(8.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "slots.total")));
Assert.assertEquals(5.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "slots.free")));
Assert.assertEquals(2.0, resource.getPropertyValue(PropertyHelper.getPropertyId("metrics/api/cluster/summary", "supervisors")));
}
}
public void testPopulateResourcesTimeout() throws Exception {
MetricDefinition metricDefinition = createNiceMock(MetricDefinition.class);
expect(metricDefinition.getMetrics()).andReturn(componentMetrics);
expect(metricDefinition.getType()).andReturn("org.apache.ambari.server.controller.metrics.RestMetricsPropertyProvider");
expect(metricDefinition.getProperties()).andReturn(metricsProperties);
replay(metricDefinition);
Map<String, PropertyInfo> metrics = StackDefinedPropertyProvider.getPropertyInfo(metricDefinition);
HashMap<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<>();
componentMetrics.put(WRAPPED_METRICS_KEY, metrics);
TestStreamProvider streamProvider = new TestStreamProvider(100L);
TestMetricsHostProvider metricsHostProvider = new TestMetricsHostProvider();
Set<Resource> resources = new HashSet<>();
RestMetricsPropertyProvider restMetricsPropertyProvider = createRestMetricsPropertyProvider(metricDefinition, componentMetrics, streamProvider,
metricsHostProvider);
// set the provider timeout to -1 millis to guarantee timeout
restMetricsPropertyProvider.setPopulateTimeout(-1L);
try {
Resource resource = new ResourceImpl(Resource.Type.HostComponent);
resource.setProperty("HostRoles/cluster_name", "c1");
resource.setProperty(HOST_COMPONENT_HOST_NAME_PROPERTY_ID, "domu-12-31-39-0e-34-e1.compute-1.internal");
resource.setProperty(HOST_COMPONENT_COMPONENT_NAME_PROPERTY_ID, "STORM_REST_API");
resources.add(resource);
// request with an empty set should get all supported properties
Request request = PropertyHelper.getReadRequest(Collections.emptySet());
Set<Resource> resourceSet = restMetricsPropertyProvider.populateResources(resources, request, null);
// make sure that the thread running the stream provider has completed
Thread.sleep(150L);
Assert.assertEquals(0, resourceSet.size());
// assert that properties never get set on the resource
Assert.assertNull(resource.getPropertyValue("metrics/api/cluster/summary/tasks.total"));
Assert.assertNull(resource.getPropertyValue("metrics/api/cluster/summary/supervisors"));
} finally {
// reset default value
restMetricsPropertyProvider.setPopulateTimeout(injector.getInstance(Configuration.class)
.getPropertyProvidersCompletionServiceTimeout());
}
}
public static class TestMetricsHostProvider implements MetricHostProvider {
@Override
public String getCollectorHostName(String clusterName, MetricsService service) throws SystemException {
return null;
}
@Override
public String getHostName(String clusterName, String componentName) {
return null;
}
@Override
public String getCollectorPort(String clusterName, MetricsService service) throws SystemException {
return null;
}
@Override
public boolean isCollectorHostLive(String clusterName, MetricsService service) throws SystemException {
return false;
}
@Override
public boolean isCollectorComponentLive(String clusterName, MetricsService service) throws SystemException {
return false;
}
@Override
public boolean isCollectorHostExternal(String clusterName) {
return false;
}
}
}
| |
/*
* 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.pig.builtin;
import java.io.IOException;
import java.util.Iterator;
import org.apache.pig.Accumulator;
import org.apache.pig.Algebraic;
import org.apache.pig.EvalFunc;
import org.apache.pig.PigException;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.backend.executionengine.ExecException;
/**
* This method should never be used directly, use {@link AVG}.
*/
public class FloatAvg extends EvalFunc<Double> implements Algebraic, Accumulator<Double> {
private static TupleFactory mTupleFactory = TupleFactory.getInstance();
@Override
public Double exec(Tuple input) throws IOException {
try {
Double sum = sum(input);
if(sum == null) {
// either we were handed an empty bag or a bag
// filled with nulls - return null in this case
return null;
}
double count = count(input);
Double avg = null;
if (count > 0)
avg = new Double(sum / count);
return avg;
} catch (ExecException ee) {
throw ee;
}
}
public String getInitial() {
return Initial.class.getName();
}
public String getIntermed() {
return Intermediate.class.getName();
}
public String getFinal() {
return Final.class.getName();
}
static public class Initial extends EvalFunc<Tuple> {
@Override
public Tuple exec(Tuple input) throws IOException {
try {
Tuple t = mTupleFactory.newTuple(2);
// input is a bag with one tuple containing
// the column we are trying to avg on
DataBag bg = (DataBag) input.get(0);
Float f = null;
if(bg.iterator().hasNext()) {
Tuple tp = bg.iterator().next();
f = (Float)(tp.get(0));
}
t.set(0, f != null ? new Double(f) : null);
if (f != null)
t.set(1, 1L);
else
t.set(1, 0L);
return t;
} catch (ExecException ee) {
throw ee;
} catch (Exception e) {
int errCode = 2106;
String msg = "Error while computing average in " + this.getClass().getSimpleName();
throw new ExecException(msg, errCode, PigException.BUG, e);
}
}
}
static public class Intermediate extends EvalFunc<Tuple> {
@Override
public Tuple exec(Tuple input) throws IOException {
try {
DataBag b = (DataBag)input.get(0);
return combine(b);
} catch (ExecException ee) {
throw ee;
} catch (Exception e) {
int errCode = 2106;
String msg = "Error while computing average in " + this.getClass().getSimpleName();
throw new ExecException(msg, errCode, PigException.BUG, e);
}
}
}
static public class Final extends EvalFunc<Double> {
@Override
public Double exec(Tuple input) throws IOException {
try {
DataBag b = (DataBag)input.get(0);
Tuple combined = combine(b);
Double sum = (Double)combined.get(0);
if(sum == null) {
return null;
}
double count = (Long)combined.get(1);
Double avg = null;
if (count > 0) {
avg = new Double(sum / count);
}
return avg;
} catch (ExecException ee) {
throw ee;
} catch (Exception e) {
int errCode = 2106;
String msg = "Error while computing average in " + this.getClass().getSimpleName();
throw new ExecException(msg, errCode, PigException.BUG, e);
}
}
}
static protected Tuple combine(DataBag values) throws ExecException {
double sum = 0;
long count = 0;
// combine is called from Intermediate and Final
// In either case, Initial would have been called
// before and would have sent in valid tuples
// Hence we don't need to check if incoming bag
// is empty
Tuple output = mTupleFactory.newTuple(2);
boolean sawNonNull = false;
for (Iterator<Tuple> it = values.iterator(); it.hasNext();) {
Tuple t = it.next();
Double d = (Double)t.get(0);
// we count nulls in avg as contributing 0
// a departure from SQL for performance of
// COUNT() which implemented by just inspecting
// size of the bag
if(d == null) {
d = 0.0;
} else {
sawNonNull = true;
}
sum += d;
count += (Long)t.get(1);
}
if(sawNonNull) {
output.set(0, new Double(sum));
} else {
output.set(0, null);
}
output.set(1, Long.valueOf(count));
return output;
}
static protected long count(Tuple input) throws ExecException {
DataBag values = (DataBag)input.get(0);
Iterator it = values.iterator();
long cnt = 0;
while (it.hasNext()){
Tuple t = (Tuple)it.next();
if (t != null && t.size() > 0 && t.get(0) != null)
cnt++;
}
return cnt;
}
static protected Double sum(Tuple input) throws ExecException, IOException {
DataBag values = (DataBag)input.get(0);
// if we were handed an empty bag, return NULL
if(values.size() == 0) {
return null;
}
double sum = 0.0;
boolean sawNonNull = false;
for (Iterator<Tuple> it = values.iterator(); it.hasNext();) {
Tuple t = it.next();
try {
Float f = (Float)(t.get(0));
if (f == null) continue;
sawNonNull = true;
sum += f;
}catch(RuntimeException exp) {
int errCode = 2103;
String msg = "Problem while computing sum of floats.";
throw new ExecException(msg, errCode, PigException.BUG, exp);
}
}
if(sawNonNull) {
return new Double(sum);
} else {
return null;
}
}
@Override
public Schema outputSchema(Schema input) {
return new Schema(new Schema.FieldSchema(null, DataType.DOUBLE));
}
/* Accumulator interface */
private Double intermediateSum = null;
private Double intermediateCount = null;
@Override
public void accumulate(Tuple b) throws IOException {
try {
Double sum = sum(b);
if(sum == null) {
return;
}
// set default values
if (intermediateSum == null || intermediateCount == null) {
intermediateSum = 0.0;
intermediateCount = 0.0;
}
double count = (Long)count(b);
if (count > 0) {
intermediateCount += count;
intermediateSum += sum;
}
} catch (ExecException ee) {
throw ee;
} catch (Exception e) {
int errCode = 2106;
String msg = "Error while computing average in " + this.getClass().getSimpleName();
throw new ExecException(msg, errCode, PigException.BUG, e);
}
}
@Override
public void cleanup() {
intermediateSum = null;
intermediateCount = null;
}
@Override
public Double getValue() {
Double avg = null;
if (intermediateCount != null && intermediateCount > 0) {
avg = new Double(intermediateSum / intermediateCount);
}
return avg;
}
}
| |
package de.zib.gndms.common.model.common;
/*
* Copyright 2008-2011 Zuse Institute Berlin (ZIB)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;
/**
* An AccessMask is used to handle access rights for the access types user, group and other.
*
* Read, write and execute rights can be set or unset by using a bit mask.
*
* @author try ma ik jo rr a zib
* @version $Id$
* @see AccessFlags for the representation of a bit mask.
* User: mjorra, Date: 22.12.2008, Time: 13:13:43
*/
public class AccessMask implements Serializable {
/**
* The serialization id.
*/
private static final long serialVersionUID = 3846269515013219026L;
/**
* AccessFlags is an enumeration for the different access types.
*
* Its value can be chosen by bit flags.
* In detail an int value will be interpreted as follows:
*
* <pre>
* If we have an int x = x1 x2 x3 in binary representation with x element of [0;7]
* then if set to 1 the meaning of the flags are
* x3 = Executable
* x2 = Writable
* x1 = Readable
* </pre>
*
*/
public enum AccessFlags {
/**
* Read access.
*/
READABLE( 0x4 ),
/**
* Write access.
*/
WRITABLE( 0x2 ),
/**
* Execution access.
*/
EXECUTABLE( 0x1 ),
/**
* Read and write access.
*/
READWRITE( 0x6 ),
/**
* Read and execution access.
*/
READEXECUT( 0X5 ),
/**
* write and execution access.
*/
WRITEEXEC( 0X3 ),
/**
* Unrestricted access.
*/
ALL( 0X7 ),
/**
* No access.
*/
NONE( 0x0 );
/**
* The maximal number for a flag.
*/
private static final int MAX = 7;
/**
* A bit mask containing the different access flags.
*/
private final int mask;
/**
* Maps a bit mask to its corresponding access flags.
*/
private static final Map<Integer, AccessFlags> VALUEFORFLAG = new HashMap<Integer, AccessFlags>();
/**
* If true, the {@code valueForFlag} Map will be initialized with all enum values.
*/
private static boolean uninitialized = true;
/**
* Sets the access flags according to the flags encoded by {@code msk}.
*
* @param msk a value, encoding the access flags.
*/
AccessFlags( final int msk ) {
mask = msk;
}
/**
* Returns the access mask, containing the flags for the different access types.
*
* @return The access mask.
*/
public int getMask( ) {
return mask;
}
/**
* Returns a String representation of the mask.
* @return The String.
*/
@Override
public String toString( ) {
return maskToString( this );
}
/**
* Returns a String representation of {@code accessFlag}'s mask.
*
* @param accessFlag An instance of AccessFlags.
* @return The String representation .
*/
public String maskToString( final AccessFlags accessFlag ) {
return maskToString( accessFlag.getMask() );
}
/**
* Returns the value of access mask, in decimal base, as String.
*
* @param accessMask an access mask as int value.
* @return a String representation of the access mask.
*/
public String maskToString( final int accessMask ) {
return Integer.toString( accessMask );
}
/**
* Returns an {@code AccessFlags} with the flags set as intended by the bit {@code mask}.
*
* @param mask the bit mask containing the settings for the access configuration.
* @return an {@code AccessFlags} with the flags set as intended by the bit {@code mask}.
*/
public static AccessFlags flagsForMask( final int mask ) {
if ( mask > MAX || mask < 0 ) {
throw new IllegalArgumentException( "Numeric mask must be between 0x0 and 0x7. Received: " + mask );
}
if ( uninitialized ) {
for ( AccessFlags f : AccessFlags.values() ) {
VALUEFORFLAG.put( f.getMask(), f );
}
uninitialized = false;
}
return VALUEFORFLAG.get( mask );
}
/**
* {@code s} must be a single character, matching an int in [0;7].
*
* @param s The character.
* @return The corresponding access flags.
*
* @see AccessFlags#fromChar(char)
*/
public static AccessFlags fromString( final String s ) {
return flagsForMask( Integer.valueOf( s ) );
}
/**
* An {@code AccessFlags} type will be returned, set as intended by the bit mask of the
* numerical value of the char.
*
* @param c a char, matching an int in [0;7].
* @return an {@code AccessFlags}, set as intended by the bit mask of the numerical value of the char.
*/
public static AccessFlags fromChar( final char c ) {
return fromString( Character.toString( c ) );
}
}
/**
* An enumeration to distinguish rights for a {@code user}, a {@code group} and {@code other}.
* It provides an index for all three entries, starting from 0 with user and incrementing in the order
* given above.
*/
public enum Ugo {
/**
* The user.
*/
USER( 0 ),
/**
* The group.
*/
GROUP( 1 ),
/**
* Others.
*/
OTHER( 2 );
/**
* The maximal number of different rights.
*/
private static final int MAXRIGHTS = 3;
/**
* The index.
*/
private final int index;
/**
* Creates a new Ugo with the given index.
* @param idx The index value.
*/
Ugo( final int idx ) {
index = idx;
}
}
/**
* This array holds the access-rights for the different groups.
* @see Ugo
*/
private AccessFlags[] access = new AccessFlags[Ugo.MAXRIGHTS];
/**
* Special attribute of the access mask.
*
* Can be s.th. like sticky bit etc.
*/
private Integer special = null;
/**
* Returns the access rights for a user.
*
* @return The access rights.
*/
public final AccessFlags getUserAccess() {
return getAccess()[ Ugo.USER.index ];
}
/**
* Sets the access rights for a user.
* @param userAccess The access rights.
*/
public final void setUserAccess( final AccessFlags userAccess ) {
getAccess()[ Ugo.USER.index ] = userAccess;
}
/**
* Sets the access rights for a user.
* @param userAccess The access rights as int.
*/
public final void setUserAccess( final int userAccess ) {
setUserAccess( AccessFlags.flagsForMask( userAccess ) );
}
/**
* Returns the access rights for a group.
*
* @return The access rights..
*/
public final AccessFlags getGroupAccess() {
return getAccess()[ Ugo.GROUP.index ];
}
/**
* Sets the access rights for a group.
* @param groupAccess The access rights.
*/
public final void setGroupAccess( final AccessFlags groupAccess ) {
getAccess()[ Ugo.GROUP.index ] = groupAccess;
}
/**
* Sets the access rights for a group.
* @param groupAccess The access rights as int.
*/
public final void setGroupAccess( final int groupAccess ) {
setGroupAccess( AccessFlags.flagsForMask( groupAccess ) );
}
/**
* Returns the access rights for others.
*
* @return The access rights.
*/
public final AccessFlags getOtherAccess() {
return getAccess()[ Ugo.OTHER.index ];
}
/**
* Sets the access rights for others.
* @param otherAccess The access rights.
*/
public final void setOtherAccess( final AccessFlags otherAccess ) {
getAccess()[ Ugo.OTHER.index ] = otherAccess;
}
/**
* Sets the access rights for others.
* @param otherAccess The access rights as int.
*/
public final void setOtherAccess( final int otherAccess ) {
setOtherAccess( AccessFlags.flagsForMask( otherAccess ) );
}
/**
* Checks whether at least one of the given access values is set by the corresponding ugo in the access mask.
* This method is especially useful for access flags read, write, or execute, then it returns true if the
* corresponding access is granted by the flag.
*
* @param ugo The ugo rights.
* @param flag The access flag.
* @return true, if at least one access right of the flag is granted, otherwise false.
*/
public final boolean queryFlagsOn( final Ugo ugo, final AccessFlags flag ) {
return ( getAccess()[ ugo.index ].getMask() & flag.getMask() ) != 0;
}
/**
* Checks whether none of the given access values is set by the corresponding ugo in the access mask.
* @see queryFlagsOn
*
* @param ugo The ugo rights.
* @param flag The access flag.
* @return true, if no access right of the flag is granted, otherwise false.
*/
public final boolean queryFlagsOff( final Ugo ugo, final AccessFlags flag ) {
return !queryFlagsOn( ugo, flag );
}
/**
* Adds the access rights of the given flag to the corresponding ugo of the access mask.
*
* @param ugo The ugo rights.
* @param flag The flag.
*/
public final void addFlag( final Ugo ugo, final AccessFlags flag ) {
getAccess()[ ugo.index ] = AccessFlags.flagsForMask(
getAccess()[ ugo.index ].getMask( ) | flag.getMask()
);
}
/**
* Deletes the access rights of the given flag to the corresponding ugo of the access mask.
*
* @param ugo The ugo rights.
* @param flag The flag.
*/
public final void removeFlag( final Ugo ugo, final AccessFlags flag ) {
getAccess()[ ugo.index ] = AccessFlags.flagsForMask(
getAccess()[ ugo.index ].getMask( ) & ( flag.getMask() ^ AccessFlags.ALL.getMask() )
);
}
/**
* Returns the access masks' int values for user, group and other as String.
* @return The String value.
*/
@Override
public final String toString( ) {
String s;
if (special != null) {
s = String.valueOf( special );
} else {
s = "";
}
return s + getUserAccess().toString() + getGroupAccess().toString() + getOtherAccess().toString();
}
public final Integer getIntValue( ) {
return (
( getSpecial() != null ?
getSpecial() : 0 ) * 512
+ getUserAccess().getMask() * 64
+ getGroupAccess().getMask()* 8
+ getOtherAccess().getMask()
);
}
/**
* Returns an {@code AccessMask} from a String containing the bitmasks for
* all three access groups.
*
* The String must consist of exactly three characters, each one representing a number in [0;7].
* The first character defines the access mask of {@code user}
* The second character defines the access mask of {@code group}
* The third character defines the access mask of {@code other}
*
* The string might be prefixed with the spacial byte (@see special).
*
* @param msk a String representing the access masks of the different access groups.
* @return an {@code AccessMask} containing the bitmasks for
* all three access groups.
* @see AccessFlags
*/
public static AccessMask fromString( final String msk ) {
AccessMask am = new AccessMask( );
am.setAsString( msk );
return am;
}
/**
* Sets the special attribute.
* @param i The special value.
*/
private void setSpecial( final Integer i ) {
special = i;
}
/**
* Returns the special attribute.
* @return The special value.
*/
public final Integer getSpecial() {
return special;
}
/**
* Returns the access flags belonging to user, group and other.
* @return The access flags.
*/
public final AccessFlags[] getAccess() {
return access;
}
/**
* Sets the access flags.
* @param access The access flags.
*/
public final void setAccess( final AccessFlags[] access ) {
this.access = access;
}
/**
* Returns the access mask as String.
* @return The String value.
*/
public final String getAsString( ) {
return toString();
}
/**
* Sets the access flags from a String.
* @param msk The given String.
* @see AccessFlags#fromString(String)
*/
public final void setAsString( final String msk ) {
int l = msk.length( );
if ( l < Ugo.MAXRIGHTS || l > Ugo.MAXRIGHTS + 1 ) {
throw new IllegalArgumentException( "msk must have the length 3 or 4. Argument is: " + msk );
}
// AccessMask am = new AccessMask();
int i = 0;
if ( l == Ugo.MAXRIGHTS + 1 ) {
setSpecial( Integer.valueOf( "" + msk.charAt( i++ ) ) );
}
setUserAccess( AccessFlags.fromChar( msk.charAt( i ) ) );
setGroupAccess( AccessFlags.fromChar( msk.charAt( ++i ) ) );
setOtherAccess( AccessFlags.fromChar( msk.charAt( ++i ) ) );
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public final boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() == getClass()) {
AccessMask mask = (AccessMask) obj;
return mask.getAsString().equals(getAsString());
} else {
return false;
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public final int hashCode() {
final int start = 18;
final int multi = 23;
int hashCode = start;
hashCode = hashCode * multi + getAsString().hashCode();
return hashCode;
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.command.CommandProcessor;
import consulo.logging.Logger;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.designSurface.GuiEditor;
import com.intellij.uiDesigner.designSurface.InsertComponentProcessor;
import com.intellij.uiDesigner.lw.LwSplitPane;
import com.intellij.uiDesigner.palette.ComponentItem;
import com.intellij.uiDesigner.palette.Palette;
import com.intellij.uiDesigner.radComponents.*;
import com.intellij.uiDesigner.shared.XYLayoutManager;
import javax.annotation.Nonnull;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class SurroundAction extends AbstractGuiEditorAction {
private static final Logger LOG = Logger.getInstance(SurroundAction.class);
private final String myComponentClass;
public SurroundAction(String componentClass) {
final String className = componentClass.substring(componentClass.lastIndexOf('.') + 1);
getTemplatePresentation().setText(className);
myComponentClass = componentClass;
}
public void actionPerformed(final GuiEditor editor, final List<RadComponent> selection, final AnActionEvent e) {
// the action is also reused as quickfix for NoScrollPaneInspection, so this code should be kept here
FormEditingUtil.remapToActionTargets(selection);
if (!editor.ensureEditable()) {
return;
}
final RadContainer selectionParent = FormEditingUtil.getSelectionParent(selection);
assert selectionParent != null;
final Palette palette = Palette.getInstance(editor.getProject());
final ComponentItem cItem = palette.getItem(myComponentClass);
assert cItem != null;
CommandProcessor.getInstance().executeCommand(
editor.getProject(),
new Runnable() {
public void run() {
RadContainer newContainer = (RadContainer) InsertComponentProcessor.createInsertedComponent(editor, cItem);
if (newContainer == null) {
return;
}
if (cItem == palette.getPanelItem()) {
if (selectionParent.getLayoutManager().isGrid()) {
try {
newContainer.setLayoutManager(LayoutManagerRegistry.createLayoutManager(selectionParent.getLayoutManager().getName()));
}
catch (Exception e1) {
LOG.error(e1);
return;
}
}
else {
newContainer.setLayoutManager(LayoutManagerRegistry.createDefaultGridLayoutManager(editor.getProject()));
}
}
Rectangle rc = new Rectangle(0, 0, 1, 1);
int minIndex = Integer.MAX_VALUE;
if (selectionParent.getLayoutManager().isGrid()) {
rc = FormEditingUtil.getSelectionBounds(selection);
}
else if (selectionParent.getLayoutManager().isIndexed()) {
for(RadComponent c: selection) {
minIndex = Math.min(minIndex, selectionParent.indexOfComponent(c));
}
}
for(RadComponent c: selection) {
selectionParent.removeComponent(c);
}
if (selectionParent.getLayoutManager().isGrid()) {
final GridConstraints newConstraints = newContainer.getConstraints();
newConstraints.setRow(rc.y);
newConstraints.setColumn(rc.x);
newConstraints.setRowSpan(rc.height);
newConstraints.setColSpan(rc.width);
}
else if (selectionParent.getLayout() instanceof XYLayoutManager && selection.size() == 1) {
newContainer.setBounds(selection.get(0).getBounds());
}
if (selection.size() == 1) {
newContainer.setCustomLayoutConstraints(selection.get(0).getCustomLayoutConstraints());
}
if (minIndex != Integer.MAX_VALUE) {
selectionParent.addComponent(newContainer, minIndex);
}
else {
selectionParent.addComponent(newContainer);
}
if (newContainer instanceof RadTabbedPane) {
// the first tab is created by RadTabbedPane itself
assert newContainer.getComponentCount() == 1;
newContainer = (RadContainer) newContainer.getComponent(0);
}
else if (newContainer instanceof RadSplitPane) {
if (selection.size() > 2) {
RadContainer panel = InsertComponentProcessor.createPanelComponent(editor);
panel.setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT);
newContainer.addComponent(panel);
newContainer = panel;
}
else {
if (selection.size() > 0) {
selection.get(0).setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT);
}
if (selection.size() > 1) {
selection.get(1).setCustomLayoutConstraints(LwSplitPane.POSITION_RIGHT);
}
}
}
// if surrounding a single control with JPanel, 1x1 grid in resulting container is sufficient
// otherwise, copy column properties and row/col spans
if (newContainer.getComponentClass().equals(JPanel.class) && selection.size() > 1) {
if (selectionParent.getLayoutManager().isGrid()) {
newContainer.getGridLayoutManager().copyGridSection(selectionParent, newContainer, rc);
}
else {
// TODO[yole]: correctly handle surround from indexed
newContainer.setLayout(new GridLayoutManager(rc.height, rc.width));
}
}
for(RadComponent c: selection) {
if (selectionParent.getLayoutManager().isGrid()) {
if (selection.size() > 1) {
c.getConstraints().setRow(c.getConstraints().getRow() - rc.y);
c.getConstraints().setColumn(c.getConstraints().getColumn() - rc.x);
}
else {
c.getConstraints().setRow(0);
c.getConstraints().setColumn(0);
c.getConstraints().setRowSpan(1);
c.getConstraints().setColSpan(1);
}
}
newContainer.addComponent(c);
}
editor.refreshAndSave(true);
}
}, null, null);
}
protected void update(@Nonnull final GuiEditor editor, final ArrayList<RadComponent> selection, final AnActionEvent e) {
FormEditingUtil.remapToActionTargets(selection);
RadContainer selectionParent = FormEditingUtil.getSelectionParent(selection);
e.getPresentation().setEnabled(selectionParent != null &&
((!selectionParent.getLayoutManager().isGrid() && selection.size() == 1) ||
isSelectionContiguous(selectionParent, selection)) &&
canWrapSelection(selection));
}
private boolean canWrapSelection(final ArrayList<RadComponent> selection) {
if (myComponentClass.equals(JScrollPane.class.getName())) {
if (selection.size() > 1) return false;
RadComponent component = selection.get(0);
return component.getDelegee() instanceof Scrollable;
}
return true;
}
private static boolean isSelectionContiguous(RadContainer selectionParent,
ArrayList<RadComponent> selection) {
if (!selectionParent.getLayoutManager().isGrid()) {
return false;
}
Rectangle rc = FormEditingUtil.getSelectionBounds(selection);
for(RadComponent c: selectionParent.getComponents()) {
if (!selection.contains(c) &&
constraintsIntersect(true, c.getConstraints(), rc) &&
constraintsIntersect(false, c.getConstraints(), rc)) {
return false;
}
}
return true;
}
private static boolean constraintsIntersect(boolean horizontal,
GridConstraints constraints,
Rectangle rc) {
int start = constraints.getCell(!horizontal);
int end = start + constraints.getSpan(!horizontal) - 1;
int otherStart = horizontal ? rc.x : rc.y;
int otherEnd = otherStart + (horizontal ? rc.width : rc.height) - 1;
return start <= otherEnd && otherStart <= end;
}
}
| |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.impl.jdbc.data;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBValueFormatting;
import org.jkiss.dbeaver.model.app.DBPPlatform;
import org.jkiss.dbeaver.model.data.DBDContentCached;
import org.jkiss.dbeaver.model.data.DBDContentStorage;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.data.storage.BytesContentStorage;
import org.jkiss.dbeaver.model.data.storage.TemporaryContentStorage;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.MimeTypes;
import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
/**
* JDBCContentBLOB
*
* @author Serge Rider
*/
public class JDBCContentBLOB extends JDBCContentLOB {
private static final Log log = Log.getLog(JDBCContentBLOB.class);
private Blob blob;
private InputStream tmpStream;
public JDBCContentBLOB(DBCExecutionContext dataSource, Blob blob) {
super(dataSource);
this.blob = blob;
}
@Override
public long getLOBLength() throws DBCException {
if (blob != null) {
try {
return blob.length();
} catch (Throwable e) {
throw new DBCException(e, executionContext);
}
}
return 0;
}
@NotNull
@Override
public String getContentType()
{
return MimeTypes.OCTET_STREAM;
}
@Override
public DBDContentStorage getContents(DBRProgressMonitor monitor)
throws DBCException
{
if (storage == null && blob != null) {
long contentLength = getContentLength();
DBPPlatform platform = executionContext.getDataSource().getContainer().getPlatform();
if (contentLength < platform.getPreferenceStore().getInt(ModelPreferences.MEMORY_CONTENT_MAX_SIZE)) {
try {
try (InputStream bs = blob.getBinaryStream()) {
storage = BytesContentStorage.createFromStream(
bs,
contentLength,
getDefaultEncoding());
}
} catch (IOException e) {
throw new DBCException("IO error while reading content", e);
} catch (Throwable e) {
throw new DBCException(e, executionContext);
}
} else {
// Create new local storage
File tempFile;
try {
tempFile = ContentUtils.createTempContentFile(monitor, platform, "blob" + blob.hashCode());
}
catch (IOException e) {
throw new DBCException("Can't create temporary file", e);
}
try (OutputStream os = new FileOutputStream(tempFile)) {
try (InputStream bs = blob.getBinaryStream()) {
ContentUtils.copyStreams(bs, contentLength, os, monitor);
}
} catch (IOException e) {
ContentUtils.deleteTempFile(tempFile);
throw new DBCException("IO error while copying stream", e);
} catch (Throwable e) {
ContentUtils.deleteTempFile(tempFile);
throw new DBCException(e, executionContext);
}
this.storage = new TemporaryContentStorage(platform, tempFile, getDefaultEncoding(), true);
}
// Free blob - we don't need it anymore
releaseBlob();
}
return storage;
}
@Override
public void release()
{
releaseTempStream();
releaseBlob();
super.release();
}
private void releaseBlob() {
if (blob != null) {
try {
blob.free();
} catch (Throwable e) {
// Log as warning only if it is an exception.
// Errors just spam log
log.debug("Error freeing BLOB: " + e.getClass().getName() + ": " + e.getMessage());
}
blob = null;
}
}
private void releaseTempStream() {
if (tmpStream != null) {
ContentUtils.close(tmpStream);
tmpStream = null;
}
}
@Override
public void bindParameter(JDBCSession session, JDBCPreparedStatement preparedStatement, DBSTypedObject columnType, int paramIndex)
throws DBCException
{
try {
if (storage != null) {
// Write new blob value
releaseTempStream();
tmpStream = storage.getContentStream();
try {
preparedStatement.setBinaryStream(paramIndex, tmpStream);
}
catch (Throwable e) {
try {
if (e instanceof SQLException) {
throw (SQLException)e;
} else {
try {
preparedStatement.setBinaryStream(paramIndex, tmpStream, storage.getContentLength());
}
catch (Throwable e1) {
if (e1 instanceof SQLException) {
throw (SQLException)e1;
} else {
preparedStatement.setBinaryStream(paramIndex, tmpStream, (int)storage.getContentLength());
}
}
}
} catch (SQLFeatureNotSupportedException e1) {
// Stream values seems to be unsupported
// Let's try bytes
int contentLength = (int) storage.getContentLength();
ByteArrayOutputStream buffer = new ByteArrayOutputStream(contentLength);
ContentUtils.copyStreams(tmpStream, contentLength, buffer, session.getProgressMonitor());
preparedStatement.setBytes(paramIndex, buffer.toByteArray());
}
}
} else if (blob != null) {
try {
if (columnType.getDataKind() == DBPDataKind.BINARY) {
preparedStatement.setBinaryStream(paramIndex, blob.getBinaryStream());
} else {
preparedStatement.setBlob(paramIndex, blob);
}
}
catch (Throwable e0) {
// Write new blob value
releaseTempStream();
tmpStream = blob.getBinaryStream();
try {
preparedStatement.setBinaryStream(paramIndex, tmpStream);
}
catch (Throwable e) {
if (e instanceof SQLException) {
throw (SQLException)e;
} else {
try {
preparedStatement.setBinaryStream(paramIndex, tmpStream, blob.length());
}
catch (Throwable e1) {
if (e1 instanceof SQLException) {
throw (SQLException)e1;
} else {
preparedStatement.setBinaryStream(paramIndex, tmpStream, (int)blob.length());
}
}
}
}
}
} else {
preparedStatement.setNull(paramIndex, java.sql.Types.BLOB);
}
}
catch (SQLException e) {
throw new DBCException(e, session.getExecutionContext());
}
catch (Throwable e) {
throw new DBCException("Error while reading content", e);
}
}
@Override
public Object getRawValue() {
return blob;
}
@Override
public boolean isNull()
{
return blob == null && storage == null;
}
@Override
protected JDBCContentLOB createNewContent()
{
return new JDBCContentBLOB(executionContext, null);
}
@Override
public String getDisplayString(DBDDisplayFormat format)
{
if (blob == null && storage == null) {
return null;
}
if (storage != null && storage instanceof DBDContentCached) {
final Object cachedValue = ((DBDContentCached) storage).getCachedValue();
if (cachedValue instanceof byte[]) {
return DBValueFormatting.formatBinaryString(executionContext.getDataSource(), (byte[]) cachedValue, format);
}
}
return "[BLOB]";
}
}
| |
/*
* Copyright (c) 2010-2015 William Bittle http://www.dyn4j.org/
* 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 dyn4j 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 org.dyn4j.collision;
import java.util.List;
import junit.framework.TestCase;
import org.dyn4j.collision.broadphase.BroadphasePair;
import org.dyn4j.collision.manifold.ClippingManifoldSolver;
import org.dyn4j.collision.manifold.Manifold;
import org.dyn4j.collision.manifold.ManifoldPoint;
import org.dyn4j.collision.narrowphase.Gjk;
import org.dyn4j.collision.narrowphase.Penetration;
import org.dyn4j.collision.narrowphase.Sat;
import org.dyn4j.collision.narrowphase.Separation;
import org.dyn4j.geometry.Segment;
import org.dyn4j.geometry.Shape;
import org.dyn4j.geometry.Transform;
import org.dyn4j.geometry.Triangle;
import org.dyn4j.geometry.Vector2;
import org.junit.Before;
import org.junit.Test;
/**
* Test case for {@link Segment} - {@link Triangle} collision detection.
* @author William Bittle
* @version 3.1.5
* @since 1.0.0
*/
public class SegmentTriangleTest extends AbstractTest {
/** The test {@link Segment} */
private Segment seg;
/** The test {@link Triangle} */
private Triangle tri;
/**
* Sets up the test.
*/
@Before
public void setup() {
this.seg = new Segment(new Vector2(-0.3, 0.2), new Vector2(0.0, -0.1));
this.tri = new Triangle(
new Vector2(0.45, -0.12),
new Vector2(-0.45, 0.38),
new Vector2(-0.15, -0.22));
}
/**
* Tests {@link Shape} AABB.
*/
@Test
public void detectShapeAABB() {
Transform t1 = new Transform();
Transform t2 = new Transform();
// test containment
TestCase.assertTrue(this.sap.detect(seg, t1, tri, t2));
TestCase.assertTrue(this.sap.detect(tri, t2, seg, t1));
// test overlap
t2.translate(0.15, 0.0);
TestCase.assertTrue(this.sap.detect(seg, t1, tri, t2));
TestCase.assertTrue(this.sap.detect(tri, t2, seg, t1));
// test only AABB overlap
t2.translate(0.0, 0.2);
TestCase.assertTrue(this.sap.detect(seg, t1, tri, t2));
TestCase.assertTrue(this.sap.detect(tri, t2, seg, t1));
// test no overlap
t2.translate(0.0, 0.5);
TestCase.assertFalse(this.sap.detect(seg, t1, tri, t2));
TestCase.assertFalse(this.sap.detect(tri, t2, seg, t1));
}
/**
* Tests {@link Collidable} AABB.
*/
@Test
public void detectCollidableAABB() {
// create some collidables
CollidableTest ct1 = new CollidableTest(seg);
CollidableTest ct2 = new CollidableTest(tri);
// test containment
TestCase.assertTrue(this.sap.detect(ct1, ct2));
TestCase.assertTrue(this.sap.detect(ct2, ct1));
// test overlap
ct2.translate(0.15, 0.0);
TestCase.assertTrue(this.sap.detect(ct1, ct2));
TestCase.assertTrue(this.sap.detect(ct2, ct1));
// test only AABB overlap
ct2.translate(0.0, 0.2);
TestCase.assertTrue(this.sap.detect(ct1, ct2));
TestCase.assertTrue(this.sap.detect(ct2, ct1));
// test no overlap
ct2.translate(0.0, 0.5);
TestCase.assertFalse(this.sap.detect(ct1, ct2));
TestCase.assertFalse(this.sap.detect(ct2, ct1));
}
/**
* Tests the broadphase detectors.
*/
@Test
public void detectBroadphase() {
List<BroadphasePair<CollidableTest, Fixture>> pairs;
// create some collidables
CollidableTest ct1 = new CollidableTest(seg);
CollidableTest ct2 = new CollidableTest(tri);
this.sap.add(ct1);
this.sap.add(ct2);
this.dyn.add(ct1);
this.dyn.add(ct2);
// test containment
pairs = this.sap.detect();
TestCase.assertEquals(1, pairs.size());
pairs = this.dyn.detect();
TestCase.assertEquals(1, pairs.size());
// test overlap
ct1.translate(0.15, 0.0);
this.sap.update(ct1);
this.dyn.update(ct1);
pairs = this.sap.detect();
TestCase.assertEquals(1, pairs.size());
pairs = this.dyn.detect();
TestCase.assertEquals(1, pairs.size());
// test only AABB overlap
ct2.translate(0.0, 0.2);
this.sap.update(ct2);
this.dyn.update(ct2);
pairs = this.sap.detect();
TestCase.assertEquals(1, pairs.size());
pairs = this.dyn.detect();
TestCase.assertEquals(1, pairs.size());
// test no overlap
ct1.translate(0.0, 0.9);
this.sap.update(ct1);
this.dyn.update(ct1);
pairs = this.sap.detect();
TestCase.assertEquals(0, pairs.size());
pairs = this.dyn.detect();
TestCase.assertEquals(0, pairs.size());
}
/**
* Tests {@link Sat}.
*/
@Test
public void detectSat() {
Penetration p = new Penetration();
Transform t1 = new Transform();
Transform t2 = new Transform();
Vector2 n = null;
// test containment
TestCase.assertTrue(this.sat.detect(seg, t1, tri, t2, p));
TestCase.assertTrue(this.sat.detect(seg, t1, tri, t2));
n = p.getNormal();
TestCase.assertEquals(0.894, n.x, 1.0e-3);
TestCase.assertEquals(0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.187, p.getDepth(), 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.sat.detect(tri, t2, seg, t1, p));
TestCase.assertTrue(this.sat.detect(tri, t2, seg, t1));
n = p.getNormal();
TestCase.assertEquals(-0.894, n.x, 1.0e-3);
TestCase.assertEquals(-0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.187, p.getDepth(), 1.0e-3);
// test overlap
t2.translate(0.15, 0.0);
TestCase.assertTrue(this.sat.detect(seg, t1, tri, t2, p));
TestCase.assertTrue(this.sat.detect(seg, t1, tri, t2));
n = p.getNormal();
TestCase.assertEquals(0.894, n.x, 1.0e-3);
TestCase.assertEquals(0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.053, p.getDepth(), 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.sat.detect(tri, t2, seg, t1, p));
TestCase.assertTrue(this.sat.detect(tri, t2, seg, t1));
n = p.getNormal();
TestCase.assertEquals(-0.894, n.x, 1.0e-3);
TestCase.assertEquals(-0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.053, p.getDepth(), 1.0e-3);
// test AABB overlap
t2.translate(0.0, 0.2);
TestCase.assertFalse(this.sat.detect(seg, t1, tri, t2, p));
TestCase.assertFalse(this.sat.detect(seg, t1, tri, t2));
// try reversing the shapes
TestCase.assertFalse(this.sat.detect(tri, t2, seg, t1, p));
TestCase.assertFalse(this.sat.detect(tri, t2, seg, t1));
// test no overlap
t2.translate(0.0, 0.5);
TestCase.assertFalse(this.sat.detect(seg, t1, tri, t2, p));
TestCase.assertFalse(this.sat.detect(seg, t1, tri, t2));
// try reversing the shapes
TestCase.assertFalse(this.sat.detect(tri, t2, seg, t1, p));
TestCase.assertFalse(this.sat.detect(tri, t2, seg, t1));
}
/**
* Tests {@link Gjk}.
*/
@Test
public void detectGjk() {
Penetration p = new Penetration();
Transform t1 = new Transform();
Transform t2 = new Transform();
Vector2 n = null;
// test containment
TestCase.assertTrue(this.gjk.detect(seg, t1, tri, t2, p));
TestCase.assertTrue(this.gjk.detect(seg, t1, tri, t2));
n = p.getNormal();
TestCase.assertEquals(0.894, n.x, 1.0e-3);
TestCase.assertEquals(0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.187, p.getDepth(), 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.gjk.detect(tri, t2, seg, t1, p));
TestCase.assertTrue(this.gjk.detect(tri, t2, seg, t1));
n = p.getNormal();
TestCase.assertEquals(-0.894, n.x, 1.0e-3);
TestCase.assertEquals(-0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.187, p.getDepth(), 1.0e-3);
// test overlap
t2.translate(0.15, 0.0);
TestCase.assertTrue(this.gjk.detect(seg, t1, tri, t2, p));
TestCase.assertTrue(this.gjk.detect(seg, t1, tri, t2));
n = p.getNormal();
TestCase.assertEquals(0.894, n.x, 1.0e-3);
TestCase.assertEquals(0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.053, p.getDepth(), 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.gjk.detect(tri, t2, seg, t1, p));
TestCase.assertTrue(this.gjk.detect(tri, t2, seg, t1));
n = p.getNormal();
TestCase.assertEquals(-0.894, n.x, 1.0e-3);
TestCase.assertEquals(-0.447, n.y, 1.0e-3);
TestCase.assertEquals(0.053, p.getDepth(), 1.0e-3);
// test AABB overlap
t2.translate(0.0, 0.2);
TestCase.assertFalse(this.gjk.detect(seg, t1, tri, t2, p));
TestCase.assertFalse(this.gjk.detect(seg, t1, tri, t2));
// try reversing the shapes
TestCase.assertFalse(this.gjk.detect(tri, t2, seg, t1, p));
TestCase.assertFalse(this.gjk.detect(tri, t2, seg, t1));
// test no overlap
t2.translate(0.0, 0.5);
TestCase.assertFalse(this.gjk.detect(seg, t1, tri, t2, p));
TestCase.assertFalse(this.gjk.detect(seg, t1, tri, t2));
// try reversing the shapes
TestCase.assertFalse(this.gjk.detect(tri, t2, seg, t1, p));
TestCase.assertFalse(this.gjk.detect(tri, t2, seg, t1));
}
/**
* Tests the {@link Gjk} distance method.
*/
@Test
public void gjkDistance() {
Separation s = new Separation();
Transform t1 = new Transform();
Transform t2 = new Transform();
Vector2 n, p1, p2;
// test containment
TestCase.assertFalse(this.gjk.distance(seg, t1, tri, t2, s));
// try reversing the shapes
TestCase.assertFalse(this.gjk.distance(tri, t2, seg, t1, s));
// test overlap
t2.translate(0.15, 0.0);
TestCase.assertFalse(this.gjk.distance(seg, t1, tri, t2, s));
// try reversing the shapes
TestCase.assertFalse(this.gjk.distance(tri, t2, seg, t1, s));
// test AABB overlap
t2.translate(0.0, 0.2);
TestCase.assertTrue(this.gjk.distance(seg, t1, tri, t2, s));
n = s.getNormal();
p1 = s.getPoint1();
p2 = s.getPoint2();
TestCase.assertEquals(0.056, s.getDistance(), 1.0e-3);
TestCase.assertEquals(0.707, n.x, 1.0e-3);
TestCase.assertEquals(0.707, n.y, 1.0e-3);
TestCase.assertEquals(-0.040, p1.x, 1.0e-3);
TestCase.assertEquals(-0.060, p1.y, 1.0e-3);
TestCase.assertEquals(0.000, p2.x, 1.0e-3);
TestCase.assertEquals(-0.019, p2.y, 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.gjk.distance(tri, t2, seg, t1, s));
n = s.getNormal();
p1 = s.getPoint1();
p2 = s.getPoint2();
TestCase.assertEquals(0.056, s.getDistance(), 1.0e-3);
TestCase.assertEquals(-0.707, n.x, 1.0e-3);
TestCase.assertEquals(-0.707, n.y, 1.0e-3);
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(-0.019, p1.y, 1.0e-3);
TestCase.assertEquals(-0.040, p2.x, 1.0e-3);
TestCase.assertEquals(-0.060, p2.y, 1.0e-3);
// test no overlap
t2.translate(0.0, 0.5);
TestCase.assertTrue(this.gjk.distance(seg, t1, tri, t2, s));
n = s.getNormal();
p1 = s.getPoint1();
p2 = s.getPoint2();
TestCase.assertEquals(0.410, s.getDistance(), 1.0e-3);
TestCase.assertEquals(0.707, n.x, 1.0e-3);
TestCase.assertEquals(0.707, n.y, 1.0e-3);
TestCase.assertEquals(-0.290, p1.x, 1.0e-3);
TestCase.assertEquals(0.190, p1.y, 1.0e-3);
TestCase.assertEquals(0.000, p2.x, 1.0e-3);
TestCase.assertEquals(0.480, p2.y, 1.0e-3);
// try reversing the shapes
TestCase.assertTrue(this.gjk.distance(tri, t2, seg, t1, s));
n = s.getNormal();
p1 = s.getPoint1();
p2 = s.getPoint2();
TestCase.assertEquals(0.410, s.getDistance(), 1.0e-3);
TestCase.assertEquals(-0.707, n.x, 1.0e-3);
TestCase.assertEquals(-0.707, n.y, 1.0e-3);
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(0.480, p1.y, 1.0e-3);
TestCase.assertEquals(-0.290, p2.x, 1.0e-3);
TestCase.assertEquals(0.190, p2.y, 1.0e-3);
}
/**
* Test the {@link ClippingManifoldSolver}.
*/
@Test
public void getClipManifold() {
Manifold m = new Manifold();
Penetration p = new Penetration();
Transform t1 = new Transform();
Transform t2 = new Transform();
ManifoldPoint mp;
Vector2 p1;
// test containment gjk
this.gjk.detect(seg, t1, tri, t2, p);
TestCase.assertTrue(this.cmfs.getManifold(p, seg, t1, tri, t2, m));
TestCase.assertEquals(2, m.getPoints().size());
// try reversing the shapes
this.gjk.detect(tri, t2, seg, t1, p);
TestCase.assertTrue(this.cmfs.getManifold(p, tri, t2, seg, t1, m));
TestCase.assertEquals(2, m.getPoints().size());
// test containment sat
this.sat.detect(seg, t1, tri, t2, p);
TestCase.assertTrue(this.cmfs.getManifold(p, seg, t1, tri, t2, m));
TestCase.assertEquals(2, m.getPoints().size());
// try reversing the shapes
this.sat.detect(tri, t2, seg, t1, p);
TestCase.assertTrue(this.cmfs.getManifold(p, tri, t2, seg, t1, m));
TestCase.assertEquals(2, m.getPoints().size());
t2.translate(0.15, 0.0);
// test overlap gjk
this.gjk.detect(seg, t1, tri, t2, p);
TestCase.assertTrue(this.cmfs.getManifold(p, seg, t1, tri, t2, m));
TestCase.assertEquals(1, m.getPoints().size());
mp = m.getPoints().get(0);
p1 = mp.getPoint();
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(-0.100, p1.y, 1.0e-3);
TestCase.assertEquals(0.053, mp.getDepth(), 1.0e-3);
// try reversing the shapes
this.gjk.detect(tri, t2, seg, t1, p);
TestCase.assertTrue(this.cmfs.getManifold(p, tri, t2, seg, t1, m));
TestCase.assertEquals(1, m.getPoints().size());
mp = m.getPoints().get(0);
p1 = mp.getPoint();
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(-0.100, p1.y, 1.0e-3);
TestCase.assertEquals(0.053, mp.getDepth(), 1.0e-3);
// test overlap sat
this.sat.detect(seg, t1, tri, t2, p);
TestCase.assertTrue(this.cmfs.getManifold(p, seg, t1, tri, t2, m));
TestCase.assertEquals(1, m.getPoints().size());
mp = m.getPoints().get(0);
p1 = mp.getPoint();
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(-0.100, p1.y, 1.0e-3);
TestCase.assertEquals(0.053, mp.getDepth(), 1.0e-3);
// try reversing the shapes
this.sat.detect(tri, t2, seg, t1, p);
TestCase.assertTrue(this.cmfs.getManifold(p, tri, t2, seg, t1, m));
TestCase.assertEquals(1, m.getPoints().size());
mp = m.getPoints().get(0);
p1 = mp.getPoint();
TestCase.assertEquals(0.000, p1.x, 1.0e-3);
TestCase.assertEquals(-0.100, p1.y, 1.0e-3);
TestCase.assertEquals(0.053, mp.getDepth(), 1.0e-3);
}
}
| |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the KiWi Project 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.
*
* Contributor(s):
*
*
*/
package kiwi.wiki.action;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import kiwi.api.content.ContentItemService;
import kiwi.api.entity.KiWiEntityManager;
import kiwi.api.informationextraction.InformationExtractionService;
import kiwi.api.tagging.TagRecommendation;
import kiwi.api.tagging.TagRecommendationService;
import kiwi.api.tagging.TaggingService;
import kiwi.api.triplestore.TripleStore;
import kiwi.model.Constants;
import kiwi.model.content.ContentItem;
import kiwi.model.tagging.Tag;
import kiwi.model.tagging.TagBean;
import kiwi.model.user.User;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
/**
* @author Sebastian Schaffert
*
*/
@Name("taggingAction")
@Scope(ScopeType.CONVERSATION)
//@Transactional
public class TaggingAction implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Logger
private static Log log;
@In FacesMessages facesMessages;
// input current user; might affect the loading of the content item
@In(create = true)
private User currentUser;
@In(create=true)
@Out
private ContentItem currentContentItem;
// the entity manager used by this KiWi system
@In
private EntityManager entityManager;
@In
private TripleStore tripleStore;
@In
private KiWiEntityManager kiwiEntityManager;
@In
private ContentItemService contentItemService;
@In
private TagRecommendationService tagRecommendationService;
@In
private TaggingService taggingService;
// newly created tag
private String tagLabel;
private boolean shown = false;
/**
* Action called by tagging.xhtml add button when submitting a new tag for the resource
*/
public void addTag() {
log.info("adding new tags for input #0", tagLabel);
// avoid detached entities
currentUser = entityManager.merge(currentUser);
currentContentItem = entityManager.merge(currentContentItem);
String[] components = tagLabel.split(",");
for(String component : components) {
log.info("adding tag #0",component);
String label = component.trim();
addTag(label);
}
// entityManager.flush();
entityManager.refresh(currentContentItem);
tripleStore.persist(currentContentItem);
entityManager.refresh(currentUser);
tripleStore.persist(currentUser);
// do we need to refresh/merge?
tagLabel = "";
log.info("tag added successfully");
}
/**
* Action called by tagging.xhtml add button when endorsing an existing tag for the resource
*/
public void addTag(ContentItem taggingItem) {
log.info("endorsing tag with label #0", taggingItem.getTitle());
// avoid detached entities
currentUser = entityManager.merge(currentUser);
currentContentItem = entityManager.merge(currentContentItem);
taggingService.createTagging(taggingItem.getTitle(), currentContentItem, taggingItem, currentUser);
entityManager.refresh(currentContentItem);
Events.instance().raiseEvent("tagUpdate");
}
public void addTag(String label) {
// TODO replace the whole rest of the method by this line after the review!
// taggingService.addTag(currentContentItem, label);
// TODO: query by uri instead of by title
ContentItem taggingItem = contentItemService.getContentItemByTitle(label);
if(taggingItem == null) {
// create new Content Item of type "tag" if the tag does not yet exist
taggingItem = contentItemService.createContentItem("content/"+label.toLowerCase().replace(" ","_")+"/"+UUID.randomUUID().toString());
taggingItem.addType(tripleStore.createUriResource(Constants.NS_KIWI_CORE+"Tag"));
contentItemService.updateTitle(taggingItem, label.toLowerCase());
kiwiEntityManager.persist(taggingItem);
log.info("created new content item for non-existant tag");
}
taggingService.createTagging(label, currentContentItem, taggingItem, currentUser);
entityManager.refresh(currentContentItem);
Events.instance().raiseEvent("tagUpdate");
}
public void addTagLine(String label) {
if(tagLabel != null && !"".equals(tagLabel)) {
tagLabel += ", ";
}
tagLabel += label;
}
public void removeTag(ContentItem taggingItem) {
log.info("removing tag #0 by user #1",taggingItem.getTitle(),currentUser.getLogin());
// avoid detached entities
if(!entityManager.contains(currentUser)) {
currentUser = entityManager.merge(currentUser);
}
if(!entityManager.contains(currentContentItem)) {
currentContentItem = entityManager.merge(currentContentItem);
}
Query q = entityManager.createNamedQuery("taggingAction.getTagByIdAuthor");
q.setParameter("login", currentUser.getLogin());
q.setParameter("id",taggingItem.getId());
List<Tag> l = (List<Tag>)q.getResultList();
for(Tag t : l) {
taggingService.removeTagging(t);
}
entityManager.refresh(currentContentItem);
Events.instance().raiseEvent("tagUpdate");
}
public void acceptRecommendation(String category, String label) {
TagCloudAction tagCloudAction = (TagCloudAction)Component.getInstance("kiwi.wiki.tagCloudAction");
for (TagRecommendation tagRecommendation : tagCloudAction.getTagRecommendationGroup(category)) {
if (tagRecommendation.getLabel().equals(label)) {
tagCloudAction.removeRecommendation(tagRecommendation);
addTagLine(tagRecommendation.getLabel());
if (tagRecommendation.getSuggestion() != null) {
InformationExtractionService informationExtractionService = (InformationExtractionService)Component.getInstance("kiwi.informationextraction.informationExtractionService");
informationExtractionService.acceptSuggestion(tagRecommendation.getSuggestion(), currentUser);
}
return;
}
}
}
public void rejectRecommendation(String category, String label) {
TagCloudAction tagCloudAction = (TagCloudAction)Component.getInstance("kiwi.wiki.tagCloudAction");
for (TagRecommendation tagRecommendation : tagCloudAction.getTagRecommendationGroup(category)) {
if (tagRecommendation.getLabel().equals(label)) {
tagCloudAction.removeRecommendation(tagRecommendation);
if (tagRecommendation.getSuggestion() != null) {
InformationExtractionService informationExtractionService = (InformationExtractionService)Component.getInstance("kiwi.informationextraction.informationExtractionService");
informationExtractionService.rejectSuggestion(tagRecommendation.getSuggestion(), currentUser);
}
return;
}
}
}
/**
* @return the tagLabel
*/
public String getTagLabel() {
return tagLabel;
}
/**
* @param tagLabel the tagLabel to set
*/
public void setTagLabel(String tagLabel) {
this.tagLabel = tagLabel;
}
public void onShow() {
shown=true;
}
public boolean isShown() {
return shown;
}
public void setShown(boolean shown) {
this.shown = shown;
}
public List<String> autocomplete(Object param) {
return taggingService.autocomplete(param.toString().toLowerCase());
/*
List<String> result = new LinkedList<String>();
javax.persistence.Query q =
entityManager.createNamedQuery("taggingAction.autocomplete");
q.setParameter("n", param.toString().toLowerCase()+"%");
q.setHint("org.hibernate.cacheable", true);
try {
result.addAll(q.getResultList());
} catch (NoResultException ex) {
}
return result;
*/
}
@DataModel
private List<TagBean> setupTagList;
/**
* A factory method for setting up the list of my tags.
*
*/
@Factory("setupTagList")
public void initTagList() {
if(setupTagList == null) {
setupTagList = new LinkedList<TagBean>();
List<Tag> tagsByUser = taggingService.getTagsByUser(currentUser);
for (Tag tag : tagsByUser) {
TagBean tagBean = new TagBean();
tagBean.setTag(tag);
tagBean.setPurpose(tag.getPurpose());
tagBean.setContentItem(tag.getTaggedResource());
setupTagList.add(tagBean);
}
}
}
/**
* Update the tag puporse
* @param tag
*/
public String updateTagPurpose() {
for(TagBean bean : setupTagList) {
if(bean.getPurpose()!=null) {
bean.getTag().setPurpose(bean.getPurpose());
kiwiEntityManager.persist(bean.getTag());
}
}
return "success";
}
}
| |
package examples;
import java.io.*;
import basico.Estoque;
import basico.Produto;
public class JavaLesson32 {
static Estoque estoque = new Estoque();
private static class Customer{
public String firstName, lastName;
public int custAge;
public Customer(String firstName, String lastName, int custAge){
this.firstName = firstName;
this.lastName = lastName;
this.custAge = custAge;
}
}
public static void main(String[] args) {
Customer[] customers = getCustomers();
PrintWriter customerOutput = createFile("teste.txt");
createCustomers(estoque, customerOutput);
customerOutput.close();
getFileInfo();
}
private static void getFileInfo() {
System.out.println("Info Written to File\n");
File listOfNames = new File("texto.txt");
try{
BufferedReader getInfo = new BufferedReader(new FileReader(listOfNames));
String custInfo = getInfo.readLine();
while(custInfo != null){
String[] produto = custInfo.split(", ");
int preco = Integer.parseInt(produto[1]);
custInfo = getInfo.readLine();
}
}
catch(FileNotFoundException e){
System.out.println("Couldn't Find File");
System.exit(0);
}
catch(IOException e){
System.out.println("IO Error");
System.exit(0);
}
}
private static void createCustomers(Estoque estoque, PrintWriter customerOutput) {
// TODO Auto-generated method stub
int percorre = 0;
File listaProdutos = new File("texto.txt");
try{
BufferedReader leitor = new BufferedReader(new FileReader(listaProdutos));
String informacaoProduto = leitor.readLine();
while(informacaoProduto != null){
String[] produtoTemp = informacaoProduto.split(", ");
double preco = Double.parseDouble(produtoTemp[1]);
int quantidade = Integer.parseInt(produtoTemp[2]);
// System.out.println(produtoTemp[3] + " " + produtoTemp[0] +
// " tem " + produtoTemp[2] + " unidade(s) e custa R$" + produtoTemp[1]);
if(produtoTemp[3].equals("bebida")){
estoque.bebidas[percorre] = new Produto(produtoTemp[0], preco, quantidade, basico.TipoProduto.bebida);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
if(produtoTemp[3].equals("snack")){
estoque.snacks[percorre] = new Produto(produtoTemp[0], preco, quantidade, basico.TipoProduto.snack);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
if(produtoTemp[3].equals("outro")){
estoque.outros[percorre] = new Produto(produtoTemp[0], preco, quantidade, basico.TipoProduto.outro);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
informacaoProduto = leitor.readLine();
}
}
catch(FileNotFoundException e){
System.out.println("Couldn't Find File");
System.exit(0);
}
catch(IOException e){
System.out.println("IO Error");
System.exit(0);
}
try{
File listaProdutos1 = new File("texto.txt");
BufferedReader leitor1 = new BufferedReader(new FileReader(listaProdutos1));
try{
File listaTemp = new File("textoTemp.txt");
customerOutput = new PrintWriter(new BufferedWriter(new FileWriter(listaTemp)));
}
catch(IOException e){
System.out.println("An I/O Error Occurred");
System.exit(0);
}
String informacaoProduto = leitor1.readLine();
String informacaoAtualizada;
String preco;
String quantidade;
while(informacaoProduto != null){
String[] produtoTemp = informacaoProduto.split(", ");
customerOutput.println("oi");
if(produtoTemp[3].equals("bebida")){
preco = String.valueOf(estoque.bebidas[percorre].getPreco());
quantidade = String.valueOf(estoque.bebidas[percorre].getQuantidade());
informacaoAtualizada = (produtoTemp[0] + ", " + preco + ", " + quantidade + ", bebida");
customerOutput.println(informacaoAtualizada);
//System.out.println(informacaoAtualizada);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
//
if(produtoTemp[3].equals("snack")){
preco = String.valueOf(estoque.bebidas[percorre].getPreco());
quantidade = String.valueOf(estoque.bebidas[percorre].getQuantidade());
informacaoAtualizada = (produtoTemp[0] + ", " + preco + ", " + quantidade + ", snack");
//System.out.println(informacaoAtualizada);
customerOutput.println(informacaoAtualizada);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
if(produtoTemp[3].equals("outro")){
preco = String.valueOf(estoque.bebidas[percorre].getPreco());
quantidade = String.valueOf(estoque.bebidas[percorre].getQuantidade());
informacaoAtualizada = (produtoTemp[0] + ", " + preco + ", " + quantidade + ", outro");
//System.out.println(informacaoAtualizada);
customerOutput.println(informacaoAtualizada);
percorre++;
if(percorre == 7){
percorre = 0;
}
}
informacaoProduto = leitor1.readLine();
}
}
catch(FileNotFoundException e){
System.out.println("Couldn't Find File");
System.exit(0);
}
catch(IOException e){
System.out.println("IO Error");
System.exit(0);
}
}
private static Customer[] getCustomers() {
Customer[] customers = new Customer[5];
customers[0] = new Customer("John", "Smith", 21);
customers[1] = new Customer("Sally", "Smith", 30);
customers[2] = new Customer("Paul", "Ryan", 21);
customers[3] = new Customer("Mark", "Jacobs", 21);
customers[4] = new Customer("Steve", "Nash", 21);
return customers;
}
private static PrintWriter createFile(String fileName){
try{
File listOfNames = new File(fileName);
PrintWriter infoToWrite = new PrintWriter(new BufferedWriter(new FileWriter(listOfNames)));
return infoToWrite;
}
catch(IOException e){
System.out.println("An IO Error");
System.exit(0);
}
return null;
}
}
| |
package com.eolwral.osmonitor;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import com.eolwral.osmonitor.core.cpuInfo;
import com.eolwral.osmonitor.core.cpuInfoList;
import com.eolwral.osmonitor.core.networkInfo;
import com.eolwral.osmonitor.core.networkInfoList;
import com.eolwral.osmonitor.core.osInfo;
import com.eolwral.osmonitor.core.processInfo;
import com.eolwral.osmonitor.core.processInfoList;
import com.eolwral.osmonitor.ipc.IpcService;
import com.eolwral.osmonitor.ipc.IpcService.ipcClientListener;
import com.eolwral.osmonitor.ipc.ipcCategory;
import com.eolwral.osmonitor.ipc.ipcData;
import com.eolwral.osmonitor.ipc.ipcMessage;
import com.eolwral.osmonitor.settings.Settings;
import com.eolwral.osmonitor.settings.Settings.NotificationType;
import com.eolwral.osmonitor.settings.Settings.StatusBarColor;
import com.eolwral.osmonitor.util.CoreUtil;
import com.eolwral.osmonitor.util.ProcessUtil;
import com.eolwral.osmonitor.util.UserInterfaceUtil;
import java.nio.ByteBuffer;
import java.util.Locale;
public class OSMonitorService extends Service implements ipcClientListener {
private static final int NOTIFYID = 20100811;
private IpcService ipcService = null;
private int UpdateInterval = 2;
private boolean isRegistered = false;
private NotificationManager nManager = null;
private NotificationCompat.Builder nBuilder = null;
// process
private int iconColor = 0;
private int fontColor = 0;
private boolean isSetTop = false;
private float cpuUsage = 0;
private float ioWaitUsage = 0;
private float[] topUsage = new float[3];
private String[] topProcess = new String[3];
// memory
private long memoryTotal = 0;
private long memoryFree = 0;
// battery
private boolean useCelsius = false;
private int battLevel = 0; // percentage value or -1 for unknown
private int temperature = 0;
// network
private long trafficOut = 0;
private long trafficIn = 0;
// private
private ProcessUtil infoHelper = null;
private Settings settings = null;
private int notificationType = NotificationType.MEMORY_BATTERY;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
settings = Settings.getInstance(this);
IpcService.Initialize(this);
ipcService = IpcService.getInstance();
refreshSettings();
initializeNotification();
if (settings.isEnableCPUMeter()) {
infoHelper = ProcessUtil.getInstance(this, false);
initService();
}
}
private void refreshSettings() {
// use notification for meta color
if (CoreUtil.isLollipop()) {
iconColor = R.drawable.ic_cpu_graph_meta;
}
else {
switch (settings.getCPUMeterColor()) {
case StatusBarColor.GREEN:
iconColor = R.drawable.ic_cpu_graph_green;
break;
case StatusBarColor.BLUE:
iconColor = R.drawable.ic_cpu_graph_blue;
break;
}
}
notificationType = settings.getNotificationType();
fontColor = settings.getNotificationFontColor();
isSetTop = settings.isNotificationOnTop();
useCelsius = settings.isUseCelsius();
// recreate connection type when refreshing settings
ipcService.createConnection();
}
@Override
public void onDestroy() {
endNotification();
endService();
if (!settings.getSessionValue().equals("Non-Exit"))
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
private void endNotification() {
nManager.cancel(NOTIFYID);
stopForeground(true);
}
private void initializeNotification() {
Intent notificationIntent = new Intent(this, OSMonitor.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
this.getBaseContext(), 0, notificationIntent, 0);
nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nBuilder = new NotificationCompat.Builder(this);
nBuilder.setContentTitle(getResources().getText(R.string.ui_appname));
nBuilder.setContentText(getResources().getText(R.string.ui_shortcut_detail));
nBuilder.setOnlyAlertOnce(true);
nBuilder.setOngoing(true);
nBuilder.setContentIntent(contentIntent);
// Set infos as public
nBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
// Use new style icon for Lollipop
if (CoreUtil.isLollipop())
nBuilder.setSmallIcon(R.drawable.ic_stat_notify);
else
nBuilder.setSmallIcon(R.drawable.ic_launcher);
if (isSetTop)
nBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
Notification osNotification = nBuilder.build();
nManager.notify(NOTIFYID, osNotification);
// set foreground to avoid recycling
startForeground(NOTIFYID, osNotification);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
goSleep();
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
wakeUp();
}
};
private void registerScreenEvent() {
IntentFilter filterScreenON = new IntentFilter(Intent.ACTION_SCREEN_ON);
registerReceiver(mReceiver, filterScreenON);
IntentFilter filterScreenOFF = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filterScreenOFF);
}
private void initService() {
if (!isRegistered) {
registerScreenEvent();
isRegistered = true;
}
wakeUp();
}
private void endService() {
if (isRegistered) {
unregisterReceiver(mReceiver);
isRegistered = false;
}
goSleep();
}
private byte[] getReceiveDataType() {
byte newCommand[] = { ipcCategory.PROCESS, ipcCategory.CPU, ipcCategory.OS };
switch (notificationType) {
case NotificationType.MEMORY_BATTERY:
newCommand = new byte[] { ipcCategory.PROCESS, ipcCategory.OS };
break;
case NotificationType.MEMORY_DISKIO:
newCommand = new byte[] { ipcCategory.PROCESS, ipcCategory.CPU, ipcCategory.OS };
break;
case NotificationType.BATTERY_DISKIO:
newCommand = new byte[] { ipcCategory.PROCESS, ipcCategory.CPU };
break;
case NotificationType.NETWORKIO:
newCommand = new byte[] { ipcCategory.PROCESS, ipcCategory.NETWORK };
break;
}
return newCommand;
}
private void wakeUp() {
UpdateInterval = settings.getInterval();
byte newCommand[] = getReceiveDataType();
ipcService.removeRequest(this);
ipcService.addRequest(newCommand, 0, this);
startBatteryMonitor();
}
private void goSleep() {
ipcService.removeRequest(this);
stopBatteryMonitor();
}
private void startBatteryMonitor() {
if (notificationType != NotificationType.MEMORY_BATTERY
&& notificationType != NotificationType.BATTERY_DISKIO)
return;
if (!isRegisterBattery) {
IntentFilter battFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(battReceiver, battFilter);
isRegisterBattery = true;
}
}
private void stopBatteryMonitor() {
if (isRegisterBattery) {
unregisterReceiver(battReceiver);
isRegisterBattery = false;
}
}
private boolean isRegisterBattery = false;
private BroadcastReceiver battReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
temperature = intent.getIntExtra("temperature", -1);
if (rawlevel >= 0 && scale > 0) {
battLevel = (rawlevel * 100) / scale;
}
}
};
@Override
public void onRecvData(byte [] result) {
if (result == null) {
byte newCommand[] = getReceiveDataType();
ipcService.addRequest(newCommand, UpdateInterval, this);
return;
}
// gather data
cpuUsage = 0;
// empty
for (int index = 0; index < 3; index++) {
topUsage[index] = 0;
topProcess[index] = "";
}
try {
ipcMessage ipcMessageResult = ipcMessage.getRootAsipcMessage(ByteBuffer.wrap(result));
for (int index = 0; index < ipcMessageResult.dataLength(); index++) {
ipcData rawData = ipcMessageResult.data(index);
if (rawData.category() == ipcCategory.OS)
extractOSInfo(rawData);
else if (rawData.category() == ipcCategory.CPU)
extractCPUInfo(rawData);
else if (rawData.category() == ipcCategory.NETWORK)
extractNetworkInfo(rawData);
else if (rawData.category() == ipcCategory.PROCESS)
extractProcessInfo(rawData);
}
} catch (Exception e) {}
refreshNotification();
// send command again
byte newCommand[] = getReceiveDataType();
ipcService.addRequest(newCommand, UpdateInterval, this);
}
private void extractProcessInfo(ipcData rawData)
{
processInfoList infoList = processInfoList.getRootAsprocessInfoList(rawData.payloadAsByteBuffer().asReadOnlyBuffer());
for (int count = 0; count < infoList.listLength(); count++) {
processInfo item = infoList.list(count);
cpuUsage += item.cpuUsage();
for (int check = 0; check < 3; check++) {
if (topUsage[check] >= item.cpuUsage())
continue;
// keep top 3 usage
for (int push = 2; push > check; push--) {
topUsage[push] = topUsage[push - 1];
topProcess[push] = topProcess[push - 1];
}
topUsage[check] = item.cpuUsage();
topProcess[check] = infoHelper.getPackageName(item.name());
// if name is not ready, use process name
if (topProcess[check] == null)
topProcess[check] = item.name();
// check cached status
if (infoHelper.checkPackageInformation(item.name()))
break;
// prepare to do cache
if (item.name().toLowerCase(Locale.getDefault()).contains("osmcore"))
infoHelper.doCacheInfo(android.os.Process.myUid(), item.owner(), item.name());
else
infoHelper.doCacheInfo(item.uid(), item.owner(), item.name());
break;
}
}
}
private void extractNetworkInfo(ipcData rawData)
{
// process processInfo
trafficOut = 0;
trafficIn = 0;
networkInfoList nwInfoList = networkInfoList.getRootAsnetworkInfoList(rawData.payloadAsByteBuffer().asReadOnlyBuffer());
for (int count = 0; count < nwInfoList.listLength(); count++) {
networkInfo nwInfo = nwInfoList.list(count);
trafficOut += nwInfo.transUsage();
trafficIn += nwInfo.recvUsage();
}
}
private void extractCPUInfo(ipcData rawData)
{
cpuInfoList infoList = cpuInfoList.getRootAscpuInfoList(rawData.payloadAsByteBuffer().asReadOnlyBuffer());
for(int count = 0; count < infoList.listLength(); count++) {
cpuInfo info = infoList.list(count);
ioWaitUsage = info.ioUtilization();
break;
}
}
private void extractOSInfo(ipcData rawData)
{
osInfo info = osInfo.getRootAsosInfo(rawData.payloadAsByteBuffer().asReadOnlyBuffer());
memoryFree = info.freeMemory() + info.bufferedMemory() + info.cachedMemory();
memoryTotal = info.totalMemory();
}
private String getBatteryInfo() {
String info = "";
if (useCelsius)
info = battLevel + "% (" + temperature / 10 + "\u2103)";
else
info = battLevel + "% (" + ((int) temperature / 10 * 9 / 5 + 32) + "\u2109)";
return info;
}
private void refreshNotification() {
Notification osNotification = nBuilder.build();
osNotification.contentView = new RemoteViews(getPackageName(),
R.layout.ui_notification);
// set contentIntent to fix
// "android.app.RemoteServiceException: Bad notification posted from package"
Intent notificationIntent = new Intent(this, OSMonitor.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
osNotification.contentIntent = PendingIntent.getActivity( this.getBaseContext(), 0, notificationIntent, 0);
osNotification.contentView.setTextViewText(R.id.notification_cpu, "CPU: "
+ UserInterfaceUtil.convertToUsage(cpuUsage) + "%");
osNotification.contentView.setProgressBar(R.id.notification_cpu_bar, 100, (int) cpuUsage, false);
switch (notificationType) {
case NotificationType.MEMORY_BATTERY:
osNotification.contentView.setTextViewText(R.id.notification_1nd, "MEM: "
+ UserInterfaceUtil.convertToSize(memoryFree, true));
osNotification.contentView.setTextViewText(R.id.notification_2nd, "BAT: " + getBatteryInfo());
osNotification.contentView.setProgressBar(R.id.notification_1nd_bar, (int) memoryTotal,
(int) (memoryTotal - memoryFree), false);
osNotification.contentView.setProgressBar(R.id.notification_2nd_bar, 100, (int) battLevel, false);
break;
case NotificationType.MEMORY_DISKIO:
osNotification.contentView.setTextViewText(R.id.notification_1nd, "MEM: "
+ UserInterfaceUtil.convertToSize(memoryFree, true));
osNotification.contentView.setTextViewText(R.id.notification_2nd, "IO: "
+ UserInterfaceUtil.convertToUsage(ioWaitUsage) + "%");
osNotification.contentView.setProgressBar(R.id.notification_1nd_bar, (int) memoryTotal,
(int) (memoryTotal - memoryFree), false);
osNotification.contentView.setProgressBar(R.id.notification_2nd_bar, 100, (int) ioWaitUsage, false);
break;
case NotificationType.BATTERY_DISKIO:
osNotification.contentView.setTextViewText(R.id.notification_1nd, "BAT: " + getBatteryInfo());
osNotification.contentView.setTextViewText(R.id.notification_2nd, "IO: "
+ UserInterfaceUtil.convertToUsage(ioWaitUsage) + "%");
osNotification.contentView.setProgressBar(R.id.notification_1nd_bar, 100, (int) battLevel, false);
osNotification.contentView.setProgressBar(R.id.notification_2nd_bar, 100, (int) ioWaitUsage, false);
break;
case NotificationType.NETWORKIO:
osNotification.contentView.setTextViewText(R.id.notification_1nd, "OUT: "
+ UserInterfaceUtil.convertToSize(trafficOut, true));
osNotification.contentView.setTextViewText(R.id.notification_2nd, "IN: "
+ UserInterfaceUtil.convertToSize(trafficIn, true));
osNotification.contentView.setProgressBar(R.id.notification_1nd_bar,
(int) (trafficOut + trafficIn), (int) trafficOut, false);
osNotification.contentView.setProgressBar(R.id.notification_2nd_bar,
(int) (trafficOut + trafficIn), (int) trafficIn, false);
break;
}
osNotification.contentView.setTextViewText(R.id.notification_top1st,
UserInterfaceUtil.convertToUsage(topUsage[0]) + "% " + topProcess[0]);
osNotification.contentView.setTextViewText(R.id.notification_top2nd,
UserInterfaceUtil.convertToUsage(topUsage[1]) + "% " + topProcess[1]);
osNotification.contentView.setTextViewText(R.id.notification_top3nd,
UserInterfaceUtil.convertToUsage(topUsage[2]) + "% " + topProcess[2]);
// use custom color
if (fontColor == -1 && CoreUtil.isLollipop()) {
osNotification.contentView.setTextColor(R.id.notification_2nd, Color.BLACK);
osNotification.contentView.setTextColor(R.id.notification_1nd, Color.BLACK);
osNotification.contentView.setTextColor(R.id.notification_cpu, Color.BLACK);
osNotification.contentView.setTextColor(R.id.notification_top1st, Color.BLACK);
osNotification.contentView.setTextColor(R.id.notification_top2nd, Color.BLACK);
osNotification.contentView.setTextColor(R.id.notification_top3nd, Color.BLACK);
}
else if (fontColor != -1) {
osNotification.contentView.setTextColor(R.id.notification_2nd, fontColor);
osNotification.contentView.setTextColor(R.id.notification_1nd, fontColor);
osNotification.contentView.setTextColor(R.id.notification_cpu, fontColor);
osNotification.contentView.setTextColor(R.id.notification_top1st, fontColor);
osNotification.contentView.setTextColor(R.id.notification_top2nd, fontColor);
osNotification.contentView.setTextColor(R.id.notification_top3nd, fontColor);
}
osNotification.icon = iconColor;
if (cpuUsage < 20)
osNotification.iconLevel = 1;
else if (cpuUsage < 40)
osNotification.iconLevel = 2;
else if (cpuUsage < 60)
osNotification.iconLevel = 3;
else if (cpuUsage < 80)
osNotification.iconLevel = 4;
else if (cpuUsage < 100)
osNotification.iconLevel = 5;
else
osNotification.iconLevel = 6;
nManager.notify(NOTIFYID, osNotification);
}
}
| |
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.actions;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diff.DiffNavigationContext;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener;
import com.intellij.openapi.vcs.changes.BackgroundFromStartOption;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffContext;
import com.intellij.openapi.vcs.changes.ui.ChangesComparator;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.CacheOneStepIterator;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
class ShowDiffFromAnnotation extends DumbAwareAction implements UpToDateLineNumberListener {
private final FileAnnotation myFileAnnotation;
private final AbstractVcs myVcs;
private final VirtualFile myFile;
private int currentLine;
private boolean myEnabled;
ShowDiffFromAnnotation(final FileAnnotation fileAnnotation, final AbstractVcs vcs, final VirtualFile file) {
super(ActionsBundle.message("action.Diff.UpdatedFiles.text"),
ActionsBundle.message("action.Diff.UpdatedFiles.description"),
AllIcons.Actions.Diff);
myFileAnnotation = fileAnnotation;
myVcs = vcs;
myFile = file;
currentLine = -1;
myEnabled = ProjectLevelVcsManager.getInstance(vcs.getProject()).getVcsFor(myFile) != null;
}
@Override
public void consume(Integer integer) {
currentLine = integer;
}
@Override
public void update(AnActionEvent e) {
final int number = currentLine;
e.getPresentation().setVisible(myEnabled);
e.getPresentation().setEnabled(myEnabled && number >= 0 && number < myFileAnnotation.getLineCount());
}
@Override
public void actionPerformed(AnActionEvent e) {
final int actualNumber = currentLine;
if (actualNumber < 0) return;
final VcsRevisionNumber revisionNumber = myFileAnnotation.getLineRevisionNumber(actualNumber);
if (revisionNumber != null) {
final VcsException[] exc = new VcsException[1];
final List<Change> changes = new LinkedList<Change>();
final FilePath[] targetPath = new FilePath[1];
ProgressManager.getInstance().run(new Task.Backgroundable(myVcs.getProject(),
"Loading revision " + revisionNumber.asString() + " contents", true,
BackgroundFromStartOption.getInstance()) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider();
try {
final Pair<CommittedChangeList, FilePath> pair = provider.getOneList(myFile, revisionNumber);
if (pair == null || pair.getFirst() == null) {
VcsBalloonProblemNotifier.showOverChangesView(myVcs.getProject(), "Can not load data for show diff", MessageType.ERROR);
return;
}
targetPath[0] = pair.getSecond() == null ? VcsUtil.getFilePath(myFile) : pair.getSecond();
final CommittedChangeList cl = pair.getFirst();
changes.addAll(cl.getChanges());
Collections.sort(changes, ChangesComparator.getInstance(true));
}
catch (VcsException e1) {
exc[0] = e1;
}
}
@Override
public void onSuccess() {
if (exc[0] != null) {
VcsBalloonProblemNotifier
.showOverChangesView(myVcs.getProject(), "Can not show diff: " + exc[0].getMessage(), MessageType.ERROR);
}
else if (!changes.isEmpty()) {
int idx = findSelfInList(changes, targetPath[0]);
final ShowDiffContext context = new ShowDiffContext(DiffDialogHints.FRAME);
if (idx != -1) {
context.putChangeContext(changes.get(idx), DiffUserDataKeysEx.NAVIGATION_CONTEXT, createDiffNavigationContext(actualNumber));
}
if (ChangeListManager.getInstance(myVcs.getProject()).isFreezedWithNotification(null)) return;
ShowDiffAction.showDiffForChange(myVcs.getProject(), changes, idx, context);
}
}
});
}
}
private static int findSelfInList(List<Change> changes, final FilePath filePath) {
int idx = -1;
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().equals(filePath))) {
idx = i;
break;
}
}
if (idx >= 0) return idx;
idx = 0;
// try to use name only
final String name = filePath.getName();
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().getName().equals(name))) {
idx = i;
break;
}
}
return idx;
}
// for current line number
private DiffNavigationContext createDiffNavigationContext(final int actualLine) {
final ContentsLines contentsLines = new ContentsLines(myFileAnnotation.getAnnotatedContent());
final Pair<Integer, String> pair = correctActualLineIfTextEmpty(contentsLines, actualLine);
return new DiffNavigationContext(new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new CacheOneStepIterator<String>(new ContextLineIterator(contentsLines, myFileAnnotation, pair.getFirst()));
}
}, pair.getSecond());
}
private final static int ourVicinity = 5;
private Pair<Integer, String> correctActualLineIfTextEmpty(final ContentsLines contentsLines, final int actualLine) {
final VcsRevisionNumber revision = myFileAnnotation.getLineRevisionNumber(actualLine);
for (int i = actualLine; (i < (actualLine + ourVicinity)) && (!contentsLines.isLineEndsFinished()); i++) {
if (!revision.equals(myFileAnnotation.getLineRevisionNumber(i))) continue;
final String lineContents = contentsLines.getLineContents(i);
if (!StringUtil.isEmptyOrSpaces(lineContents)) {
return new Pair<Integer, String>(i, lineContents);
}
}
int bound = Math.max(actualLine - ourVicinity, 0);
for (int i = actualLine - 1; (i >= bound); --i) {
if (!revision.equals(myFileAnnotation.getLineRevisionNumber(i))) continue;
final String lineContents = contentsLines.getLineContents(i);
if (!StringUtil.isEmptyOrSpaces(lineContents)) {
return new Pair<Integer, String>(i, lineContents);
}
}
return new Pair<Integer, String>(actualLine, contentsLines.getLineContents(actualLine));
}
/**
* Slightly break the contract: can return null from next() while had claimed hasNext()
*/
private static class ContextLineIterator implements Iterator<String> {
private final ContentsLines myContentsLines;
private final VcsRevisionNumber myRevisionNumber;
private final FileAnnotation myAnnotation;
private final int myStopAtLine;
// we assume file has at least one line ;)
private int myCurrentLine; // to start looking for next line with revision from
private ContextLineIterator(final ContentsLines contentLines, final FileAnnotation annotation, final int stopAtLine) {
myAnnotation = annotation;
myRevisionNumber = myAnnotation.originalRevision(stopAtLine);
myStopAtLine = stopAtLine;
myContentsLines = contentLines;
}
@Override
public boolean hasNext() {
return lineNumberInBounds();
}
private boolean lineNumberInBounds() {
final int knownLinesNumber = myContentsLines.getKnownLinesNumber();
return ((knownLinesNumber == -1) || (myCurrentLine < knownLinesNumber)) && (myCurrentLine < myStopAtLine);
}
@Override
public String next() {
int nextLine;
while (lineNumberInBounds()) {
final VcsRevisionNumber vcsRevisionNumber = myAnnotation.originalRevision(myCurrentLine);
if (myRevisionNumber.equals(vcsRevisionNumber)) {
nextLine = myCurrentLine;
final String text = myContentsLines.getLineContents(nextLine);
if (!StringUtil.isEmptyOrSpaces(text)) {
++myCurrentLine;
return text;
}
}
++myCurrentLine;
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| |
// Copyright (C) 2015 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.google.gerrit.httpd.auth.oauth;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.httpd.HtmlDomUtil;
import com.google.gerrit.httpd.LoginUrlToken;
import com.google.gerrit.httpd.template.SiteHeaderFooter;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Singleton
/* OAuth web filter uses active OAuth session to perform OAuth requests */
class OAuthWebFilter implements Filter {
static final String GERRIT_LOGIN = "/login";
private final Provider<String> urlProvider;
private final Provider<OAuthSession> oauthSessionProvider;
private final DynamicMap<OAuthServiceProvider> oauthServiceProviders;
private final SiteHeaderFooter header;
private OAuthServiceProvider ssoProvider;
@Inject
OAuthWebFilter(@CanonicalWebUrl @Nullable Provider<String> urlProvider,
DynamicMap<OAuthServiceProvider> oauthServiceProviders,
Provider<OAuthSession> oauthSessionProvider,
SiteHeaderFooter header) {
this.urlProvider = urlProvider;
this.oauthServiceProviders = oauthServiceProviders;
this.oauthSessionProvider = oauthSessionProvider;
this.header = header;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
pickSSOServiceProvider();
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
OAuthSession oauthSession = oauthSessionProvider.get();
if (request.getParameter("link") != null) {
oauthSession.setLinkMode(true);
oauthSession.setServiceProvider(null);
}
String provider = httpRequest.getParameter("provider");
OAuthServiceProvider service = ssoProvider == null
? oauthSession.getServiceProvider()
: ssoProvider;
if (isGerritLogin(httpRequest) || oauthSession.isOAuthFinal(httpRequest)) {
if (service == null && Strings.isNullOrEmpty(provider)) {
selectProvider(httpRequest, httpResponse, null);
return;
} else {
if (service == null) {
service = findService(provider);
}
oauthSession.setServiceProvider(service);
oauthSession.login(httpRequest, httpResponse, service);
}
} else {
chain.doFilter(httpRequest, response);
}
}
private OAuthServiceProvider findService(String providerId)
throws ServletException {
Set<String> plugins = oauthServiceProviders.plugins();
for (String pluginName : plugins) {
Map<String, Provider<OAuthServiceProvider>> m =
oauthServiceProviders.byPlugin(pluginName);
for (Map.Entry<String, Provider<OAuthServiceProvider>> e
: m.entrySet()) {
if (providerId.equals(
String.format("%s_%s", pluginName, e.getKey()))) {
return e.getValue().get();
}
}
}
throw new ServletException("No provider found for: " + providerId);
}
private void selectProvider(HttpServletRequest req, HttpServletResponse res,
@Nullable String errorMessage)
throws IOException {
String self = req.getRequestURI();
String cancel = MoreObjects.firstNonNull(
urlProvider != null ? urlProvider.get() : "/", "/");
cancel += LoginUrlToken.getToken(req);
Document doc = header.parse(OAuthWebFilter.class, "LoginForm.html");
HtmlDomUtil.find(doc, "hostName").setTextContent(req.getServerName());
HtmlDomUtil.find(doc, "login_form").setAttribute("action", self);
HtmlDomUtil.find(doc, "cancel_link").setAttribute("href", cancel);
Element emsg = HtmlDomUtil.find(doc, "error_message");
if (Strings.isNullOrEmpty(errorMessage)) {
emsg.getParentNode().removeChild(emsg);
} else {
emsg.setTextContent(errorMessage);
}
Element providers = HtmlDomUtil.find(doc, "providers");
Set<String> plugins = oauthServiceProviders.plugins();
for (String pluginName : plugins) {
Map<String, Provider<OAuthServiceProvider>> m =
oauthServiceProviders.byPlugin(pluginName);
for (Map.Entry<String, Provider<OAuthServiceProvider>> e
: m.entrySet()) {
addProvider(providers, pluginName, e.getKey(),
e.getValue().get().getName());
}
}
sendHtml(res, doc);
}
private static void addProvider(Element form, String pluginName,
String id, String serviceName) {
Element div = form.getOwnerDocument().createElement("div");
div.setAttribute("id", id);
Element hyperlink = form.getOwnerDocument().createElement("a");
hyperlink.setAttribute("href", String.format("?provider=%s_%s",
pluginName, id));
hyperlink.setTextContent(serviceName +
" (" + pluginName + " plugin)");
div.appendChild(hyperlink);
form.appendChild(div);
}
private static void sendHtml(HttpServletResponse res, Document doc)
throws IOException {
byte[] bin = HtmlDomUtil.toUTF8(doc);
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
res.setContentType("text/html");
res.setCharacterEncoding(UTF_8.name());
res.setContentLength(bin.length);
try (ServletOutputStream out = res.getOutputStream()) {
out.write(bin);
}
}
private void pickSSOServiceProvider()
throws ServletException {
SortedSet<String> plugins = oauthServiceProviders.plugins();
if (plugins.isEmpty()) {
throw new ServletException(
"OAuth service provider wasn't installed");
}
if (plugins.size() == 1) {
SortedMap<String, Provider<OAuthServiceProvider>> services =
oauthServiceProviders.byPlugin(Iterables.getOnlyElement(plugins));
if (services.size() == 1) {
ssoProvider = Iterables.getOnlyElement(services.values()).get();
}
}
}
private static boolean isGerritLogin(HttpServletRequest request) {
return request.getRequestURI().indexOf(GERRIT_LOGIN) >= 0;
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionHelper;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.EncodingEnvironmentUtil;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.ParamsGroup;
import com.intellij.execution.configurations.PtyCommandLine;
import com.intellij.execution.console.ConsoleExecuteAction;
import com.intellij.execution.console.ConsoleHistoryController;
import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.runners.ConsoleTitleGen;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.actions.CloseAction;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel;
import com.intellij.idea.ActionsBundle;
import com.intellij.internal.statistic.UsageTrigger;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
import com.intellij.openapi.editor.actions.SplitLineAction;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.psi.PsiFile;
import com.intellij.remote.CredentialsType;
import com.intellij.remote.RemoteProcess;
import com.intellij.remote.Tunnelable;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.GuiUtils;
import com.intellij.ui.JBColor;
import com.intellij.ui.SideBorder;
import com.intellij.ui.content.Content;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.PathMappingSettings;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.net.NetUtils;
import com.intellij.util.ui.MessageCategory;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugProcessStarter;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XDebuggerManager;
import com.jetbrains.python.PythonHelper;
import com.jetbrains.python.console.actions.ShowVarsAction;
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener;
import com.jetbrains.python.debugger.PyDebugRunner;
import com.jetbrains.python.debugger.PySourcePosition;
import com.jetbrains.python.debugger.PyVariableViewSettings;
import com.jetbrains.python.debugger.settings.PyDebuggerSettings;
import com.jetbrains.python.remote.PyRemotePathMapper;
import com.jetbrains.python.remote.PyRemoteProcessHandlerBase;
import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase;
import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
import com.jetbrains.python.run.*;
import com.jetbrains.python.sdk.PySdkUtil;
import icons.PythonIcons;
import org.apache.xmlrpc.XmlRpcException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import static com.intellij.execution.runners.AbstractConsoleRunnerWithHistory.registerActionShortcuts;
/**
* @author traff, oleg
*/
public class PydevConsoleRunnerImpl implements PydevConsoleRunner {
public static final String WORKING_DIR_AND_PYTHON_PATHS = "WORKING_DIR_AND_PYTHON_PATHS";
public static final String CONSOLE_START_COMMAND = "import sys; print('Python %s on %s' % (sys.version, sys.platform))\n" +
"sys.path.extend([" + WORKING_DIR_AND_PYTHON_PATHS + "])\n";
private static final Logger LOG = Logger.getInstance(PydevConsoleRunnerImpl.class.getName());
@SuppressWarnings("SpellCheckingInspection")
public static final String PYDEV_PYDEVCONSOLE_PY = "pydev/pydevconsole.py";
public static final int PORTS_WAITING_TIMEOUT = 20000;
private static final String CONSOLE_FEATURE = "python.console";
private static final String DOCKER_CONTAINER_PROJECT_PATH = "/opt/project";
private final Project myProject;
private final String myTitle;
private final String myWorkingDir;
private final Consumer<String> myRerunAction;
@NotNull
private Sdk mySdk;
private GeneralCommandLine myGeneralCommandLine;
protected int[] myPorts;
private PydevConsoleCommunication myPydevConsoleCommunication;
private PyConsoleProcessHandler myProcessHandler;
protected PythonConsoleExecuteActionHandler myConsoleExecuteActionHandler;
private List<ConsoleListener> myConsoleListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final PyConsoleType myConsoleType;
private Map<String, String> myEnvironmentVariables;
private String myCommandLine;
@NotNull private final PyConsoleOptions.PyConsoleSettings myConsoleSettings;
private String[] myStatementsToExecute = ArrayUtil.EMPTY_STRING_ARRAY;
private boolean myEnableAfterConnection = true;
private static final long HANDSHAKE_TIMEOUT = 60000;
private PyRemoteProcessHandlerBase myRemoteProcessHandlerBase;
private String myConsoleTitle = null;
private PythonConsoleView myConsoleView;
public PydevConsoleRunnerImpl(@NotNull final Project project,
@NotNull Sdk sdk,
@NotNull final PyConsoleType consoleType,
@Nullable final String workingDir,
Map<String, String> environmentVariables,
@NotNull PyConsoleOptions.PyConsoleSettings settingsProvider,
@NotNull Consumer<String> rerunAction, String... statementsToExecute) {
myProject = project;
mySdk = sdk;
myTitle = consoleType.getTitle();
myWorkingDir = workingDir;
myConsoleType = consoleType;
myEnvironmentVariables = environmentVariables;
myConsoleSettings = settingsProvider;
myStatementsToExecute = statementsToExecute;
myRerunAction = rerunAction;
}
public void setConsoleTitle(String consoleTitle) {
myConsoleTitle = consoleTitle;
}
public void setEnableAfterConnection(boolean enableAfterConnection) {
myEnableAfterConnection = enableAfterConnection;
}
private List<AnAction> fillToolBarActions(final DefaultActionGroup toolbarActions,
final RunContentDescriptor contentDescriptor) {
//toolbarActions.add(backspaceHandlingAction);
toolbarActions.add(createRerunAction());
List<AnAction> actions = ContainerUtil.newArrayList();
//stop
actions.add(createStopAction());
//close
actions.add(createCloseAction(contentDescriptor));
// run action
actions.add(
new ConsoleExecuteAction(myConsoleView, myConsoleExecuteActionHandler, myConsoleExecuteActionHandler.getEmptyExecuteAction(),
myConsoleExecuteActionHandler));
// Help
actions.add(CommonActionsManager.getInstance().createHelpAction("interactive_console"));
actions.add(new SoftWrapAction());
toolbarActions.addAll(actions);
actions.add(0, createRerunAction());
actions.add(PyConsoleUtil.createInterruptAction(myConsoleView));
actions.add(PyConsoleUtil.createTabCompletionAction(myConsoleView));
actions.add(createSplitLineAction());
toolbarActions.add(new ShowVarsAction(myConsoleView, myPydevConsoleCommunication));
toolbarActions.add(ConsoleHistoryController.getController(myConsoleView).getBrowseHistory());
toolbarActions.add(new ConnectDebuggerAction());
DefaultActionGroup settings = new DefaultActionGroup("Settings", true);
settings.getTemplatePresentation().setIcon(AllIcons.General.SecondaryGroup);
settings.add(new PyVariableViewSettings.SimplifiedView(null));
settings.add(new PyVariableViewSettings.AsyncView());
toolbarActions.add(settings);
toolbarActions.add(new NewConsoleAction());
return actions;
}
@Override
public void open() {
PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject);
if (toolWindow != null) {
toolWindow.getToolWindow().activate(() -> {
}, true);
}
else {
runSync();
}
}
@Override
public void runSync() {
myPorts = findAvailablePorts(myProject, myConsoleType);
assert myPorts != null;
myGeneralCommandLine = createCommandLine(mySdk, myEnvironmentVariables, myWorkingDir, myPorts);
myCommandLine = myGeneralCommandLine.getCommandLineString();
try {
initAndRun();
ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Connecting to Console", false) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
indicator.setText("Connecting to console...");
connect(myStatementsToExecute);
}
});
}
catch (ExecutionException e) {
LOG.warn("Error running console", e);
showErrorsInConsole(e);
}
}
@Override
public void run() {
TransactionGuard.submitTransaction(myProject, () -> FileDocumentManager.getInstance().saveAllDocuments());
myPorts = findAvailablePorts(myProject, myConsoleType);
assert myPorts != null;
myGeneralCommandLine = createCommandLine(mySdk, myEnvironmentVariables, myWorkingDir, myPorts);
myCommandLine = myGeneralCommandLine.getCommandLineString();
UIUtil
.invokeLaterIfNeeded(() -> ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Connecting to Console", false) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
indicator.setText("Connecting to console...");
try {
initAndRun();
connect(myStatementsToExecute);
}
catch (final Exception e) {
LOG.warn("Error running console", e);
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> showErrorsInConsole(e));
}
}
}));
}
private void showErrorsInConsole(Exception e) {
DefaultActionGroup actionGroup = new DefaultActionGroup(createRerunAction());
final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar("PydevConsoleRunnerErrors",
actionGroup, false);
// Runner creating
final JPanel panel = new JPanel(new BorderLayout());
panel.add(actionToolbar.getComponent(), BorderLayout.WEST);
NewErrorTreeViewPanel errorViewPanel = new NewErrorTreeViewPanel(myProject, null, false, false, null);
String[] messages = StringUtil.isNotEmpty(e.getMessage()) ? StringUtil.splitByLines(e.getMessage()) : ArrayUtil.EMPTY_STRING_ARRAY;
if (messages.length == 0) {
messages = new String[]{"Unknown error"};
}
errorViewPanel.addMessage(MessageCategory.ERROR, messages, null, -1, -1, null);
panel.add(errorViewPanel, BorderLayout.CENTER);
final RunContentDescriptor contentDescriptor =
new RunContentDescriptor(null, myProcessHandler, panel, "Error running console");
actionGroup.add(createCloseAction(contentDescriptor));
showContentDescriptor(contentDescriptor);
}
protected void showContentDescriptor(RunContentDescriptor contentDescriptor) {
ToolWindow toolwindow = PythonConsoleToolWindow.getToolWindow(myProject);
if (toolwindow != null) {
PythonConsoleToolWindow.getInstance(myProject).init(toolwindow, contentDescriptor);
}
else {
ExecutionManager
.getInstance(myProject).getContentManager().showRunContent(getExecutor(), contentDescriptor);
}
}
private static Executor getExecutor() {
return DefaultRunExecutor.getRunExecutorInstance();
}
public static int[] findAvailablePorts(Project project, PyConsoleType consoleType) {
final int[] ports;
try {
// File "pydev/console/pydevconsole.py", line 223, in <module>
// port, client_port = sys.argv[1:3]
ports = NetUtils.findAvailableSocketPorts(2);
}
catch (IOException e) {
ExecutionHelper.showErrors(project, Collections.<Exception>singletonList(e), consoleType.getTitle(), null);
return null;
}
return ports;
}
protected GeneralCommandLine createCommandLine(@NotNull final Sdk sdk,
@NotNull final Map<String, String> environmentVariables,
String workingDir, int[] ports) {
return doCreateConsoleCmdLine(sdk, environmentVariables, workingDir, ports, PythonHelper.CONSOLE);
}
@NotNull
protected GeneralCommandLine doCreateConsoleCmdLine(Sdk sdk,
Map<String, String> environmentVariables,
String workingDir,
int[] ports,
PythonHelper helper) {
GeneralCommandLine cmd =
PythonCommandLineState.createPythonCommandLine(myProject, new PythonConsoleRunParams(myConsoleSettings, workingDir, sdk,
environmentVariables), false,
PtyCommandLine.isEnabled() && !SystemInfo.isWindows);
cmd.withWorkDirectory(myWorkingDir);
ParamsGroup exeGroup = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_EXE_OPTIONS);
if (exeGroup != null && !myConsoleSettings.getInterpreterOptions().isEmpty()) {
exeGroup.addParametersString(myConsoleSettings.getInterpreterOptions());
}
ParamsGroup group = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT);
helper.addToGroup(group, cmd);
for (int port : ports) {
group.addParameter(String.valueOf(port));
}
return cmd;
}
private PythonConsoleView createConsoleView() {
PythonConsoleView consoleView = new PythonConsoleView(myProject, myTitle, mySdk, false);
myPydevConsoleCommunication.setConsoleFile(consoleView.getVirtualFile());
consoleView.addMessageFilter(new PythonTracebackFilter(myProject));
return consoleView;
}
private Process createProcess() throws ExecutionException {
if (PySdkUtil.isRemote(mySdk)) {
PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
UsageTrigger.trigger(CONSOLE_FEATURE + ".remote");
PyRemoteSdkAdditionalDataBase data = (PyRemoteSdkAdditionalDataBase)mySdk.getSdkAdditionalData();
CredentialsType connectionType = data.getRemoteConnectionType();
if (connectionType == CredentialsType.SSH_HOST ||
connectionType == CredentialsType.WEB_DEPLOYMENT ||
connectionType == CredentialsType.VAGRANT) {
return createRemoteConsoleProcess(manager,
myGeneralCommandLine.getParametersList().getArray(),
myGeneralCommandLine.getEnvironment(),
myGeneralCommandLine.getWorkDirectory());
}
RemoteConsoleProcessData remoteConsoleProcessData =
PythonConsoleRemoteProcessCreatorKt.createRemoteConsoleProcess(manager, myGeneralCommandLine.getParametersList().getArray(),
myGeneralCommandLine.getEnvironment(),
myGeneralCommandLine.getWorkDirectory(),
PydevConsoleRunner
.getPathMapper(myProject, mySdk, myConsoleSettings),
myProject, data, getRunnerFileFromHelpers());
myRemoteProcessHandlerBase = remoteConsoleProcessData.getRemoteProcessHandlerBase();
myCommandLine = myRemoteProcessHandlerBase.getCommandLine();
myPydevConsoleCommunication = remoteConsoleProcessData.getPydevConsoleCommunication();
return myRemoteProcessHandlerBase.getProcess();
}
throw new PythonRemoteInterpreterManager.PyRemoteInterpreterExecutionException();
}
else {
myCommandLine = myGeneralCommandLine.getCommandLineString();
Map<String, String> envs = myGeneralCommandLine.getEnvironment();
EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(envs, myGeneralCommandLine.getCharset());
UsageTrigger.trigger(CONSOLE_FEATURE + ".local");
final Process server = myGeneralCommandLine.createProcess();
try {
myPydevConsoleCommunication = new PydevConsoleCommunication(myProject, myPorts[0], server, myPorts[1]);
}
catch (Exception e) {
throw new ExecutionException(e.getMessage());
}
return server;
}
}
protected String getRunnerFileFromHelpers() {
return PYDEV_PYDEVCONSOLE_PY;
}
private RemoteProcess createRemoteConsoleProcess(PythonRemoteInterpreterManager manager,
String[] command,
Map<String, String> env,
File workDirectory)
throws ExecutionException {
PyRemoteSdkAdditionalDataBase data = (PyRemoteSdkAdditionalDataBase)mySdk.getSdkAdditionalData();
assert data != null;
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setWorkDirectory(workDirectory);
commandLine.withParameters(command);
commandLine.getEnvironment().putAll(env);
commandLine.getParametersList().set(0, PythonRemoteInterpreterManager.toSystemDependent(new File(data.getHelpersPath(),
getRunnerFileFromHelpers())
.getPath(),
PySourcePosition.isWindowsPath(
data.getInterpreterPath())
));
commandLine.getParametersList().set(1, "0");
commandLine.getParametersList().set(2, "0");
try {
PyRemotePathMapper pathMapper = PydevConsoleRunner.getPathMapper(myProject, mySdk, myConsoleSettings);
assert pathMapper != null;
commandLine.putUserData(PyRemoteProcessStarter.OPEN_FOR_INCOMING_CONNECTION, true);
// we do not have an option to setup Docker container settings now for Python console so we should bind at least project
// directory to some path inside the Docker container
commandLine.putUserData(PythonRemoteInterpreterManager.ADDITIONAL_MAPPINGS, buildDockerPathMappings());
myRemoteProcessHandlerBase = PyRemoteProcessStarterManagerUtil
.getManager(data).startRemoteProcess(myProject, commandLine, manager, data,
pathMapper);
myCommandLine = myRemoteProcessHandlerBase.getCommandLine();
RemoteProcess remoteProcess = myRemoteProcessHandlerBase.getProcess();
Couple<Integer> remotePorts = getRemotePortsFromProcess(remoteProcess);
if (remoteProcess instanceof Tunnelable) {
Tunnelable tunnelableProcess = (Tunnelable)remoteProcess;
tunnelableProcess.addLocalTunnel(myPorts[0], remotePorts.first);
tunnelableProcess.addRemoteTunnel(remotePorts.second, "localhost", myPorts[1]);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Using tunneled communication for Python console: port %d (=> %d) on IDE side, " +
"port %d (=> %d) on pydevconsole.py side", myPorts[1], remotePorts.second, myPorts[0],
remotePorts.first));
}
myPydevConsoleCommunication = new PydevRemoteConsoleCommunication(myProject, myPorts[0], remoteProcess, myPorts[1]);
}
else {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Using direct communication for Python console: port %d on IDE side, port %d on pydevconsole.py side",
remotePorts.second, remotePorts.first));
}
myPydevConsoleCommunication =
new PydevRemoteConsoleCommunication(myProject, remotePorts.first, remoteProcess, remotePorts.second);
}
return remoteProcess;
}
catch (Exception e) {
throw new ExecutionException(e.getMessage(), e);
}
}
@NotNull
private PathMappingSettings buildDockerPathMappings() {
return new PathMappingSettings(Collections.singletonList(new PathMappingSettings.PathMapping(myProject.getBasePath(),
DOCKER_CONTAINER_PROJECT_PATH)));
}
public static Couple<Integer> getRemotePortsFromProcess(RemoteProcess process) throws ExecutionException {
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") Scanner s = new Scanner(process.getInputStream());
return Couple.of(readInt(s, process), readInt(s, process));
}
private static int readInt(Scanner s, Process process) throws ExecutionException {
long started = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
boolean flag = false;
while (System.currentTimeMillis() - started < PORTS_WAITING_TIMEOUT) {
if (s.hasNextLine()) {
String line = s.nextLine();
sb.append(line).append("\n");
try {
int i = Integer.parseInt(line);
if (flag) {
LOG.warn("Unexpected strings in output:\n" + sb.toString());
}
return i;
}
catch (NumberFormatException ignored) {
flag = true;
continue;
}
}
TimeoutUtil.sleep(200);
if (process.exitValue() != 0) {
String error;
try {
error = "Console process terminated with error:\n" + StreamUtil.readText(process.getErrorStream()) + sb.toString();
}
catch (Exception ignored) {
error = "Console process terminated with exit code " + process.exitValue() + ", output:" + sb.toString();
}
throw new ExecutionException(error);
}
else {
break;
}
}
throw new ExecutionException("Couldn't read integer value from stream");
}
private PyConsoleProcessHandler createProcessHandler(final Process process) {
if (PySdkUtil.isRemote(mySdk)) {
PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
PyRemoteSdkAdditionalDataBase data = (PyRemoteSdkAdditionalDataBase)mySdk.getSdkAdditionalData();
assert data != null;
myProcessHandler =
manager.createConsoleProcessHandler((RemoteProcess)process, myConsoleView, myPydevConsoleCommunication,
myCommandLine, CharsetToolkit.UTF8_CHARSET,
manager.setupMappings(myProject, data, null),
myRemoteProcessHandlerBase.getRemoteSocketToLocalHostProvider());
}
else {
LOG.error("Can't create remote console process handler");
}
}
else {
myProcessHandler = new PyConsoleProcessHandler(process, myConsoleView, myPydevConsoleCommunication, myCommandLine,
CharsetToolkit.UTF8_CHARSET);
}
return myProcessHandler;
}
private void initAndRun() throws ExecutionException {
// Create Server process
final Process process = createProcess();
UIUtil.invokeLaterIfNeeded(() -> {
// Init console view
myConsoleView = createConsoleView();
if (myConsoleView != null) {
((JComponent)myConsoleView).setBorder(new SideBorder(JBColor.border(), SideBorder.LEFT));
}
myProcessHandler = createProcessHandler(process);
myConsoleExecuteActionHandler = createExecuteActionHandler();
ProcessTerminatedListener.attach(myProcessHandler);
PythonConsoleView consoleView = myConsoleView;
myProcessHandler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull ProcessEvent event) {
consoleView.setEditable(false);
}
});
// Attach to process
myConsoleView.attachToProcess(myProcessHandler);
createContentDescriptorAndActions();
// Run
myProcessHandler.startNotify();
});
}
protected void createContentDescriptorAndActions() {
// Runner creating
final DefaultActionGroup toolbarActions = new DefaultActionGroup();
final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar("PydevConsoleRunner", toolbarActions, false);
// Runner creating
final JPanel panel = new JPanel(new BorderLayout());
panel.add(actionToolbar.getComponent(), BorderLayout.WEST);
panel.add(myConsoleView.getComponent(), BorderLayout.CENTER);
actionToolbar.setTargetComponent(panel);
if (myConsoleTitle == null) {
myConsoleTitle = new ConsoleTitleGen(myProject, myTitle) {
@NotNull
@Override
protected List<String> getActiveConsoles(@NotNull String consoleTitle) {
PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject);
if (toolWindow != null && toolWindow.getToolWindow() != null) {
return Lists.newArrayList(toolWindow.getToolWindow().getContentManager().getContents()).stream().map(c -> c.getDisplayName())
.collect(
Collectors.toList());
}
else {
return super.getActiveConsoles(consoleTitle);
}
}
}.makeTitle();
}
final RunContentDescriptor contentDescriptor =
new RunContentDescriptor(myConsoleView, myProcessHandler, panel, myConsoleTitle, null);
contentDescriptor.setFocusComputable(() -> myConsoleView.getConsoleEditor().getContentComponent());
contentDescriptor.setAutoFocusContent(true);
// tool bar actions
final List<AnAction> actions = fillToolBarActions(toolbarActions, contentDescriptor);
registerActionShortcuts(actions, myConsoleView.getConsoleEditor().getComponent());
registerActionShortcuts(actions, panel);
getConsoleView().addConsoleFolding(false);
showContentDescriptor(contentDescriptor);
}
private void connect(final String[] statements2execute) {
if (handshake()) {
ApplicationManager.getApplication().invokeLater(() -> {
// Propagate console communication to language console
final PythonConsoleView consoleView = myConsoleView;
consoleView.setConsoleCommunication(myPydevConsoleCommunication);
consoleView.setSdk(mySdk);
consoleView.setExecutionHandler(myConsoleExecuteActionHandler);
myProcessHandler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
consoleView.print(event.getText(), outputType);
}
});
if (myEnableAfterConnection) {
enableConsoleExecuteAction();
}
if (statements2execute.length == 1 && statements2execute[0].isEmpty()) {
statements2execute[0] = "\t";
}
for (String statement : statements2execute) {
consoleView.executeStatement(statement + "\n", ProcessOutputTypes.SYSTEM);
}
fireConsoleInitializedEvent(consoleView);
consoleView.initialized();
});
}
else {
myConsoleView.print("Couldn't connect to console process.", ProcessOutputTypes.STDERR);
myProcessHandler.destroyProcess();
myConsoleView.setEditable(false);
}
}
protected AnAction createRerunAction() {
return new RestartAction(this);
}
private void enableConsoleExecuteAction() {
myConsoleExecuteActionHandler.setEnabled(true);
}
private boolean handshake() {
boolean res;
long started = System.currentTimeMillis();
do {
try {
res = myPydevConsoleCommunication.handshake();
}
catch (XmlRpcException ignored) {
res = false;
}
if (res) {
break;
}
else {
long now = System.currentTimeMillis();
if (now - started > HANDSHAKE_TIMEOUT) {
break;
}
else {
TimeoutUtil.sleep(100);
}
}
}
while (true);
return res;
}
private AnAction createStopAction() {
AnAction generalStopAction = ActionManager.getInstance().getAction(IdeActions.ACTION_STOP_PROGRAM);
final AnAction stopAction = new DumbAwareAction() {
@Override
public void update(AnActionEvent e) {
generalStopAction.update(e);
}
@Override
public void actionPerformed(AnActionEvent e) {
e = stopConsole(e);
generalStopAction.actionPerformed(e);
}
};
stopAction.copyFrom(generalStopAction);
return stopAction;
}
private class SoftWrapAction extends ToggleAction implements DumbAware {
private boolean isSelected = myConsoleSettings.isUseSoftWraps();
SoftWrapAction() {
super(ActionsBundle.actionText("EditorToggleUseSoftWraps"), ActionsBundle.actionDescription("EditorToggleUseSoftWraps"),
AllIcons.Actions.ToggleSoftWrap);
updateEditors();
}
@Override
public boolean isSelected(AnActionEvent e) {
return isSelected;
}
private void updateEditors() {
myConsoleView.getEditor().getSettings().setUseSoftWraps(isSelected);
myConsoleView.getConsoleEditor().getSettings().setUseSoftWraps(isSelected);
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
isSelected = state;
updateEditors();
myConsoleSettings.setUseSoftWraps(isSelected);
}
}
private AnAction createCloseAction(final RunContentDescriptor descriptor) {
final AnAction generalCloseAction = new CloseAction(getExecutor(), descriptor, myProject);
final AnAction stopAction = new DumbAwareAction() {
@Override
public void update(AnActionEvent e) {
generalCloseAction.update(e);
}
@Override
public void actionPerformed(AnActionEvent e) {
e = stopConsole(e);
clearContent(descriptor);
generalCloseAction.actionPerformed(e);
}
};
stopAction.copyFrom(generalCloseAction);
return stopAction;
}
protected void clearContent(RunContentDescriptor descriptor) {
PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject);
if (toolWindow != null && toolWindow.getToolWindow() != null) {
Content content = toolWindow.getToolWindow().getContentManager().findContent(descriptor.getDisplayName());
assert content != null;
toolWindow.getToolWindow().getContentManager().removeContent(content, true);
}
}
private AnActionEvent stopConsole(AnActionEvent e) {
if (myPydevConsoleCommunication != null) {
e = new AnActionEvent(e.getInputEvent(), e.getDataContext(), e.getPlace(),
e.getPresentation(), e.getActionManager(), e.getModifiers());
try {
closeCommunication();
// waiting for REPL communication before destroying process handler
Thread.sleep(300);
}
catch (Exception ignored) {
// Ignore
}
}
return e;
}
protected AnAction createSplitLineAction() {
class ConsoleSplitLineAction extends EditorAction {
private static final String CONSOLE_SPLIT_LINE_ACTION_ID = "Console.SplitLine";
public ConsoleSplitLineAction() {
super(new EditorWriteActionHandler() {
private final SplitLineAction mySplitLineAction = new SplitLineAction();
@Override
public boolean isEnabled(Editor editor, DataContext dataContext) {
return mySplitLineAction.getHandler().isEnabled(editor, dataContext);
}
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
((EditorWriteActionHandler)mySplitLineAction.getHandler()).executeWriteAction(editor, caret, dataContext);
editor.getCaretModel().getCurrentCaret().moveCaretRelatively(0, 1, false, true);
}
});
}
public void setup() {
EmptyAction.setupAction(this, CONSOLE_SPLIT_LINE_ACTION_ID, null);
}
}
ConsoleSplitLineAction action = new ConsoleSplitLineAction();
action.setup();
return action;
}
private void closeCommunication() {
if (!myProcessHandler.isProcessTerminated()) {
myPydevConsoleCommunication.close();
}
}
@NotNull
protected PythonConsoleExecuteActionHandler createExecuteActionHandler() {
myConsoleExecuteActionHandler =
new PydevConsoleExecuteActionHandler(myConsoleView, myProcessHandler, myPydevConsoleCommunication);
myConsoleExecuteActionHandler.setEnabled(false);
new ConsoleHistoryController(myConsoleType.getTypeId(), "", myConsoleView).install();
return myConsoleExecuteActionHandler;
}
@Override
public PydevConsoleCommunication getPydevConsoleCommunication() {
return myPydevConsoleCommunication;
}
static VirtualFile getConsoleFile(PsiFile psiFile) {
VirtualFile file = psiFile.getViewProvider().getVirtualFile();
if (file instanceof LightVirtualFile) {
file = ((LightVirtualFile)file).getOriginalFile();
}
return file;
}
@Override
public void addConsoleListener(ConsoleListener consoleListener) {
myConsoleListeners.add(consoleListener);
}
private void fireConsoleInitializedEvent(LanguageConsoleView consoleView) {
for (ConsoleListener listener : myConsoleListeners) {
listener.handleConsoleInitialized(consoleView);
}
myConsoleListeners.clear();
}
@Override
public PythonConsoleExecuteActionHandler getConsoleExecuteActionHandler() {
return myConsoleExecuteActionHandler;
}
private static class RestartAction extends AnAction {
private PydevConsoleRunnerImpl myConsoleRunner;
private RestartAction(PydevConsoleRunnerImpl runner) {
copyFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_RERUN));
getTemplatePresentation().setIcon(AllIcons.Actions.Restart);
myConsoleRunner = runner;
}
@Override
public void actionPerformed(AnActionEvent e) {
myConsoleRunner.rerun();
}
}
private void rerun() {
new Task.Backgroundable(myProject, "Restarting Console", true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
if (myProcessHandler != null) {
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> closeCommunication());
boolean processStopped = myProcessHandler.waitFor(5000L);
if (!processStopped && myProcessHandler.canKillProcess()) {
myProcessHandler.killProcess();
}
myProcessHandler.waitFor();
}
GuiUtils.invokeLaterIfNeeded(() -> myRerunAction.consume(myConsoleTitle), ModalityState.defaultModalityState());
}
}.queue();
}
private class ConnectDebuggerAction extends ToggleAction implements DumbAware {
private boolean mySelected = false;
private XDebugSession mySession = null;
public ConnectDebuggerAction() {
super("Attach Debugger", "Enables tracing of code executed in console", AllIcons.Actions.StartDebugger);
}
@Override
public boolean isSelected(AnActionEvent e) {
return mySelected;
}
@Override
public void update(AnActionEvent e) {
if (mySession != null) {
e.getPresentation().setEnabled(false);
}
else {
super.update(e);
e.getPresentation().setEnabled(true);
}
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
mySelected = state;
if (mySelected) {
try {
mySession = connectToDebugger();
}
catch (Exception e1) {
LOG.error(e1);
Messages.showErrorDialog("Can't connect to debugger", "Error Connecting Debugger");
}
}
else {
//TODO: disable debugging
}
}
}
private static class NewConsoleAction extends AnAction implements DumbAware {
public NewConsoleAction() {
super("New Console", "Creates new python console", AllIcons.General.Add);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(true);
}
@Override
public void actionPerformed(AnActionEvent e) {
PydevConsoleRunner runner =
PythonConsoleRunnerFactory.getInstance().createConsoleRunner(e.getData(CommonDataKeys.PROJECT), e.getData(LangDataKeys.MODULE));
runner.run();
}
}
private XDebugSession connectToDebugger() throws ExecutionException {
final ServerSocket serverSocket = PythonCommandLineState.createServerSocket();
final XDebugSession session = XDebuggerManager.getInstance(myProject).
startSessionAndShowTab("Python Console Debugger", PythonIcons.Python.Python, null, true, new XDebugProcessStarter() {
@NotNull
public XDebugProcess start(@NotNull final XDebugSession session) {
PythonDebugLanguageConsoleView debugConsoleView = new PythonDebugLanguageConsoleView(myProject, mySdk);
PyConsoleDebugProcessHandler consoleDebugProcessHandler =
new PyConsoleDebugProcessHandler(myProcessHandler);
PyConsoleDebugProcess consoleDebugProcess =
new PyConsoleDebugProcess(session, serverSocket, debugConsoleView,
consoleDebugProcessHandler);
PythonDebugConsoleCommunication communication =
PyDebugRunner.initDebugConsoleView(myProject, consoleDebugProcess, debugConsoleView, consoleDebugProcessHandler, session);
communication.addCommunicationListener(new ConsoleCommunicationListener() {
@Override
public void commandExecuted(boolean more) {
session.rebuildViews();
}
@Override
public void inputRequested() {
}
});
myPydevConsoleCommunication.setDebugCommunication(communication);
debugConsoleView.attachToProcess(consoleDebugProcessHandler);
consoleDebugProcess.waitForNextConnection();
try {
consoleDebugProcess.connect(myPydevConsoleCommunication);
}
catch (Exception e) {
LOG.error(e); //TODO
}
myProcessHandler.notifyTextAvailable("\nDebugger connected.\n", ProcessOutputTypes.STDERR);
return consoleDebugProcess;
}
});
return session;
}
@Override
public PyConsoleProcessHandler getProcessHandler() {
return myProcessHandler;
}
@Override
public PythonConsoleView getConsoleView() {
return myConsoleView;
}
public static PythonConsoleRunnerFactory factory() {
return new PydevConsoleRunnerFactory();
}
public static class PythonConsoleRunParams implements PythonRunParams {
private final PyConsoleOptions.PyConsoleSettings myConsoleSettings;
private String myWorkingDir;
private Sdk mySdk;
private Map<String, String> myEnvironmentVariables;
public PythonConsoleRunParams(@NotNull PyConsoleOptions.PyConsoleSettings consoleSettings,
@NotNull String workingDir,
@NotNull Sdk sdk,
@NotNull Map<String, String> envs) {
myConsoleSettings = consoleSettings;
myWorkingDir = workingDir;
mySdk = sdk;
myEnvironmentVariables = envs;
myEnvironmentVariables.putAll(consoleSettings.getEnvs());
PyDebuggerSettings debuggerSettings = PyDebuggerSettings.getInstance();
if (debuggerSettings.isLoadValuesAsync()) {
myEnvironmentVariables.put(PyVariableViewSettings.PYDEVD_LOAD_VALUES_ASYNC, "True");
}
}
@Override
public String getInterpreterOptions() {
return myConsoleSettings.getInterpreterOptions();
}
@Override
public void setInterpreterOptions(String interpreterOptions) {
throw new UnsupportedOperationException();
}
@Override
public String getWorkingDirectory() {
return myWorkingDir;
}
@Override
public void setWorkingDirectory(String workingDirectory) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public String getSdkHome() {
return mySdk.getHomePath();
}
@Override
public void setSdkHome(String sdkHome) {
throw new UnsupportedOperationException();
}
@Override
public void setModule(Module module) {
throw new UnsupportedOperationException();
}
@Override
public String getModuleName() {
return myConsoleSettings.getModuleName();
}
@Override
public boolean isUseModuleSdk() {
return myConsoleSettings.isUseModuleSdk();
}
@Override
public void setUseModuleSdk(boolean useModuleSdk) {
throw new UnsupportedOperationException();
}
@Override
public boolean isPassParentEnvs() {
return myConsoleSettings.isPassParentEnvs();
}
@Override
public void setPassParentEnvs(boolean passParentEnvs) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, String> getEnvs() {
return myEnvironmentVariables;
}
@Override
public void setEnvs(Map<String, String> envs) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public PathMappingSettings getMappingSettings() {
throw new UnsupportedOperationException();
}
@Override
public void setMappingSettings(@Nullable PathMappingSettings mappingSettings) {
throw new UnsupportedOperationException();
}
@Override
public boolean shouldAddContentRoots() {
return myConsoleSettings.shouldAddContentRoots();
}
@Override
public boolean shouldAddSourceRoots() {
return myConsoleSettings.shouldAddSourceRoots();
}
@Override
public void setAddContentRoots(boolean flag) {
throw new UnsupportedOperationException();
}
@Override
public void setAddSourceRoots(boolean flag) {
throw new UnsupportedOperationException();
}
}
}
| |
// This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package excelimporter.proxies;
public class Log
{
private final com.mendix.systemwideinterfaces.core.IMendixObject logMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "ExcelImporter.Log";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
Logline("Logline"),
Log_XMLDocumentTemplate("ExcelImporter.Log_XMLDocumentTemplate");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@Override
public java.lang.String toString()
{
return metaName;
}
}
public Log(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "ExcelImporter.Log"));
}
protected Log(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject logMendixObject)
{
if (logMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("ExcelImporter.Log", logMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a ExcelImporter.Log");
this.logMendixObject = logMendixObject;
this.context = context;
}
/**
* @deprecated Use 'Log.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static excelimporter.proxies.Log initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return excelimporter.proxies.Log.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static excelimporter.proxies.Log initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new excelimporter.proxies.Log(context, mendixObject);
}
public static excelimporter.proxies.Log load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return excelimporter.proxies.Log.initialize(context, mendixObject);
}
public static java.util.List<excelimporter.proxies.Log> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<excelimporter.proxies.Log> result = new java.util.ArrayList<excelimporter.proxies.Log>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//ExcelImporter.Log" + xpathConstraint))
result.add(excelimporter.proxies.Log.initialize(context, obj));
return result;
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of Logline
*/
public final java.lang.String getLogline()
{
return getLogline(getContext());
}
/**
* @param context
* @return value of Logline
*/
public final java.lang.String getLogline(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.Logline.toString());
}
/**
* Set value of Logline
* @param logline
*/
public final void setLogline(java.lang.String logline)
{
setLogline(getContext(), logline);
}
/**
* Set value of Logline
* @param context
* @param logline
*/
public final void setLogline(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String logline)
{
getMendixObject().setValue(context, MemberNames.Logline.toString(), logline);
}
/**
* @return value of Log_XMLDocumentTemplate
*/
public final excelimporter.proxies.XMLDocumentTemplate getLog_XMLDocumentTemplate() throws com.mendix.core.CoreException
{
return getLog_XMLDocumentTemplate(getContext());
}
/**
* @param context
* @return value of Log_XMLDocumentTemplate
*/
public final excelimporter.proxies.XMLDocumentTemplate getLog_XMLDocumentTemplate(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
excelimporter.proxies.XMLDocumentTemplate result = null;
com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Log_XMLDocumentTemplate.toString());
if (identifier != null)
result = excelimporter.proxies.XMLDocumentTemplate.load(context, identifier);
return result;
}
/**
* Set value of Log_XMLDocumentTemplate
* @param log_xmldocumenttemplate
*/
public final void setLog_XMLDocumentTemplate(excelimporter.proxies.XMLDocumentTemplate log_xmldocumenttemplate)
{
setLog_XMLDocumentTemplate(getContext(), log_xmldocumenttemplate);
}
/**
* Set value of Log_XMLDocumentTemplate
* @param context
* @param log_xmldocumenttemplate
*/
public final void setLog_XMLDocumentTemplate(com.mendix.systemwideinterfaces.core.IContext context, excelimporter.proxies.XMLDocumentTemplate log_xmldocumenttemplate)
{
if (log_xmldocumenttemplate == null)
getMendixObject().setValue(context, MemberNames.Log_XMLDocumentTemplate.toString(), null);
else
getMendixObject().setValue(context, MemberNames.Log_XMLDocumentTemplate.toString(), log_xmldocumenttemplate.getMendixObject().getId());
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return logMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final excelimporter.proxies.Log that = (excelimporter.proxies.Log) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "ExcelImporter.Log";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| |
/*
* 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.flink.api.common.operators;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.resources.CPUResource;
import org.apache.flink.api.common.resources.GPUResource;
import org.apache.flink.api.common.resources.Resource;
import org.apache.flink.configuration.MemorySize;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Describe the different resource factors of the operator with UDF.
*
* <p>Resource provides {@link #merge(ResourceSpec)} method for chained operators when generating
* job graph.
*
* <p>Resource provides {@link #lessThanOrEqual(ResourceSpec)} method to compare these fields in
* sequence:
*
* <ol>
* <li>CPU cores
* <li>Task Heap Memory
* <li>Task Off-Heap Memory
* <li>Managed Memory
* <li>Extended resources
* </ol>
*/
@Internal
public final class ResourceSpec implements Serializable {
private static final long serialVersionUID = 1L;
/** A ResourceSpec that indicates an unknown set of resources. */
public static final ResourceSpec UNKNOWN = new ResourceSpec();
/**
* The default ResourceSpec used for operators and transformation functions. Currently equal to
* {@link #UNKNOWN}.
*/
public static final ResourceSpec DEFAULT = UNKNOWN;
/** A ResourceSpec that indicates zero amount of resources. */
public static final ResourceSpec ZERO = ResourceSpec.newBuilder(0.0, 0).build();
/** How many cpu cores are needed. Can be null only if it is unknown. */
@Nullable private final Resource cpuCores;
/** How much task heap memory is needed. */
@Nullable // can be null only for UNKNOWN
private final MemorySize taskHeapMemory;
/** How much task off-heap memory is needed. */
@Nullable // can be null only for UNKNOWN
private final MemorySize taskOffHeapMemory;
/** How much managed memory is needed. */
@Nullable // can be null only for UNKNOWN
private final MemorySize managedMemory;
private final Map<String, Resource> extendedResources;
private ResourceSpec(
final Resource cpuCores,
final MemorySize taskHeapMemory,
final MemorySize taskOffHeapMemory,
final MemorySize managedMemory,
final Resource... extendedResources) {
checkNotNull(cpuCores);
checkArgument(cpuCores instanceof CPUResource, "cpuCores must be CPUResource");
this.cpuCores = cpuCores;
this.taskHeapMemory = checkNotNull(taskHeapMemory);
this.taskOffHeapMemory = checkNotNull(taskOffHeapMemory);
this.managedMemory = checkNotNull(managedMemory);
this.extendedResources =
Arrays.stream(extendedResources)
.filter(resource -> !checkNotNull(resource).isZero())
.collect(Collectors.toMap(Resource::getName, Function.identity()));
}
/** Creates a new ResourceSpec with all fields unknown. */
private ResourceSpec() {
this.cpuCores = null;
this.taskHeapMemory = null;
this.taskOffHeapMemory = null;
this.managedMemory = null;
this.extendedResources = new HashMap<>();
}
/**
* Used by system internally to merge the other resources of chained operators when generating
* the job graph.
*
* @param other Reference to resource to merge in.
* @return The new resource with merged values.
*/
public ResourceSpec merge(final ResourceSpec other) {
checkNotNull(other, "Cannot merge with null resources");
if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
return UNKNOWN;
}
ResourceSpec target =
new ResourceSpec(
this.cpuCores.merge(other.cpuCores),
this.taskHeapMemory.add(other.taskHeapMemory),
this.taskOffHeapMemory.add(other.taskOffHeapMemory),
this.managedMemory.add(other.managedMemory));
target.extendedResources.putAll(extendedResources);
for (Resource resource : other.extendedResources.values()) {
target.extendedResources.merge(resource.getName(), resource, (v1, v2) -> v1.merge(v2));
}
return target;
}
/**
* Subtracts another resource spec from this one.
*
* @param other The other resource spec to subtract.
* @return The subtracted resource spec.
*/
public ResourceSpec subtract(final ResourceSpec other) {
checkNotNull(other, "Cannot subtract null resources");
if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
return UNKNOWN;
}
checkArgument(
other.lessThanOrEqual(this),
"Cannot subtract a larger ResourceSpec from this one.");
Map<String, Resource> resultExtendedResources = new HashMap<>(extendedResources);
for (Resource resource : other.extendedResources.values()) {
resultExtendedResources.merge(
resource.getName(), resource, (v1, v2) -> v1.subtract(v2));
}
return new ResourceSpec(
this.cpuCores.subtract(other.cpuCores),
this.taskHeapMemory.subtract(other.taskHeapMemory),
this.taskOffHeapMemory.subtract(other.taskOffHeapMemory),
this.managedMemory.subtract(other.managedMemory),
resultExtendedResources.values().toArray(new Resource[0]));
}
public Resource getCpuCores() {
throwUnsupportedOperationExceptionIfUnknown();
return this.cpuCores;
}
public MemorySize getTaskHeapMemory() {
throwUnsupportedOperationExceptionIfUnknown();
return this.taskHeapMemory;
}
public MemorySize getTaskOffHeapMemory() {
throwUnsupportedOperationExceptionIfUnknown();
return taskOffHeapMemory;
}
public MemorySize getManagedMemory() {
throwUnsupportedOperationExceptionIfUnknown();
return managedMemory;
}
public Resource getGPUResource() {
throwUnsupportedOperationExceptionIfUnknown();
return extendedResources.get(GPUResource.NAME);
}
public Map<String, Resource> getExtendedResources() {
throwUnsupportedOperationExceptionIfUnknown();
return extendedResources;
}
private void throwUnsupportedOperationExceptionIfUnknown() {
if (this.equals(UNKNOWN)) {
throw new UnsupportedOperationException();
}
}
/**
* Checks the current resource less than or equal with the other resource by comparing all the
* fields in the resource.
*
* @param other The resource to compare
* @return True if current resource is less than or equal with the other resource, otherwise
* return false.
*/
public boolean lessThanOrEqual(final ResourceSpec other) {
checkNotNull(other, "Cannot compare with null resources");
if (this.equals(UNKNOWN) && other.equals(UNKNOWN)) {
return true;
} else if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
throw new IllegalArgumentException(
"Cannot compare specified resources with UNKNOWN resources.");
}
int cmp1 = this.cpuCores.getValue().compareTo(other.getCpuCores().getValue());
int cmp2 = this.taskHeapMemory.compareTo(other.taskHeapMemory);
int cmp3 = this.taskOffHeapMemory.compareTo(other.taskOffHeapMemory);
int cmp4 = this.managedMemory.compareTo(other.managedMemory);
if (cmp1 <= 0 && cmp2 <= 0 && cmp3 <= 0 && cmp4 <= 0) {
for (Resource resource : extendedResources.values()) {
if (!other.extendedResources.containsKey(resource.getName())
|| other.extendedResources
.get(resource.getName())
.getValue()
.compareTo(resource.getValue())
< 0) {
return false;
}
}
return true;
}
return false;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj != null && obj.getClass() == ResourceSpec.class) {
ResourceSpec that = (ResourceSpec) obj;
return Objects.equals(this.cpuCores, that.cpuCores)
&& Objects.equals(this.taskHeapMemory, that.taskHeapMemory)
&& Objects.equals(this.taskOffHeapMemory, that.taskOffHeapMemory)
&& Objects.equals(this.managedMemory, that.managedMemory)
&& Objects.equals(extendedResources, that.extendedResources);
} else {
return false;
}
}
@Override
public int hashCode() {
int result = Objects.hashCode(cpuCores);
result = 31 * result + Objects.hashCode(taskHeapMemory);
result = 31 * result + Objects.hashCode(taskOffHeapMemory);
result = 31 * result + Objects.hashCode(managedMemory);
result = 31 * result + extendedResources.hashCode();
return result;
}
@Override
public String toString() {
if (this.equals(UNKNOWN)) {
return "ResourceSpec{UNKNOWN}";
}
final StringBuilder extResources = new StringBuilder(extendedResources.size() * 10);
for (Map.Entry<String, Resource> resource : extendedResources.entrySet()) {
extResources
.append(", ")
.append(resource.getKey())
.append('=')
.append(resource.getValue().getValue());
}
return "ResourceSpec{"
+ "cpuCores="
+ cpuCores.getValue()
+ ", taskHeapMemory="
+ taskHeapMemory.toHumanReadableString()
+ ", taskOffHeapMemory="
+ taskOffHeapMemory.toHumanReadableString()
+ ", managedMemory="
+ managedMemory.toHumanReadableString()
+ extResources
+ '}';
}
// ------------------------------------------------------------------------
// serialization
// ------------------------------------------------------------------------
private Object readResolve() {
// try to preserve the singleton property for UNKNOWN
return this.equals(UNKNOWN) ? UNKNOWN : this;
}
// ------------------------------------------------------------------------
// builder
// ------------------------------------------------------------------------
public static Builder newBuilder(double cpuCores, int taskHeapMemoryMB) {
return new Builder(new CPUResource(cpuCores), MemorySize.ofMebiBytes(taskHeapMemoryMB));
}
/** Builder for the {@link ResourceSpec}. */
public static class Builder {
private Resource cpuCores;
private MemorySize taskHeapMemory;
private MemorySize taskOffHeapMemory = MemorySize.ZERO;
private MemorySize managedMemory = MemorySize.ZERO;
private GPUResource gpuResource = new GPUResource(0.0);
private Builder(CPUResource cpuCores, MemorySize taskHeapMemory) {
this.cpuCores = cpuCores;
this.taskHeapMemory = taskHeapMemory;
}
public Builder setCpuCores(double cpuCores) {
this.cpuCores = new CPUResource(cpuCores);
return this;
}
public Builder setTaskHeapMemory(MemorySize taskHeapMemory) {
this.taskHeapMemory = taskHeapMemory;
return this;
}
public Builder setTaskHeapMemoryMB(int taskHeapMemoryMB) {
this.taskHeapMemory = MemorySize.ofMebiBytes(taskHeapMemoryMB);
return this;
}
public Builder setTaskOffHeapMemory(MemorySize taskOffHeapMemory) {
this.taskOffHeapMemory = taskOffHeapMemory;
return this;
}
public Builder setOffTaskHeapMemoryMB(int taskOffHeapMemoryMB) {
this.taskOffHeapMemory = MemorySize.ofMebiBytes(taskOffHeapMemoryMB);
return this;
}
public Builder setManagedMemory(MemorySize managedMemory) {
this.managedMemory = managedMemory;
return this;
}
public Builder setManagedMemoryMB(int managedMemoryMB) {
this.managedMemory = MemorySize.ofMebiBytes(managedMemoryMB);
return this;
}
public Builder setGPUResource(double gpus) {
this.gpuResource = new GPUResource(gpus);
return this;
}
public ResourceSpec build() {
return new ResourceSpec(
cpuCores, taskHeapMemory, taskOffHeapMemory, managedMemory, gpuResource);
}
}
}
| |
/**
*
* 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.adobe.plugins;
import java.io.IOException;
import java.io.InputStream;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.json.JSONArray;
import android.app.Activity;
//import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES10;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.util.Log;
public class FastCanvasRenderer implements GLSurfaceView.Renderer {
// ==========================================================================
public FastCanvasRenderer(FastCanvasView view) {
super();
mView = view;
// Frame limiter
//startTime = System.currentTimeMillis();
}
// ==========================================================================
private String mRenderCommands;
private LinkedList<FastCanvasMessage> mLocalQueue = new LinkedList<FastCanvasMessage>();
private List<FastCanvasTexture> mTextures = new ArrayList<FastCanvasTexture>();
private List<FastCanvasMessage> mCaptureQueue = new ArrayList<FastCanvasMessage>();
private FastCanvasView mView;
// Frame limiter
//private long startTime;
// ==========================================================================
private void flushQueue() {
synchronized( this ) {
if (!FastCanvas.copyMessageQueue(mLocalQueue)) {
// Tear down. if any to be done.
return;
}
}
mRenderCommands = "";
FastCanvasMessage m;
while ( mLocalQueue.size() > 0 ) {
m = mLocalQueue.remove();
if (m.type == FastCanvasMessage.Type.LOAD) {
Activity theActivity = FastCanvas.getActivity();
if ( theActivity != null ) {
// If we are re-using a texture ID, unload the old texture
for (int i = 0; i < mTextures.size(); i++) {
if (mTextures.get(i).id == m.textureID) {
unloadTexture(m.textureID);
break;
}
}
// Load and track the texture
String path = "www/" + m.url;
boolean success = false;
FastCanvasTextureDimension dim = new FastCanvasTextureDimension();
// See the following for why PNG files with premultiplied alpha and GLUtils don't get along
// http://stackoverflow.com/questions/3921685/issues-with-glutils-teximage2d-and-alpha-in-textures
if (path.toLowerCase(Locale.US).endsWith(".png")) {
success = FastCanvasJNI.addPngTexture(theActivity.getAssets(), path, m.textureID, dim);
if (success == false) {
Log.i("CANVAS", "CanvasRenderer loadTexture failed to load PNG in native code, falling back to GLUtils.");
}
}
if (success == false) {
try {
InputStream instream = theActivity.getAssets().open(path);
final Bitmap bmp = BitmapFactory.decodeStream(instream);
loadTexture(bmp, m.textureID);
dim.width = bmp.getWidth();
dim.height = bmp.getHeight();
success = true;
} catch (IOException e) {
Log.i("CANVAS", "CanvasRenderer loadTexture error=", e);
m.callbackContext.error( e.getMessage() );
}
}
if (success == true) {
FastCanvasTexture t = new FastCanvasTexture (m.url, m.textureID);
mTextures.add(t);
JSONArray args = new JSONArray();
args.put(dim.width);
args.put(dim.height);
m.callbackContext.success(args);
}
}
} else if (m.type == FastCanvasMessage.Type.UNLOAD ) {
// Stop tracking the texture
for (int i = 0; i < mTextures.size(); i++) {
if (mTextures.get(i).id == m.textureID) {
mTextures.remove(i);
break;
}
}
unloadTexture(m.textureID);
} else if (m.type == FastCanvasMessage.Type.RELOAD ) {
Activity theActivity = FastCanvas.getActivity();
if ( theActivity != null ) {
// Reload the texture
String path = "www/" + m.url;
boolean success = false;
if (path.toLowerCase(Locale.US).endsWith(".png")) {
success = FastCanvasJNI.addPngTexture(theActivity.getAssets(), path, m.textureID, null);
}
if (success == false) {
try {
InputStream instream = theActivity.getAssets().open(path);
final Bitmap bmp = BitmapFactory.decodeStream(instream);
loadTexture(bmp, m.textureID);
} catch (IOException e) {
Log.i("CANVAS", "CanvasRenderer reloadTexture error=", e);
}
}
}
} else if (m.type == FastCanvasMessage.Type.RENDER ) {
mRenderCommands = m.drawCommands;
while(!mCaptureQueue.isEmpty()) {
FastCanvasMessage captureMessage = mCaptureQueue.get(0);
FastCanvasJNI.captureGLLayer(captureMessage.callbackContext.getCallbackId(),captureMessage.x,
captureMessage.y, captureMessage.width, captureMessage.height, captureMessage.url);
mCaptureQueue.remove(0);
}
} else if (m.type == FastCanvasMessage.Type.SET_ORTHO) {
Log.i("CANVAS", "CanvasRenderer setOrtho width=" + m.width + ", height=" + m.height);
FastCanvasJNI.setOrtho(m.width, m.height);
} else if(m.type == FastCanvasMessage.Type.CAPTURE) {
Log.i("CANVAS", "CanvasRenderer capture");
mCaptureQueue.add(m);
} else if (m.type == FastCanvasMessage.Type.SET_BACKGROUND) {
Log.i("CANVAS", "CanvasRenderer setBackground color=" + m.drawCommands);
// Some validation of the background color string is
// done in JS, but the format of m.drawCommands cannot
// be fully validated so we're going to give this a shot
// and simply fail silently if an error occurs in parsing
try {
int red = Integer.valueOf( m.drawCommands.substring( 0, 2 ), 16 );
int green = Integer.valueOf( m.drawCommands.substring( 2, 4 ), 16 );
int blue = Integer.valueOf( m.drawCommands.substring( 4, 6 ), 16 );
FastCanvasJNI.setBackgroundColor (red, green, blue);
} catch(Exception e) {
Log.e("CANVAS", "Parsing background color: \"" + m.drawCommands + "\"", e);
}
}
}
}
// ==========================================================================
private void checkError() {
int error = GLES10.glGetError();
if (error != GLES10.GL_NO_ERROR) {
Log.i("CANVAS", "CanvasRenderer glError=" + error);
}
assert error == GLES10.GL_NO_ERROR;
}
private boolean mDebugTextureChecked = false;
private void debugTexture()
{
if ( !mDebugTextureChecked ) {/* Not for PGBuild
synchronized( this ) {
Activity theActivity = FastCanvas.getActivity();
if ( theActivity != null ) {
try {
// grabbing debug font image from the library
// project's resource folder rather than the
// main projects assets directory
Log.i("CANVAS", "Loading debug texture" );
Resources res = FastCanvas.getActivity().getResources();
InputStream instream = res.openRawResource(R.drawable.debugfont);
Bitmap tmp = BitmapFactory.decodeStream(instream);
Bitmap bmp = Bitmap.createBitmap(tmp.getWidth(), tmp.getHeight(), Bitmap.Config.ARGB_8888);
android.graphics.Canvas c = new android.graphics.Canvas();
c.setBitmap(bmp);
android.graphics.Paint p = new android.graphics.Paint();
p.setFilterBitmap(true);
c.drawBitmap(tmp, 0, 0, p);
tmp.recycle();
loadTexture(bmp, -1);
bmp.recycle();
} catch(Exception e) {
Log.i("CANVAS", "Debug texture unavailable to load: " + e.getMessage());
}
}
}*/
mDebugTextureChecked = true;
}
}
// ==========================================================================
public void onDrawFrame(GL10 gl) {
if (!mView.isPaused) {
/*
// Frame limiter.
try {
long endTime = System.currentTimeMillis();
long dt = endTime - startTime;
if (dt < 33)
Thread.sleep(33 - dt);
startTime = System.currentTimeMillis();
} catch ( Exception e ) {
}
*/
flushQueue();
debugTexture();
FastCanvasJNI.render(mRenderCommands);
checkError();
}
}
// ==========================================================================
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i("CANVAS", "CanvasRenderer onSurfaceCreated. config:" + config.toString() + " gl:" + gl.toString());
IntBuffer ib = IntBuffer.allocate(100);
ib.position(0);
GLES10.glGetIntegerv( GLES10.GL_RED_BITS, ib );
int red = ib.get(0);
GLES10.glGetIntegerv( GLES10.GL_GREEN_BITS, ib );
int green = ib.get(0);
GLES10.glGetIntegerv( GLES10.GL_BLUE_BITS, ib );
int blue = ib.get(0);
GLES10.glGetIntegerv( GLES10.GL_STENCIL_BITS, ib );
int stencil = ib.get(0);
GLES10.glGetIntegerv( GLES10.GL_DEPTH_BITS, ib );
int depth = ib.get(0);
Log.i( "CANVAS", "CanvasRenderer R=" + red + " G=" + green + " B=" + blue + " DEPETH=" + depth + " STENCIL=" + stencil );
}
// ==========================================================================
public void onSurfaceChanged(GL10 gl, int width, int height) {
Log.i("CANVAS", "CanvasRenderer onSurfaceChanged. width:" + width + " height:" + height + " gl:" + gl.toString());
FastCanvasJNI.surfaceChanged(width, height);
}
// ==========================================================================
// Not an override - this is a way for the view to tell the renderer when the context has been destroyed
public void onSurfaceDestroyed() {
Log.i("CANVAS", "CanvasRenderer onSurfaceDestroyed");
mDebugTextureChecked = false;
}
// ==========================================================================
public void loadTexture(Bitmap bmp, int id) {
if (bmp == null) {
Log.i("CANVAS", "CanvasRenderer Aborting loadtexture " + id);
return;
}
int[] glID = new int[1];
GLES10.glGenTextures(1, glID, 0);
GLES10.glBindTexture(GLES10.GL_TEXTURE_2D, glID[0]);
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_MIN_FILTER, GLES10.GL_LINEAR);
GLES10.glTexParameterf(GLES10.GL_TEXTURE_2D, GLES10.GL_TEXTURE_MAG_FILTER, GLES10.GL_LINEAR);
int width = bmp.getWidth();
int height = bmp.getHeight();
int p2Width = 2;
while (p2Width < width) {
p2Width *= 2;
}
int p2Height = 2;
while (p2Height < height) {
p2Height *= 2;
}
if (width == p2Width && height == p2Height) {
GLUtils.texImage2D(GLES10.GL_TEXTURE_2D, 0, bmp, 0);
} else {
Log.i( "Canvas", "Canvas::AddTexture scaling texture " + id + " to power of 2" );
GLES10.glTexImage2D(GLES10.GL_TEXTURE_2D, 0, GLES10.GL_RGBA, p2Width, p2Height, 0, GLES10.GL_RGBA, GLES10.GL_UNSIGNED_BYTE, null);
GLUtils.texSubImage2D(GLES10.GL_TEXTURE_2D, 0, 0, 0, bmp);
width = p2Width;
height = p2Height;
}
checkError();
FastCanvasJNI.addTexture(id, glID[0], width, height);
Log.i("CANVAS", "CanvasRenderer Leaving loadtexture " + id);
}
// ==========================================================================
public void unloadTexture( int id) {
FastCanvasJNI.removeTexture(id);
Log.i("CANVAS", "CanvasRenderer unloadtexture");
checkError();
}
// ==========================================================================
public void reloadTextures() {
Log.i("CANVAS", "CanvasRenderer reloadtextures");
Iterator<FastCanvasTexture> ti = mTextures.iterator();
while (ti.hasNext()) {
FastCanvasTexture t = ti.next();
FastCanvasMessage m = new FastCanvasMessage(FastCanvasMessage.Type.RELOAD);
m.url = t.url;
m.textureID = t.id;
Log.i("CANVAS", "CanvasRenderer queueing reload texture " + m.textureID + ", " + m.url);
mLocalQueue.add(m);
}
}
}
| |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.parser.api.ProjectBuildFileParser;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.rules.BuckPyFunction;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.util.Escaper;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreStrings;
import com.facebook.buck.util.ObjectMappers;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
/**
* Evaluates a build file and prints out an equivalent build file with all includes/macros expanded.
* When complex macros are in play, this helps clarify what the resulting build rule definitions
* are.
*/
public class AuditRulesCommand extends AbstractCommand {
/** Indent to use in generated build file. */
private static final String INDENT = " ";
/** Properties that should be listed last in the declaration of a build rule. */
private static final ImmutableSet<String> LAST_PROPERTIES = ImmutableSet.of("deps", "visibility");
@Option(
name = "--type",
aliases = {"-t"},
usage = "The types of rule to filter by"
)
@Nullable
private List<String> types = null;
@Option(name = "--json", usage = "Print JSON representation of each rule")
private boolean json;
@Argument private List<String> arguments = new ArrayList<>();
public List<String> getArguments() {
return arguments;
}
public ImmutableSet<String> getTypes() {
return types == null ? ImmutableSet.of() : ImmutableSet.copyOf(types);
}
@Override
public String getShortDescription() {
return "List build rule definitions resulting from expanding macros.";
}
@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
ProjectFilesystem projectFilesystem = params.getCell().getFilesystem();
try (ProjectBuildFileParser parser =
params
.getCell()
.createBuildFileParser(
new DefaultTypeCoercerFactory(), params.getConsole(), params.getBuckEventBus())) {
PrintStream out = params.getConsole().getStdOut();
for (String pathToBuildFile : getArguments()) {
if (!json) {
// Print a comment with the path to the build file.
out.printf("# %s\n\n", pathToBuildFile);
}
// Resolve the path specified by the user.
Path path = Paths.get(pathToBuildFile);
if (!path.isAbsolute()) {
Path root = projectFilesystem.getRootPath();
path = root.resolve(path);
}
// Parse the rules from the build file.
List<Map<String, Object>> rawRules;
try {
rawRules = parser.getAll(path, new AtomicLong());
} catch (BuildFileParseException e) {
throw new HumanReadableException(e);
}
// Format and print the rules from the raw data, filtered by type.
final ImmutableSet<String> types = getTypes();
Predicate<String> includeType = type -> types.isEmpty() || types.contains(type);
printRulesToStdout(params, rawRules, includeType);
}
} catch (BuildFileParseException e) {
throw new HumanReadableException("Unable to create parser");
}
return 0;
}
@Override
public boolean isReadOnly() {
return true;
}
private void printRulesToStdout(
CommandRunnerParams params,
List<Map<String, Object>> rawRules,
final Predicate<String> includeType)
throws IOException {
Iterable<Map<String, Object>> filteredRules =
FluentIterable.from(rawRules)
.filter(
rawRule -> {
String type = (String) rawRule.get(BuckPyFunction.TYPE_PROPERTY_NAME);
return includeType.apply(type);
});
PrintStream stdOut = params.getConsole().getStdOut();
if (json) {
Map<String, Object> rulesKeyedByName = new HashMap<>();
for (Map<String, Object> rawRule : filteredRules) {
String name = (String) rawRule.get("name");
Preconditions.checkNotNull(name);
rulesKeyedByName.put(name, Maps.filterValues(rawRule, v -> shouldInclude(v)));
}
// We create a new JsonGenerator that does not close the stream.
try (JsonGenerator generator =
ObjectMappers.createGenerator(stdOut)
.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
.useDefaultPrettyPrinter()) {
ObjectMappers.WRITER.writeValue(generator, rulesKeyedByName);
}
stdOut.print('\n');
} else {
for (Map<String, Object> rawRule : filteredRules) {
printRuleAsPythonToStdout(stdOut, rawRule);
}
}
}
private void printRuleAsPythonToStdout(PrintStream out, Map<String, Object> rawRule) {
String type = (String) rawRule.get(BuckPyFunction.TYPE_PROPERTY_NAME);
out.printf("%s(\n", type);
// The properties in the order they should be displayed for this rule.
LinkedHashSet<String> properties = new LinkedHashSet<>();
// Always display the "name" property first.
properties.add("name");
// Add the properties specific to the rule.
SortedSet<String> customProperties = new TreeSet<>();
for (String key : rawRule.keySet()) {
// Ignore keys that start with "buck.".
if (!(key.startsWith(BuckPyFunction.INTERNAL_PROPERTY_NAME_PREFIX)
|| LAST_PROPERTIES.contains(key))) {
customProperties.add(key);
}
}
properties.addAll(customProperties);
// Add common properties that should be displayed last.
properties.addAll(Sets.intersection(LAST_PROPERTIES, rawRule.keySet()));
// Write out the properties and their corresponding values.
for (String property : properties) {
Object rawValue = rawRule.get(property);
if (!shouldInclude(rawValue)) {
continue;
}
String displayValue = createDisplayString(INDENT, rawValue);
out.printf("%s%s = %s,\n", INDENT, property, displayValue);
}
// Close the rule definition.
out.printf(")\n\n");
}
private boolean shouldInclude(@Nullable Object rawValue) {
return rawValue != null
&& rawValue != Optional.empty()
&& !(rawValue instanceof Collection && ((Collection<?>) rawValue).isEmpty());
}
/**
* @param value in a Map returned by {@link ProjectBuildFileParser#getAll(Path, AtomicLong)}.
* @return a string that represents the Python equivalent of the value.
*/
@VisibleForTesting
static String createDisplayString(@Nullable Object value) {
return createDisplayString("", value);
}
static String createDisplayString(String indent, @Nullable Object value) {
if (value == null) {
return "None";
} else if (value instanceof Boolean) {
return MoreStrings.capitalize(value.toString());
} else if (value instanceof String) {
return Escaper.escapeAsPythonString(value.toString());
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof List) {
StringBuilder out = new StringBuilder("[\n");
String indentPlus1 = indent + INDENT;
for (Object item : (List<?>) value) {
out.append(indentPlus1).append(createDisplayString(indentPlus1, item)).append(",\n");
}
out.append(indent).append("]");
return out.toString();
} else if (value instanceof Map) {
StringBuilder out = new StringBuilder("{\n");
String indentPlus1 = indent + INDENT;
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
out.append(indentPlus1)
.append(createDisplayString(indentPlus1, entry.getKey()))
.append(": ")
.append(createDisplayString(indentPlus1, entry.getValue()))
.append(",\n");
}
out.append(indent).append("}");
return out.toString();
} else {
throw new IllegalStateException();
}
}
}
| |
/*
* Copyright (C) 2016 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.google.android.exoplayer2.metadata.id3;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataDecoderException;
import com.google.android.exoplayer2.util.Assertions;
import java.nio.charset.Charset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Test for {@link Id3Decoder}.
*/
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Config.TARGET_SDK, manifest = Config.NONE)
public final class Id3DecoderTest {
private static final byte[] TAG_HEADER = new byte[] {73, 68, 51, 4, 0, 0, 0, 0, 0, 0};
private static final int FRAME_HEADER_LENGTH = 10;
private static final int ID3_TEXT_ENCODING_UTF_8 = 3;
@Test
public void testDecodeTxxxFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("TXXX", new byte[] {3, 0, 109, 100, 105, 97, 108, 111, 103,
95, 86, 73, 78, 68, 73, 67, 79, 49, 53, 50, 55, 54, 54, 52, 95, 115, 116, 97, 114, 116, 0});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
TextInformationFrame textInformationFrame = (TextInformationFrame) metadata.get(0);
assertThat(textInformationFrame.id).isEqualTo("TXXX");
assertThat(textInformationFrame.description).isEmpty();
assertThat(textInformationFrame.value).isEqualTo("mdialog_VINDICO1527664_start");
// Test empty.
rawId3 = buildSingleFrameTag("TXXX", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(0);
// Test encoding byte only.
rawId3 = buildSingleFrameTag("TXXX", new byte[] {ID3_TEXT_ENCODING_UTF_8});
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
textInformationFrame = (TextInformationFrame) metadata.get(0);
assertThat(textInformationFrame.id).isEqualTo("TXXX");
assertThat(textInformationFrame.description).isEmpty();
assertThat(textInformationFrame.value).isEmpty();
}
@Test
public void testDecodeTextInformationFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("TIT2", new byte[] {3, 72, 101, 108, 108, 111, 32, 87, 111,
114, 108, 100, 0});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
TextInformationFrame textInformationFrame = (TextInformationFrame) metadata.get(0);
assertThat(textInformationFrame.id).isEqualTo("TIT2");
assertThat(textInformationFrame.description).isNull();
assertThat(textInformationFrame.value).isEqualTo("Hello World");
// Test empty.
rawId3 = buildSingleFrameTag("TIT2", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(0);
// Test encoding byte only.
rawId3 = buildSingleFrameTag("TIT2", new byte[] {ID3_TEXT_ENCODING_UTF_8});
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
textInformationFrame = (TextInformationFrame) metadata.get(0);
assertThat(textInformationFrame.id).isEqualTo("TIT2");
assertThat(textInformationFrame.description).isNull();
assertThat(textInformationFrame.value).isEmpty();
}
@Test
public void testDecodeWxxxFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("WXXX", new byte[] {ID3_TEXT_ENCODING_UTF_8, 116, 101, 115,
116, 0, 104, 116, 116, 112, 115, 58, 47, 47, 116, 101, 115, 116, 46, 99, 111, 109, 47, 97,
98, 99, 63, 100, 101, 102});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
UrlLinkFrame urlLinkFrame = (UrlLinkFrame) metadata.get(0);
assertThat(urlLinkFrame.id).isEqualTo("WXXX");
assertThat(urlLinkFrame.description).isEqualTo("test");
assertThat(urlLinkFrame.url).isEqualTo("https://test.com/abc?def");
// Test empty.
rawId3 = buildSingleFrameTag("WXXX", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(0);
// Test encoding byte only.
rawId3 = buildSingleFrameTag("WXXX", new byte[] {ID3_TEXT_ENCODING_UTF_8});
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
urlLinkFrame = (UrlLinkFrame) metadata.get(0);
assertThat(urlLinkFrame.id).isEqualTo("WXXX");
assertThat(urlLinkFrame.description).isEmpty();
assertThat(urlLinkFrame.url).isEmpty();
}
@Test
public void testDecodeUrlLinkFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("WCOM", new byte[] {104, 116, 116, 112, 115, 58, 47, 47,
116, 101, 115, 116, 46, 99, 111, 109, 47, 97, 98, 99, 63, 100, 101, 102});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
UrlLinkFrame urlLinkFrame = (UrlLinkFrame) metadata.get(0);
assertThat(urlLinkFrame.id).isEqualTo("WCOM");
assertThat(urlLinkFrame.description).isNull();
assertThat(urlLinkFrame.url).isEqualTo("https://test.com/abc?def");
// Test empty.
rawId3 = buildSingleFrameTag("WCOM", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
urlLinkFrame = (UrlLinkFrame) metadata.get(0);
assertThat(urlLinkFrame.id).isEqualTo("WCOM");
assertThat(urlLinkFrame.description).isNull();
assertThat(urlLinkFrame.url).isEmpty();
}
@Test
public void testDecodePrivFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("PRIV", new byte[] {116, 101, 115, 116, 0, 1, 2, 3, 4});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
PrivFrame privFrame = (PrivFrame) metadata.get(0);
assertThat(privFrame.owner).isEqualTo("test");
assertThat(privFrame.privateData).isEqualTo(new byte[]{1, 2, 3, 4});
// Test empty.
rawId3 = buildSingleFrameTag("PRIV", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
privFrame = (PrivFrame) metadata.get(0);
assertThat(privFrame.owner).isEmpty();
assertThat(privFrame.privateData).isEqualTo(new byte[0]);
}
@Test
public void testDecodeApicFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("APIC", new byte[] {3, 105, 109, 97, 103, 101, 47, 106, 112,
101, 103, 0, 16, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 0});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
ApicFrame apicFrame = (ApicFrame) metadata.get(0);
assertThat(apicFrame.mimeType).isEqualTo("image/jpeg");
assertThat(apicFrame.pictureType).isEqualTo(16);
assertThat(apicFrame.description).isEqualTo("Hello World");
assertThat(apicFrame.pictureData).hasLength(10);
assertThat(apicFrame.pictureData).isEqualTo(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
}
@Test
public void testDecodeCommentFrame() throws MetadataDecoderException {
byte[] rawId3 = buildSingleFrameTag("COMM", new byte[] {ID3_TEXT_ENCODING_UTF_8, 101, 110, 103,
100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, 0, 116, 101, 120, 116, 0});
Id3Decoder decoder = new Id3Decoder();
Metadata metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
CommentFrame commentFrame = (CommentFrame) metadata.get(0);
assertThat(commentFrame.language).isEqualTo("eng");
assertThat(commentFrame.description).isEqualTo("description");
assertThat(commentFrame.text).isEqualTo("text");
// Test empty.
rawId3 = buildSingleFrameTag("COMM", new byte[0]);
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(0);
// Test language only.
rawId3 = buildSingleFrameTag("COMM", new byte[] {ID3_TEXT_ENCODING_UTF_8, 101, 110, 103});
metadata = decoder.decode(rawId3, rawId3.length);
assertThat(metadata.length()).isEqualTo(1);
commentFrame = (CommentFrame) metadata.get(0);
assertThat(commentFrame.language).isEqualTo("eng");
assertThat(commentFrame.description).isEmpty();
assertThat(commentFrame.text).isEmpty();
}
private static byte[] buildSingleFrameTag(String frameId, byte[] frameData) {
byte[] frameIdBytes = frameId.getBytes(Charset.forName(C.UTF8_NAME));
Assertions.checkState(frameIdBytes.length == 4);
byte[] tagData = new byte[TAG_HEADER.length + FRAME_HEADER_LENGTH + frameData.length];
System.arraycopy(TAG_HEADER, 0, tagData, 0, TAG_HEADER.length);
// Fill in the size part of the tag header.
int offset = TAG_HEADER.length - 4;
int tagSize = frameData.length + FRAME_HEADER_LENGTH;
tagData[offset++] = (byte) ((tagSize >> 21) & 0x7F);
tagData[offset++] = (byte) ((tagSize >> 14) & 0x7F);
tagData[offset++] = (byte) ((tagSize >> 7) & 0x7F);
tagData[offset++] = (byte) (tagSize & 0x7F);
// Fill in the frame header.
tagData[offset++] = frameIdBytes[0];
tagData[offset++] = frameIdBytes[1];
tagData[offset++] = frameIdBytes[2];
tagData[offset++] = frameIdBytes[3];
tagData[offset++] = (byte) ((frameData.length >> 24) & 0xFF);
tagData[offset++] = (byte) ((frameData.length >> 16) & 0xFF);
tagData[offset++] = (byte) ((frameData.length >> 8) & 0xFF);
tagData[offset++] = (byte) (frameData.length & 0xFF);
offset += 2; // Frame flags set to 0
// Fill in the frame data.
System.arraycopy(frameData, 0, tagData, offset, frameData.length);
return tagData;
}
}
| |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.event;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventObject;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import com.vaadin.server.ErrorEvent;
import com.vaadin.server.ErrorHandler;
import com.vaadin.shared.Registration;
/**
* <code>EventRouter</code> class implementing the inheritable event listening
* model. For more information on the event model see the
* {@link com.vaadin.event package documentation}.
*
* @author Vaadin Ltd.
* @since 3.0
*/
@SuppressWarnings("serial")
public class EventRouter implements MethodEventSource {
/**
* List of registered listeners.
*/
private LinkedHashSet<ListenerMethod> listenerList = null;
/*
* Registers a new listener with the specified activation method to listen
* events generated by this component. Don't add a JavaDoc comment here, we
* use the default documentation from implemented interface.
*/
@Override
public Registration addListener(Class<?> eventType, Object object,
Method method) {
Objects.requireNonNull(object, "Listener must not be null.");
if (listenerList == null) {
listenerList = new LinkedHashSet<>();
}
ListenerMethod listenerMethod = new ListenerMethod(eventType, object,
method);
listenerList.add(listenerMethod);
return () -> listenerList.remove(listenerMethod);
}
/*
* Registers a new listener with the specified named activation method to
* listen events generated by this component. Don't add a JavaDoc comment
* here, we use the default documentation from implemented interface.
*/
@Override
public Registration addListener(Class<?> eventType, Object object,
String methodName) {
Objects.requireNonNull(object, "Listener must not be null.");
if (listenerList == null) {
listenerList = new LinkedHashSet<>();
}
ListenerMethod listenerMethod = new ListenerMethod(eventType, object,
methodName);
listenerList.add(listenerMethod);
return () -> listenerList.remove(listenerMethod);
}
/*
* Removes all registered listeners matching the given parameters. Don't add
* a JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
@Override
public void removeListener(Class<?> eventType, Object target) {
if (listenerList != null) {
final Iterator<ListenerMethod> i = listenerList.iterator();
while (i.hasNext()) {
final ListenerMethod lm = i.next();
if (lm.matches(eventType, target)) {
i.remove();
return;
}
}
}
}
/*
* Removes the event listener methods matching the given given paramaters.
* Don't add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
@Override
public void removeListener(Class<?> eventType, Object target,
Method method) {
if (listenerList != null) {
final Iterator<ListenerMethod> i = listenerList.iterator();
while (i.hasNext()) {
final ListenerMethod lm = i.next();
if (lm.matches(eventType, target, method)) {
i.remove();
return;
}
}
}
}
/*
* Removes the event listener method matching the given given parameters.
* Don't add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
@Override
public void removeListener(Class<?> eventType, Object target,
String methodName) {
// Find the correct method
final Method[] methods = target.getClass().getMethods();
Method method = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(methodName)) {
method = methods[i];
}
}
if (method == null) {
throw new IllegalArgumentException();
}
// Remove the listeners
if (listenerList != null) {
final Iterator<ListenerMethod> i = listenerList.iterator();
while (i.hasNext()) {
final ListenerMethod lm = i.next();
if (lm.matches(eventType, target, method)) {
i.remove();
return;
}
}
}
}
/**
* Removes all listeners from event router.
*/
public void removeAllListeners() {
listenerList = null;
}
/**
* Sends an event to all registered listeners. The listeners will decide if
* the activation method should be called or not.
*
* @param event
* the Event to be sent to all listeners.
*/
public void fireEvent(EventObject event) {
fireEvent(event, null);
}
/**
* Sends an event to all registered listeners. The listeners will decide if
* the activation method should be called or not.
* <p>
* If an error handler is set, the processing of other listeners will
* continue after the error handler method call unless the error handler
* itself throws an exception.
*
* @param event
* the Event to be sent to all listeners.
* @param errorHandler
* error handler to use to handle any exceptions thrown by
* listeners or null to let the exception propagate to the
* caller, preventing further listener calls
*/
public void fireEvent(EventObject event, ErrorHandler errorHandler) {
// It is not necessary to send any events if there are no listeners
if (listenerList != null) {
// Make a copy of the listener list to allow listeners to be added
// inside listener methods. Fixes #3605.
// Send the event to all listeners. The listeners themselves
// will filter out unwanted events.
final Object[] listeners = listenerList.toArray();
for (int i = 0; i < listeners.length; i++) {
ListenerMethod listenerMethod = (ListenerMethod) listeners[i];
if (null != errorHandler) {
try {
listenerMethod.receiveEvent(event);
} catch (Exception e) {
errorHandler.error(new ErrorEvent(e));
}
} else {
listenerMethod.receiveEvent(event);
}
}
}
}
/**
* Checks if the given Event type is listened by a listener registered to
* this router.
*
* @param eventType
* the event type to be checked
* @return true if a listener is registered for the given event type
*/
public boolean hasListeners(Class<?> eventType) {
if (listenerList != null) {
for (ListenerMethod lm : listenerList) {
if (lm.isType(eventType)) {
return true;
}
}
}
return false;
}
/**
* Returns all listeners that match or extend the given event type.
*
* @param eventType
* The type of event to return listeners for.
* @return A collection with all registered listeners. Empty if no listeners
* are found.
*/
public Collection<?> getListeners(Class<?> eventType) {
List<Object> listeners = new ArrayList<>();
if (listenerList != null) {
for (ListenerMethod lm : listenerList) {
if (lm.isOrExtendsType(eventType)) {
listeners.add(lm.getTarget());
}
}
}
return listeners;
}
private Logger getLogger() {
return Logger.getLogger(EventRouter.class.getName());
}
}
| |
/*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.admin.util;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.plaf.basic.*;
import vnmr.util.*;
import vnmr.admin.ui.*;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2002
* Company:
* @author
* @version 1.0
*/
public class AddRemoveTool extends ModelessDialog implements ActionListener
{
/** The split pane used for display. */
protected JSplitPane m_spDisplay;
/** The panel on the left. */
protected JPanel m_pnlLeft = new JPanel();
/** The panel for the right. */
protected JPanel m_pnlRight = new JPanel();
/** The list for the left. */
protected JList m_listLeft = new JList();
/** The list for the right. */
protected JList m_listRight = new JList();
/** The arraylist that has values for the left. */
protected ArrayList m_aListLeft = new ArrayList();
/** The arraylist that has values for the right. */
protected ArrayList m_aListRight = new ArrayList();
/** The ui object for the split pane. */
protected ButtonDividerUI m_objDividerUI;
protected ActionListener m_alBtn;
/** The east arrow button. */
protected JButton m_btnEast = new JButton(); /*new BasicArrowButton(BasicArrowButton.EAST,
Color.green, Color.gray, Color.darkGray,
Color.white);*/
/** The west arrow button. */
protected JButton m_btnWest = new JButton(); /*new BasicArrowButton(BasicArrowButton.WEST,
Color.green, Color.gray, Color.darkGray,
Color.white);*/
protected Container m_contentPane;
protected java.util.Timer timer;
protected String labelString; // The label for the window
protected int delay; // the delay time between blinks
public AddRemoveTool(String strToolLbl)
{
super(strToolLbl);
setVisible(false);
m_pnlLeft.setLayout(new BorderLayout());
m_pnlRight.setLayout(new BorderLayout());
dolayout();
m_contentPane = getContentPane();
setAbandonEnabled(true);
setCloseEnabled(true);
abandonButton.setActionCommand("cancel");
abandonButton.addActionListener(this);
closeButton.setActionCommand("close");
closeButton.addActionListener(this);
helpButton.setActionCommand("help");
helpButton.addActionListener(this);
m_alBtn = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
updateListData(e);
if (timer != null)
timer.cancel();
}
};
m_btnEast.setIcon(Util.getImageIcon("eastarrow.gif"));
m_btnEast.addActionListener(m_alBtn);
m_btnEast.setActionCommand("east");
m_btnEast.setBackground(Color.white);
m_btnEast.setForeground(Color.green);
m_btnWest.setIcon(Util.getImageIcon("westarrow.gif"));
m_btnWest.addActionListener(m_alBtn);
m_btnWest.setActionCommand("west");
m_btnWest.setBackground(Color.white);
m_btnWest.setForeground(Color.yellow);
m_objDividerUI = new ButtonDividerUI();
initBlink();
setResizable(true);
setTitle(strToolLbl);
}
protected void dolayout()
{
JScrollPane scpLeft = new JScrollPane(m_listLeft);
JScrollPane scpRight = new JScrollPane(m_listRight);
m_pnlLeft.add(scpLeft);
m_pnlRight.add(scpRight);
m_spDisplay = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
m_pnlLeft, m_pnlRight);
m_spDisplay.setUI(m_objDividerUI);
getContentPane().add(m_spDisplay);
m_aListLeft = WUserUtil.readUserListFile();
m_aListRight.add("color");
m_listLeft.setListData(m_aListLeft.toArray());
m_listRight.setListData(m_aListRight.toArray());
setLocation( 300, 500 );
int nWidth = buttonPane.getWidth();
int nHeight = buttonPane.getPreferredSize().height +
m_spDisplay.getPreferredSize().height + 100;
setSize(500, 300);
}
protected void initBlink()
{
String blinkFrequency = null;
delay = (blinkFrequency == null) ? 400 :
(1000 / Integer.parseInt(blinkFrequency));
labelString = null;
if (labelString == null)
labelString = "Blink";
Font font = new java.awt.Font("TimesRoman", Font.PLAIN, 24);
setFont(font);
}
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if (timer != null)
timer.cancel();
if(cmd.equals("close"))
{
// run the script to save data
saveData();
setVisible(false);
dispose();
}
else if (cmd.equals("cancel"))
{
undoAction();
setVisible(false);
dispose();
}
else if (cmd.equals("help"))
displayHelp();
}
/**
* Returns the list that has values for the left.
*/
public ArrayList getLeftList()
{
return m_aListLeft;
}
/**
* Sets the arraylist for the left.
*/
public void setLeftList(ArrayList aList)
{
m_aListLeft = aList;
m_listLeft.setListData(m_aListLeft.toArray());
}
/**
* Returns the list that has values for the right.
*/
public ArrayList getRightList()
{
return m_aListRight;
}
/**
* Sets the list that has values for the right.
*/
public void setRightList(ArrayList aList)
{
m_aListRight = aList;
m_listRight.setListData(m_aListRight.toArray());
}
/**
* Returns the dividerui for the split pane.
*/
public BasicSplitPaneUI getDividerUI()
{
return m_objDividerUI;
}
protected void saveData()
{
// child classes overwrite this method to save data on close action.
}
protected void undoAction()
{
// child classes overwrite this method to undo action.
}
/**
* Updates the list data.
*/
protected void updateListData(ActionEvent e)
{
if (e.getActionCommand().equals("east"))
{
Object[] aItems = m_listLeft.getSelectedValues();
doAddRemove(false, aItems);
}
else
{
Object[] aItems = m_listRight.getSelectedValues();
doAddRemove(true, aItems);
}
m_listLeft.setListData(m_aListLeft.toArray());
m_listRight.setListData(m_aListRight.toArray());
}
protected void doAddRemove(boolean bLeftAdd, Object[] objItems)
{
String strName = null;
for (int i = 0; i < objItems.length; i++)
{
strName = (String)objItems[i];
if (bLeftAdd)
{
m_aListLeft.add(strName);
m_aListRight.remove(strName);
}
else
{
m_aListRight.add(strName);
m_aListLeft.remove(strName);
}
}
Collections.sort(m_aListLeft);
Collections.sort(m_aListRight);
}
class ButtonDividerUI extends BasicSplitPaneUI
{
public BasicSplitPaneDivider createDefaultDivider()
{
BasicSplitPaneDivider divider = new BasicSplitPaneDivider(this)
{
public int getDividerSize()
{
return m_btnEast.getPreferredSize().width;
}
};
int nHeight = m_pnlLeft.getSize().height / 4;
nHeight = (nHeight <= 0) ? 30 : nHeight;
divider.setLayout(new BoxLayout(divider, BoxLayout.Y_AXIS));
divider.add(Box.createVerticalStrut(nHeight));
divider.add(m_btnEast);
divider.add(Box.createVerticalStrut(nHeight));
divider.add(m_btnWest);
divider.add(Box.createVerticalStrut(nHeight));
return divider;
}
}
}
| |
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* 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 'jMonkeyEngine' 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 com.jme3.bullet.control;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
/**
* AbstractPhysicsControl manages the lifecycle of a physics object that is
* attached to a spatial in the SceneGraph.
*
* @author normenhansen
*/
public abstract class AbstractPhysicsControl implements PhysicsControl, JmeCloneable {
private final Quaternion tmp_inverseWorldRotation = new Quaternion();
protected Spatial spatial;
protected boolean enabled = true;
protected boolean added = false;
protected PhysicsSpace space = null;
protected boolean applyLocal = false;
/**
* Called when the control is added to a new spatial, create any
* spatial-dependent data here.
*
* @param spat The new spatial, guaranteed not to be null
*/
protected abstract void createSpatialData(Spatial spat);
/**
* Called when the control is removed from a spatial, remove any
* spatial-dependent data here.
*
* @param spat The old spatial, guaranteed not to be null
*/
protected abstract void removeSpatialData(Spatial spat);
/**
* Called when the physics object is supposed to move to the spatial
* position.
*
* @param vec
*/
protected abstract void setPhysicsLocation(Vector3f vec);
/**
* Called when the physics object is supposed to move to the spatial
* rotation.
*
* @param quat
*/
protected abstract void setPhysicsRotation(Quaternion quat);
/**
* Called when the physics object is supposed to add all objects it needs to
* manage to the physics space.
*
* @param space
*/
protected abstract void addPhysics(PhysicsSpace space);
/**
* Called when the physics object is supposed to remove all objects added to
* the physics space.
*
* @param space
*/
protected abstract void removePhysics(PhysicsSpace space);
public boolean isApplyPhysicsLocal() {
return applyLocal;
}
/**
* When set to true, the physics coordinates will be applied to the local
* translation of the Spatial
*
* @param applyPhysicsLocal
*/
public void setApplyPhysicsLocal(boolean applyPhysicsLocal) {
applyLocal = applyPhysicsLocal;
}
protected Vector3f getSpatialTranslation() {
if (applyLocal) {
return spatial.getLocalTranslation();
}
return spatial.getWorldTranslation();
}
protected Quaternion getSpatialRotation() {
if (applyLocal) {
return spatial.getLocalRotation();
}
return spatial.getWorldRotation();
}
/**
* Applies a physics transform to the spatial
*
* @param worldLocation
* @param worldRotation
*/
protected void applyPhysicsTransform(Vector3f worldLocation, Quaternion worldRotation) {
if (enabled && spatial != null) {
Vector3f localLocation = spatial.getLocalTranslation();
Quaternion localRotationQuat = spatial.getLocalRotation();
if (!applyLocal && spatial.getParent() != null) {
localLocation.set(worldLocation).subtractLocal(spatial.getParent().getWorldTranslation());
localLocation.divideLocal(spatial.getParent().getWorldScale());
tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().multLocal(localLocation);
localRotationQuat.set(worldRotation);
tmp_inverseWorldRotation.set(spatial.getParent().getWorldRotation()).inverseLocal().mult(localRotationQuat, localRotationQuat);
spatial.setLocalTranslation(localLocation);
spatial.setLocalRotation(localRotationQuat);
} else {
spatial.setLocalTranslation(worldLocation);
spatial.setLocalRotation(worldRotation);
}
}
}
@Override
public void cloneFields( Cloner cloner, Object original ) {
this.spatial = cloner.clone(spatial);
createSpatialData(this.spatial);
}
public void setSpatial(Spatial spatial) {
if (this.spatial != null && this.spatial != spatial) {
removeSpatialData(this.spatial);
} else if (this.spatial == spatial) {
return;
}
this.spatial = spatial;
if (spatial == null) {
return;
}
createSpatialData(this.spatial);
setPhysicsLocation(getSpatialTranslation());
setPhysicsRotation(getSpatialRotation());
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
if (space != null) {
if (enabled && !added) {
if (spatial != null) {
setPhysicsLocation(getSpatialTranslation());
setPhysicsRotation(getSpatialRotation());
}
addPhysics(space);
added = true;
} else if (!enabled && added) {
removePhysics(space);
added = false;
}
}
}
public boolean isEnabled() {
return enabled;
}
public void update(float tpf) {
}
public void render(RenderManager rm, ViewPort vp) {
}
public void setPhysicsSpace(PhysicsSpace space) {
if (space == null) {
if (this.space != null) {
removePhysics(this.space);
added = false;
}
} else {
if (this.space == space) {
return;
} else if (this.space != null) {
removePhysics(this.space);
}
addPhysics(space);
added = true;
}
this.space = space;
}
public PhysicsSpace getPhysicsSpace() {
return space;
}
@Override
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(enabled, "enabled", true);
oc.write(applyLocal, "applyLocalPhysics", false);
oc.write(spatial, "spatial", null);
}
@Override
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
enabled = ic.readBoolean("enabled", true);
spatial = (Spatial) ic.readSavable("spatial", null);
applyLocal = ic.readBoolean("applyLocalPhysics", false);
}
}
| |
package com.amazon.jenkins.ec2fleet;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.ActiveInstance;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSpotFleetInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeSpotFleetInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceState;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.SpotFleetRequestConfig;
import com.amazonaws.services.ec2.model.SpotFleetRequestConfigData;
import hudson.Functions;
import hudson.model.FreeStyleProject;
import hudson.model.Node;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Result;
import hudson.model.StringParameterDefinition;
import hudson.model.StringParameterValue;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.QueueTaskFuture;
import hudson.slaves.OfflineCause;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@SuppressWarnings({"ArraysAsListWithZeroOrOneArgument", "deprecation"})
public class AutoResubmitIntegrationTest extends IntegrationTest {
@Before
public void before() {
EC2Api ec2Api = spy(EC2Api.class);
Registry.setEc2Api(ec2Api);
AmazonEC2 amazonEC2 = mock(AmazonEC2.class);
when(ec2Api.connect(anyString(), anyString(), Mockito.nullable(String.class))).thenReturn(amazonEC2);
final Instance instance = new Instance()
.withState(new InstanceState().withName(InstanceStateName.Running))
.withPublicIpAddress("public-io")
.withInstanceId("i-1");
when(amazonEC2.describeInstances(any(DescribeInstancesRequest.class))).thenReturn(
new DescribeInstancesResult().withReservations(
new Reservation().withInstances(
instance
)));
when(amazonEC2.describeSpotFleetInstances(any(DescribeSpotFleetInstancesRequest.class)))
.thenReturn(new DescribeSpotFleetInstancesResult()
.withActiveInstances(new ActiveInstance().withInstanceId("i-1")));
DescribeSpotFleetRequestsResult describeSpotFleetRequestsResult = new DescribeSpotFleetRequestsResult();
describeSpotFleetRequestsResult.setSpotFleetRequestConfigs(Arrays.asList(
new SpotFleetRequestConfig()
.withSpotFleetRequestState("active")
.withSpotFleetRequestConfig(
new SpotFleetRequestConfigData().withTargetCapacity(1))));
when(amazonEC2.describeSpotFleetRequests(any(DescribeSpotFleetRequestsRequest.class)))
.thenReturn(describeSpotFleetRequestsResult);
}
@Test
public void should_successfully_resubmit_freestyle_task() throws Exception {
EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
0, 0, 10, 1, false, false,
false, 0, 0, false,
10, false);
j.jenkins.clouds.add(cloud);
List<QueueTaskFuture> rs = getQueueTaskFutures(1);
System.out.println("check if zero nodes!");
Assert.assertEquals(0, j.jenkins.getNodes().size());
assertAtLeastOneNode();
final Node node = j.jenkins.getNodes().get(0);
assertQueueIsEmpty();
System.out.println("disconnect node");
node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));
// due to test nature job could be failed if started or aborted as we call disconnect
// in prod code it's not matter
assertLastBuildResult(Result.FAILURE, Result.ABORTED);
node.toComputer().connect(true);
assertNodeIsOnline(node);
assertQueueAndNodesIdle(node);
Assert.assertEquals(1, j.jenkins.getProjects().size());
Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult());
Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size());
cancelTasks(rs);
}
@Test
public void should_successfully_resubmit_parametrized_task() throws Exception {
EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
0, 0, 10, 1, false, false,
false, 0, 0, false,
10, false);
j.jenkins.clouds.add(cloud);
List<QueueTaskFuture> rs = new ArrayList<>();
final FreeStyleProject project = j.createFreeStyleProject();
project.setAssignedLabel(new LabelAtom("momo"));
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("number", "opa")));
/*
example of actions for project
actions = {CopyOnWriteArrayList@14845} size = 2
0 = {ParametersAction@14853}
safeParameters = {TreeSet@14855} size = 0
parameters = {ArrayList@14856} size = 1
0 = {StringParameterValue@14862} "(StringParameterValue) number='1'"
value = "1"
name = "number"
description = ""
parameterDefinitionNames = {ArrayList@14857} size = 1
0 = "number"
build = null
run = {FreeStyleBuild@14834} "parameter #14"
*/
project.getBuildersList().add(Functions.isWindows() ? new BatchFile("Ping -n %number% 127.0.0.1 > nul") : new Shell("sleep ${number}"));
rs.add(project.scheduleBuild2(0, new ParametersAction(new StringParameterValue("number", "30"))));
System.out.println("check if zero nodes!");
Assert.assertEquals(0, j.jenkins.getNodes().size());
assertAtLeastOneNode();
final Node node = j.jenkins.getNodes().get(0);
assertQueueIsEmpty();
System.out.println("disconnect node");
node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));
assertLastBuildResult(Result.FAILURE, Result.ABORTED);
node.toComputer().connect(true);
assertNodeIsOnline(node);
assertQueueAndNodesIdle(node);
Assert.assertEquals(1, j.jenkins.getProjects().size());
Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult());
Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size());
cancelTasks(rs);
}
@Test
public void should_not_resubmit_if_disabled() throws Exception {
EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
0, 0, 10, 1, false, false,
true, 0, 0, false, 10, false);
j.jenkins.clouds.add(cloud);
List<QueueTaskFuture> rs = getQueueTaskFutures(1);
System.out.println("check if zero nodes!");
Assert.assertEquals(0, j.jenkins.getNodes().size());
assertAtLeastOneNode();
final Node node = j.jenkins.getNodes().get(0);
assertQueueIsEmpty();
System.out.println("disconnect node");
node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));
assertLastBuildResult(Result.FAILURE, Result.ABORTED);
node.toComputer().connect(true);
assertNodeIsOnline(node);
assertQueueAndNodesIdle(node);
Assert.assertEquals(1, j.jenkins.getProjects().size());
Assert.assertEquals(Result.FAILURE, j.jenkins.getProjects().get(0).getLastBuild().getResult());
Assert.assertEquals(1, j.jenkins.getProjects().get(0).getBuilds().size());
cancelTasks(rs);
}
}
| |
/*
* Copyright (c) 2013, Oracle and/or its affiliates. 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.jdeps;
import com.sun.tools.classfile.Dependency.Location;
import com.sun.tools.jdeps.PlatformClassPath.JDKArchive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Dependency Analyzer.
*/
public class Analyzer {
/**
* Type of the dependency analysis. Appropriate level of data
* will be stored.
*/
public enum Type {
SUMMARY,
PACKAGE,
CLASS,
VERBOSE
};
private final Type type;
private final Map<Archive, ArchiveDeps> results = new HashMap<>();
private final Map<Location, Archive> map = new HashMap<>();
private final Archive NOT_FOUND
= new Archive(JdepsTask.getMessage("artifact.not.found"));
/**
* Constructs an Analyzer instance.
*
* @param type Type of the dependency analysis
*/
public Analyzer(Type type) {
this.type = type;
}
/**
* Performs the dependency analysis on the given archives.
*/
public void run(List<Archive> archives) {
// build a map from Location to Archive
for (Archive archive: archives) {
for (Location l: archive.getClasses()) {
if (!map.containsKey(l)) {
map.put(l, archive);
} else {
// duplicated class warning?
}
}
}
// traverse and analyze all dependencies
for (Archive archive : archives) {
ArchiveDeps deps;
if (type == Type.CLASS || type == Type.VERBOSE) {
deps = new ClassVisitor(archive);
} else {
deps = new PackageVisitor(archive);
}
archive.visitDependences(deps);
results.put(archive, deps);
}
}
public boolean hasDependences(Archive archive) {
if (results.containsKey(archive)) {
return results.get(archive).deps.size() > 0;
}
return false;
}
public interface Visitor {
/**
* Visits the source archive to its destination archive of
* a recorded dependency.
*/
void visitArchiveDependence(Archive origin, Archive target, Profile profile);
/**
* Visits a recorded dependency from origin to target which can be
* a fully-qualified classname, a package name, a profile or
* archive name depending on the Analyzer's type.
*/
void visitDependence(String origin, Archive source, String target, Archive archive, Profile profile);
}
public void visitArchiveDependences(Archive source, Visitor v) {
ArchiveDeps r = results.get(source);
for (ArchiveDeps.Dep d: r.requireArchives()) {
v.visitArchiveDependence(r.archive, d.archive, d.profile);
}
}
public void visitDependences(Archive source, Visitor v) {
ArchiveDeps r = results.get(source);
for (Map.Entry<String, SortedSet<ArchiveDeps.Dep>> e: r.deps.entrySet()) {
String origin = e.getKey();
for (ArchiveDeps.Dep d: e.getValue()) {
// filter intra-dependency unless in verbose mode
if (type == Type.VERBOSE || d.archive != source) {
v.visitDependence(origin, source, d.target, d.archive, d.profile);
}
}
}
}
/**
* ArchiveDeps contains the dependencies for an Archive that
* can have one or more classes.
*/
private abstract class ArchiveDeps implements Archive.Visitor {
final Archive archive;
final SortedMap<String, SortedSet<Dep>> deps;
ArchiveDeps(Archive archive) {
this.archive = archive;
this.deps = new TreeMap<>();
}
void add(String origin, String target, Archive targetArchive, String pkgName) {
SortedSet<Dep> set = deps.get(origin);
if (set == null) {
deps.put(origin, set = new TreeSet<>());
}
Profile p = targetArchive instanceof JDKArchive
? Profile.getProfile(pkgName) : null;
set.add(new Dep(target, targetArchive, p));
}
/**
* Returns the list of Archive dependences. The returned
* list contains one {@code Dep} instance per one archive
* and with the minimum profile this archive depends on.
*/
List<Dep> requireArchives() {
Map<Archive,Profile> map = new HashMap<>();
for (Set<Dep> set: deps.values()) {
for (Dep d: set) {
if (this.archive != d.archive) {
Profile p = map.get(d.archive);
if (p == null || (d.profile != null && p.profile < d.profile.profile)) {
map.put(d.archive, d.profile);
}
}
}
}
List<Dep> list = new ArrayList<>();
for (Map.Entry<Archive,Profile> e: map.entrySet()) {
list.add(new Dep("", e.getKey(), e.getValue()));
}
return list;
}
/**
* Dep represents a dependence where the target can be
* a classname or packagename and the archive and profile
* the target belongs to.
*/
class Dep implements Comparable<Dep> {
final String target;
final Archive archive;
final Profile profile;
Dep(String target, Archive archive, Profile p) {
this.target = target;
this.archive = archive;
this.profile = p;
}
@Override
public boolean equals(Object o) {
if (o instanceof Dep) {
Dep d = (Dep)o;
return this.archive == d.archive && this.target.equals(d.target);
}
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + Objects.hashCode(this.archive);
hash = 17 * hash + Objects.hashCode(this.target);
return hash;
}
@Override
public int compareTo(Dep o) {
if (this.target.equals(o.target)) {
if (this.archive == o.archive) {
return 0;
} else {
return this.archive.getFileName().compareTo(o.archive.getFileName());
}
}
return this.target.compareTo(o.target);
}
}
public abstract void visit(Location o, Location t);
}
private class ClassVisitor extends ArchiveDeps {
ClassVisitor(Archive archive) {
super(archive);
}
@Override
public void visit(Location o, Location t) {
Archive targetArchive =
this.archive.getClasses().contains(t) ? this.archive : map.get(t);
if (targetArchive == null) {
map.put(t, targetArchive = NOT_FOUND);
}
String origin = o.getClassName();
String target = t.getClassName();
add(origin, target, targetArchive, t.getPackageName());
}
}
private class PackageVisitor extends ArchiveDeps {
PackageVisitor(Archive archive) {
super(archive);
}
@Override
public void visit(Location o, Location t) {
Archive targetArchive =
this.archive.getClasses().contains(t) ? this.archive : map.get(t);
if (targetArchive == null) {
map.put(t, targetArchive = NOT_FOUND);
}
String origin = packageOf(o);
String target = packageOf(t);
add(origin, target, targetArchive, t.getPackageName());
}
public String packageOf(Location o) {
String pkg = o.getPackageName();
return pkg.isEmpty() ? "<unnamed>" : pkg;
}
}
}
| |
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* 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 'jMonkeyEngine' 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 com.jme3.animation;
import com.jme3.math.FastMath;
import com.jme3.util.TempVars;
import java.util.BitSet;
/**
* <code>AnimChannel</code> provides controls, such as play, pause,
* fast forward, etc, for an animation. The animation
* channel may influence the entire model or specific bones of the model's
* skeleton. A single model may have multiple animation channels influencing
* various parts of its body. For example, a character model may have an
* animation channel for its feet, and another for its torso, and
* the animations for each channel are controlled independently.
*
* @author Kirill Vainer
*/
public final class AnimChannel {
private static final float DEFAULT_BLEND_TIME = 0.15f;
private AnimControl control;
private BitSet affectedBones;
private Animation animation;
private Animation blendFrom;
private float time;
private float speed;
private float timeBlendFrom;
private float blendTime;
private float speedBlendFrom;
private boolean notified=false;
private LoopMode loopMode, loopModeBlendFrom;
private float blendAmount = 1f;
private float blendRate = 0;
AnimChannel(AnimControl control){
this.control = control;
}
/**
* Returns the parent control of this AnimChannel.
*
* @return the parent control of this AnimChannel.
* @see AnimControl
*/
public AnimControl getControl() {
return control;
}
/**
* @return The name of the currently playing animation, or null if
* none is assigned.
*
* @see AnimChannel#setAnim(java.lang.String)
*/
public String getAnimationName() {
return animation != null ? animation.getName() : null;
}
/**
* @return The loop mode currently set for the animation. The loop mode
* determines what will happen to the animation once it finishes
* playing.
*
* For more information, see the LoopMode enum class.
* @see LoopMode
* @see AnimChannel#setLoopMode(com.jme3.animation.LoopMode)
*/
public LoopMode getLoopMode() {
return loopMode;
}
/**
* @param loopMode Set the loop mode for the channel. The loop mode
* determines what will happen to the animation once it finishes
* playing.
*
* For more information, see the LoopMode enum class.
* @see LoopMode
*/
public void setLoopMode(LoopMode loopMode) {
this.loopMode = loopMode;
}
/**
* @return The speed that is assigned to the animation channel. The speed
* is a scale value starting from 0.0, at 1.0 the animation will play
* at its default speed.
*
* @see AnimChannel#setSpeed(float)
*/
public float getSpeed() {
return speed;
}
/**
* @param speed Set the speed of the animation channel. The speed
* is a scale value starting from 0.0, at 1.0 the animation will play
* at its default speed.
*/
public void setSpeed(float speed) {
this.speed = speed;
if(blendTime>0){
this.speedBlendFrom = speed;
blendTime = Math.min(blendTime, animation.getLength() / speed);
blendRate = 1/ blendTime;
}
}
/**
* @return The time of the currently playing animation. The time
* starts at 0 and continues on until getAnimMaxTime().
*
* @see AnimChannel#setTime(float)
*/
public float getTime() {
return time;
}
/**
* @param time Set the time of the currently playing animation, the time
* is clamped from 0 to {@link #getAnimMaxTime()}.
*/
public void setTime(float time) {
this.time = FastMath.clamp(time, 0, getAnimMaxTime());
}
/**
* @return The length of the currently playing animation, or zero
* if no animation is playing.
*
* @see AnimChannel#getTime()
*/
public float getAnimMaxTime(){
return animation != null ? animation.getLength() : 0f;
}
/**
* Set the current animation that is played by this AnimChannel.
* <p>
* This resets the time to zero, and optionally blends the animation
* over <code>blendTime</code> seconds with the currently playing animation.
* Notice that this method will reset the control's speed to 1.0.
*
* @param name The name of the animation to play
* @param blendTime The blend time over which to blend the new animation
* with the old one. If zero, then no blending will occur and the new
* animation will be applied instantly.
*/
public void setAnim(String name, float blendTime){
if (name == null)
throw new IllegalArgumentException("name cannot be null");
if (blendTime < 0f)
throw new IllegalArgumentException("blendTime cannot be less than zero");
Animation anim = control.animationMap.get(name);
if (anim == null)
throw new IllegalArgumentException("Cannot find animation named: '"+name+"'");
control.notifyAnimChange(this, name);
if (animation != null && blendTime > 0f){
this.blendTime = blendTime;
// activate blending
blendTime = Math.min(blendTime, anim.getLength() / speed);
blendFrom = animation;
timeBlendFrom = time;
speedBlendFrom = speed;
loopModeBlendFrom = loopMode;
blendAmount = 0f;
blendRate = 1f / blendTime;
}else{
blendFrom = null;
}
animation = anim;
time = 0;
speed = 1f;
loopMode = LoopMode.Loop;
notified = false;
}
/**
* Set the current animation that is played by this AnimChannel.
* <p>
* See {@link #setAnim(java.lang.String, float)}.
* The blendTime argument by default is 150 milliseconds.
*
* @param name The name of the animation to play
*/
public void setAnim(String name){
setAnim(name, DEFAULT_BLEND_TIME);
}
/**
* Add all the bones of the model's skeleton to be
* influenced by this animation channel.
*/
public void addAllBones() {
affectedBones = null;
}
/**
* Add a single bone to be influenced by this animation channel.
*/
public void addBone(String name) {
addBone(control.getSkeleton().getBone(name));
}
/**
* Add a single bone to be influenced by this animation channel.
*/
public void addBone(Bone bone) {
int boneIndex = control.getSkeleton().getBoneIndex(bone);
if(affectedBones == null) {
affectedBones = new BitSet(control.getSkeleton().getBoneCount());
}
affectedBones.set(boneIndex);
}
/**
* Add bones to be influenced by this animation channel starting from the
* given bone name and going toward the root bone.
*/
public void addToRootBone(String name) {
addToRootBone(control.getSkeleton().getBone(name));
}
/**
* Add bones to be influenced by this animation channel starting from the
* given bone and going toward the root bone.
*/
public void addToRootBone(Bone bone) {
addBone(bone);
while (bone.getParent() != null) {
bone = bone.getParent();
addBone(bone);
}
}
/**
* Add bones to be influenced by this animation channel, starting
* from the given named bone and going toward its children.
*/
public void addFromRootBone(String name) {
addFromRootBone(control.getSkeleton().getBone(name));
}
/**
* Add bones to be influenced by this animation channel, starting
* from the given bone and going toward its children.
*/
public void addFromRootBone(Bone bone) {
addBone(bone);
if (bone.getChildren() == null)
return;
for (Bone childBone : bone.getChildren()) {
addBone(childBone);
addFromRootBone(childBone);
}
}
BitSet getAffectedBones(){
return affectedBones;
}
public void reset(boolean rewind){
if(rewind){
setTime(0);
if(control.getSkeleton()!=null){
control.getSkeleton().resetAndUpdate();
}else{
TempVars vars = TempVars.get();
update(0, vars);
vars.release();
}
}
animation = null;
notified = false;
}
void update(float tpf, TempVars vars) {
if (animation == null)
return;
if (blendFrom != null && blendAmount != 1.0f){
// The blendFrom anim is set, the actual animation
// playing will be set
// blendFrom.setTime(timeBlendFrom, 1f, control, this, vars);
blendFrom.setTime(timeBlendFrom, 1f - blendAmount, control, this, vars);
timeBlendFrom += tpf * speedBlendFrom;
timeBlendFrom = AnimationUtils.clampWrapTime(timeBlendFrom,
blendFrom.getLength(),
loopModeBlendFrom);
if (timeBlendFrom < 0){
timeBlendFrom = -timeBlendFrom;
speedBlendFrom = -speedBlendFrom;
}
blendAmount += tpf * blendRate;
if (blendAmount > 1f){
blendAmount = 1f;
blendFrom = null;
}
}
animation.setTime(time, blendAmount, control, this, vars);
time += tpf * speed;
if (animation.getLength() > 0){
if (!notified && (time >= animation.getLength() || time < 0)) {
if (loopMode == LoopMode.DontLoop) {
// Note that this flag has to be set before calling the notify
// since the notify may start a new animation and then unset
// the flag.
notified = true;
}
control.notifyAnimCycleDone(this, animation.getName());
}
}
time = AnimationUtils.clampWrapTime(time, animation.getLength(), loopMode);
if (time < 0){
// Negative time indicates that speed should be inverted
// (for cycle loop mode only)
time = -time;
speed = -speed;
}
}
}
| |
/* Copyright 2015 Sven van der Meer <vdmeer.sven@mykolab.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.skb.datatool.backend;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.Validate;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import de.vandermeer.skb.base.info.FileTarget;
import de.vandermeer.skb.base.info.STGroupValidator;
import de.vandermeer.skb.base.info.StgFileLoader;
import de.vandermeer.skb.base.utils.collections.Skb_CollectionTransformer;
import de.vandermeer.skb.datatool.commons.CoreSettings;
import de.vandermeer.skb.datatool.commons.DataEntry;
import de.vandermeer.skb.datatool.commons.DataSet;
/**
* Backend to write templates to file.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.0.1 build 160301 (01-Mar-16) for Java 1.8
* @since v0.0.1
*/
public class BackendWriter {
/** The original file name. */
private String fileName;
/** The final file name to write to. */
private String fileNameFinal;
/** The loader for STG files. */
private StgFileLoader stgLoader;
/** Local STG. */
private STGroup stg;
/** The file target created from the file name. */
private FileTarget fileTarget;
/** Core settings. */
private CoreSettings cs;
/** Expected chunks for the ST template. */
private final Map<String, Set<String>> expectedStChunks = new HashMap<String, Set<String>>() {private static final long serialVersionUID = 1L;{
put("build", new HashSet<String>() {private static final long serialVersionUID = 1L;{
add("entry");
add("entry2");
}});
}};
/**
* Creates a new backend writer
* @param fileName the output file name
* @param cs the core settings for the writer
* @throws IllegalArgumentException if any required argument is not valid
*/
public BackendWriter(String fileName, CoreSettings cs){
Validate.notNull(cs);
this.cs = cs;
if(fileName!=null){
this.fileName = fileName;
if(this.cs.getTarget()!=null){
this.fileNameFinal = fileName + "." + cs.getTarget().getDefinition().getExtension();
}
else{
this.fileNameFinal = fileName;
}
FileTarget.createFile(this.fileNameFinal);
this.fileTarget = new FileTarget(this.fileNameFinal);
Validate.validState(this.fileTarget.isValid(), "errors writing to file <%s>\n%s", this.fileName, this.fileTarget.getInitError().render());
}
if(cs.getTarget()!=null){
this.stgLoader = new StgFileLoader(cs.getTarget().getStgFileName());
Validate.validState(this.stgLoader.getLoadErrors().size()==0, "problem creating STG loader for file <%s>\n%s", cs.getTarget().getStgFileName(), this.stgLoader.getLoadErrors().render());
STGroup stg = this.stgLoader.load();
Validate.validState(this.stgLoader.getLoadErrors().size()==0, "errors loading STG file <%s>\n%s", cs.getTarget().getStgFileName(), this.stgLoader.getLoadErrors().render());
Validate.notNull(stg, "unknown error loading STG file <%s>", cs.getTarget().getStgFileName());
STGroupValidator stgVal = new STGroupValidator(stg, this.expectedStChunks);
Validate.validState(stgVal.getValidationErrors().size()==0, "STG validation errors for file <%s>\n%s", cs.getTarget().getStgFileName(), stgVal.getValidationErrors().render());
this.stg = stg;
Validate.notNull(this.stg);
}
}
/**
* Writes output.
* @param bl the backend loader
* @throws IllegalArgumentException if any required argument is not valid
* @throws IOException if writing to a file failed
*/
public void writeOutput(BackendLoader bl) throws IOException{
Validate.notNull(bl);
String toWrite = null;
if(this.cs.getTarget()!=null){
ST st = this.fillTemplate(bl);
if(st!=null){
toWrite = st.render();
}
}
else{
toWrite = Skb_CollectionTransformer.MAP_TO_TEXT(bl.getMainDataSet().getMap());
}
if(toWrite!=null){
if(this.fileTarget!=null && this.fileTarget.asFile()!=null){
FileUtils.write(this.fileTarget.asFile(), toWrite, "UTF-8");
}
else{
System.out.println(toWrite);
}
}
else{
throw new IllegalArgumentException("failed to create output string, tried ST and Transformer");
}
}
/**
* Fills the template with all found data sets
* @param bl backend loader with data sets
* @return created template
*/
public ST fillTemplate(BackendLoader bl){
Validate.notNull(bl);
DataSet<?> entries1 = bl.getMainDataSet();
if(entries1!=null){
ST st = this.writeST(entries1);
DataSet<?> entries2 = bl.getSecondayDataSet();
if(entries2!=null){
st = this.addToST(entries2, st);
}
return st;
}
return null;
}
/**
* Writes a data set to a template.
* @param ds the data set to write
* @param <E> type of the data set
* @return the created template
*/
public <E extends DataEntry> ST writeST(DataSet<E> ds) {
Validate.notNull(ds);
if(this.cs.getTarget()!=null){
ST st = stg.getInstanceOf("build");
for(E entry : ds.getEntries()){
st.add("entry", entry);
}
return st;
}
return null;
}
/**
* Adds a data set to the ST (entry2)
* @param ds the data set to be added
* @param <E> type of data set
* @param st the template to add to
* @return the template
*/
public <E extends DataEntry> ST addToST(DataSet<E> ds, ST st) {
Validate.notNull(ds);
Validate.notNull(st);
for(E entry2 : ds.getEntries()){
st.add("entry2", entry2);
}
return st;
}
/**
* Returns the output mode.
* @return description of what a write will do
*/
public String getOutputMode(){
if(this.cs.getTarget()==null){
return "no target, writing Map<>";
}
else if(this.cs.getTarget()!=null && this.fileTarget==null){
return "for target <" + this.cs.getTarget().getDefinition().getTargetName() + "> writing to STDOUT";
}
else if(this.cs.getTarget()!=null && this.fileTarget!=null){
return "for target <" + this.cs.getTarget().getDefinition().getTargetName() + "> writing to <" + ((this.fileTarget==null)?"standard out":this.fileTarget.getAbsoluteName()) +">";
}
return null;
}
}
| |
/*
* Copyright 2011 Goldman Sachs.
*
* 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.gs.collections.impl.utility;
import com.gs.collections.api.LazyIterable;
import com.gs.collections.api.block.procedure.ObjectIntProcedure;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Procedures;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.math.IntegerSum;
import com.gs.collections.impl.math.Sum;
import org.junit.Assert;
import org.junit.Test;
public class LazyIterateTest
{
@Test
public void selectForEach()
{
LazyIterable<Integer> select = LazyIterate.select(Interval.oneTo(5), Predicates.lessThan(5));
int sum = select.injectInto(0, AddFunction.INTEGER_TO_INT);
Assert.assertEquals(10, sum);
}
@Test
public void selectForEachWithIndex()
{
LazyIterable<Integer> select = LazyIterate.select(Interval.oneTo(5), Predicates.lessThan(5));
final Sum sum = new IntegerSum(0);
select.forEachWithIndex(new ObjectIntProcedure<Integer>()
{
public void value(Integer object, int index)
{
sum.add(object);
sum.add(index);
}
});
Assert.assertEquals(16, sum.getValue().intValue());
}
@Test
public void selectIterator()
{
LazyIterable<Integer> select = LazyIterate.select(Interval.oneTo(5), Predicates.lessThan(5));
Sum sum = new IntegerSum(0);
for (Integer each : select)
{
sum.add(each);
}
Assert.assertEquals(10, sum.getValue().intValue());
}
@Test
public void selectForEachWith()
{
LazyIterable<Integer> select = LazyIterate.select(Interval.oneTo(5), Predicates.lessThan(5));
Sum sum = new IntegerSum(0);
select.forEachWith(new Procedure2<Integer, Sum>()
{
public void value(Integer each, Sum aSum)
{
aSum.add(each);
}
}, sum);
Assert.assertEquals(10, sum.getValue().intValue());
}
@Test
public void rejectForEach()
{
LazyIterable<Integer> select = LazyIterate.reject(Interval.oneTo(5), Predicates.lessThan(5));
int sum = select.injectInto(0, AddFunction.INTEGER_TO_INT);
Assert.assertEquals(5, sum);
}
@Test
public void rejectForEachWithIndex()
{
LazyIterable<Integer> select = LazyIterate.reject(Interval.oneTo(5), Predicates.lessThan(5));
final Sum sum = new IntegerSum(0);
select.forEachWithIndex(new ObjectIntProcedure<Integer>()
{
public void value(Integer object, int index)
{
sum.add(object);
sum.add(index);
}
});
Assert.assertEquals(5, sum.getValue().intValue());
}
@Test
public void rejectIterator()
{
LazyIterable<Integer> select = LazyIterate.reject(Interval.oneTo(5), Predicates.lessThan(5));
Sum sum = new IntegerSum(0);
for (Integer each : select)
{
sum.add(each);
}
Assert.assertEquals(5, sum.getValue().intValue());
}
@Test
public void rejectForEachWith()
{
LazyIterable<Integer> select = LazyIterate.reject(Interval.oneTo(5), Predicates.lessThan(5));
Sum sum = new IntegerSum(0);
select.forEachWith(new Procedure2<Integer, Sum>()
{
public void value(Integer each, Sum aSum)
{
aSum.add(each);
}
}, sum);
Assert.assertEquals(5, sum.getValue().intValue());
}
@Test
public void collectForEach()
{
LazyIterable<String> select = LazyIterate.collect(Interval.oneTo(5), Functions.getToString());
Appendable builder = new StringBuilder();
Procedure<String> appendProcedure = Procedures.append(builder);
select.forEach(appendProcedure);
Assert.assertEquals("12345", builder.toString());
}
@Test
public void collectForEachWithIndex()
{
LazyIterable<String> select = LazyIterate.collect(Interval.oneTo(5), Functions.getToString());
final StringBuilder builder = new StringBuilder("");
select.forEachWithIndex(new ObjectIntProcedure<String>()
{
public void value(String object, int index)
{
builder.append(object);
builder.append(index);
}
});
Assert.assertEquals("1021324354", builder.toString());
}
@Test
public void collectIterator()
{
LazyIterable<String> select = LazyIterate.collect(Interval.oneTo(5), Functions.getToString());
StringBuilder builder = new StringBuilder("");
for (String each : select)
{
builder.append(each);
}
Assert.assertEquals("12345", builder.toString());
}
@Test
public void collectForEachWith()
{
LazyIterable<String> select = LazyIterate.collect(Interval.oneTo(5), Functions.getToString());
StringBuilder builder = new StringBuilder("");
select.forEachWith(new Procedure2<String, StringBuilder>()
{
public void value(String each, StringBuilder aBuilder)
{
aBuilder.append(each);
}
}, builder);
Assert.assertEquals("12345", builder.toString());
}
@Test
public void asDeferred()
{
MutableList<Integer> expected = FastList.newList(Interval.oneTo(5));
MutableList<Integer> actual0 = LazyIterate.adapt(Interval.oneTo(5)).toList();
MutableList<Integer> actual1 = Interval.oneTo(5).asLazy().toList();
MutableList<Integer> actual2 = FastList.newList(Interval.oneTo(5)).asLazy().toList();
MutableList<Integer> actual3 = actual2.asUnmodifiable().asLazy().toList();
MutableList<Integer> actual4 = actual2.asSynchronized().asLazy().toList();
MutableList<Integer> actual5 = actual2.asLazy().select(Predicates.alwaysTrue()).toList();
MutableList<Integer> actual6 = actual2.toImmutable().asLazy().toList();
ImmutableList<Integer> actual7 = actual2.asLazy().toList().toImmutable();
Assert.assertEquals(expected, actual0);
Assert.assertEquals(expected, actual1);
Assert.assertEquals(expected, actual2);
Assert.assertEquals(expected, actual3);
Assert.assertEquals(expected, actual4);
Assert.assertEquals(expected, actual5);
Assert.assertEquals(expected, actual6);
Assert.assertEquals(expected, actual7);
}
}
| |
package org.jgroups.tests;
import org.jgroups.*;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.protocols.pbcast.STABLE;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Tests unicast functionality
* @author Bela Ban
*/
@Test(groups=Global.FUNCTIONAL,singleThreaded=true)
public class UnicastUnitTest {
protected JChannel a, b, c, d;
@AfterMethod protected void tearDown() throws Exception {Util.closeReverse(a,b,c,d);}
public void testUnicastMessageInCallbackExistingMember() throws Throwable {
a=create("A", false); b=create("B", false);
a.connect("UnicastUnitTest");
MyReceiver receiver=new MyReceiver(a);
a.setReceiver(receiver);
b.connect("UnicastUnitTest");
a.setReceiver(null); // so the receiver doesn't get a view change
Throwable ex=receiver.getEx();
if(ex != null)
throw ex;
}
/** Tests sending msgs from A to B */
// @Test(invocationCount=10)
public void testMessagesToOther() throws Exception {
a=create("A", false); b=create("B", false);
_testMessagesToOther();
}
public void testMessagesToOtherBatching() throws Exception {
a=create("A", true); b=create("B", true);
_testMessagesToOther();
}
public void testMessagesToEverybodyElse() throws Exception {
MyReceiver<String> r1=new MyReceiver(), r2=new MyReceiver(), r3=new MyReceiver(), r4=new MyReceiver();
a=create("A", false);
b=create("B", false);
c=create("C", false);
d=create("D", false);
connect(a,b,c,d);
a.setReceiver(r1);
b.setReceiver(r2);
c.setReceiver(r3);
d.setReceiver(r4);
for(JChannel sender: Arrays.asList(a,b,c,d)) {
for(JChannel receiver: Arrays.asList(a,b,c,d)) {
for(int i=1; i <= 5; i++) {
Message msg=new BytesMessage(receiver.getAddress(), String.format("%s%d", sender.getAddress(), i));
sender.send(msg);
}
}
}
for(int i=0; i < 10; i++) {
if(Stream.of(r1,r2,r3,r4).allMatch(r -> r.list().size() == 20))
break;
Util.sleep(500);
}
Stream.of(r1,r2,r3,r4).forEach(r -> System.out.printf("%s\n", r.list));
List<Integer> expected_list=Arrays.asList(1,2,3,4,5);
System.out.print("Checking (per-sender) FIFO ordering of messages: ");
Stream.of(r1,r2,r3,r4).forEach(r -> Stream.of(a, b, c, d).forEach(ch -> {
String name=ch.getName();
List<String> list=r.list();
List<String> l=list.stream().filter(el -> el.startsWith(name)).collect(Collectors.toList());
List<Integer> nl=l.stream().map(s -> s.substring(1)).map(Integer::valueOf).collect(Collectors.toList());
assert nl.equals(expected_list) : String.format("%s: expected: %s, actual: %s", name, expected_list, nl);
}));
System.out.println("OK");
}
public void testPartition() throws Exception {
a=create("A", false);
b=create("B", false);
connect(a,b);
System.out.println("-- Creating network partition");
Stream.of(a,b).forEach(ch -> {
DISCARD discard=new DISCARD().discardAll(true);
try {
ch.getProtocolStack().insertProtocol(discard, ProtocolStack.Position.ABOVE, TP.class);
}
catch(Exception e) {
e.printStackTrace();
}
});
for(int i=0; i < 10; i++) {
if(Stream.of(a,b).allMatch(ch -> ch.getView().size() == 1))
break;
Util.sleep(1000);
}
Stream.of(a,b).forEach(ch -> System.out.printf("%s: %s\n", ch.getAddress(), ch.getView()));
System.out.println("-- Removing network partition; waiting for merge");
Stream.of(a,b).forEach(ch -> ch.getProtocolStack().removeProtocol(DISCARD.class));
for(int i=0; i < 10; i++) {
if(Stream.of(a,b).allMatch(ch -> ch.getView().size() == 2))
break;
Util.sleep(1000);
}
Stream.of(a,b).forEach(ch -> System.out.printf("%s: %s\n", ch.getAddress(), ch.getView()));
}
protected void _testMessagesToOther() throws Exception {
connect(a,b);
Address dest=b.getAddress();
Message[] msgs={
msg(dest), // reg
msg(dest),
msg(dest).setFlag(Message.Flag.OOB),
msg(dest).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest)
};
MyReceiver<Integer> receiver=new MyReceiver();
b.setReceiver(receiver);
send(a, msgs);
checkReception(receiver, false, 1,2,3,4,5);
}
// @Test(invocationCount=10)
public void testMessagesToSelf() throws Exception {
a=create("A", false); b=create("B", false);
_testMessagesToSelf();
}
public void testMessagesToSelfBatching() throws Exception {
a=create("A", true); b=create("B", true);
_testMessagesToSelf();
}
protected void _testMessagesToSelf() throws Exception {
connect(a,b);
Address dest=a.getAddress();
Message[] msgs={
msg(dest),
msg(dest),
msg(dest).setFlag(Message.Flag.OOB),
msg(dest).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest),
msg(dest).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest),
msg(dest)
};
MyReceiver<Integer> receiver=new MyReceiver<>();
a.setReceiver(receiver);
send(a, msgs);
checkReception(receiver, false, 1,2,3,5,8,9);
}
public void testMessagesToSelf2() throws Exception {
a=create("A", false); b=create("B", false);
_testMessagesToSelf2();
}
public void testMessagesToSelf2Batching() throws Exception {
a=create("A", true); b=create("B", true);
_testMessagesToSelf2();
}
protected void _testMessagesToSelf2() throws Exception {
connect(a,b);
Address dest=a.getAddress();
Message[] msgs={
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.Flag.OOB),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.Flag.OOB),
msg(dest).setFlag(Message.Flag.OOB),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
msg(dest),
msg(dest).setFlag(Message.Flag.OOB).setFlag(Message.TransientFlag.DONT_LOOPBACK),
};
MyReceiver<Integer> receiver=new MyReceiver<>();
a.setReceiver(receiver);
send(a, msgs);
checkReception(receiver, false, 2,5,6,10);
}
protected static void send(JChannel ch, Message... msgs) throws Exception {
int cnt=1;
for(Message msg: msgs) {
assert msg.getDest() != null;
msg.setObject(cnt++);
ch.send(msg);
}
}
protected static void checkReception(MyReceiver<Integer> r, boolean check_order, int... num) {
List<Integer> received=r.list();
for(int i=0; i < 10; i++) {
if(received.size() == num.length)
break;
Util.sleep(500);
}
List<Integer> expected=new ArrayList<>(num.length);
for(int n: num) expected.add(n);
System.out.println("received=" + received + ", expected=" + expected);
assert received.size() == expected.size() : "list=" + received + ", expected=" + expected;
assert received.containsAll(expected) : "list=" + received + ", expected=" + expected;
if(check_order)
for(int i=0; i < num.length; i++)
assert num[i] == received.get(i);
}
protected static Message msg(Address dest) {return new BytesMessage(dest);}
protected static JChannel create(String name, boolean use_batching) throws Exception {
Protocol[] protocols={
new UDP().setBindAddress(Util.getLoopback()),
new LOCAL_PING(),
// new TEST_PING(),
new MERGE3().setMinInterval(500).setMaxInterval(3000).setCheckInterval(4000),
new FD_ALL3().setTimeout(2000).setInterval(500),
new NAKACK2(),
new MAKE_BATCH().sleepTime(100).unicasts(use_batching),
new UNICAST3(),
new STABLE(),
new GMS().setJoinTimeout(1000),
new FRAG2().setFragSize(8000),
};
return new JChannel(protocols).name(name);
}
protected static void connect(JChannel... channels) throws Exception {
for(JChannel ch: channels)
ch.connect("UnicastUnitTest");
Util.waitUntilAllChannelsHaveSameView(10000, 1000, channels);
}
protected static class MyReceiver<T> implements Receiver {
protected JChannel channel;
protected Throwable ex;
protected final List<T> list=new ArrayList<>();
public MyReceiver() {this(null);}
public MyReceiver(JChannel ch) {this.channel=ch;}
public Throwable getEx() {return ex;}
public List<T> list() {return list;}
public void clear() {list.clear();}
public void receive(Message msg) {
T obj=msg.getObject();
synchronized(list) {
list.add(obj);
}
}
/* public void viewAccepted(View new_view) {
if(channel == null) return;
Address local_addr=channel.getAddress();
assert local_addr != null;
System.out.println("[" + local_addr + "]: " + new_view);
List<Address> members=new LinkedList<>(new_view.getMembers());
assert 2 == members.size() : "members=" + members + ", local_addr=" + local_addr + ", view=" + new_view;
Address dest=members.get(0);
Message unicast_msg=new EmptyMessage(dest);
try {
channel.send(unicast_msg);
}
catch(Throwable e) {
ex=e;
throw new RuntimeException(e);
}
}*/
}
}
| |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.bpel.model.impl;
import java.util.Collection;
import org.eclipse.bpel.model.AssignE4X;
import org.eclipse.bpel.model.BPELPackage;
import org.eclipse.bpel.model.ExtensionAssignOperation;
import org.eclipse.bpel.model.util.BPELConstants;
import org.eclipse.bpel.model.util.BPELUtils;
import org.eclipse.bpel.model.util.ReconciliationHelper;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Assign E4X</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.bpel.model.impl.AssignE4XImpl#getValidate <em>Validate</em>}</li>
* <li>{@link org.eclipse.bpel.model.impl.AssignE4XImpl#getExtensionAssignOperation <em>Extension Assign Operation</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class AssignE4XImpl extends ActivityImpl implements AssignE4X {
/**
* The default value of the '{@link #getValidate() <em>Validate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValidate()
* @generated
* @ordered
*/
protected static final Boolean VALIDATE_EDEFAULT = Boolean.FALSE;
/**
* The cached value of the '{@link #getValidate() <em>Validate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValidate()
* @generated
* @ordered
*/
protected Boolean validate = VALIDATE_EDEFAULT;
/**
* The cached value of the '{@link #getExtensionAssignOperation() <em>Extension Assign Operation</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getExtensionAssignOperation()
* @generated
* @ordered
*/
protected EList<ExtensionAssignOperation> extensionAssignOperation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AssignE4XImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return BPELPackage.Literals.ASSIGN_E4X;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Boolean getValidate() {
return validate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void setValidate(Boolean newValidate) {
Boolean oldValidate = validate;
if (!isReconciling) {
ReconciliationHelper.replaceAttribute(this,
BPELConstants.AT_VALIDATE,
BPELUtils.boolean2XML(newValidate));
}
validate = newValidate;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
BPELPackage.ASSIGN_E4X__VALIDATE, oldValidate, validate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ExtensionAssignOperation> getExtensionAssignOperation() {
if (extensionAssignOperation == null) {
extensionAssignOperation = new EObjectContainmentEList<ExtensionAssignOperation>(
ExtensionAssignOperation.class, this,
BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION);
}
return extensionAssignOperation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseRemove(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION:
return ((InternalEList<?>) getExtensionAssignOperation())
.basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BPELPackage.ASSIGN_E4X__VALIDATE:
return getValidate();
case BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION:
return getExtensionAssignOperation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case BPELPackage.ASSIGN_E4X__VALIDATE:
setValidate((Boolean) newValue);
return;
case BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION:
getExtensionAssignOperation().clear();
getExtensionAssignOperation().addAll(
(Collection<? extends ExtensionAssignOperation>) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case BPELPackage.ASSIGN_E4X__VALIDATE:
setValidate(VALIDATE_EDEFAULT);
return;
case BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION:
getExtensionAssignOperation().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case BPELPackage.ASSIGN_E4X__VALIDATE:
return VALIDATE_EDEFAULT == null ? validate != null
: !VALIDATE_EDEFAULT.equals(validate);
case BPELPackage.ASSIGN_E4X__EXTENSION_ASSIGN_OPERATION:
return extensionAssignOperation != null
&& !extensionAssignOperation.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String toString() {
if (eIsProxy())
return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (Validate: "); //$NON-NLS-1$
result.append(validate);
result.append(')');
return result.toString();
}
protected void adoptContent(EReference reference, Object object) {
if (object instanceof ExtensionAssignOperation) {
ReconciliationHelper.adoptChild(this, extensionAssignOperation,
(ExtensionAssignOperation) object,
BPELConstants.ND_EXTENSION_ASSIGN_OPERATION);
}
super.adoptContent(reference, object);
}
protected void orphanContent(EReference reference, Object obj) {
if (obj instanceof ExtensionAssignOperation) {
ReconciliationHelper.orphanChild(this,
(ExtensionAssignOperation) obj);
}
super.orphanContent(reference, obj);
}
} //AssignE4XImpl
| |
/*
* Copyright 2005-2006,2010 Jeremias Maerki.
*
* 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.krysalis.barcode4j.fop;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.fop.area.PageViewport;
import org.apache.fop.render.Graphics2DAdapter;
import org.apache.fop.render.Graphics2DImagePainter;
import org.apache.fop.render.ImageAdapter;
import org.apache.fop.render.Renderer;
import org.apache.fop.render.RendererContext;
import org.apache.fop.render.RendererContextConstants;
import org.apache.fop.render.XMLHandler;
import org.apache.xmlgraphics.ps.PSGenerator;
import org.apache.xmlgraphics.ps.PSImageUtils;
import org.krysalis.barcode4j.BarcodeDimension;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.BarcodeCanvasSetupException;
import org.krysalis.barcode4j.output.Orientation;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.output.eps.EPSCanvasProvider;
import org.krysalis.barcode4j.output.java2d.Java2DCanvasProvider;
import org.krysalis.barcode4j.output.svg.SVGCanvasProvider;
import org.krysalis.barcode4j.tools.ConfigurationUtil;
import org.krysalis.barcode4j.tools.UnitConv;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import com.github.mbhk.barcode4j.Configuration;
/**
* XMLHandler for Apache FOP that handles the Barcode XML by converting it to
* SVG or by rendering it directly to the output format.
*
* @author Jeremias Maerki
* @version $Id$
*/
public class BarcodeXMLHandler implements XMLHandler, RendererContextConstants {
private static final boolean DEBUG = false;
/** The context constant for the PostScript generator that is being used to drawn into. */
private static final String PS_GENERATOR = "psGenerator";
@Override
public void handleXML(RendererContext context,
Document doc, String ns) throws Exception {
final Configuration cfg = ConfigurationUtil.buildConfiguration(doc);
final String msg = ConfigurationUtil.getMessage(cfg);
if (DEBUG) {
System.out.println("Barcode message: " + msg);
}
final String renderMode = cfg.getAttribute("render-mode", "native");
final Orientation orientation = Orientation.fromInt(cfg.getAttributeAsInteger("orientation", 0));
final PageViewport page = (PageViewport)context.getProperty(PAGE_VIEWPORT);
final BarcodeGenerator bargen = BarcodeUtil.getInstance().
createBarcodeGenerator(cfg);
final String expandedMsg = FopVariableUtil.getExpandedMessage(
page, msg);
boolean handled = false;
String effRenderMode = renderMode;
if ("native".equals(renderMode)) {
if (context.getProperty(PS_GENERATOR) != null) {
renderUsingEPS(context, bargen, expandedMsg, orientation);
effRenderMode = "native";
handled = true;
}
} else if ("g2d".equals(renderMode)) {
handled = renderUsingGraphics2D(context, bargen, expandedMsg, orientation);
if (handled) {
effRenderMode = "g2d";
}
} else if ("bitmap".equals(renderMode)) {
handled = renderUsingBitmap(context, bargen, expandedMsg, orientation);
if (handled) {
effRenderMode = "bitmap";
}
}
if (!handled) {
//Convert the Barcode XML to SVG and let it render through
//an SVG handler
convertToSVG(context, bargen, expandedMsg, orientation);
effRenderMode = "svg";
}
if (DEBUG) {
System.out.println("Effective render mode: " + effRenderMode);
}
}
private void renderUsingEPS(RendererContext context, BarcodeGenerator bargen,
String msg, Orientation orientation) throws IOException {
final PSGenerator gen = (PSGenerator)context.getProperty(PS_GENERATOR);
final ByteArrayOutputStream baout = new ByteArrayOutputStream(1024);
final EPSCanvasProvider canvas = new EPSCanvasProvider(baout, orientation);
bargen.generateBarcode(canvas, msg);
canvas.finish();
final BarcodeDimension barDim = canvas.getDimensions();
final float bw = (float)UnitConv.mm2pt(barDim.getWidthPlusQuiet(orientation));
final float bh = (float)UnitConv.mm2pt(barDim.getHeightPlusQuiet(orientation));
final float width = (Integer)context.getProperty(WIDTH) / 1000f;
final float height = (Integer)context.getProperty(HEIGHT) / 1000f;
final float x = (Integer)context.getProperty(XPOS) / 1000f;
final float y = (Integer)context.getProperty(YPOS) / 1000f;
if (DEBUG) {
System.out.println(" --> EPS");
}
PSImageUtils.renderEPS(new java.io.ByteArrayInputStream(baout.toByteArray()),
"Barcode:" + msg,
new Rectangle2D.Float(x, y, width, height),
new Rectangle2D.Float(0, 0, bw, bh),
gen);
}
private boolean renderUsingGraphics2D(RendererContext context,
final BarcodeGenerator bargen,
final String msg, final Orientation orientation) throws IOException {
final Graphics2DAdapter g2dAdapter = context.getRenderer().getGraphics2DAdapter();
if (g2dAdapter == null) {
//We can't paint the barcode
return false;
} else {
final BarcodeDimension barDim = bargen.calcDimensions(msg);
// get the 'width' and 'height' attributes of the barcode
final int w = (int)Math.ceil(UnitConv.mm2pt(barDim.getWidthPlusQuiet())) * 1000;
final int h = (int)Math.ceil(UnitConv.mm2pt(barDim.getHeightPlusQuiet())) * 1000;
final Graphics2DImagePainter painter = new Graphics2DImagePainter() {
@Override
public void paint(Graphics2D g2d, Rectangle2D area) {
Java2DCanvasProvider canvas = new Java2DCanvasProvider(null, orientation);
canvas.setGraphics2D(g2d);
g2d.scale(area.getWidth() / barDim.getWidthPlusQuiet(),
area.getHeight() / barDim.getHeightPlusQuiet());
bargen.generateBarcode(canvas, msg);
}
@Override
public Dimension getImageSize() {
return new Dimension(w, h);
}
};
if (DEBUG) {
System.out.println(" --> Java2D");
}
g2dAdapter.paintImage(painter,
context, (Integer) context.getProperty("xpos")
, (Integer) context.getProperty("ypos")
, (Integer) context.getProperty("width")
, (Integer) context.getProperty("height"));
return true;
}
}
private boolean renderUsingBitmap(RendererContext context,
final BarcodeGenerator bargen,
final String msg, final Orientation orientation) throws IOException {
final ImageAdapter imgAdapter = context.getRenderer().getImageAdapter();
if (imgAdapter == null) {
//We can't paint the barcode
return false;
} else {
final BitmapCanvasProvider canvas = new BitmapCanvasProvider(
300, BufferedImage.TYPE_BYTE_BINARY, false, orientation);
bargen.generateBarcode(canvas, msg);
if (DEBUG) {
System.out.println(" --> Bitmap");
}
imgAdapter.paintImage(canvas.getBufferedImage(),
context,
(Integer)context.getProperty("xpos"),
(Integer)context.getProperty("ypos"),
(Integer)context.getProperty("width"),
(Integer)context.getProperty("height"));
return true;
}
}
/**
* Converts the barcode XML to SVG.
* @param context the renderer context
* @param bargen the barcode generator
* @param msg the barcode message
* @throws BarcodeCanvasSetupException In case of an error while generating the barcode
*/
private void convertToSVG(RendererContext context,
BarcodeGenerator bargen, String msg, Orientation orientation)
throws BarcodeCanvasSetupException {
final DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
final SVGCanvasProvider canvas = new SVGCanvasProvider(impl, true, orientation);
bargen.generateBarcode(canvas, msg);
final Document svg = canvas.getDOM();
//Call the renderXML() method of the renderer to render the SVG
if (DEBUG) {
System.out.println(" --> SVG");
}
context.getRenderer().renderXML(context,
svg, SVGDOMImplementation.SVG_NAMESPACE_URI);
}
public String getMimeType() {
return XMLHandler.HANDLE_ALL;
}
@Override
public String getNamespace() {
return BarcodeElementMapping.NAMESPACE;
}
@Override
public boolean supportsRenderer(Renderer renderer) {
return renderer.getGraphics2DAdapter() != null;
}
}
| |
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* 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.
*/
package javassist.expr;
import javassist.*;
import javassist.bytecode.*;
import javassist.compiler.*;
/**
* Method invocation (caller-side expression).
*/
public class MethodCall extends Expr {
/**
* Undocumented constructor. Do not use; internal-use only.
*/
protected MethodCall(int pos, CodeIterator i, CtClass declaring,
MethodInfo m) {
super(pos, i, declaring, m);
}
private int getNameAndType(ConstPool cp) {
int pos = currentPos;
int c = iterator.byteAt(pos);
int index = iterator.u16bitAt(pos + 1);
if (c == INVOKEINTERFACE)
return cp.getInterfaceMethodrefNameAndType(index);
else
return cp.getMethodrefNameAndType(index);
}
/**
* Returns the method or constructor containing the method-call
* expression represented by this object.
*/
public CtBehavior where() { return super.where(); }
/**
* Returns the line number of the source line containing the
* method call.
*
* @return -1 if this information is not available.
*/
public int getLineNumber() {
return super.getLineNumber();
}
/**
* Returns the source file containing the method call.
*
* @return null if this information is not available.
*/
public String getFileName() {
return super.getFileName();
}
/**
* Returns the class of the target object,
* which the method is called on.
*/
protected CtClass getCtClass() throws NotFoundException {
return thisClass.getClassPool().get(getClassName());
}
/**
* Returns the class name of the target object,
* which the method is called on.
*/
public String getClassName() {
String cname;
ConstPool cp = getConstPool();
int pos = currentPos;
int c = iterator.byteAt(pos);
int index = iterator.u16bitAt(pos + 1);
if (c == INVOKEINTERFACE)
cname = cp.getInterfaceMethodrefClassName(index);
else
cname = cp.getMethodrefClassName(index);
if (cname.charAt(0) == '[')
cname = Descriptor.toClassName(cname);
return cname;
}
/**
* Returns the name of the called method.
*/
public String getMethodName() {
ConstPool cp = getConstPool();
int nt = getNameAndType(cp);
return cp.getUtf8Info(cp.getNameAndTypeName(nt));
}
/**
* Returns the called method.
*/
public CtMethod getMethod() throws NotFoundException {
return getCtClass().getMethod(getMethodName(), getSignature());
}
/**
* Returns the method signature (the parameter types
* and the return type).
* The method signature is represented by a character string
* called method descriptor, which is defined in the JVM specification.
*
* @see javassist.CtBehavior#getSignature()
* @see javassist.bytecode.Descriptor
* @since 3.1
*/
public String getSignature() {
ConstPool cp = getConstPool();
int nt = getNameAndType(cp);
return cp.getUtf8Info(cp.getNameAndTypeDescriptor(nt));
}
/**
* Returns the list of exceptions that the expression may throw.
* This list includes both the exceptions that the try-catch statements
* including the expression can catch and the exceptions that
* the throws declaration allows the method to throw.
*/
public CtClass[] mayThrow() {
return super.mayThrow();
}
/**
* Returns true if the called method is of a superclass of the current
* class.
*/
public boolean isSuper() {
return iterator.byteAt(currentPos) == INVOKESPECIAL
&& !where().getDeclaringClass().getName().equals(getClassName());
}
/*
* Returns the parameter types of the called method.
public CtClass[] getParameterTypes() throws NotFoundException {
return Descriptor.getParameterTypes(getMethodDesc(),
thisClass.getClassPool());
}
*/
/*
* Returns the return type of the called method.
public CtClass getReturnType() throws NotFoundException {
return Descriptor.getReturnType(getMethodDesc(),
thisClass.getClassPool());
}
*/
/**
* Replaces the method call with the bytecode derived from
* the given source text.
*
* <p>$0 is available even if the called method is static.
*
* @param statement a Java statement except try-catch.
*/
public void replace(String statement) throws CannotCompileException {
thisClass.getClassFile(); // to call checkModify().
ConstPool constPool = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
String classname, methodname, signature;
int opcodeSize;
int c = iterator.byteAt(pos);
if (c == INVOKEINTERFACE) {
opcodeSize = 5;
classname = constPool.getInterfaceMethodrefClassName(index);
methodname = constPool.getInterfaceMethodrefName(index);
signature = constPool.getInterfaceMethodrefType(index);
}
else if (c == INVOKESTATIC
|| c == INVOKESPECIAL || c == INVOKEVIRTUAL) {
opcodeSize = 3;
classname = constPool.getMethodrefClassName(index);
methodname = constPool.getMethodrefName(index);
signature = constPool.getMethodrefType(index);
}
else
throw new CannotCompileException("not method invocation");
Javac jc = new Javac(thisClass);
ClassPool cp = thisClass.getClassPool();
CodeAttribute ca = iterator.get();
try {
CtClass[] params = Descriptor.getParameterTypes(signature, cp);
CtClass retType = Descriptor.getReturnType(signature, cp);
int paramVar = ca.getMaxLocals();
jc.recordParams(classname, params,
true, paramVar, withinStatic());
int retVar = jc.recordReturnType(retType, true);
if (c == INVOKESTATIC)
jc.recordStaticProceed(classname, methodname);
else if (c == INVOKESPECIAL)
jc.recordSpecialProceed(Javac.param0Name, classname,
methodname, signature);
else
jc.recordProceed(Javac.param0Name, methodname);
/* Is $_ included in the source code?
*/
checkResultValue(retType, statement);
Bytecode bytecode = jc.getBytecode();
storeStack(params, c == INVOKESTATIC, paramVar, bytecode);
jc.recordLocalVariables(ca, pos);
if (retType != CtClass.voidType) {
bytecode.addConstZero(retType);
bytecode.addStore(retVar, retType); // initialize $_
}
jc.compileStmnt(statement);
if (retType != CtClass.voidType)
bytecode.addLoad(retVar, retType);
replace0(pos, bytecode, opcodeSize);
}
catch (CompileError e) { throw new CannotCompileException(e); }
catch (NotFoundException e) { throw new CannotCompileException(e); }
catch (BadBytecode e) {
throw new CannotCompileException("broken method");
}
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.protocol.saml;
import org.keycloak.Config;
import org.keycloak.dom.saml.v2.metadata.EndpointType;
import org.keycloak.dom.saml.v2.metadata.EntitiesDescriptorType;
import org.keycloak.dom.saml.v2.metadata.EntityDescriptorType;
import org.keycloak.dom.saml.v2.metadata.KeyDescriptorType;
import org.keycloak.dom.saml.v2.metadata.KeyTypes;
import org.keycloak.dom.saml.v2.metadata.SPSSODescriptorType;
import org.keycloak.exportimport.ClientDescriptionConverter;
import org.keycloak.exportimport.ClientDescriptionConverterFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.saml.SignatureAlgorithm;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.exceptions.ParsingException;
import org.keycloak.saml.common.exceptions.ProcessingException;
import org.keycloak.saml.processing.core.parsers.saml.SAMLParser;
import org.keycloak.saml.processing.core.saml.v2.util.SAMLMetadataUtil;
import org.keycloak.saml.processing.core.util.CoreConfigUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class EntityDescriptorDescriptionConverter implements ClientDescriptionConverter, ClientDescriptionConverterFactory {
public static final String ID = "saml2-entity-descriptor";
@Override
public boolean isSupported(String description) {
description = description.trim();
return (description.startsWith("<") && description.endsWith(">") && description.contains("EntityDescriptor"));
}
@Override
public ClientRepresentation convertToInternal(String description) {
return loadEntityDescriptors(new ByteArrayInputStream(description.getBytes()));
}
private static ClientRepresentation loadEntityDescriptors(InputStream is) {
Object metadata;
try {
metadata = new SAMLParser().parse(is);
} catch (ParsingException e) {
throw new RuntimeException(e);
}
EntitiesDescriptorType entities;
if (EntitiesDescriptorType.class.isInstance(metadata)) {
entities = (EntitiesDescriptorType) metadata;
} else {
entities = new EntitiesDescriptorType();
entities.addEntityDescriptor(metadata);
}
if (entities.getEntityDescriptor().size() != 1) {
throw new RuntimeException("Expected one entity descriptor");
}
EntityDescriptorType entity = (EntityDescriptorType) entities.getEntityDescriptor().get(0);
String entityId = entity.getEntityID();
ClientRepresentation app = new ClientRepresentation();
app.setClientId(entityId);
Map<String, String> attributes = new HashMap<>();
app.setAttributes(attributes);
List<String> redirectUris = new LinkedList<>();
app.setRedirectUris(redirectUris);
app.setFullScopeAllowed(true);
app.setProtocol(SamlProtocol.LOGIN_PROTOCOL);
attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE, SamlProtocol.ATTRIBUTE_TRUE_VALUE); // default to true
attributes.put(SamlConfigAttributes.SAML_SERVER_SIGNATURE_KEYINFO_EXT, SamlProtocol.ATTRIBUTE_FALSE_VALUE); // default to false
attributes.put(SamlConfigAttributes.SAML_SIGNATURE_ALGORITHM, SignatureAlgorithm.RSA_SHA256.toString());
attributes.put(SamlConfigAttributes.SAML_AUTHNSTATEMENT, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
SPSSODescriptorType spDescriptorType = CoreConfigUtil.getSPDescriptor(entity);
if (spDescriptorType.isWantAssertionsSigned()) {
attributes.put(SamlConfigAttributes.SAML_ASSERTION_SIGNATURE, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
}
String logoutPost = getLogoutLocation(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
if (logoutPost != null) attributes.put(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, logoutPost);
String logoutRedirect = getLogoutLocation(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get());
if (logoutRedirect != null) attributes.put(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, logoutRedirect);
String assertionConsumerServicePostBinding = CoreConfigUtil.getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
if (assertionConsumerServicePostBinding != null) {
attributes.put(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, assertionConsumerServicePostBinding);
redirectUris.add(assertionConsumerServicePostBinding);
}
String assertionConsumerServiceRedirectBinding = CoreConfigUtil.getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get());
if (assertionConsumerServiceRedirectBinding != null) {
attributes.put(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_REDIRECT_ATTRIBUTE, assertionConsumerServiceRedirectBinding);
redirectUris.add(assertionConsumerServiceRedirectBinding);
}
String assertionConsumerServiceSoapBinding = CoreConfigUtil.getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_SOAP_BINDING.get());
if (assertionConsumerServiceSoapBinding != null) {
redirectUris.add(assertionConsumerServiceSoapBinding);
}
String assertionConsumerServicePaosBinding = CoreConfigUtil.getServiceURL(spDescriptorType, JBossSAMLURIConstants.SAML_PAOS_BINDING.get());
if (assertionConsumerServicePaosBinding != null) {
redirectUris.add(assertionConsumerServicePaosBinding);
}
if (spDescriptorType.getNameIDFormat() != null) {
for (String format : spDescriptorType.getNameIDFormat()) {
String attribute = SamlClient.samlNameIDFormatToClientAttribute(format);
if (attribute != null) {
attributes.put(SamlConfigAttributes.SAML_NAME_ID_FORMAT_ATTRIBUTE, attribute);
break;
}
}
}
for (KeyDescriptorType keyDescriptor : spDescriptorType.getKeyDescriptor()) {
X509Certificate cert = null;
try {
cert = SAMLMetadataUtil.getCertificate(keyDescriptor);
} catch (ConfigurationException e) {
throw new RuntimeException(e);
} catch (ProcessingException e) {
throw new RuntimeException(e);
}
String certPem = KeycloakModelUtils.getPemFromCertificate(cert);
if (keyDescriptor.getUse() == KeyTypes.SIGNING) {
attributes.put(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
attributes.put(SamlConfigAttributes.SAML_SIGNING_CERTIFICATE_ATTRIBUTE, certPem);
} else if (keyDescriptor.getUse() == KeyTypes.ENCRYPTION) {
attributes.put(SamlConfigAttributes.SAML_ENCRYPT, SamlProtocol.ATTRIBUTE_TRUE_VALUE);
attributes.put(SamlConfigAttributes.SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE, certPem);
}
}
return app;
}
private static String getLogoutLocation(SPSSODescriptorType idp, String bindingURI) {
String logoutResponseLocation = null;
List<EndpointType> endpoints = idp.getSingleLogoutService();
for (EndpointType endpoint : endpoints) {
if (endpoint.getBinding().toString().equals(bindingURI)) {
if (endpoint.getLocation() != null) {
logoutResponseLocation = endpoint.getLocation().toString();
} else {
logoutResponseLocation = null;
}
break;
}
}
return logoutResponseLocation;
}
@Override
public ClientDescriptionConverter create(KeycloakSession session) {
return this;
}
@Override
public void init(Config.Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public void close() {
}
@Override
public String getId() {
return ID;
}
}
| |
/*******************************************************************************
* Copyright 2021 Tremolo Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.tremolosecurity.proxy.dynamicconfiguration;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.config.xml.AuthChainType;
import com.tremolosecurity.config.xml.ConfigType;
import com.tremolosecurity.config.xml.CustomAzRuleType;
import com.tremolosecurity.config.xml.MechanismType;
import com.tremolosecurity.config.xml.ParamListType;
import com.tremolosecurity.config.xml.ParamType;
import com.tremolosecurity.config.xml.ResultGroupType;
import com.tremolosecurity.config.xml.ResultType;
import com.tremolosecurity.config.xml.TargetType;
import com.tremolosecurity.config.xml.TremoloType;
import com.tremolosecurity.k8s.watch.K8sWatchTarget;
import com.tremolosecurity.k8s.watch.K8sWatcher;
import com.tremolosecurity.openunison.util.config.OpenUnisonConfigLoader;
import com.tremolosecurity.provisioning.core.ProvisioningEngine;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.proxy.dynamicloaders.DynamicAuthMechs;
import com.tremolosecurity.proxy.dynamicloaders.DynamicAuthorizations;
import com.tremolosecurity.proxy.dynamicloaders.DynamicResultGroups;
import com.tremolosecurity.provisioning.targets.LoadTargetsFromK8s;
import com.tremolosecurity.provisioning.util.HttpCon;
import com.tremolosecurity.saml.Attribute;
import com.tremolosecurity.server.GlobalEntries;
public class LoadAuthMechsFromK8s implements DynamicAuthMechs, K8sWatchTarget {
static org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(LoadAuthMechsFromK8s.class.getName());
K8sWatcher k8sWatch;
TremoloType tremolo;
private ProvisioningEngine provisioningEngine;
private ConfigManager cfgMgr;
private MechanismType createAuthMech (JSONObject item, String name) throws Exception {
MechanismType mechType = new MechanismType();
JSONObject spec = (JSONObject) item.get("spec");
mechType.setName(name);
mechType.setClassName((String) spec.get("className"));
mechType.setUri((String) spec.get("uri"));
mechType.setInit(new ConfigType());
mechType.setParams(new ParamListType());
JSONObject params = (JSONObject) spec.get("init");
for (Object o : params.keySet()) {
String keyName = (String) o;
Object v = params.get(keyName);
if (v instanceof String) {
String val = (String) v;
ParamType pt = new ParamType();
pt.setName(keyName);
pt.setValue(val);
mechType.getInit().getParam().add(pt);
} else if (v instanceof JSONArray) {
for (Object ov : ((JSONArray) v)) {
ParamType pt = new ParamType();
pt.setName(keyName);
pt.setValue((String) ov);
mechType.getInit().getParam().add(pt);
}
}
}
JSONArray secretParams = (JSONArray) spec.get("secretParams");
if (secretParams != null) {
HttpCon nonwatchHttp = this.k8sWatch.getK8s().createClient();
String token = this.k8sWatch.getK8s().getAuthToken();
try {
for (Object o : secretParams) {
JSONObject secretParam = (JSONObject) o;
String paramName = (String) secretParam.get("name");
String secretName = (String) secretParam.get("secretName");
String secretKey = (String) secretParam.get("secretKey");
String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue(secretValue);
mechType.getInit().getParam().add(pt);
}
} finally {
nonwatchHttp.getHttp().close();
nonwatchHttp.getBcm().close();
}
}
return mechType;
}
@Override
public void loadDynamicAuthMechs(ConfigManager cfgMgr, ProvisioningEngine provisioningEngine,
Map<String, Attribute> init) throws ProvisioningException {
this.tremolo = cfgMgr.getCfg();
String k8sTarget = init.get("k8starget").getValues().get(0);
String namespace = init.get("namespace").getValues().get(0);
String uri = "/apis/openunison.tremolo.io/v1/namespaces/" + namespace + "/authmechs";
this.provisioningEngine = provisioningEngine;
this.cfgMgr = cfgMgr;
this.k8sWatch = new K8sWatcher(k8sTarget,namespace,uri,this,cfgMgr,provisioningEngine);
this.k8sWatch.initalRun();
}
@Override
public void addObject(TremoloType cfg, JSONObject item) throws ProvisioningException {
String rawJson = item.toJSONString();
StringBuffer b = new StringBuffer();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b,rawJson);
try {
JSONObject newRoot = (JSONObject) new JSONParser().parse(b.toString());
JSONObject metadata = (JSONObject) newRoot.get("metadata");
if (metadata == null) {
throw new ProvisioningException("No metadata");
}
String name = (String) metadata.get("name");
logger.info("Adding authentication mechanism " + name);
try {
MechanismType mt = this.createAuthMech(item, name);
GlobalEntries.getGlobalEntries().getConfigManager().addAuthenticationMechanism(mt);
synchronized (GlobalEntries.getGlobalEntries().getConfigManager().getCfg()) {
MechanismType curMech = null;
for (MechanismType itMech : GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism()) {
if (itMech.getName().equals(mt.getName())) {
curMech = itMech;
break;
}
}
if (curMech != null) {
GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism().remove(curMech);
}
GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism().add(mt);
}
} catch (Exception e) {
logger.warn("Could not initialize authentication mechanism " + name,e);
return;
}
} catch (ParseException e) {
throw new ProvisioningException("Could not parse custom authorization",e);
}
}
@Override
public void modifyObject(TremoloType cfg, JSONObject item) throws ProvisioningException {
String rawJson = item.toJSONString();
StringBuffer b = new StringBuffer();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b,rawJson);
try {
JSONObject newRoot = (JSONObject) new JSONParser().parse(b.toString());
JSONObject metadata = (JSONObject) newRoot.get("metadata");
if (metadata == null) {
throw new ProvisioningException("No metadata");
}
String name = (String) metadata.get("name");
logger.info("Modifying authentication mechanism " + name);
try {
MechanismType mt = this.createAuthMech(item, name);
GlobalEntries.getGlobalEntries().getConfigManager().addAuthenticationMechanism(mt);
synchronized (GlobalEntries.getGlobalEntries().getConfigManager().getCfg()) {
MechanismType curMech = null;
for (MechanismType itMech : GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism()) {
if (itMech.getName().equals(mt.getName())) {
curMech = itMech;
break;
}
}
if (curMech != null) {
GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism().remove(curMech);
}
GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getAuthMechs().getMechanism().add(mt);
}
} catch (Exception e) {
logger.warn("Could not initialize authentication mechanism " + name,e);
return;
}
} catch (ParseException e) {
throw new ProvisioningException("Could not parse custom authorization",e);
}
}
@Override
public void deleteObject(TremoloType cfg, JSONObject item) throws ProvisioningException {
JSONObject metadata = (JSONObject) item.get("metadata");
if (metadata == null) {
throw new ProvisioningException("No metadata");
}
String name = (String) metadata.get("name");
logger.info("Deleting authentication mechanism" + name);
GlobalEntries.getGlobalEntries().getConfigManager().removeAuthenticationMechanism(name);
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.indexer.updater;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import com.metamx.common.FileUtils;
import com.metamx.common.Granularity;
import io.druid.client.DruidDataSource;
import io.druid.data.input.impl.DelimitedParseSpec;
import io.druid.data.input.impl.DimensionsSpec;
import io.druid.data.input.impl.StringInputRowParser;
import io.druid.data.input.impl.TimestampSpec;
import io.druid.granularity.QueryGranularity;
import io.druid.indexer.HadoopDruidDetermineConfigurationJob;
import io.druid.indexer.HadoopDruidIndexerConfig;
import io.druid.indexer.HadoopDruidIndexerJob;
import io.druid.indexer.HadoopIOConfig;
import io.druid.indexer.HadoopIngestionSpec;
import io.druid.indexer.HadoopTuningConfig;
import io.druid.indexer.JobHelper;
import io.druid.indexer.Jobby;
import io.druid.indexer.SQLMetadataStorageUpdaterJobHandler;
import io.druid.metadata.MetadataSegmentManagerConfig;
import io.druid.metadata.MetadataStorageConnectorConfig;
import io.druid.metadata.MetadataStorageTablesConfig;
import io.druid.metadata.SQLMetadataSegmentManager;
import io.druid.metadata.TestDerbyConnector;
import io.druid.metadata.storage.derby.DerbyConnector;
import io.druid.query.Query;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.DoubleSumAggregatorFactory;
import io.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory;
import io.druid.segment.IndexSpec;
import io.druid.segment.TestIndex;
import io.druid.segment.data.RoaringBitmapSerdeFactory;
import io.druid.segment.indexing.DataSchema;
import io.druid.segment.indexing.granularity.UniformGranularitySpec;
import io.druid.timeline.DataSegment;
import org.joda.time.Interval;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.exceptions.CallbackFailedException;
import org.skife.jdbi.v2.tweak.HandleCallback;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class HadoopConverterJobTest
{
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule();
private String storageLocProperty = null;
private File tmpSegmentDir = null;
private static final String DATASOURCE = "testDatasource";
private static final String STORAGE_PROPERTY_KEY = "druid.storage.storageDirectory";
private Supplier<MetadataStorageTablesConfig> metadataStorageTablesConfigSupplier;
private DerbyConnector connector;
private final Interval interval = Interval.parse("2011-01-01T00:00:00.000Z/2011-05-01T00:00:00.000Z");
@After
public void tearDown()
{
if (storageLocProperty == null) {
System.clearProperty(STORAGE_PROPERTY_KEY);
} else {
System.setProperty(STORAGE_PROPERTY_KEY, storageLocProperty);
}
tmpSegmentDir = null;
}
@Before
public void setUp() throws Exception
{
final MetadataStorageUpdaterJobSpec metadataStorageUpdaterJobSpec = new MetadataStorageUpdaterJobSpec()
{
@Override
public String getSegmentTable()
{
return derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable();
}
@Override
public MetadataStorageConnectorConfig get()
{
return derbyConnectorRule.getMetadataConnectorConfig();
}
};
final File scratchFileDir = temporaryFolder.newFolder();
storageLocProperty = System.getProperty(STORAGE_PROPERTY_KEY);
tmpSegmentDir = temporaryFolder.newFolder();
System.setProperty(STORAGE_PROPERTY_KEY, tmpSegmentDir.getAbsolutePath());
final URL url = Preconditions.checkNotNull(Query.class.getClassLoader().getResource("druid.sample.tsv"));
final File tmpInputFile = temporaryFolder.newFile();
FileUtils.retryCopy(
new ByteSource()
{
@Override
public InputStream openStream() throws IOException
{
return url.openStream();
}
},
tmpInputFile,
FileUtils.IS_EXCEPTION,
3
);
final HadoopDruidIndexerConfig hadoopDruidIndexerConfig = new HadoopDruidIndexerConfig(
new HadoopIngestionSpec(
new DataSchema(
DATASOURCE,
new StringInputRowParser(
new DelimitedParseSpec(
new TimestampSpec("ts", "iso", null),
new DimensionsSpec(Arrays.asList(TestIndex.DIMENSIONS), null, null),
"\t",
"\u0001",
Arrays.asList(TestIndex.COLUMNS)
)
),
new AggregatorFactory[]{
new DoubleSumAggregatorFactory(TestIndex.METRICS[0], TestIndex.METRICS[0]),
new HyperUniquesAggregatorFactory("quality_uniques", "quality")
},
new UniformGranularitySpec(
Granularity.MONTH,
QueryGranularity.DAY,
ImmutableList.<Interval>of(interval)
)
),
new HadoopIOConfig(
ImmutableMap.<String, Object>of(
"type", "static",
"paths", tmpInputFile.getAbsolutePath()
),
metadataStorageUpdaterJobSpec,
tmpSegmentDir.getAbsolutePath()
),
new HadoopTuningConfig(
scratchFileDir.getAbsolutePath(),
null,
null,
null,
null,
null,
false,
false,
false,
false,
null,
false,
false,
false,
null,
null,
false
)
)
);
metadataStorageTablesConfigSupplier = derbyConnectorRule.metadataTablesConfigSupplier();
connector = derbyConnectorRule.getConnector();
try {
connector.getDBI().withHandle(
new HandleCallback<Void>()
{
@Override
public Void withHandle(Handle handle) throws Exception
{
handle.execute("DROP TABLE druid_segments");
return null;
}
}
);
}
catch (CallbackFailedException e) {
// Who cares
}
List<Jobby> jobs = ImmutableList.of(
new Jobby()
{
@Override
public boolean run()
{
connector.createSegmentTable(connector.getDBI(), metadataStorageUpdaterJobSpec.getSegmentTable());
return true;
}
},
new HadoopDruidDetermineConfigurationJob(hadoopDruidIndexerConfig),
new HadoopDruidIndexerJob(
hadoopDruidIndexerConfig,
new SQLMetadataStorageUpdaterJobHandler(connector)
)
);
JobHelper.runJobs(jobs, hadoopDruidIndexerConfig);
}
private List<DataSegment> getDataSegments(
SQLMetadataSegmentManager manager
) throws InterruptedException
{
manager.start();
while (!manager.isStarted()) {
Thread.sleep(10);
}
manager.poll();
final DruidDataSource druidDataSource = manager.getInventoryValue(DATASOURCE);
manager.stop();
return Lists.newArrayList(druidDataSource.getSegments());
}
@Test
public void testSimpleJob() throws IOException, InterruptedException
{
final SQLMetadataSegmentManager manager = new SQLMetadataSegmentManager(
HadoopDruidConverterConfig.jsonMapper,
new Supplier<MetadataSegmentManagerConfig>()
{
@Override
public MetadataSegmentManagerConfig get()
{
return new MetadataSegmentManagerConfig();
}
},
metadataStorageTablesConfigSupplier,
connector
);
final List<DataSegment> oldSemgments = getDataSegments(manager);
final File tmpDir = temporaryFolder.newFolder();
final HadoopConverterJob converterJob = new HadoopConverterJob(
new HadoopDruidConverterConfig(
DATASOURCE,
interval,
new IndexSpec(new RoaringBitmapSerdeFactory(), "uncompressed", "uncompressed"),
oldSemgments,
true,
tmpDir.toURI(),
ImmutableMap.<String, String>of(),
null,
tmpSegmentDir.toURI().toString()
)
);
final List<DataSegment> segments = Lists.newArrayList(converterJob.run());
Assert.assertNotNull("bad result", segments);
Assert.assertEquals("wrong segment count", 4, segments.size());
Assert.assertTrue(converterJob.getLoadedBytes() > 0);
Assert.assertTrue(converterJob.getWrittenBytes() > 0);
Assert.assertTrue(converterJob.getWrittenBytes() > converterJob.getLoadedBytes());
Assert.assertEquals(oldSemgments.size(), segments.size());
final DataSegment segment = segments.get(0);
Assert.assertTrue(interval.contains(segment.getInterval()));
Assert.assertTrue(segment.getVersion().endsWith("_converted"));
Assert.assertTrue(segment.getLoadSpec().get("path").toString().contains("_converted"));
for (File file : tmpDir.listFiles()) {
Assert.assertFalse(file.isDirectory());
Assert.assertTrue(file.isFile());
}
final Comparator<DataSegment> segmentComparator = new Comparator<DataSegment>()
{
@Override
public int compare(DataSegment o1, DataSegment o2)
{
return o1.getIdentifier().compareTo(o2.getIdentifier());
}
};
Collections.sort(
oldSemgments,
segmentComparator
);
Collections.sort(
segments,
segmentComparator
);
for (int i = 0; i < oldSemgments.size(); ++i) {
final DataSegment oldSegment = oldSemgments.get(i);
final DataSegment newSegment = segments.get(i);
Assert.assertEquals(oldSegment.getDataSource(), newSegment.getDataSource());
Assert.assertEquals(oldSegment.getInterval(), newSegment.getInterval());
Assert.assertEquals(
Sets.<String>newHashSet(oldSegment.getMetrics()),
Sets.<String>newHashSet(newSegment.getMetrics())
);
Assert.assertEquals(
Sets.<String>newHashSet(oldSegment.getDimensions()),
Sets.<String>newHashSet(newSegment.getDimensions())
);
Assert.assertEquals(oldSegment.getVersion() + "_converted", newSegment.getVersion());
Assert.assertTrue(oldSegment.getSize() < newSegment.getSize());
Assert.assertEquals(oldSegment.getBinaryVersion(), newSegment.getBinaryVersion());
}
}
private static void corrupt(
DataSegment segment
) throws IOException
{
final Map<String, Object> localLoadSpec = segment.getLoadSpec();
final Path segmentPath = Paths.get(localLoadSpec.get("path").toString());
final MappedByteBuffer buffer = Files.map(segmentPath.toFile(), FileChannel.MapMode.READ_WRITE);
while (buffer.hasRemaining()) {
buffer.put((byte) 0xFF);
}
}
@Test
@Ignore // This takes a long time due to retries
public void testHadoopFailure() throws IOException, InterruptedException
{
final SQLMetadataSegmentManager manager = new SQLMetadataSegmentManager(
HadoopDruidConverterConfig.jsonMapper,
new Supplier<MetadataSegmentManagerConfig>()
{
@Override
public MetadataSegmentManagerConfig get()
{
return new MetadataSegmentManagerConfig();
}
},
metadataStorageTablesConfigSupplier,
connector
);
final List<DataSegment> oldSemgments = getDataSegments(manager);
final File tmpDir = temporaryFolder.newFolder();
final HadoopConverterJob converterJob = new HadoopConverterJob(
new HadoopDruidConverterConfig(
DATASOURCE,
interval,
new IndexSpec(new RoaringBitmapSerdeFactory(), "uncompressed", "uncompressed"),
oldSemgments,
true,
tmpDir.toURI(),
ImmutableMap.<String, String>of(),
null,
tmpSegmentDir.toURI().toString()
)
);
corrupt(oldSemgments.get(0));
final List<DataSegment> result = converterJob.run();
Assert.assertNull("result should be null", result);
final List<DataSegment> segments = getDataSegments(manager);
Assert.assertEquals(oldSemgments.size(), segments.size());
Assert.assertEquals(oldSemgments, segments);
}
}
| |
/*
* 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.activemq.artemis.core.server.cluster;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal;
import org.apache.activemq.artemis.core.client.impl.Topology;
import org.apache.activemq.artemis.core.config.ClusterConnectionConfiguration;
import org.apache.activemq.artemis.core.protocol.core.Channel;
import org.apache.activemq.artemis.core.protocol.core.ChannelHandler;
import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterConnectMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterConnectReplyMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.NodeAnnounceMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.QuorumVoteMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.QuorumVoteReplyMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ScaleDownAnnounceMessage;
import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumManager;
import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteHandler;
import org.apache.activemq.artemis.core.server.cluster.qourum.Vote;
import org.apache.activemq.artemis.core.server.impl.Activation;
import org.apache.activemq.artemis.spi.core.remoting.Acceptor;
import org.jboss.logging.Logger;
/**
* used for creating and managing cluster control connections for each cluster connection and the replication connection
*/
public class ClusterController implements ActiveMQComponent {
private static final Logger logger = Logger.getLogger(ClusterController.class);
private final QuorumManager quorumManager;
private final ActiveMQServer server;
private final Map<SimpleString, ServerLocatorInternal> locators = new HashMap<>();
private SimpleString defaultClusterConnectionName;
private ServerLocator defaultLocator;
private ServerLocator replicationLocator;
private final Executor executor;
private CountDownLatch replicationClusterConnectedLatch;
private boolean started;
private SimpleString replicatedClusterName;
public ClusterController(ActiveMQServer server, ScheduledExecutorService scheduledExecutor) {
this.server = server;
executor = server.getExecutorFactory().getExecutor();
quorumManager = new QuorumManager(scheduledExecutor, this);
}
@Override
public void start() throws Exception {
if (started)
return;
//set the default locator that will be used to connecting to the default cluster.
defaultLocator = locators.get(defaultClusterConnectionName);
//create a locator for replication, either the default or the specified if not set
if (replicatedClusterName != null && !replicatedClusterName.equals(defaultClusterConnectionName)) {
replicationLocator = locators.get(replicatedClusterName);
if (replicationLocator == null) {
ActiveMQServerLogger.LOGGER.noClusterConnectionForReplicationCluster();
replicationLocator = defaultLocator;
}
} else {
replicationLocator = defaultLocator;
}
//latch so we know once we are connected
replicationClusterConnectedLatch = new CountDownLatch(1);
//and add the quorum manager as a topology listener
if (defaultLocator != null) {
defaultLocator.addClusterTopologyListener(quorumManager);
}
if (quorumManager != null) {
//start the quorum manager
quorumManager.start();
}
started = true;
//connect all the locators in a separate thread
for (ServerLocatorInternal serverLocatorInternal : locators.values()) {
if (serverLocatorInternal.isConnectable()) {
executor.execute(new ConnectRunnable(serverLocatorInternal));
}
}
}
@Override
public void stop() throws Exception {
//close all the locators
for (ServerLocatorInternal serverLocatorInternal : locators.values()) {
serverLocatorInternal.close();
}
//stop the quorum manager
quorumManager.stop();
started = false;
}
@Override
public boolean isStarted() {
return started;
}
public QuorumManager getQuorumManager() {
return quorumManager;
}
//set the default cluster connections name
public void setDefaultClusterConnectionName(SimpleString defaultClusterConnection) {
this.defaultClusterConnectionName = defaultClusterConnection;
}
/**
* add a locator for a cluster connection.
*
* @param name the cluster connection name
* @param dg the discovery group to use
* @param config the cluster connection config
*/
public void addClusterConnection(SimpleString name,
DiscoveryGroupConfiguration dg,
ClusterConnectionConfiguration config) {
ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(dg);
configAndAdd(name, serverLocator, config);
}
/**
* add a locator for a cluster connection.
*
* @param name the cluster connection name
* @param tcConfigs the transport configurations to use
*/
public void addClusterConnection(SimpleString name,
TransportConfiguration[] tcConfigs,
ClusterConnectionConfiguration config) {
ServerLocatorImpl serverLocator = (ServerLocatorImpl) ActiveMQClient.createServerLocatorWithHA(tcConfigs);
configAndAdd(name, serverLocator, config);
}
private void configAndAdd(SimpleString name,
ServerLocatorInternal serverLocator,
ClusterConnectionConfiguration config) {
serverLocator.setConnectionTTL(config.getConnectionTTL());
serverLocator.setClientFailureCheckPeriod(config.getClientFailureCheckPeriod());
//if the cluster isn't available we want to hang around until it is
serverLocator.setReconnectAttempts(-1);
serverLocator.setInitialConnectAttempts(-1);
//this is used for replication so need to use the server packet decoder
serverLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(serverLocator));
locators.put(name, serverLocator);
}
/**
* add a cluster listener
*
* @param listener
*/
public void addClusterTopologyListenerForReplication(ClusterTopologyListener listener) {
replicationLocator.addClusterTopologyListener(listener);
}
/**
* add an interceptor
*
* @param interceptor
*/
public void addIncomingInterceptorForReplication(Interceptor interceptor) {
replicationLocator.addIncomingInterceptor(interceptor);
}
/**
* connect to a specific node in the cluster used for replication
*
* @param transportConfiguration the configuration of the node to connect to.
* @return the Cluster Control
* @throws Exception
*/
public ClusterControl connectToNode(TransportConfiguration transportConfiguration) throws Exception {
ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) defaultLocator.createSessionFactory(transportConfiguration, 0, false);
return connectToNodeInCluster(sessionFactory);
}
/**
* connect to a specific node in the cluster used for replication
*
* @param transportConfiguration the configuration of the node to connect to.
* @return the Cluster Control
* @throws Exception
*/
public ClusterControl connectToNodeInReplicatedCluster(TransportConfiguration transportConfiguration) throws Exception {
ClientSessionFactoryInternal sessionFactory = (ClientSessionFactoryInternal) replicationLocator.createSessionFactory(transportConfiguration, 0, false);
return connectToNodeInCluster(sessionFactory);
}
/**
* connect to an already defined node in the cluster
*
* @param sf the session factory
* @return the Cluster Control
*/
public ClusterControl connectToNodeInCluster(ClientSessionFactoryInternal sf) {
sf.getServerLocator().setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(sf.getServerLocator()));
return new ClusterControl(sf, server);
}
/**
* retry interval for connecting to the cluster
*
* @return the retry interval
*/
public long getRetryIntervalForReplicatedCluster() {
return replicationLocator.getRetryInterval();
}
/**
* wait until we have connected to the cluster.
*
* @throws InterruptedException
*/
public void awaitConnectionToReplicationCluster() throws InterruptedException {
replicationClusterConnectedLatch.await();
}
/**
* used to set a channel handler on the connection that can be used by the cluster control
*
* @param channel the channel to set the handler
* @param acceptorUsed the acceptor used for connection
* @param remotingConnection the connection itself
* @param activation
*/
public void addClusterChannelHandler(Channel channel,
Acceptor acceptorUsed,
CoreRemotingConnection remotingConnection,
Activation activation) {
channel.setHandler(new ClusterControllerChannelHandler(channel, acceptorUsed, remotingConnection, activation.getActivationChannelHandler(channel, acceptorUsed)));
}
public int getDefaultClusterSize() {
return defaultLocator.getTopology().getMembers().size();
}
public Topology getDefaultClusterTopology() {
return defaultLocator.getTopology();
}
public SimpleString getNodeID() {
return server.getNodeID();
}
public String getIdentity() {
return server.getIdentity();
}
public void setReplicatedClusterName(String replicatedClusterName) {
this.replicatedClusterName = new SimpleString(replicatedClusterName);
}
/**
* a handler for handling packets sent between the cluster.
*/
private final class ClusterControllerChannelHandler implements ChannelHandler {
private final Channel clusterChannel;
private final Acceptor acceptorUsed;
private final CoreRemotingConnection remotingConnection;
private final ChannelHandler channelHandler;
boolean authorized = false;
private ClusterControllerChannelHandler(Channel clusterChannel,
Acceptor acceptorUsed,
CoreRemotingConnection remotingConnection,
ChannelHandler channelHandler) {
this.clusterChannel = clusterChannel;
this.acceptorUsed = acceptorUsed;
this.remotingConnection = remotingConnection;
this.channelHandler = channelHandler;
}
@Override
public void handlePacket(Packet packet) {
if (!isStarted()) {
return;
}
if (!authorized) {
if (packet.getType() == PacketImpl.CLUSTER_CONNECT) {
ClusterConnection clusterConnection = acceptorUsed.getClusterConnection();
//if this acceptor isn't associated with a cluster connection use the default
if (clusterConnection == null) {
clusterConnection = server.getClusterManager().getDefaultConnection(null);
}
ClusterConnectMessage msg = (ClusterConnectMessage) packet;
if (server.getConfiguration().isSecurityEnabled() && !clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword())) {
clusterChannel.send(new ClusterConnectReplyMessage(false));
} else {
authorized = true;
clusterChannel.send(new ClusterConnectReplyMessage(true));
}
}
} else {
if (packet.getType() == PacketImpl.NODE_ANNOUNCE) {
NodeAnnounceMessage msg = (NodeAnnounceMessage) packet;
Pair<TransportConfiguration, TransportConfiguration> pair;
if (msg.isBackup()) {
pair = new Pair<>(null, msg.getConnector());
} else {
pair = new Pair<>(msg.getConnector(), msg.getBackupConnector());
}
if (logger.isTraceEnabled()) {
logger.trace("Server " + server + " receiving nodeUp from NodeID=" + msg.getNodeID() + ", pair=" + pair);
}
if (acceptorUsed != null) {
ClusterConnection clusterConn = acceptorUsed.getClusterConnection();
if (clusterConn != null) {
String scaleDownGroupName = msg.getScaleDownGroupName();
clusterConn.nodeAnnounced(msg.getCurrentEventID(), msg.getNodeID(), msg.getBackupGroupName(), scaleDownGroupName, pair, msg.isBackup());
} else {
logger.debug("Cluster connection is null on acceptor = " + acceptorUsed);
}
} else {
logger.debug("there is no acceptor used configured at the CoreProtocolManager " + this);
}
} else if (packet.getType() == PacketImpl.QUORUM_VOTE) {
QuorumVoteMessage quorumVoteMessage = (QuorumVoteMessage) packet;
QuorumVoteHandler voteHandler = quorumManager.getVoteHandler(quorumVoteMessage.getHandler());
quorumVoteMessage.decode(voteHandler);
Vote vote = quorumManager.vote(quorumVoteMessage.getHandler(), quorumVoteMessage.getVote());
clusterChannel.send(new QuorumVoteReplyMessage(quorumVoteMessage.getHandler(), vote));
} else if (packet.getType() == PacketImpl.SCALEDOWN_ANNOUNCEMENT) {
ScaleDownAnnounceMessage message = (ScaleDownAnnounceMessage) packet;
//we don't really need to check as it should always be true
if (server.getNodeID().equals(message.getTargetNodeId())) {
server.addScaledDownNode(message.getScaledDownNodeId());
}
} else if (channelHandler != null) {
channelHandler.handlePacket(packet);
}
}
}
}
/**
* used for making the initial connection in the cluster
*/
private final class ConnectRunnable implements Runnable {
private final ServerLocatorInternal serverLocator;
private ConnectRunnable(ServerLocatorInternal serverLocator) {
this.serverLocator = serverLocator;
}
@Override
public void run() {
try {
serverLocator.connect();
if (serverLocator == replicationLocator) {
replicationClusterConnectedLatch.countDown();
}
} catch (ActiveMQException e) {
if (!started) {
return;
}
server.getScheduledPool().schedule(this, serverLocator.getRetryInterval(), TimeUnit.MILLISECONDS);
}
}
}
public ServerLocator getReplicationLocator() {
return this.replicationLocator;
}
}
| |
/**
* Copyright (C) 2006-2009 Dustin Sallings
* Copyright (C) 2009-2011 Couchbase, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
* IN THE SOFTWARE.
*/
package net.spy.memcached;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import net.spy.memcached.ops.Operation;
class MemcachedNodeROImpl implements MemcachedNode {
private final MemcachedNode root;
public MemcachedNodeROImpl(MemcachedNode n) {
super();
root = n;
}
@Override
public String toString() {
return root.toString();
}
public void addOp(Operation op) {
throw new UnsupportedOperationException();
}
public void insertOp(Operation op) {
throw new UnsupportedOperationException();
}
public void connected() {
throw new UnsupportedOperationException();
}
public void copyInputQueue() {
throw new UnsupportedOperationException();
}
public void fillWriteBuffer(boolean optimizeGets) {
throw new UnsupportedOperationException();
}
public void fixupOps() {
throw new UnsupportedOperationException();
}
public int getBytesRemainingToWrite() {
return root.getBytesRemainingToWrite();
}
public SocketChannel getChannel() {
throw new UnsupportedOperationException();
}
public Operation getCurrentReadOp() {
throw new UnsupportedOperationException();
}
public Operation getCurrentWriteOp() {
throw new UnsupportedOperationException();
}
public ByteBuffer getRbuf() {
throw new UnsupportedOperationException();
}
public int getReconnectCount() {
return root.getReconnectCount();
}
public int getSelectionOps() {
return root.getSelectionOps();
}
public SelectionKey getSk() {
throw new UnsupportedOperationException();
}
public SocketAddress getSocketAddress() {
return root.getSocketAddress();
}
public ByteBuffer getWbuf() {
throw new UnsupportedOperationException();
}
public boolean hasReadOp() {
return root.hasReadOp();
}
public boolean hasWriteOp() {
return root.hasReadOp();
}
public boolean isActive() {
return root.isActive();
}
public void reconnecting() {
throw new UnsupportedOperationException();
}
public void registerChannel(SocketChannel ch, SelectionKey selectionKey) {
throw new UnsupportedOperationException();
}
public Operation removeCurrentReadOp() {
throw new UnsupportedOperationException();
}
public Operation removeCurrentWriteOp() {
throw new UnsupportedOperationException();
}
public void setChannel(SocketChannel to) {
throw new UnsupportedOperationException();
}
public void setSk(SelectionKey to) {
throw new UnsupportedOperationException();
}
public void setupResend() {
throw new UnsupportedOperationException();
}
public void transitionWriteItem() {
throw new UnsupportedOperationException();
}
public int writeSome() throws IOException {
throw new UnsupportedOperationException();
}
public Collection<Operation> destroyInputQueue() {
throw new UnsupportedOperationException();
}
public void authComplete() {
throw new UnsupportedOperationException();
}
public void setupForAuth() {
throw new UnsupportedOperationException();
}
public int getContinuousTimeout() {
throw new UnsupportedOperationException();
}
public void setContinuousTimeout(boolean isIncrease) {
throw new UnsupportedOperationException();
}
public boolean isAuthenticated() {
throw new UnsupportedOperationException();
}
public long lastReadDelta() {
throw new UnsupportedOperationException();
}
public void completedRead() {
throw new UnsupportedOperationException();
}
@Override
public MemcachedConnection getConnection() {
throw new UnsupportedOperationException();
}
@Override
public void setConnection(MemcachedConnection connection) {
throw new UnsupportedOperationException();
}
}
| |
package com.alibaba.jstorm.zk;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorEventType;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.UnhandledErrorListener;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ZooKeeperServer;
import backtype.storm.utils.Utils;
import com.alibaba.jstorm.callback.DefaultWatcherCallBack;
import com.alibaba.jstorm.callback.WatcherCallBack;
import com.alibaba.jstorm.utils.JStormUtils;
import com.alibaba.jstorm.utils.PathUtils;
/**
* ZK simple wrapper
*
* @author yannian
*
*/
public class Zookeeper {
private static Logger LOG = Logger.getLogger(Zookeeper.class);
public CuratorFramework mkClient(Map conf, List<String> servers,
Object port, String root) {
return mkClient(conf, servers, port, root, new DefaultWatcherCallBack());
}
/**
* connect ZK, register Watch/unhandle Watch
*
* @return
*/
public CuratorFramework mkClient(Map conf, List<String> servers,
Object port, String root, final WatcherCallBack watcher) {
CuratorFramework fk = Utils.newCurator(conf, servers, port, root);
fk.getCuratorListenable().addListener(new CuratorListener() {
@Override
public void eventReceived(CuratorFramework _fk, CuratorEvent e)
throws Exception {
if (e.getType().equals(CuratorEventType.WATCHED)) {
WatchedEvent event = e.getWatchedEvent();
watcher.execute(event.getState(), event.getType(),
event.getPath());
}
}
});
fk.getUnhandledErrorListenable().addListener(
new UnhandledErrorListener() {
@Override
public void unhandledError(String msg, Throwable error) {
String errmsg = "Unrecoverable Zookeeper error, halting process: "
+ msg;
LOG.error(errmsg, error);
JStormUtils.halt_process(1,
"Unrecoverable Zookeeper error");
}
});
fk.start();
return fk;
}
public String createNode(CuratorFramework zk, String path, byte[] data,
org.apache.zookeeper.CreateMode mode) throws Exception {
String npath = PathUtils.normalize_path(path);
return zk.create().withMode(mode).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath(npath, data);
}
public String createNode(CuratorFramework zk, String path, byte[] data)
throws Exception {
return createNode(zk, path, data,
org.apache.zookeeper.CreateMode.PERSISTENT);
}
public boolean existsNode(CuratorFramework zk, String path, boolean watch)
throws Exception {
Stat stat = null;
if (watch) {
stat = zk.checkExists().watched()
.forPath(PathUtils.normalize_path(path));
} else {
stat = zk.checkExists().forPath(PathUtils.normalize_path(path));
}
return stat != null;
}
public void deleteNode(CuratorFramework zk, String path) throws Exception {
zk.delete().forPath(PathUtils.normalize_path(path));
}
public void mkdirs(CuratorFramework zk, String path) throws Exception {
String npath = PathUtils.normalize_path(path);
// the node is "/"
if (npath.equals("/")) {
return;
}
// the node exist
if (existsNode(zk, npath, false)) {
return;
}
mkdirs(zk, PathUtils.parent_path(npath));
try {
createNode(zk, npath, JStormUtils.barr((byte) 7),
org.apache.zookeeper.CreateMode.PERSISTENT);
} catch (KeeperException e) {
;// this can happen when multiple clients doing mkdir at same
// time
LOG.warn("zookeeper mkdirs for path" + path, e);
}
}
public byte[] getData(CuratorFramework zk, String path, boolean watch)
throws Exception {
String npath = PathUtils.normalize_path(path);
try {
if (existsNode(zk, npath, watch)) {
if (watch) {
return zk.getData().watched().forPath(npath);
} else {
return zk.getData().forPath(npath);
}
}
} catch (KeeperException e) {
LOG.error("zookeeper getdata for path" + path, e);
}
return null;
}
public List<String> getChildren(CuratorFramework zk, String path,
boolean watch) throws Exception {
String npath = PathUtils.normalize_path(path);
if (watch) {
return zk.getChildren().watched().forPath(npath);
} else {
return zk.getChildren().forPath(npath);
}
}
public Stat setData(CuratorFramework zk, String path, byte[] data)
throws Exception {
String npath = PathUtils.normalize_path(path);
return zk.setData().forPath(npath, data);
}
public boolean exists(CuratorFramework zk, String path, boolean watch)
throws Exception {
return existsNode(zk, path, watch);
}
public void deletereRcursive(CuratorFramework zk, String path)
throws Exception {
String npath = PathUtils.normalize_path(path);
if (existsNode(zk, npath, false)) {
List<String> childs = getChildren(zk, npath, false);
for (String child : childs) {
String childFullPath = PathUtils.full_path(npath, child);
deletereRcursive(zk, childFullPath);
}
deleteNode(zk, npath);
}
}
public static Factory mkInprocessZookeeper(String localdir, int port)
throws IOException, InterruptedException {
LOG.info("Starting inprocess zookeeper at port " + port + " and dir "
+ localdir);
File localfile = new File(localdir);
ZooKeeperServer zk = new ZooKeeperServer(localfile, localfile, 2000);
Factory factory = new Factory(new InetSocketAddress(port), 0);
factory.startup(zk);
return factory;
}
public void shutdownInprocessZookeeper(Factory handle) {
handle.shutdown();
}
}
| |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.bridge;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.concurrent.CopyOnWriteArraySet;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.queue.MessageQueueThread;
import com.facebook.react.bridge.queue.ReactQueueConfiguration;
import com.facebook.react.common.LifecycleState;
/**
* Abstract ContextWrapper for Android application or activity {@link Context} and
* {@link CatalystInstance}
*/
public class ReactContext extends ContextWrapper {
private static final String EARLY_JS_ACCESS_EXCEPTION_MESSAGE =
"Tried to access a JS module before the React instance was fully set up. Calls to " +
"ReactContext#getJSModule should only happen once initialize() has been called on your " +
"native module.";
private final CopyOnWriteArraySet<LifecycleEventListener> mLifecycleEventListeners =
new CopyOnWriteArraySet<>();
private final CopyOnWriteArraySet<ActivityEventListener> mActivityEventListeners =
new CopyOnWriteArraySet<>();
private LifecycleState mLifecycleState = LifecycleState.BEFORE_CREATE;
private @Nullable CatalystInstance mCatalystInstance;
private @Nullable LayoutInflater mInflater;
private @Nullable MessageQueueThread mUiMessageQueueThread;
private @Nullable MessageQueueThread mNativeModulesMessageQueueThread;
private @Nullable MessageQueueThread mJSMessageQueueThread;
private @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler;
private @Nullable WeakReference<Activity> mCurrentActivity;
public ReactContext(Context base) {
super(base);
}
/**
* Set and initialize CatalystInstance for this Context. This should be called exactly once.
*/
public void initializeWithInstance(CatalystInstance catalystInstance) {
if (catalystInstance == null) {
throw new IllegalArgumentException("CatalystInstance cannot be null.");
}
if (mCatalystInstance != null) {
throw new IllegalStateException("ReactContext has been already initialized");
}
mCatalystInstance = catalystInstance;
ReactQueueConfiguration queueConfig = catalystInstance.getReactQueueConfiguration();
mUiMessageQueueThread = queueConfig.getUIQueueThread();
mNativeModulesMessageQueueThread = queueConfig.getNativeModulesQueueThread();
mJSMessageQueueThread = queueConfig.getJSQueueThread();
}
public void setNativeModuleCallExceptionHandler(
@Nullable NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler) {
mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
}
// We override the following method so that views inflated with the inflater obtained from this
// context return the ReactContext in #getContext(). The default implementation uses the base
// context instead, so it couldn't be cast to ReactContext.
// TODO: T7538796 Check requirement for Override of getSystemService ReactContext
@Override
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return mInflater;
}
return getBaseContext().getSystemService(name);
}
/**
* @return handle to the specified JS module for the CatalystInstance associated with this Context
*/
public <T extends JavaScriptModule> T getJSModule(Class<T> jsInterface) {
if (mCatalystInstance == null) {
throw new RuntimeException(EARLY_JS_ACCESS_EXCEPTION_MESSAGE);
}
return mCatalystInstance.getJSModule(jsInterface);
}
public <T extends JavaScriptModule> T getJSModule(
ExecutorToken executorToken,
Class<T> jsInterface) {
if (mCatalystInstance == null) {
throw new RuntimeException(EARLY_JS_ACCESS_EXCEPTION_MESSAGE);
}
return mCatalystInstance.getJSModule(executorToken, jsInterface);
}
public <T extends NativeModule> boolean hasNativeModule(Class<T> nativeModuleInterface) {
if (mCatalystInstance == null) {
throw new RuntimeException(
"Trying to call native module before CatalystInstance has been set!");
}
return mCatalystInstance.hasNativeModule(nativeModuleInterface);
}
/**
* @return the instance of the specified module interface associated with this ReactContext.
*/
public <T extends NativeModule> T getNativeModule(Class<T> nativeModuleInterface) {
if (mCatalystInstance == null) {
throw new RuntimeException(
"Trying to call native module before CatalystInstance has been set!");
}
return mCatalystInstance.getNativeModule(nativeModuleInterface);
}
public CatalystInstance getCatalystInstance() {
return Assertions.assertNotNull(mCatalystInstance);
}
public boolean hasActiveCatalystInstance() {
return mCatalystInstance != null && !mCatalystInstance.isDestroyed();
}
public LifecycleState getLifecycleState() {
return mLifecycleState;
}
public void addLifecycleEventListener(final LifecycleEventListener listener) {
mLifecycleEventListeners.add(listener);
if (hasActiveCatalystInstance()) {
switch (mLifecycleState) {
case BEFORE_CREATE:
case BEFORE_RESUME:
break;
case RESUMED:
runOnUiQueueThread(new Runnable() {
@Override
public void run() {
try {
listener.onHostResume();
} catch (RuntimeException e) {
handleException(e);
}
}
});
break;
default:
throw new RuntimeException("Unhandled lifecycle state.");
}
}
}
public void removeLifecycleEventListener(LifecycleEventListener listener) {
mLifecycleEventListeners.remove(listener);
}
public void addActivityEventListener(ActivityEventListener listener) {
mActivityEventListeners.add(listener);
}
public void removeActivityEventListener(ActivityEventListener listener) {
mActivityEventListeners.remove(listener);
}
/**
* Should be called by the hosting Fragment in {@link Fragment#onResume}
*/
public void onHostResume(@Nullable Activity activity) {
UiThreadUtil.assertOnUiThread();
mLifecycleState = LifecycleState.RESUMED;
mCurrentActivity = new WeakReference(activity);
for (LifecycleEventListener listener : mLifecycleEventListeners) {
try {
listener.onHostResume();
} catch (RuntimeException e) {
handleException(e);
}
}
}
public void onNewIntent(@Nullable Activity activity, Intent intent) {
UiThreadUtil.assertOnUiThread();
mCurrentActivity = new WeakReference(activity);
for (ActivityEventListener listener : mActivityEventListeners) {
try {
listener.onNewIntent(intent);
} catch (RuntimeException e) {
handleException(e);
}
}
}
/**
* Should be called by the hosting Fragment in {@link Fragment#onPause}
*/
public void onHostPause() {
UiThreadUtil.assertOnUiThread();
mLifecycleState = LifecycleState.BEFORE_RESUME;
for (LifecycleEventListener listener : mLifecycleEventListeners) {
try {
listener.onHostPause();
} catch (RuntimeException e) {
handleException(e);
}
}
}
/**
* Should be called by the hosting Fragment in {@link Fragment#onDestroy}
*/
public void onHostDestroy() {
UiThreadUtil.assertOnUiThread();
mLifecycleState = LifecycleState.BEFORE_CREATE;
for (LifecycleEventListener listener : mLifecycleEventListeners) {
try {
listener.onHostDestroy();
} catch (RuntimeException e) {
handleException(e);
}
}
mCurrentActivity = null;
}
/**
* Destroy this instance, making it unusable.
*/
public void destroy() {
UiThreadUtil.assertOnUiThread();
if (mCatalystInstance != null) {
mCatalystInstance.destroy();
}
}
/**
* Should be called by the hosting Fragment in {@link Fragment#onActivityResult}
*/
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
for (ActivityEventListener listener : mActivityEventListeners) {
try {
listener.onActivityResult(activity, requestCode, resultCode, data);
} catch (RuntimeException e) {
handleException(e);
}
}
}
public void assertOnUiQueueThread() {
Assertions.assertNotNull(mUiMessageQueueThread).assertIsOnThread();
}
public boolean isOnUiQueueThread() {
return Assertions.assertNotNull(mUiMessageQueueThread).isOnThread();
}
public void runOnUiQueueThread(Runnable runnable) {
Assertions.assertNotNull(mUiMessageQueueThread).runOnQueue(runnable);
}
public void assertOnNativeModulesQueueThread() {
Assertions.assertNotNull(mNativeModulesMessageQueueThread).assertIsOnThread();
}
public boolean isOnNativeModulesQueueThread() {
return Assertions.assertNotNull(mNativeModulesMessageQueueThread).isOnThread();
}
public void runOnNativeModulesQueueThread(Runnable runnable) {
Assertions.assertNotNull(mNativeModulesMessageQueueThread).runOnQueue(runnable);
}
public void assertOnJSQueueThread() {
Assertions.assertNotNull(mJSMessageQueueThread).assertIsOnThread();
}
public boolean isOnJSQueueThread() {
return Assertions.assertNotNull(mJSMessageQueueThread).isOnThread();
}
public void runOnJSQueueThread(Runnable runnable) {
Assertions.assertNotNull(mJSMessageQueueThread).runOnQueue(runnable);
}
/**
* Passes the given exception to the current
* {@link com.facebook.react.bridge.NativeModuleCallExceptionHandler} if one exists, rethrowing
* otherwise.
*/
public void handleException(RuntimeException e) {
if (mCatalystInstance != null &&
!mCatalystInstance.isDestroyed() &&
mNativeModuleCallExceptionHandler != null) {
mNativeModuleCallExceptionHandler.handleException(e);
} else {
throw e;
}
}
public boolean hasCurrentActivity() {
return mCurrentActivity != null && mCurrentActivity.get() != null;
}
/**
* Same as {@link Activity#startActivityForResult(Intent, int)}, this just redirects the call to
* the current activity. Returns whether the activity was started, as this might fail if this
* was called before the context is in the right state.
*/
public boolean startActivityForResult(Intent intent, int code, Bundle bundle) {
Activity activity = getCurrentActivity();
Assertions.assertNotNull(activity);
activity.startActivityForResult(intent, code, bundle);
return true;
}
/**
* Get the activity to which this context is currently attached, or {@code null} if not attached.
* DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE
* MEMORY LEAKS.
*/
public @Nullable Activity getCurrentActivity() {
if (mCurrentActivity == null) {
return null;
}
return mCurrentActivity.get();
}
/**
* Get the C pointer (as a long) to the JavaScriptCore context associated with this instance.
*/
public long getJavaScriptContext() {
return mCatalystInstance.getJavaScriptContext();
}
}
| |
package com.codeforces.commons.cache;
import com.codeforces.commons.math.RandomUtil;
import com.codeforces.commons.process.ThreadUtil;
import com.codeforces.commons.time.TimeUtil;
import org.apache.commons.codec.binary.Hex;
import org.junit.Assert;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Maxim Shipko (sladethe@gmail.com)
* Date: 29.12.12
*/
@SuppressWarnings({"CallToSystemGC", "ThrowableResultOfMethodCallIgnored", "ErrorNotRethrown", "SimplifiableAssertion"})
final class CacheTestUtil {
private CacheTestUtil() {
throw new UnsupportedOperationException();
}
public static void testStoringOfValues(
Class<?> cacheTestClass, Cache<String, byte[]> cache,
int sectionCount, int keyPerSectionCount, int totalKeyCount, int valueLength) {
CachePath[] cachePaths = getCachePaths(sectionCount, keyPerSectionCount, totalKeyCount);
for (int i = 0; i < 5; ++i) {
String operationName;
switch (i) {
case 0:
operationName = cacheTestClass.getSimpleName() + ".testStoringOfValues";
break;
case 1:
operationName = cacheTestClass.getSimpleName() + ".testStoringOfValues (after warm up)";
break;
default:
operationName = String.format(
"%s.testStoringOfValues (after warm up %d)", cacheTestClass.getSimpleName(), i
);
break;
}
determineOperationTime(operationName, () -> {
for (int pathIndex = 0; pathIndex < totalKeyCount; ++pathIndex) {
checkStoringOneValue(cache, cachePaths[pathIndex], valueLength);
}
});
}
}
public static void testOverridingOfValuesWithLifetime(
Class<?> cacheTestClass, Cache<String, byte[]> cache, int valueLength) {
determineOperationTime(cacheTestClass.getSimpleName() + ".testOverridingOfValuesWithLifetime", () -> {
byte[] temporaryBytes = RandomUtil.getRandomBytes(valueLength);
byte[] finalBytes = RandomUtil.getRandomBytes(valueLength);
cache.put("S", "K", temporaryBytes, 1000L);
Assert.assertTrue(
"Restored value (with lifetime) does not equal to original value.",
Arrays.equals(temporaryBytes, cache.get("S", "K"))
);
cache.put("S", "K", finalBytes, 1000L);
ThreadUtil.sleep(500L);
Assert.assertNotNull("Value is 'null' after previous value lifetime expiration.", cache.get("S", "K"));
Assert.assertEquals("Restored value does not equal to original value.", finalBytes, cache.get("S", "K"));
ThreadUtil.sleep(1000L);
Assert.assertNull("Value is not 'null' after lifetime expiration.", cache.get("S", "K"));
});
}
public static void testConcurrentStoringOfValues(
Class<?> cacheTestClass, Cache<String, byte[]> cache,
int sectionCount, int keyPerSectionCount, int totalKeyCount, int valueLength, int threadCount) {
CachePath[] cachePaths = getCachePaths(sectionCount, keyPerSectionCount, totalKeyCount);
AtomicReference<AssertionError> assertionError = new AtomicReference<>();
AtomicReference<Throwable> unexpectedThrowable = new AtomicReference<>();
for (int i = 0; i < 5; ++i) {
String operationName;
switch (i) {
case 0:
operationName = cacheTestClass.getSimpleName() + ".testConcurrentStoringOfValues";
break;
case 1:
operationName = cacheTestClass.getSimpleName() + ".testConcurrentStoringOfValues (after warm up)";
break;
default:
operationName = String.format(
"%s.testConcurrentStoringOfValues (after warm up %d)", cacheTestClass.getSimpleName(), i
);
break;
}
determineOperationTime(operationName, () -> executeConcurrentStoringOfValues(
cache, cachePaths, assertionError, unexpectedThrowable, totalKeyCount, valueLength, threadCount
));
if (unexpectedThrowable.get() != null) {
throw new AssertionError("Got unexpected exception in thread pool.", unexpectedThrowable.get());
}
}
}
public static void testConcurrentStoringOfValuesWithLifetime(
Class<?> cacheTestClass, Cache<String, byte[]> cache,
int sectionCount, int keyPerSectionCount, int totalKeyCount, int valueLength,
int sleepingThreadCount, long valueLifetimeMillis, long valueCheckIntervalMillis) {
CachePath[] cachePaths = getCachePaths(sectionCount, keyPerSectionCount, totalKeyCount);
AtomicReference<AssertionError> assertionError = new AtomicReference<>();
AtomicReference<Throwable> unexpectedThrowable = new AtomicReference<>();
determineOperationTime(cacheTestClass.getSimpleName() + ".testConcurrentStoringOfValuesWithLifetime", () -> {
ExecutorService executorService = Executors.newFixedThreadPool(
sleepingThreadCount,
ThreadUtil.getCustomPoolThreadFactory(
thread -> thread.setUncaughtExceptionHandler((t, e) -> unexpectedThrowable.set(e))
)
);
AtomicInteger pathIndexCounter = new AtomicInteger();
for (int threadIndex = 0; threadIndex < sleepingThreadCount; ++threadIndex) {
@SuppressWarnings("PointlessArithmeticExpression") long threadSleepTime = 1L * threadIndex;
executorService.execute(() -> {
ThreadUtil.sleep(threadSleepTime);
int pathIndex;
while (assertionError.get() == null
&& (pathIndex = pathIndexCounter.getAndIncrement()) < totalKeyCount) {
try {
checkStoringOneValueWithLifetime(
cache, cachePaths[pathIndex], valueLength,
valueLifetimeMillis, valueCheckIntervalMillis
);
} catch (AssertionError error) {
assertionError.set(error);
}
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(1L, TimeUnit.HOURS);
} catch (InterruptedException ignored) {
// No operations.
}
if (assertionError.get() != null) {
throw assertionError.get();
}
});
if (unexpectedThrowable.get() != null) {
throw new AssertionError("Got unexpected exception in thread pool.", unexpectedThrowable.get());
}
}
private static void executeConcurrentStoringOfValues(
Cache<String, byte[]> cache, CachePath[] cachePaths,
AtomicReference<AssertionError> assertionError, AtomicReference<Throwable> unexpectedThrowable,
int totalKeyCount, int valueLength, int threadCount) {
ExecutorService executorService = Executors.newFixedThreadPool(threadCount, ThreadUtil.getCustomPoolThreadFactory(thread -> thread.setUncaughtExceptionHandler((t, e) -> unexpectedThrowable.set(e))));
AtomicInteger pathIndexCounter = new AtomicInteger();
for (int threadIndex = 0; threadIndex < threadCount; ++threadIndex) {
executorService.execute(() -> {
int pathIndex;
while (assertionError.get() == null
&& (pathIndex = pathIndexCounter.getAndIncrement()) < totalKeyCount) {
try {
checkStoringOneValue(cache, cachePaths[pathIndex], valueLength);
} catch (AssertionError error) {
assertionError.set(error);
}
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(1L, TimeUnit.HOURS);
} catch (InterruptedException ignored) {
// No operations.
}
if (assertionError.get() != null) {
throw assertionError.get();
}
}
public static void checkStoringOneValue(Cache<String, byte[]> cache, CachePath cachePath, int valueLength) {
String section = cachePath.getSection();
String key = cachePath.getKey();
byte[] value = RandomUtil.getRandomBytes(valueLength);
cache.put(section, key, value);
Assert.assertTrue(
"Restored value does not equal to original value.",
Arrays.equals(value, cache.get(section, key))
);
cache.remove(section, key);
Assert.assertNull("Value is not 'null' after removal.", cache.get(section, key));
}
public static void checkStoringOneValueWithLifetime(
Cache<String, byte[]> cache, CachePath cachePath, int valueLength,
long valueLifetimeMillis, long valueCheckIntervalMillis) {
String section = cachePath.getSection();
String key = cachePath.getKey();
byte[] value = RandomUtil.getRandomBytes(valueLength);
long cachePutTime = System.currentTimeMillis();
cache.put(section, key, value, valueLifetimeMillis);
Assert.assertArrayEquals("Restored value (with lifetime) does not equal to original value.", value, cache.get(section, key));
ThreadUtil.sleep(valueLifetimeMillis - valueCheckIntervalMillis);
byte[] restoredValue = cache.get(section, key);
long actualSleepingTime = System.currentTimeMillis() - cachePutTime;
if (actualSleepingTime < valueLifetimeMillis - valueCheckIntervalMillis * 0.5) {
Assert.assertArrayEquals(String.format(
"Restored value (with lifetime) does not equal to original value after sleeping some time (%s) " +
"(restored=%s, expected=%s, section=%s, key=%s, valueLifetime=%s, valueCheckInterval=%s).",
TimeUtil.formatInterval(actualSleepingTime),
toShortString(restoredValue), toShortString(value), section, key,
TimeUtil.formatInterval(valueLifetimeMillis), TimeUtil.formatInterval(valueCheckIntervalMillis)
), value, restoredValue);
}
ThreadUtil.sleep(2L * valueCheckIntervalMillis);
Assert.assertNull(
"Restored value (with lifetime) does not equal to 'null' after lifetime expiration.",
cache.get(section, key)
);
cache.put(section, key, value, valueLifetimeMillis);
Assert.assertTrue(
"Restored value (with lifetime) does not equal to original value.",
Arrays.equals(value, cache.get(section, key))
);
cache.remove(section, key);
Assert.assertNull("Value (with lifetime) is not 'null' after removal.", cache.get(section, key));
}
public static CachePath[] getCachePaths(int sectionCount, int keyPerSectionCount, int totalKeyCount) {
@SuppressWarnings("UnsecureRandomNumberGeneration") Random random = new Random();
byte[] buffer = new byte[16];
Map<String, List<String>> keysBySection = new HashMap<>(sectionCount);
for (int sectionIndex = 0; sectionIndex < sectionCount; ++sectionIndex) {
String section;
do {
section = getRandomToken(random, buffer);
} while (keysBySection.containsKey(section));
Set<String> keys = new HashSet<>(keyPerSectionCount);
while (keys.size() < keyPerSectionCount) {
keys.add(getRandomToken(random, buffer));
}
keysBySection.put(section, new ArrayList<>(keys));
}
List<CachePath> cachePaths = new ArrayList<>(totalKeyCount);
for (Map.Entry<String, List<String>> sectionEntry : keysBySection.entrySet()) {
List<String> keys = sectionEntry.getValue();
for (int keyIndex = 0; keyIndex < keyPerSectionCount; ++keyIndex) {
cachePaths.add(new CachePath(sectionEntry.getKey(), keys.get(keyIndex)));
}
}
Collections.shuffle(cachePaths);
return cachePaths.toArray(new CachePath[totalKeyCount]);
}
@Nonnull
private static String getRandomToken(@Nonnull Random random, @Nonnull byte[] buffer) {
random.nextBytes(buffer);
return Hex.encodeHexString(buffer);
}
public static void determineOperationTime(@Nonnull String operationName, @Nonnull Runnable operation) {
System.gc();
ThreadUtil.sleep(1L);
System.gc();
long startTime = System.nanoTime();
operation.run();
long finishTime = System.nanoTime();
System.out.printf(
"Operation '%s' takes %.3f ms.%n",
operationName, (finishTime - startTime) / 1_000_000.0D
);
System.out.flush();
}
@Nonnull
private static String toShortString(@Nullable byte[] array) {
if (array == null) {
return "null";
}
int length = array.length;
if (length == 0) {
return "[]";
}
StringBuilder stringBuilder = new StringBuilder("[").append(array[0]);
if (length <= 7) {
for (int i = 1; i < length; ++i) {
stringBuilder.append(", ").append(array[i]);
}
} else {
for (int i = 1; i < 3; ++i) {
stringBuilder.append(", ").append(array[i]);
}
stringBuilder
.append(", ... ").append(array[length - 3])
.append(", ").append(array[length - 2])
.append(", ").append(array[length - 1]);
}
stringBuilder.append(']');
return stringBuilder.toString();
}
}
| |
/**
* 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.hdfs.server.federation;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODE_ID_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_INTERNAL_NAMESERVICES_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RPC_BIND_HOST_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_BIND_HOST_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICES;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICE_ID;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HTTP_POLICY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMENODES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.addDirectory;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.waitNamenodeRegistered;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_ADMIN_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_ADMIN_BIND_HOST_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_CACHE_TIME_TO_LIVE_MS;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_DEFAULT_NAMESERVICE;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_HANDLER_COUNT_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_HEARTBEAT_INTERVAL_MS;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_HTTPS_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_HTTP_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_HTTP_BIND_HOST_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_MONITOR_NAMENODE;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_RPC_BIND_HOST_KEY;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.DFS_ROUTER_SAFEMODE_ENABLE;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.FEDERATION_FILE_RESOLVER_CLIENT_CLASS;
import static org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys.FEDERATION_NAMENODE_RESOLVER_CLIENT_CLASS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSCluster.NameNodeInfo;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.hdfs.MiniDFSNNTopology.NNConf;
import org.apache.hadoop.hdfs.MiniDFSNNTopology.NSConf;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.server.federation.resolver.ActiveNamenodeResolver;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamenodeServiceState;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamespaceInfo;
import org.apache.hadoop.hdfs.server.federation.resolver.FileSubclusterResolver;
import org.apache.hadoop.hdfs.server.federation.resolver.NamenodeStatusReport;
import org.apache.hadoop.hdfs.server.federation.router.Router;
import org.apache.hadoop.hdfs.server.federation.router.RouterClient;
import org.apache.hadoop.hdfs.server.federation.router.RouterRpcClient;
import org.apache.hadoop.hdfs.server.federation.router.RouterRpcServer;
import org.apache.hadoop.hdfs.server.namenode.FSImage;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.http.HttpConfig;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.service.Service.STATE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test utility to mimic a federated HDFS cluster with multiple routers.
*/
public class MiniRouterDFSCluster {
private static final Logger LOG =
LoggerFactory.getLogger(MiniRouterDFSCluster.class);
public static final String TEST_STRING = "teststring";
public static final String TEST_DIR = "testdir";
public static final String TEST_FILE = "testfile";
private static final Random RND = new Random();
/** Nameservices in the federated cluster. */
private List<String> nameservices;
/** Namenodes in the federated cluster. */
private List<NamenodeContext> namenodes;
/** Routers in the federated cluster. */
private List<RouterContext> routers;
/** If the Namenodes are in high availability.*/
private boolean highAvailability;
/** Number of datanodes per nameservice. */
private int numDatanodesPerNameservice = 2;
/** Custom storage type for each datanode. */
private StorageType[][] storageTypes = null;
/** Racks for datanodes. */
private String[] racks = null;
/** Mini cluster. */
private MiniDFSCluster cluster;
protected static final long DEFAULT_HEARTBEAT_INTERVAL_MS =
TimeUnit.SECONDS.toMillis(5);
protected static final long DEFAULT_CACHE_INTERVAL_MS =
TimeUnit.SECONDS.toMillis(5);
/** Heartbeat interval in milliseconds. */
private long heartbeatInterval;
/** Cache flush interval in milliseconds. */
private long cacheFlushInterval;
/** Router configuration initializes. */
private Configuration routerConf;
/** Router configuration overrides. */
private Configuration routerOverrides;
/** Namenode configuration overrides. */
private Configuration namenodeOverrides;
/** If the DNs are shared. */
private boolean sharedDNs = true;
/**
* Router context.
*/
public static class RouterContext {
private Router router;
private FileContext fileContext;
private String nameserviceId;
private String namenodeId;
private int rpcPort;
private int httpPort;
private DFSClient client;
private Configuration conf;
private RouterClient adminClient;
private URI fileSystemUri;
public RouterContext(Configuration conf, String nsId, String nnId) {
this.conf = conf;
this.nameserviceId = nsId;
this.namenodeId = nnId;
this.router = new Router();
this.router.init(conf);
}
public Router getRouter() {
return this.router;
}
public String getNameserviceId() {
return this.nameserviceId;
}
public String getNamenodeId() {
return this.namenodeId;
}
public int getRpcPort() {
return this.rpcPort;
}
public int getHttpPort() {
return this.httpPort;
}
public FileContext getFileContext() {
return this.fileContext;
}
public URI getFileSystemURI() {
return fileSystemUri;
}
public String getHttpAddress() {
InetSocketAddress httpAddress = router.getHttpServerAddress();
return NetUtils.getHostPortString(httpAddress);
}
public void initRouter() throws URISyntaxException {
// Store the bound points for the router interfaces
InetSocketAddress rpcAddress = router.getRpcServerAddress();
if (rpcAddress != null) {
this.rpcPort = rpcAddress.getPort();
this.fileSystemUri =
URI.create("hdfs://" + NetUtils.getHostPortString(rpcAddress));
// Override the default FS to point to the router RPC
DistributedFileSystem.setDefaultUri(conf, fileSystemUri);
try {
this.fileContext = FileContext.getFileContext(conf);
} catch (UnsupportedFileSystemException e) {
this.fileContext = null;
}
}
InetSocketAddress httpAddress = router.getHttpServerAddress();
if (httpAddress != null) {
this.httpPort = httpAddress.getPort();
}
}
public FileSystem getFileSystem() throws IOException {
return DistributedFileSystem.get(conf);
}
public DFSClient getClient(UserGroupInformation user)
throws IOException, URISyntaxException, InterruptedException {
LOG.info("Connecting to router at {}", fileSystemUri);
return user.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws IOException {
return new DFSClient(fileSystemUri, conf);
}
});
}
public RouterClient getAdminClient() throws IOException {
if (adminClient == null) {
InetSocketAddress routerSocket = router.getAdminServerAddress();
LOG.info("Connecting to router admin at {}", routerSocket);
adminClient = new RouterClient(routerSocket, conf);
}
return adminClient;
}
public void resetAdminClient() {
adminClient = null;
}
public DFSClient getClient() throws IOException, URISyntaxException {
if (client == null) {
LOG.info("Connecting to router at {}", fileSystemUri);
client = new DFSClient(fileSystemUri, conf);
}
return client;
}
public Configuration getConf() {
return conf;
}
public RouterRpcServer getRouterRpcServer() {
return router.getRpcServer();
}
public RouterRpcClient getRouterRpcClient() {
return getRouterRpcServer().getRPCClient();
}
}
/**
* Namenode context in the federated cluster.
*/
public class NamenodeContext {
private Configuration conf;
private NameNode namenode;
private String nameserviceId;
private String namenodeId;
private FileContext fileContext;
private int rpcPort;
private int servicePort;
private int lifelinePort;
private int httpPort;
private int httpsPort;
private URI fileSystemUri;
private int index;
private DFSClient client;
public NamenodeContext(
Configuration conf, String nsId, String nnId, int index) {
this.conf = conf;
this.nameserviceId = nsId;
this.namenodeId = nnId;
this.index = index;
}
public NameNode getNamenode() {
return this.namenode;
}
public String getNameserviceId() {
return this.nameserviceId;
}
public String getNamenodeId() {
return this.namenodeId;
}
public FileContext getFileContext() {
return this.fileContext;
}
public void setNamenode(NameNode nn) throws URISyntaxException {
this.namenode = nn;
// Store the bound ports and override the default FS with the local NN RPC
this.rpcPort = nn.getNameNodeAddress().getPort();
this.servicePort = nn.getServiceRpcAddress().getPort();
this.lifelinePort = nn.getServiceRpcAddress().getPort();
if (nn.getHttpAddress() != null) {
this.httpPort = nn.getHttpAddress().getPort();
}
if (nn.getHttpsAddress() != null) {
this.httpsPort = nn.getHttpsAddress().getPort();
}
this.fileSystemUri = new URI("hdfs://" + namenode.getHostAndPort());
DistributedFileSystem.setDefaultUri(this.conf, this.fileSystemUri);
try {
this.fileContext = FileContext.getFileContext(this.conf);
} catch (UnsupportedFileSystemException e) {
this.fileContext = null;
}
}
public String getRpcAddress() {
return namenode.getNameNodeAddress().getHostName() + ":" + rpcPort;
}
public String getServiceAddress() {
return namenode.getServiceRpcAddress().getHostName() + ":" + servicePort;
}
public String getLifelineAddress() {
return namenode.getServiceRpcAddress().getHostName() + ":" + lifelinePort;
}
public String getWebAddress() {
if (conf.get(DFS_HTTP_POLICY_KEY)
.equals(HttpConfig.Policy.HTTPS_ONLY.name())) {
return getHttpsAddress();
}
return getHttpAddress();
}
public String getHttpAddress() {
return namenode.getHttpAddress().getHostName() + ":" + httpPort;
}
public String getHttpsAddress() {
return namenode.getHttpsAddress().getHostName() + ":" + httpsPort;
}
public FileSystem getFileSystem() throws IOException {
return DistributedFileSystem.get(conf);
}
public void resetClient() {
client = null;
}
public DFSClient getClient(UserGroupInformation user)
throws IOException, URISyntaxException, InterruptedException {
LOG.info("Connecting to namenode at {}", fileSystemUri);
return user.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws IOException {
return new DFSClient(fileSystemUri, conf);
}
});
}
public DFSClient getClient() throws IOException, URISyntaxException {
if (client == null) {
LOG.info("Connecting to namenode at {}", fileSystemUri);
client = new DFSClient(fileSystemUri, conf);
}
return client;
}
public String getConfSuffix() {
String suffix = nameserviceId;
if (highAvailability) {
suffix += "." + namenodeId;
}
return suffix;
}
public Configuration getConf() {
return conf;
}
}
public MiniRouterDFSCluster(
boolean ha, int numNameservices, int numNamenodes,
long heartbeatInterval, long cacheFlushInterval,
Configuration overrideConf) {
this.highAvailability = ha;
this.heartbeatInterval = heartbeatInterval;
this.cacheFlushInterval = cacheFlushInterval;
configureNameservices(numNameservices, numNamenodes, overrideConf);
}
public MiniRouterDFSCluster(
boolean ha, int numNameservices, int numNamenodes,
long heartbeatInterval, long cacheFlushInterval) {
this(ha, numNameservices, numNamenodes,
heartbeatInterval, cacheFlushInterval, null);
}
public MiniRouterDFSCluster(boolean ha, int numNameservices) {
this(ha, numNameservices, 2,
DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_CACHE_INTERVAL_MS,
null);
}
public MiniRouterDFSCluster(
boolean ha, int numNameservices, int numNamenodes) {
this(ha, numNameservices, numNamenodes,
DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_CACHE_INTERVAL_MS,
null);
}
public MiniRouterDFSCluster(boolean ha, int numNameservices,
Configuration overrideConf) {
this(ha, numNameservices, 2,
DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_CACHE_INTERVAL_MS, overrideConf);
}
/**
* Add configuration settings to override default Router settings.
*
* @param conf Router configuration overrides.
*/
public void addRouterOverrides(Configuration conf) {
if (this.routerOverrides == null) {
this.routerOverrides = conf;
} else {
this.routerOverrides.addResource(conf);
}
}
/**
* Add configuration settings to override default Namenode settings.
*
* @param conf Namenode configuration overrides.
*/
public void addNamenodeOverrides(Configuration conf) {
if (this.namenodeOverrides == null) {
this.namenodeOverrides = conf;
} else {
this.namenodeOverrides.addResource(conf);
}
}
/**
* Generate the configuration for a client.
*
* @param nsId Nameservice identifier.
* @return New namenode configuration.
*/
public Configuration generateNamenodeConfiguration(String nsId) {
Configuration conf = new HdfsConfiguration();
conf.set(DFS_NAMESERVICES, getNameservicesKey());
conf.set(FS_DEFAULT_NAME_KEY, "hdfs://" + nsId);
for (String ns : nameservices) {
if (highAvailability) {
conf.set(
DFS_HA_NAMENODES_KEY_PREFIX + "." + ns,
NAMENODES[0] + "," + NAMENODES[1]);
}
for (NamenodeContext context : getNamenodes(ns)) {
String suffix = context.getConfSuffix();
conf.set(DFS_NAMENODE_RPC_ADDRESS_KEY + "." + suffix,
"127.0.0.1:" + context.rpcPort);
conf.set(DFS_NAMENODE_HTTP_ADDRESS_KEY + "." + suffix,
"127.0.0.1:" + context.httpPort);
conf.set(DFS_NAMENODE_RPC_BIND_HOST_KEY + "." + suffix,
"0.0.0.0");
conf.set(DFS_NAMENODE_HTTPS_ADDRESS_KEY + "." + suffix,
"127.0.0.1:" + context.httpsPort);
conf.set(
HdfsClientConfigKeys.Failover.PROXY_PROVIDER_KEY_PREFIX + "." + ns,
ConfiguredFailoverProxyProvider.class.getName());
// If the service port is enabled by default, we need to set them up
boolean servicePortEnabled = false;
if (servicePortEnabled) {
conf.set(DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY + "." + suffix,
"127.0.0.1:" + context.servicePort);
conf.set(DFS_NAMENODE_SERVICE_RPC_BIND_HOST_KEY + "." + suffix,
"0.0.0.0");
}
}
}
if (this.namenodeOverrides != null) {
conf.addResource(this.namenodeOverrides);
}
return conf;
}
/**
* Generate the configuration for a client.
*
* @return New configuration for a client.
*/
public Configuration generateClientConfiguration() {
Configuration conf = new HdfsConfiguration(false);
String ns0 = getNameservices().get(0);
conf.addResource(generateNamenodeConfiguration(ns0));
return conf;
}
/**
* Generate the configuration for a Router.
*
* @param nsId Nameservice identifier.
* @param nnId Namenode identifier.
* @return New configuration for a Router.
*/
public Configuration generateRouterConfiguration(String nsId, String nnId) {
Configuration conf;
if (this.routerConf == null) {
conf = new Configuration(false);
} else {
conf = new Configuration(routerConf);
}
conf.addResource(generateNamenodeConfiguration(nsId));
conf.setInt(DFS_ROUTER_HANDLER_COUNT_KEY, 10);
conf.set(DFS_ROUTER_RPC_ADDRESS_KEY, "127.0.0.1:0");
conf.set(DFS_ROUTER_RPC_BIND_HOST_KEY, "0.0.0.0");
conf.set(DFS_ROUTER_ADMIN_ADDRESS_KEY, "127.0.0.1:0");
conf.set(DFS_ROUTER_ADMIN_BIND_HOST_KEY, "0.0.0.0");
conf.set(DFS_ROUTER_HTTP_ADDRESS_KEY, "127.0.0.1:0");
conf.set(DFS_ROUTER_HTTPS_ADDRESS_KEY, "127.0.0.1:0");
conf.set(DFS_ROUTER_HTTP_BIND_HOST_KEY, "0.0.0.0");
conf.set(DFS_ROUTER_DEFAULT_NAMESERVICE, nameservices.get(0));
conf.setLong(DFS_ROUTER_HEARTBEAT_INTERVAL_MS, heartbeatInterval);
conf.setLong(DFS_ROUTER_CACHE_TIME_TO_LIVE_MS, cacheFlushInterval);
// Use mock resolver classes
conf.setClass(FEDERATION_NAMENODE_RESOLVER_CLIENT_CLASS,
MockResolver.class, ActiveNamenodeResolver.class);
conf.setClass(FEDERATION_FILE_RESOLVER_CLIENT_CLASS,
MockResolver.class, FileSubclusterResolver.class);
// Disable safemode on startup
conf.setBoolean(DFS_ROUTER_SAFEMODE_ENABLE, false);
// Set the nameservice ID for the default NN monitor
conf.set(DFS_NAMESERVICE_ID, nsId);
if (nnId != null) {
conf.set(DFS_HA_NAMENODE_ID_KEY, nnId);
}
// Namenodes to monitor
StringBuilder sb = new StringBuilder();
for (String ns : this.nameservices) {
for (NamenodeContext context : getNamenodes(ns)) {
String suffix = context.getConfSuffix();
if (sb.length() != 0) {
sb.append(",");
}
sb.append(suffix);
}
}
conf.set(DFS_ROUTER_MONITOR_NAMENODE, sb.toString());
// Add custom overrides if available
if (this.routerOverrides != null) {
for (Entry<String, String> entry : this.routerOverrides) {
String confKey = entry.getKey();
String confValue = entry.getValue();
conf.set(confKey, confValue);
}
}
return conf;
}
public void configureNameservices(int numNameservices, int numNamenodes,
Configuration overrideConf) {
this.nameservices = new ArrayList<>();
this.namenodes = new ArrayList<>();
NamenodeContext context = null;
int nnIndex = 0;
for (int i=0; i<numNameservices; i++) {
String ns = "ns" + i;
this.nameservices.add("ns" + i);
Configuration nnConf = generateNamenodeConfiguration(ns);
if (overrideConf != null) {
nnConf.addResource(overrideConf);
}
if (!highAvailability) {
context = new NamenodeContext(nnConf, ns, null, nnIndex++);
this.namenodes.add(context);
} else {
for (int j=0; j<numNamenodes; j++) {
context = new NamenodeContext(nnConf, ns, NAMENODES[j], nnIndex++);
this.namenodes.add(context);
}
}
}
}
public void setNumDatanodesPerNameservice(int num) {
this.numDatanodesPerNameservice = num;
}
/**
* Set custom storage type configuration for each datanode.
* If storageTypes is uninitialized or passed null then
* StorageType.DEFAULT is used.
*/
public void setStorageTypes(StorageType[][] storageTypes) {
this.storageTypes = storageTypes;
}
/**
* Set racks for each datanode. If racks is uninitialized or passed null then
* default is used.
*/
public void setRacks(String[] racks) {
this.racks = racks;
}
/**
* Set the DNs to belong to only one subcluster.
*/
public void setIndependentDNs() {
this.sharedDNs = false;
}
public String getNameservicesKey() {
StringBuilder sb = new StringBuilder();
for (String nsId : this.nameservices) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(nsId);
}
return sb.toString();
}
public String getRandomNameservice() {
int randIndex = RND.nextInt(nameservices.size());
return nameservices.get(randIndex);
}
public List<String> getNameservices() {
return nameservices;
}
public List<NamenodeContext> getNamenodes(String nameservice) {
List<NamenodeContext> nns = new ArrayList<>();
for (NamenodeContext c : namenodes) {
if (c.nameserviceId.equals(nameservice)) {
nns.add(c);
}
}
return nns;
}
public NamenodeContext getRandomNamenode() {
Random rand = new Random();
int i = rand.nextInt(this.namenodes.size());
return this.namenodes.get(i);
}
public List<NamenodeContext> getNamenodes() {
return this.namenodes;
}
public boolean isHighAvailability() {
return highAvailability;
}
public NamenodeContext getNamenode(String nameservice, String namenode) {
for (NamenodeContext c : this.namenodes) {
if (c.nameserviceId.equals(nameservice)) {
if (namenode == null || namenode.isEmpty() ||
c.namenodeId == null || c.namenodeId.isEmpty()) {
return c;
} else if (c.namenodeId.equals(namenode)) {
return c;
}
}
}
return null;
}
public List<RouterContext> getRouters(String nameservice) {
List<RouterContext> nns = new ArrayList<>();
for (RouterContext c : routers) {
if (c.nameserviceId.equals(nameservice)) {
nns.add(c);
}
}
return nns;
}
public RouterContext getRouterContext(String nsId, String nnId) {
for (RouterContext c : routers) {
if (nnId == null) {
return c;
}
if (c.namenodeId.equals(nnId) &&
c.nameserviceId.equals(nsId)) {
return c;
}
}
return null;
}
public RouterContext getRandomRouter() {
Random rand = new Random();
return routers.get(rand.nextInt(routers.size()));
}
public List<RouterContext> getRouters() {
return routers;
}
public RouterContext buildRouter(String nsId, String nnId)
throws URISyntaxException, IOException {
Configuration config = generateRouterConfiguration(nsId, nnId);
RouterContext rc = new RouterContext(config, nsId, nnId);
return rc;
}
public void startCluster() {
startCluster(null);
}
public void startCluster(Configuration overrideConf) {
try {
MiniDFSNNTopology topology = new MiniDFSNNTopology();
for (String ns : nameservices) {
NSConf conf = new MiniDFSNNTopology.NSConf(ns);
if (highAvailability) {
for (int i=0; i<namenodes.size()/nameservices.size(); i++) {
NNConf nnConf = new MiniDFSNNTopology.NNConf("nn" + i);
conf.addNN(nnConf);
}
} else {
NNConf nnConf = new MiniDFSNNTopology.NNConf(null);
conf.addNN(nnConf);
}
topology.addNameservice(conf);
}
topology.setFederation(true);
// Generate conf for namenodes and datanodes
String ns0 = nameservices.get(0);
Configuration nnConf = generateNamenodeConfiguration(ns0);
if (overrideConf != null) {
nnConf.addResource(overrideConf);
// Router also uses this configurations as initial values.
routerConf = new Configuration(overrideConf);
}
// Set independent DNs across subclusters
int numDNs = nameservices.size() * numDatanodesPerNameservice;
Configuration[] dnConfs = null;
if (!sharedDNs) {
dnConfs = new Configuration[numDNs];
int dnId = 0;
for (String nsId : nameservices) {
Configuration subclusterConf = new Configuration(nnConf);
subclusterConf.set(DFS_INTERNAL_NAMESERVICES_KEY, nsId);
for (int i = 0; i < numDatanodesPerNameservice; i++) {
dnConfs[dnId] = subclusterConf;
dnId++;
}
}
}
// Start mini DFS cluster
cluster = new MiniDFSCluster.Builder(nnConf)
.numDataNodes(numDNs)
.nnTopology(topology)
.dataNodeConfOverlays(dnConfs)
.storageTypes(storageTypes)
.racks(racks)
.build();
cluster.waitActive();
// Store NN pointers
for (int i = 0; i < namenodes.size(); i++) {
NameNode nn = cluster.getNameNode(i);
namenodes.get(i).setNamenode(nn);
}
} catch (Exception e) {
LOG.error("Cannot start Router DFS cluster: {}", e.getMessage(), e);
if (cluster != null) {
cluster.shutdown();
}
}
}
public void startRouters()
throws InterruptedException, URISyntaxException, IOException {
// Create one router per nameservice
this.routers = new ArrayList<>();
for (String ns : this.nameservices) {
for (NamenodeContext context : getNamenodes(ns)) {
RouterContext router = buildRouter(ns, context.namenodeId);
this.routers.add(router);
}
}
// Start all routers
for (RouterContext router : this.routers) {
router.router.start();
}
// Wait until all routers are active and record their ports
for (RouterContext router : this.routers) {
waitActive(router);
router.initRouter();
}
}
public void waitActive(NamenodeContext nn) throws IOException {
cluster.waitActive(nn.index);
}
public void waitActive(RouterContext router)
throws InterruptedException {
for (int loopCount = 0; loopCount < 20; loopCount++) {
// Validate connection of routers to NNs
if (router.router.getServiceState() == STATE.STARTED) {
return;
}
Thread.sleep(1000);
}
fail("Timeout waiting for " + router.router + " to activate");
}
public void registerNamenodes() throws IOException {
for (RouterContext r : this.routers) {
ActiveNamenodeResolver resolver = r.router.getNamenodeResolver();
for (NamenodeContext nn : this.namenodes) {
// Generate a report
NamenodeStatusReport report = new NamenodeStatusReport(
nn.nameserviceId, nn.namenodeId,
nn.getRpcAddress(), nn.getServiceAddress(),
nn.getLifelineAddress(), "http", nn.getWebAddress());
FSImage fsImage = nn.namenode.getNamesystem().getFSImage();
NamespaceInfo nsInfo = fsImage.getStorage().getNamespaceInfo();
report.setNamespaceInfo(nsInfo);
// Determine HA state from nn public state string
String nnState = nn.namenode.getState();
HAServiceState haState = HAServiceState.ACTIVE;
for (HAServiceState state : HAServiceState.values()) {
if (nnState.equalsIgnoreCase(state.name())) {
haState = state;
break;
}
}
report.setHAServiceState(haState);
// Register with the resolver
resolver.registerNamenode(report);
}
}
}
public void waitNamenodeRegistration() throws Exception {
for (RouterContext r : this.routers) {
Router router = r.router;
for (NamenodeContext nn : this.namenodes) {
ActiveNamenodeResolver nnResolver = router.getNamenodeResolver();
waitNamenodeRegistered(
nnResolver, nn.nameserviceId, nn.namenodeId, null);
}
}
}
public void waitRouterRegistrationQuorum(RouterContext router,
FederationNamenodeServiceState state, String nsId, String nnId)
throws Exception {
LOG.info("Waiting for NN {} {} to transition to {}", nsId, nnId, state);
ActiveNamenodeResolver nnResolver = router.router.getNamenodeResolver();
waitNamenodeRegistered(nnResolver, nsId, nnId, state);
}
/**
* Wait for name spaces to be active.
* @throws Exception If we cannot check the status or we timeout.
*/
public void waitActiveNamespaces() throws Exception {
for (RouterContext r : this.routers) {
Router router = r.router;
final ActiveNamenodeResolver resolver = router.getNamenodeResolver();
for (FederationNamespaceInfo ns : resolver.getNamespaces()) {
final String nsId = ns.getNameserviceId();
waitNamenodeRegistered(
resolver, nsId, FederationNamenodeServiceState.ACTIVE);
}
}
}
/**
* Get the federated path for a nameservice.
* @param nsId Nameservice identifier.
* @return Path in the Router.
*/
public String getFederatedPathForNS(String nsId) {
return "/" + nsId;
}
/**
* Get the namenode path for a nameservice.
* @param nsId Nameservice identifier.
* @return Path in the Namenode.
*/
public String getNamenodePathForNS(String nsId) {
return "/target-" + nsId;
}
/**
* Get the federated test directory for a nameservice.
* @param nsId Nameservice identifier.
* @return Example:
* <ul>
* <li>/ns0/testdir which maps to ns0->/target-ns0/testdir
* </ul>
*/
public String getFederatedTestDirectoryForNS(String nsId) {
return getFederatedPathForNS(nsId) + "/" + TEST_DIR;
}
/**
* Get the namenode test directory for a nameservice.
* @param nsId Nameservice identifier.
* @return example:
* <ul>
* <li>/target-ns0/testdir
* </ul>
*/
public String getNamenodeTestDirectoryForNS(String nsId) {
return getNamenodePathForNS(nsId) + "/" + TEST_DIR;
}
/**
* Get the federated test file for a nameservice.
* @param nsId Nameservice identifier.
* @return example:
* <ul>
* <li>/ns0/testfile which maps to ns0->/target-ns0/testfile
* </ul>
*/
public String getFederatedTestFileForNS(String nsId) {
return getFederatedPathForNS(nsId) + "/" + TEST_FILE;
}
/**
* Get the namenode test file for a nameservice.
* @param nsId Nameservice identifier.
* @return example:
* <ul>
* <li>/target-ns0/testfile
* </ul>
*/
public String getNamenodeTestFileForNS(String nsId) {
return getNamenodePathForNS(nsId) + "/" + TEST_FILE;
}
/**
* Switch a namenode in a nameservice to be the active.
* @param nsId Nameservice identifier.
* @param nnId Namenode identifier.
*/
public void switchToActive(String nsId, String nnId) {
try {
int total = cluster.getNumNameNodes();
NameNodeInfo[] nns = cluster.getNameNodeInfos();
for (int i = 0; i < total; i++) {
NameNodeInfo nn = nns[i];
if (nn.getNameserviceId().equals(nsId) &&
nn.getNamenodeId().equals(nnId)) {
cluster.transitionToActive(i);
}
}
} catch (Throwable e) {
LOG.error("Cannot transition to active", e);
}
}
/**
* Switch a namenode in a nameservice to be in standby.
* @param nsId Nameservice identifier.
* @param nnId Namenode identifier.
*/
public void switchToStandby(String nsId, String nnId) {
try {
int total = cluster.getNumNameNodes();
NameNodeInfo[] nns = cluster.getNameNodeInfos();
for (int i = 0; i < total; i++) {
NameNodeInfo nn = nns[i];
if (nn.getNameserviceId().equals(nsId) &&
nn.getNamenodeId().equals(nnId)) {
cluster.transitionToStandby(i);
}
}
} catch (Throwable e) {
LOG.error("Cannot transition to standby", e);
}
}
/**
* Stop the federated HDFS cluster.
*/
public void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
if (routers != null) {
for (RouterContext context : routers) {
stopRouter(context);
}
}
}
/**
* Stop a router.
* @param router Router context.
*/
public void stopRouter(RouterContext router) {
try {
router.router.shutDown();
int loopCount = 0;
while (router.router.getServiceState() != STATE.STOPPED) {
loopCount++;
Thread.sleep(1000);
if (loopCount > 20) {
LOG.error("Cannot shutdown router {}", router.rpcPort);
break;
}
}
} catch (InterruptedException e) {
}
}
/////////////////////////////////////////////////////////////////////////////
// Namespace Test Fixtures
/////////////////////////////////////////////////////////////////////////////
/**
* Creates test directories via the namenode.
* 1) /target-ns0/testfile
* 2) /target-ns1/testfile
* @throws IOException
*/
public void createTestDirectoriesNamenode() throws IOException {
// Add a test dir to each NS and verify
for (String ns : getNameservices()) {
NamenodeContext context = getNamenode(ns, null);
if (!createTestDirectoriesNamenode(context)) {
throw new IOException("Cannot create test directory for ns " + ns);
}
}
}
public boolean createTestDirectoriesNamenode(NamenodeContext nn)
throws IOException {
FileSystem fs = nn.getFileSystem();
String testDir = getNamenodeTestDirectoryForNS(nn.nameserviceId);
return addDirectory(fs, testDir);
}
public void deleteAllFiles() throws IOException {
// Delete all files via the NNs and verify
for (NamenodeContext context : getNamenodes()) {
FileSystem fs = context.getFileSystem();
FileStatus[] status = fs.listStatus(new Path("/"));
for (int i = 0; i <status.length; i++) {
Path p = status[i].getPath();
fs.delete(p, true);
}
status = fs.listStatus(new Path("/"));
assertEquals(status.length, 0);
}
}
/////////////////////////////////////////////////////////////////////////////
// MockRouterResolver Test Fixtures
/////////////////////////////////////////////////////////////////////////////
/**
* <ul>
* <li>/ -> [ns0->/].
* <li>/nso -> ns0->/target-ns0.
* <li>/ns1 -> ns1->/target-ns1.
* </ul>
*/
public void installMockLocations() {
for (RouterContext r : routers) {
MockResolver resolver =
(MockResolver) r.router.getSubclusterResolver();
// create table entries
for (String nsId : nameservices) {
// Direct path
String routerPath = getFederatedPathForNS(nsId);
String nnPath = getNamenodePathForNS(nsId);
resolver.addLocation(routerPath, nsId, nnPath);
}
// Root path points to both first nameservice
String ns0 = nameservices.get(0);
resolver.addLocation("/", ns0, "/");
}
}
public MiniDFSCluster getCluster() {
return cluster;
}
/**
* Wait until the federated cluster is up and ready.
* @throws IOException If we cannot wait for the cluster to be up.
*/
public void waitClusterUp() throws IOException {
cluster.waitClusterUp();
registerNamenodes();
try {
waitNamenodeRegistration();
} catch (Exception e) {
throw new IOException("Cannot wait for the namenodes", e);
}
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.testsuite.forms;
import org.hamcrest.Matchers;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.authentication.actiontoken.resetcred.ResetCredentialsActionToken;
import org.jboss.arquillian.graphene.page.Page;
import org.keycloak.common.Profile;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventType;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.Constants;
import org.keycloak.models.utils.SystemClientUtil;
import org.keycloak.protocol.oidc.utils.RedirectUtils;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;
import org.keycloak.testsuite.arquillian.annotation.DisableFeature;
import org.keycloak.testsuite.federation.kerberos.AbstractKerberosTest;
import org.keycloak.testsuite.pages.AppPage;
import org.keycloak.testsuite.pages.AppPage.RequestType;
import org.keycloak.testsuite.pages.ErrorPage;
import org.keycloak.testsuite.pages.InfoPage;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.LoginPasswordResetPage;
import org.keycloak.testsuite.pages.LoginPasswordUpdatePage;
import org.keycloak.testsuite.pages.VerifyEmailPage;
import org.keycloak.testsuite.updaters.ClientAttributeUpdater;
import org.keycloak.testsuite.util.BrowserTabUtil;
import org.keycloak.testsuite.util.GreenMailRule;
import org.keycloak.testsuite.util.MailUtils;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.RealmBuilder;
import org.keycloak.testsuite.util.SecondBrowser;
import org.keycloak.testsuite.util.UserActionTokenBuilder;
import org.keycloak.testsuite.util.UserBuilder;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.Closeable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.*;
import org.keycloak.testsuite.util.WaitUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
@AuthServerContainerExclude(AuthServer.REMOTE)
public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
private String userId;
private UserRepresentation defaultUser;
@Drone
@SecondBrowser
protected WebDriver driver2;
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
RealmBuilder.edit(testRealm)
.client(org.keycloak.testsuite.util.ClientBuilder.create().clientId("client-user").serviceAccount());
}
@Before
public void setup() {
log.info("Adding login-test user");
defaultUser = UserBuilder.create()
.username("login-test")
.email("login@test.com")
.enabled(true)
.build();
userId = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealm(), defaultUser, "password");
defaultUser.setId(userId);
expectedMessagesCount = 0;
getCleanup().addUserId(userId);
}
@Rule
public GreenMailRule greenMail = new GreenMailRule();
@Page
protected AppPage appPage;
@Page
protected LoginPage loginPage;
@Page
protected ErrorPage errorPage;
@Page
protected InfoPage infoPage;
@Page
protected VerifyEmailPage verifyEmailPage;
@Page
protected LoginPasswordResetPage resetPasswordPage;
@Page
protected LoginPasswordUpdatePage updatePasswordPage;
@Rule
public AssertEvents events = new AssertEvents(this);
private int expectedMessagesCount;
@Test
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true) // TODO remove this (KEYCLOAK-16228)
public void resetPasswordLink() throws IOException, MessagingException {
String username = "login-test";
String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials";
driver.navigate().to(resetUri);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.user(userId)
.detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/")
.client("account")
.detail(Details.USERNAME, username)
.detail(Details.EMAIL, "login@test.com")
.session((String)null)
.assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("resetPassword", "resetPassword");
events.expectRequiredAction(EventType.UPDATE_PASSWORD)
.detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/")
.client("account")
.user(userId).detail(Details.USERNAME, username).assertEvent();
String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, username)
.detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/")
.client("account")
.assertEvent().getSessionId();
oauth.openLogout();
events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent();
loginPage.open();
loginPage.login("login-test", "resetPassword");
events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent();
assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
}
@Test
public void resetPassword() throws IOException, MessagingException {
resetPassword("login-test");
}
@Test
public void resetPasswordTwice() throws IOException, MessagingException {
String changePasswordUrl = resetPassword("login-test");
events.clear();
assertSecondPasswordResetFails(changePasswordUrl, oauth.getClientId()); // KC_RESTART doesn't exist, it was deleted after first successful reset-password flow was finished
}
@Test
public void resetPasswordTwiceInNewBrowser() throws IOException, MessagingException {
String changePasswordUrl = resetPassword("login-test");
events.clear();
String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials";
driver.navigate().to(resetUri); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
driver.manage().deleteAllCookies();
assertSecondPasswordResetFails(changePasswordUrl, oauth.getClientId());
}
public void assertSecondPasswordResetFails(String changePasswordUrl, String clientId) {
driver.navigate().to(changePasswordUrl.trim());
errorPage.assertCurrent();
assertEquals("Action expired. Please continue with login now.", errorPage.getError());
events.expect(EventType.RESET_PASSWORD)
.client(clientId)
.session((String) null)
.user(userId)
.error(Errors.EXPIRED_CODE)
.assertEvent();
}
@Test
public void resetPasswordWithSpacesInUsername() throws IOException, MessagingException {
resetPassword(" login-test ");
}
@Test
public void resetPasswordCancelChangeUser() throws IOException, MessagingException {
initiateResetPasswordFromResetPasswordPage("test-user@localhost");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).detail(Details.USERNAME, "test-user@localhost")
.session((String) null)
.detail(Details.EMAIL, "test-user@localhost").assertEvent();
loginPage.login("login@test.com", "password");
EventRepresentation loginEvent = events.expectLogin().user(userId).detail(Details.USERNAME, "login@test.com").assertEvent();
String code = oauth.getCurrentQuery().get("code");
OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
assertEquals(200, tokenResponse.getStatusCode());
assertEquals(userId, oauth.verifyToken(tokenResponse.getAccessToken()).getSubject());
events.expectCodeToToken(loginEvent.getDetails().get(Details.CODE_ID), loginEvent.getSessionId()).user(userId).assertEvent();
}
@Test
public void resetPasswordByEmail() throws IOException, MessagingException {
resetPassword("login@test.com");
}
private String resetPassword(String username) throws IOException, MessagingException {
return resetPassword(username, "resetPassword");
}
private String resetPassword(String username, String password) throws IOException, MessagingException {
initiateResetPasswordFromResetPasswordPage(username);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.user(userId)
.detail(Details.USERNAME, username.trim())
.detail(Details.EMAIL, "login@test.com")
.session((String)null)
.assertEvent();
assertEquals(expectedMessagesCount, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[greenMail.getReceivedMessages().length - 1];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
assertEquals("You need to change your password.", updatePasswordPage.getFeedbackMessage());
updatePasswordPage.changePassword(password, password);
events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, username.trim()).assertEvent();
assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, username.trim()).assertEvent().getSessionId();
oauth.openLogout();
events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent();
loginPage.open();
loginPage.login("login-test", password);
sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId();
assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
oauth.openLogout();
events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent();
return changePasswordUrl;
}
private void resetPasswordInvalidPassword(String username, String password, String error) throws IOException, MessagingException {
initiateResetPasswordFromResetPasswordPage(username);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).user(userId).session((String) null)
.detail(Details.USERNAME, username).detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(expectedMessagesCount, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[greenMail.getReceivedMessages().length - 1];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword(password, password);
updatePasswordPage.assertCurrent();
assertEquals(error, updatePasswordPage.getError());
events.expectRequiredAction(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_REJECTED).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId();
}
private void initiateResetPasswordFromResetPasswordPage(String username) {
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
expectedMessagesCount++;
}
@Test
public void resetPasswordWrongEmail() throws IOException, MessagingException, InterruptedException {
initiateResetPasswordFromResetPasswordPage("invalid");
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.RESET_PASSWORD).user((String) null).session((String) null).detail(Details.USERNAME, "invalid").removeDetail(Details.EMAIL).removeDetail(Details.CODE_ID).error("user_not_found").assertEvent();
}
@Test
public void resetPasswordMissingUsername() throws IOException, MessagingException, InterruptedException {
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("");
resetPasswordPage.assertCurrent();
assertEquals("Please specify username.", resetPasswordPage.getUsernameError());
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.RESET_PASSWORD).user((String) null).session((String) null).clearDetails().error("username_missing").assertEvent();
}
@Test
public void resetPasswordExpiredCode() throws IOException, MessagingException, InterruptedException {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
try {
setTimeOffset(1800 + 23);
driver.navigate().to(changePasswordUrl.trim());
loginPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
}
}
@Test
public void resetPasswordExpiredCodeShort() throws IOException, MessagingException, InterruptedException {
final AtomicInteger originalValue = new AtomicInteger();
RealmRepresentation realmRep = testRealm().toRepresentation();
originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan());
realmRep.setActionTokenGeneratedByUserLifespan(60);
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
loginPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeShortPerActionLifespan() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build());
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
loginPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeShortPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
//Make sure that one attribute settings won't affect the other
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build());
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
loginPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
// KEYCLOAK-4016
@Test
public void resetPasswordExpiredCodeAndAuthSession() throws IOException, MessagingException, InterruptedException {
final AtomicInteger originalValue = new AtomicInteger();
RealmRepresentation realmRep = testRealm().toRepresentation();
originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan());
realmRep.setActionTokenGeneratedByUserLifespan(60);
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&", "&");
setTimeOffset(70);
log.debug("Going to reset password URI.");
driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
log.debug("Removing cookies.");
driver.manage().deleteAllCookies();
driver.navigate().to(changePasswordUrl.trim());
errorPage.assertCurrent();
Assert.assertEquals("Action expired.", errorPage.getError());
String backToAppLink = errorPage.getBackToApplicationLink();
Assert.assertTrue(backToAppLink.endsWith("/app/auth"));
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeAndAuthSessionPerActionLifespan() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build());
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&", "&");
setTimeOffset(70);
log.debug("Going to reset password URI.");
driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
log.debug("Removing cookies.");
driver.manage().deleteAllCookies();
driver.navigate().to(changePasswordUrl.trim());
errorPage.assertCurrent();
Assert.assertEquals("Action expired.", errorPage.getError());
String backToAppLink = errorPage.getBackToApplicationLink();
Assert.assertTrue(backToAppLink.endsWith("/app/auth"));
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeAndAuthSessionPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
//Make sure that one attribute settings won't affect the other
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build());
testRealm().update(realmRep);
try {
initiateResetPasswordFromResetPasswordPage("login-test");
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&", "&");
setTimeOffset(70);
log.debug("Going to reset password URI.");
driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
log.debug("Removing cookies.");
driver.manage().deleteAllCookies();
driver.navigate().to(changePasswordUrl.trim());
errorPage.assertCurrent();
Assert.assertEquals("Action expired.", errorPage.getError());
String backToAppLink = errorPage.getBackToApplicationLink();
Assert.assertTrue(backToAppLink.endsWith("/app/auth"));
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
// KEYCLOAK-5061
@Test
public void resetPasswordExpiredCodeForgotPasswordFlow() throws IOException, MessagingException, InterruptedException {
final AtomicInteger originalValue = new AtomicInteger();
RealmRepresentation realmRep = testRealm().toRepresentation();
originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan());
realmRep.setActionTokenGeneratedByUserLifespan(60);
testRealm().update(realmRep);
try {
// Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint
String loginUrl = oauth.getLoginFormUrl();
String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works
driver.navigate().to(forgotPasswordUrl);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login-test");
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
expectedMessagesCount++;
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
resetPasswordPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeForgotPasswordFlowPerActionLifespan() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build());
testRealm().update(realmRep);
try {
// Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint
String loginUrl = oauth.getLoginFormUrl();
String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works
driver.navigate().to(forgotPasswordUrl);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login-test");
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
expectedMessagesCount++;
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
resetPasswordPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordExpiredCodeForgotPasswordFlowPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes()));
//Make sure that one attribute settings won't affect the other
realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build());
testRealm().update(realmRep);
try {
// Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint
String loginUrl = oauth.getLoginFormUrl();
String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works
driver.navigate().to(forgotPasswordUrl);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login-test");
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
expectedMessagesCount++;
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.session((String)null)
.user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
driver.navigate().to(changePasswordUrl.trim());
resetPasswordPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
realmRep.setAttributes(originalAttributes);
testRealm().update(realmRep);
}
}
@Test
public void resetPasswordDisabledUser() throws IOException, MessagingException, InterruptedException {
UserRepresentation user = findUser("login-test");
try {
user.setEnabled(false);
updateUser(user);
initiateResetPasswordFromResetPasswordPage("login-test");
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.RESET_PASSWORD).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("user_disabled").assertEvent();
} finally {
user.setEnabled(true);
updateUser(user);
}
}
@Test
public void resetPasswordNoEmail() throws IOException, MessagingException, InterruptedException {
final String email;
UserRepresentation user = findUser("login-test");
email = user.getEmail();
try {
user.setEmail("");
updateUser(user);
initiateResetPasswordFromResetPasswordPage("login-test");
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.RESET_PASSWORD_ERROR).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("invalid_email").assertEvent();
} finally {
user.setEmail(email);
updateUser(user);
}
}
@Test
public void resetPasswordWrongSmtp() throws IOException, MessagingException, InterruptedException {
final String[] host = new String[1];
Map<String, String> smtpConfig = new HashMap<>();
smtpConfig.putAll(testRealm().toRepresentation().getSmtpServer());
host[0] = smtpConfig.get("host");
smtpConfig.put("host", "invalid_host");
RealmRepresentation realmRep = testRealm().toRepresentation();
Map<String, String> oldSmtp = realmRep.getSmtpServer();
try {
realmRep.setSmtpServer(smtpConfig);
testRealm().update(realmRep);
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login-test");
errorPage.assertCurrent();
assertEquals("Failed to send email, please try again later.", errorPage.getError());
assertEquals(0, greenMail.getReceivedMessages().length);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD_ERROR).user(userId)
.session((String)null)
.detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error(Errors.EMAIL_SEND_FAILED).assertEvent();
} finally {
// Revert SMTP back
realmRep.setSmtpServer(oldSmtp);
testRealm().update(realmRep);
}
}
private void setPasswordPolicy(String policy) {
RealmRepresentation realmRep = testRealm().toRepresentation();
realmRep.setPasswordPolicy(policy);
testRealm().update(realmRep);
}
@Test
public void resetPasswordWithLengthPasswordPolicy() throws IOException, MessagingException {
setPasswordPolicy("length");
initiateResetPasswordFromResetPasswordPage("login-test");
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).session((String)null).user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent();
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("invalid", "invalid");
assertEquals("Invalid password: minimum length 8.", resetPasswordPage.getErrorMessage());
events.expectRequiredAction(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_REJECTED).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId();
updatePasswordPage.changePassword("resetPasswordWithPasswordPolicy", "resetPasswordWithPasswordPolicy");
events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId();
assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId();
oauth.openLogout();
events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent();
loginPage.open();
loginPage.login("login-test", "resetPasswordWithPasswordPolicy");
assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent();
}
@Test
public void resetPasswordWithPasswordHistoryPolicy() throws IOException, MessagingException {
//Block passwords that are equal to previous passwords. Default value is 3.
setPasswordPolicy("passwordHistory");
try {
setTimeOffset(2000000);
resetPassword("login-test", "password1");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(4000000);
resetPassword("login-test", "password2");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(6000000);
resetPassword("login-test", "password3");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password3", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(8000000);
resetPassword("login-test", "password");
} finally {
setTimeOffset(0);
}
}
@Test
public void resetPasswordLinkOpenedInNewBrowser() throws IOException, MessagingException {
resetPasswordLinkOpenedInNewBrowser(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
}
private void resetPasswordLinkOpenedInNewBrowser(String expectedSystemClientId) throws IOException, MessagingException {
String username = "login-test";
String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials";
driver.navigate().to(resetUri);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
log.info("Should be at login page again.");
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.user(userId)
.detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/")
.client(expectedSystemClientId)
.detail(Details.USERNAME, username)
.detail(Details.EMAIL, "login@test.com")
.session((String)null)
.assertEvent();
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
log.debug("Going to reset password URI.");
driver.navigate().to(resetUri); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
log.debug("Removing cookies.");
driver.manage().deleteAllCookies();
log.debug("Going to URI from e-mail.");
driver.navigate().to(changePasswordUrl.trim());
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("resetPassword", "resetPassword");
infoPage.assertCurrent();
assertEquals("Your account has been updated.", infoPage.getInfo());
}
// KEYCLOAK-5982
@Test
public void resetPasswordLinkOpenedInNewBrowserAndAccountClientRenamed() throws IOException, MessagingException {
// Temporarily rename client "account" . Revert it back after the test
try (Closeable accountClientUpdater = ClientAttributeUpdater.forClient(adminClient, "test", Constants.ACCOUNT_MANAGEMENT_CLIENT_ID)
.setClientId("account-changed")
.update()) {
// Assert resetPassword link opened in new browser works even if client "account" not available
resetPasswordLinkOpenedInNewBrowser(SystemClientUtil.SYSTEM_CLIENT_ID);
}
}
@Test
public void resetPasswordLinkNewBrowserSessionPreserveClient() throws IOException, MessagingException {
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword("login-test");
loginPage.assertCurrent();
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
driver2.navigate().to(changePasswordUrl.trim());
changePasswordOnUpdatePage(driver2);
assertThat(driver2.getCurrentUrl(), Matchers.containsString("client_id=test-app"));
assertThat(driver2.getPageSource(), Matchers.containsString("Your account has been updated."));
}
// KEYCLOAK-15239
@Test
public void resetPasswordWithSpnegoEnabled() throws IOException, MessagingException {
// Just switch SPNEGO authenticator requirement to alternative. No real usage of SPNEGO needed for this test
AuthenticationExecutionModel.Requirement origRequirement = AbstractKerberosTest.updateKerberosAuthExecutionRequirement(AuthenticationExecutionModel.Requirement.ALTERNATIVE, testRealm());
try {
resetPassword("login-test");
} finally {
// Revert
AbstractKerberosTest.updateKerberosAuthExecutionRequirement(origRequirement, testRealm());
}
}
@Test
public void failResetPasswordServiceAccount() {
String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "client-user";
UserRepresentation serviceAccount = testRealm().users()
.search(username).get(0);
serviceAccount.toString();
UserResource serviceAccount1 = testRealm().users().get(serviceAccount.getId());
serviceAccount = serviceAccount1.toRepresentation();
serviceAccount.setEmail("client-user@test.com");
serviceAccount1.update(serviceAccount);
String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials";
driver.navigate().to(resetUri);
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
loginPage.assertCurrent();
assertEquals("Invalid username or password.", errorPage.getError());
}
@Test
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true) // TODO remove this (KEYCLOAK-16228)
public void resetPasswordLinkNewTabAndProperRedirectAccount() throws IOException {
final String REQUIRED_URI = OAuthClient.AUTH_SERVER_ROOT + "/realms/test/account/applications";
final String REDIRECT_URI = getAccountRedirectUrl() + "?path=applications";
final String CLIENT_ID = "account";
final String ACCOUNT_MANAGEMENT_TITLE = getProjectName() + " Account Management";
try (BrowserTabUtil tabUtil = BrowserTabUtil.getInstanceAndSetEnv(driver)) {
assertThat(tabUtil.getCountOfTabs(), Matchers.is(1));
driver.navigate().to(REQUIRED_URI);
resetPasswordTwiceInNewTab(defaultUser, CLIENT_ID, false, REDIRECT_URI, REQUIRED_URI);
assertThat(driver.getTitle(), Matchers.equalTo(ACCOUNT_MANAGEMENT_TITLE));
oauth.openLogout();
driver.navigate().to(REQUIRED_URI);
resetPasswordTwiceInNewTab(defaultUser, CLIENT_ID, true, REDIRECT_URI, REQUIRED_URI);
assertThat(driver.getTitle(), Matchers.equalTo(ACCOUNT_MANAGEMENT_TITLE));
}
}
@Test
public void resetPasswordLinkNewTabAndProperRedirectClient() throws IOException {
final String REDIRECT_URI = getAuthServerRoot() + "realms/master/app/auth";
final String CLIENT_ID = "test-app";
try (BrowserTabUtil tabUtil = BrowserTabUtil.getInstanceAndSetEnv(driver);
ClientAttributeUpdater cau = ClientAttributeUpdater.forClient(getAdminClient(), TEST_REALM_NAME, CLIENT_ID)
.filterRedirectUris(uri -> uri.contains(REDIRECT_URI))
.update()) {
assertThat(tabUtil.getCountOfTabs(), Matchers.is(1));
loginPage.open();
resetPasswordTwiceInNewTab(defaultUser, CLIENT_ID, false, REDIRECT_URI);
assertThat(driver.getCurrentUrl(), Matchers.containsString(REDIRECT_URI));
oauth.openLogout();
loginPage.open();
resetPasswordTwiceInNewTab(defaultUser, CLIENT_ID, true, REDIRECT_URI);
assertThat(driver.getCurrentUrl(), Matchers.containsString(REDIRECT_URI));
}
}
@Test
public void resetPasswordInfoMessageWithDuplicateEmailsAllowed() throws IOException {
RealmRepresentation realmRep = testRealm().toRepresentation();
Boolean originalLoginWithEmailAllowed = realmRep.isLoginWithEmailAllowed();
Boolean originalDuplicateEmailsAllowed = realmRep.isDuplicateEmailsAllowed();
try {
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
assertEquals("Enter your username or email address and we will send you instructions on how to create a new password.", resetPasswordPage.getInfoMessage());
realmRep.setLoginWithEmailAllowed(false);
realmRep.setDuplicateEmailsAllowed(true);
testRealm().update(realmRep);
loginPage.open();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
assertEquals("Enter your username and we will send you instructions on how to create a new password.", resetPasswordPage.getInfoMessage());
} finally {
realmRep.setLoginWithEmailAllowed(originalLoginWithEmailAllowed);
realmRep.setDuplicateEmailsAllowed(originalDuplicateEmailsAllowed);
testRealm().update(realmRep);
}
}
// KEYCLOAK-15170
@Test
public void changeEmailAddressAfterSendingEmail() throws IOException {
initiateResetPasswordFromResetPasswordPage(defaultUser.getUsername());
assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
UserResource user = testRealm().users().get(defaultUser.getId());
UserRepresentation userRep = user.toRepresentation();
userRep.setEmail("vmuzikar@redhat.com");
user.update(userRep);
driver.navigate().to(changePasswordUrl.trim());
errorPage.assertCurrent();
assertEquals("Invalid email address.", errorPage.getError());
}
private void changePasswordOnUpdatePage(WebDriver driver) {
assertThat(driver.getPageSource(), Matchers.containsString("You need to change your password."));
final WebElement newPassword = driver.findElement(By.id("password-new"));
newPassword.sendKeys("resetPassword");
final WebElement confirmPassword = driver.findElement(By.id("password-confirm"));
confirmPassword.sendKeys("resetPassword");
final WebElement submit = driver.findElement(By.cssSelector("input[type=\"submit\"]"));
submit.click();
}
private void resetPasswordTwiceInNewTab(UserRepresentation user, String clientId, boolean shouldLogOut, String redirectUri) throws IOException {
resetPasswordTwiceInNewTab(user, clientId, shouldLogOut, redirectUri, redirectUri);
}
private void resetPasswordTwiceInNewTab(UserRepresentation user, String clientId, boolean shouldLogOut, String redirectUri, String requiredUri) throws IOException {
events.clear();
updateForgottenPassword(user, clientId, redirectUri, requiredUri);
if (shouldLogOut) {
String sessionId = events.expectLogin().user(user.getId()).detail(Details.USERNAME, user.getUsername())
.detail(Details.REDIRECT_URI, redirectUri)
.client(clientId)
.assertEvent().getSessionId();
oauth.openLogout();
events.expectLogout(sessionId).user(user.getId()).session(sessionId).assertEvent();
}
BrowserTabUtil util = BrowserTabUtil.getInstanceAndSetEnv(driver);
assertThat(util.getCountOfTabs(), Matchers.equalTo(2));
util.closeTab(1);
assertThat(util.getCountOfTabs(), Matchers.equalTo(1));
if (shouldLogOut) {
final ClientRepresentation client = testRealm().clients()
.findByClientId(clientId)
.stream()
.findFirst()
.orElse(null);
assertThat(client, Matchers.notNullValue());
updateForgottenPassword(user, clientId, getValidRedirectUriWithRootUrl(client.getRootUrl(), client.getRedirectUris()));
} else {
doForgotPassword(user.getUsername());
}
}
private void updateForgottenPassword(UserRepresentation user, String clientId, String redirectUri) throws IOException {
updateForgottenPassword(user, clientId, redirectUri, redirectUri);
}
private void updateForgottenPassword(UserRepresentation user, String clientId, String redirectUri, String requiredUri) throws IOException {
final int emailCount = greenMail.getReceivedMessages().length;
doForgotPassword(user.getUsername());
assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());
events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
.user(user.getId())
.client(clientId)
.detail(Details.REDIRECT_URI, redirectUri)
.detail(Details.USERNAME, user.getUsername())
.detail(Details.EMAIL, user.getEmail())
.session((String) null)
.assertEvent();
assertEquals(emailCount + 1, greenMail.getReceivedMessages().length);
final MimeMessage message = greenMail.getReceivedMessages()[emailCount];
final String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
BrowserTabUtil util = BrowserTabUtil.getInstanceAndSetEnv(driver);
util.newTab(changePasswordUrl.trim());
changePasswordOnUpdatePage(driver);
events.expectRequiredAction(EventType.UPDATE_PASSWORD)
.detail(Details.REDIRECT_URI, redirectUri)
.client(clientId)
.user(user.getId()).detail(Details.USERNAME, user.getUsername()).assertEvent();
assertThat(driver.getCurrentUrl(), Matchers.containsString(requiredUri));
}
private void doForgotPassword(String username) {
loginPage.assertCurrent();
loginPage.resetPassword();
resetPasswordPage.assertCurrent();
resetPasswordPage.changePassword(username);
WaitUtils.waitForPageToLoad();
}
private String getValidRedirectUriWithRootUrl(String rootUrl, Collection<String> redirectUris) {
final boolean isRootUrlValid = isValidUrl(rootUrl);
return redirectUris.stream()
.map(uri -> isRootUrlValid && uri.startsWith("/") ? rootUrl + uri : uri)
.map(uri -> uri.startsWith("/") ? OAuthClient.AUTH_SERVER_ROOT + uri : uri)
.map(RedirectUtils::validateRedirectUriWildcard)
.findFirst()
.orElse(null);
}
private boolean isValidUrl(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
}
| |
/**
* 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.ambari.server.orm.entities;
import static org.apache.commons.lang.StringUtils.defaultString;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.UniqueConstraint;
import org.apache.ambari.server.state.HostComponentAdminState;
import org.apache.ambari.server.state.MaintenanceState;
import org.apache.ambari.server.state.SecurityState;
import org.apache.ambari.server.state.State;
import com.google.common.base.Objects;
@Entity
@Table(
name = "hostcomponentdesiredstate",
uniqueConstraints = @UniqueConstraint(
name = "UQ_hcdesiredstate_name",
columnNames = { "component_name", "service_name", "host_id", "cluster_id" }) )
@TableGenerator(
name = "hostcomponentdesiredstate_id_generator",
table = "ambari_sequences",
pkColumnName = "sequence_name",
valueColumnName = "sequence_value",
pkColumnValue = "hostcomponentdesiredstate_id_seq",
initialValue = 0)
@NamedQueries({
@NamedQuery(name = "HostComponentDesiredStateEntity.findAll", query = "SELECT hcds from HostComponentDesiredStateEntity hcds"),
@NamedQuery(name = "HostComponentDesiredStateEntity.findByServiceAndComponent", query =
"SELECT hcds from HostComponentDesiredStateEntity hcds WHERE hcds.serviceName=:serviceName AND hcds.componentName=:componentName"),
@NamedQuery(name = "HostComponentDesiredStateEntity.findByServiceComponentAndHost", query =
"SELECT hcds from HostComponentDesiredStateEntity hcds WHERE hcds.serviceName=:serviceName AND hcds.componentName=:componentName AND hcds.hostEntity.hostName=:hostName"),
@NamedQuery(name = "HostComponentDesiredStateEntity.findByIndex", query =
"SELECT hcds from HostComponentDesiredStateEntity hcds WHERE hcds.clusterId=:clusterId AND hcds.serviceName=:serviceName AND hcds.componentName=:componentName AND hcds.hostId=:hostId"),
})
public class HostComponentDesiredStateEntity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "hostcomponentdesiredstate_id_generator")
@Column(name = "id", nullable = false, insertable = true, updatable = false)
private Long id;
@Column(name = "cluster_id", nullable = false, insertable = false, updatable = false, length = 10)
private Long clusterId;
@Column(name = "service_name", nullable = false, insertable = false, updatable = false)
private String serviceName;
@Column(name = "host_id", nullable = false, insertable = false, updatable = false)
private Long hostId;
@Column(name = "component_name", insertable = false, updatable = false)
private String componentName = "";
@Basic
@Column(name = "desired_state", nullable = false, insertable = true, updatable = true)
@Enumerated(value = EnumType.STRING)
private State desiredState = State.INIT;
@Basic
@Column(name = "security_state", nullable = false, insertable = true, updatable = true)
@Enumerated(value = EnumType.STRING)
private SecurityState securityState = SecurityState.UNSECURED;
@Enumerated(value = EnumType.STRING)
@Column(name = "admin_state", nullable = true, insertable = true, updatable = true)
private HostComponentAdminState adminState;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "cluster_id", referencedColumnName = "cluster_id", nullable = false),
@JoinColumn(name = "service_name", referencedColumnName = "service_name", nullable = false),
@JoinColumn(name = "component_name", referencedColumnName = "component_name", nullable = false)})
private ServiceComponentDesiredStateEntity serviceComponentDesiredStateEntity;
@ManyToOne
@JoinColumn(name = "host_id", referencedColumnName = "host_id", nullable = false)
private HostEntity hostEntity;
@Enumerated(value = EnumType.STRING)
@Column(name="maintenance_state", nullable = false, insertable = true, updatable = true)
private MaintenanceState maintenanceState = MaintenanceState.OFF;
@Basic
@Column(name = "restart_required", insertable = true, updatable = true, nullable = false)
private Integer restartRequired = 0;
public Long getId() { return id; }
public Long getClusterId() {
return clusterId;
}
public void setClusterId(Long clusterId) {
this.clusterId = clusterId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public Long getHostId() {
return hostEntity != null ? hostEntity.getHostId() : null;
}
public String getComponentName() {
return defaultString(componentName);
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public State getDesiredState() {
return desiredState;
}
public void setDesiredState(State desiredState) {
this.desiredState = desiredState;
}
public SecurityState getSecurityState() {
return securityState;
}
public void setSecurityState(SecurityState securityState) {
this.securityState = securityState;
}
public HostComponentAdminState getAdminState() {
return adminState;
}
public void setAdminState(HostComponentAdminState attribute) {
adminState = attribute;
}
public MaintenanceState getMaintenanceState() {
return maintenanceState;
}
public void setMaintenanceState(MaintenanceState state) {
maintenanceState = state;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HostComponentDesiredStateEntity that = (HostComponentDesiredStateEntity) o;
if (!Objects.equal(id, that.id)) {
return false;
}
if (!Objects.equal(clusterId, that.clusterId)) {
return false;
}
if (!Objects.equal(componentName, that.componentName)) {
return false;
}
if (!Objects.equal(desiredState, that.desiredState)) {
return false;
}
if (!Objects.equal(hostEntity, that.hostEntity)) {
return false;
}
if (!Objects.equal(serviceName, that.serviceName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (clusterId != null ? clusterId.hashCode() : 0);
result = 31 * result + (hostEntity != null ? hostEntity.hashCode() : 0);
result = 31 * result + (componentName != null ? componentName.hashCode() : 0);
result = 31 * result + (desiredState != null ? desiredState.hashCode() : 0);
result = 31 * result + (serviceName != null ? serviceName.hashCode() : 0);
return result;
}
public ServiceComponentDesiredStateEntity getServiceComponentDesiredStateEntity() {
return serviceComponentDesiredStateEntity;
}
public void setServiceComponentDesiredStateEntity(ServiceComponentDesiredStateEntity serviceComponentDesiredStateEntity) {
this.serviceComponentDesiredStateEntity = serviceComponentDesiredStateEntity;
}
public HostEntity getHostEntity() {
return hostEntity;
}
public void setHostEntity(HostEntity hostEntity) {
this.hostEntity = hostEntity;
}
public boolean isRestartRequired() {
return restartRequired == 0 ? false : true;
}
public void setRestartRequired(boolean restartRequired) {
this.restartRequired = (restartRequired == false ? 0 : 1);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return Objects.toStringHelper(this).add("serviceName", serviceName).add("componentName",
componentName).add("hostId", hostId).add("desiredState", desiredState).toString();
}
}
| |
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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://www.eclipse.org/legal/cpl-v10.html
*
* 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) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2004 David Corbin <dcorbin@users.sourceforge.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.javasupport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.IOInputStream;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Java::JavaObject")
public class JavaObject extends RubyObject {
private static Object NULL_LOCK = new Object();
protected JavaObject(Ruby runtime, RubyClass rubyClass, Object value) {
super(runtime, rubyClass);
dataWrapStruct(value);
}
protected JavaObject(Ruby runtime, Object value) {
this(runtime, runtime.getJavaSupport().getJavaObjectClass(), value);
}
public static JavaObject wrap(Ruby runtime, Object value) {
if (value != null) {
if (value instanceof Class) {
return JavaClass.get(runtime, (Class<?>) value);
} else if (value.getClass().isArray()) {
return new JavaArray(runtime, value);
}
}
return new JavaObject(runtime, value);
}
public Class<?> getJavaClass() {
Object dataStruct = dataGetStruct();
return dataStruct != null ? dataStruct.getClass() : Void.TYPE;
}
public Object getValue() {
return dataGetStruct();
}
public static RubyClass createJavaObjectClass(Ruby runtime, RubyModule javaModule) {
// FIXME: Ideally JavaObject instances should be marshallable, which means that
// the JavaObject metaclass should have an appropriate allocator. JRUBY-414
RubyClass result = javaModule.defineClassUnder("JavaObject", runtime.getObject(), JAVA_OBJECT_ALLOCATOR);
registerRubyMethods(runtime, result);
result.getMetaClass().undefineMethod("new");
result.getMetaClass().undefineMethod("allocate");
return result;
}
protected static void registerRubyMethods(Ruby runtime, RubyClass result) {
result.defineAnnotatedMethods(JavaObject.class);
}
public boolean equals(Object other) {
return other instanceof JavaObject &&
this.dataGetStruct() == ((JavaObject) other).dataGetStruct();
}
public int hashCode() {
Object dataStruct = dataGetStruct();
if (dataStruct != null) {
return dataStruct.hashCode();
}
return 0;
}
@JRubyMethod
public RubyFixnum hash() {
return getRuntime().newFixnum(hashCode());
}
@JRubyMethod
public IRubyObject to_s() {
Object dataStruct = dataGetStruct();
if (dataStruct != null) {
String stringValue = dataStruct.toString();
if (stringValue != null) {
return RubyString.newUnicodeString(getRuntime(), dataStruct.toString());
}
return getRuntime().getNil();
}
return RubyString.newEmptyString(getRuntime());
}
@JRubyMethod(name = {"==", "eql?"}, required = 1)
public IRubyObject op_equal(IRubyObject other) {
if (!(other instanceof JavaObject)) {
other = (JavaObject)other.dataGetStruct();
if (!(other instanceof JavaObject)) {
return getRuntime().getFalse();
}
}
if (getValue() == null && ((JavaObject) other).getValue() == null) {
return getRuntime().getTrue();
}
boolean isEqual = getValue().equals(((JavaObject) other).getValue());
return isEqual ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "equal?", required = 1)
public IRubyObject same(IRubyObject other) {
if (!(other instanceof JavaObject)) {
other = (JavaObject)other.dataGetStruct();
if (!(other instanceof JavaObject)) {
return getRuntime().getFalse();
}
}
if (getValue() == null && ((JavaObject) other).getValue() == null) {
return getRuntime().getTrue();
}
boolean isSame = getValue() == ((JavaObject) other).getValue();
return isSame ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod
public RubyString java_type() {
return getRuntime().newString(getJavaClass().getName());
}
@JRubyMethod
public IRubyObject java_class() {
return JavaClass.get(getRuntime(), getJavaClass());
}
@JRubyMethod
public RubyFixnum length() {
throw getRuntime().newTypeError("not a java array");
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject aref(IRubyObject index) {
throw getRuntime().newTypeError("not a java array");
}
@JRubyMethod(name = "[]=", required = 2)
public IRubyObject aset(IRubyObject index, IRubyObject someValue) {
throw getRuntime().newTypeError("not a java array");
}
@JRubyMethod(name = "fill", required = 3)
public IRubyObject afill(IRubyObject beginIndex, IRubyObject endIndex, IRubyObject someValue) {
throw getRuntime().newTypeError("not a java array");
}
@JRubyMethod(name = "java_proxy?")
public IRubyObject is_java_proxy() {
return getRuntime().getTrue();
}
@JRubyMethod(name = "synchronized")
public IRubyObject ruby_synchronized(ThreadContext context, Block block) {
Object lock = getValue();
synchronized (lock != null ? lock : NULL_LOCK) {
return block.yield(context, null);
}
}
@JRubyMethod(frame = true)
public IRubyObject marshal_dump() {
if (Serializable.class.isAssignableFrom(getJavaClass())) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(getValue());
return getRuntime().newString(new ByteList(baos.toByteArray()));
} catch (IOException ioe) {
throw getRuntime().newIOErrorFromException(ioe);
}
} else {
throw getRuntime().newTypeError("no marshal_dump is defined for class " + getJavaClass());
}
}
@JRubyMethod(frame = true)
public IRubyObject marshal_load(ThreadContext context, IRubyObject str) {
try {
ByteList byteList = str.convertToString().getByteList();
ByteArrayInputStream bais = new ByteArrayInputStream(byteList.bytes, byteList.begin, byteList.realSize);
ObjectInputStream ois = new ObjectInputStream(bais);
dataWrapStruct(ois.readObject());
return this;
} catch (IOException ioe) {
throw context.getRuntime().newIOErrorFromException(ioe);
} catch (ClassNotFoundException cnfe) {
throw context.getRuntime().newTypeError("Class not found unmarshaling Java type: " + cnfe.getLocalizedMessage());
}
}
private static final ObjectAllocator JAVA_OBJECT_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new JavaObject(runtime, klazz, null);
}
};
}
| |
/*
* Copyright (C) 2012 - present by Yann Le Tallec.
* Please see distribution for license.
*/
package com.assylias.jbloomberg;
import com.bloomberglp.blpapi.CorrelationID;
import com.bloomberglp.blpapi.Datetime;
import com.bloomberglp.blpapi.Element;
import com.bloomberglp.blpapi.Message;
import com.bloomberglp.blpapi.Name;
import com.bloomberglp.blpapi.Service;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
public class MockMessage extends Message {
private String type;
private String toString;
private CorrelationID cId;
public MockMessage setMessageType(String type) {
this.type = type;
return this;
}
public MockMessage setToString(String s) {
this.toString = s;
return this;
}
public MockMessage setCorrelationID(CorrelationID cId) {
this.cId = cId;
return this;
}
public MockMessage setCorrelationID(long cId) {
this.cId = new CorrelationID(cId);
return this;
}
@Override
public Name messageType() {
return new Name(type);
}
@Override
public String topicName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Service service() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Fragment fragmentType() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Recap recapType() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public CorrelationID correlationID() {
return cId;
}
@Override @Deprecated
public CorrelationID correlationIDAt(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public CorrelationID correlationID(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int numCorrelationIds() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Element asElement() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int numElements() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isValid() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasElement(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasElement(Name name, boolean excludeNullElements) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasElement(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasElement(String name, boolean excludeNullElements) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Element getElement(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Element getElement(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getElementAsBool(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getElementAsBool(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public byte[] getElementAsBytes(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public byte[] getElementAsBytes(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public char getElementAsChar(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public char getElementAsChar(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getElementAsInt32(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getElementAsInt32(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getElementAsInt64(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getElementAsInt64(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public double getElementAsFloat64(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public double getElementAsFloat64(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public float getElementAsFloat32(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public float getElementAsFloat32(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getElementAsString(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getElementAsString(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsDatetime(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsDatetime(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsDate(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsDate(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsTime(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Datetime getElementAsTime(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Name getElementAsName(Name name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Name getElementAsName(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRequestId() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String toString() {
return toString;
}
@Override
public void print(OutputStream output) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void print(Writer writer) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long timeReceivedMillis() {
throw new UnsupportedOperationException();
}
}
| |
package org.apache.samoa.tasks;
/*
* #%L
* SAMOA
* %%
* Copyright (C) 2014 - 2015 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.
* #L%
*/
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.samoa.evaluation.BasicClassificationPerformanceEvaluator;
import org.apache.samoa.evaluation.BasicRegressionPerformanceEvaluator;
import org.apache.samoa.evaluation.ClassificationPerformanceEvaluator;
import org.apache.samoa.evaluation.EvaluatorProcessor;
import org.apache.samoa.evaluation.PerformanceEvaluator;
import org.apache.samoa.evaluation.RegressionPerformanceEvaluator;
import org.apache.samoa.learners.ClassificationLearner;
import org.apache.samoa.learners.Learner;
import org.apache.samoa.learners.RegressionLearner;
import org.apache.samoa.learners.classifiers.trees.VerticalHoeffdingTree;
import org.apache.samoa.moa.streams.InstanceStream;
import org.apache.samoa.moa.streams.generators.RandomTreeGenerator;
import org.apache.samoa.streams.PrequentialSourceProcessor;
import org.apache.samoa.topology.ComponentFactory;
import org.apache.samoa.topology.Stream;
import org.apache.samoa.topology.Topology;
import org.apache.samoa.topology.TopologyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.javacliparser.ClassOption;
import com.github.javacliparser.Configurable;
import com.github.javacliparser.FileOption;
import com.github.javacliparser.IntOption;
import com.github.javacliparser.StringOption;
/**
* Prequential Evaluation task is a scheme in evaluating performance of online classifiers which uses each instance for
* testing online classifiers model and then it further uses the same instance for training the model(Test-then-train)
*
* @author Arinto Murdopo
*
*/
public class PrequentialEvaluation implements Task, Configurable {
private static final long serialVersionUID = -8246537378371580550L;
private static Logger logger = LoggerFactory.getLogger(PrequentialEvaluation.class);
public ClassOption learnerOption = new ClassOption("learner", 'l', "Classifier to train.", Learner.class,
VerticalHoeffdingTree.class.getName());
public ClassOption streamTrainOption = new ClassOption("trainStream", 's', "Stream to learn from.",
InstanceStream.class,
RandomTreeGenerator.class.getName());
public ClassOption evaluatorOption = new ClassOption("evaluator", 'e',
"Classification performance evaluation method.",
PerformanceEvaluator.class, BasicClassificationPerformanceEvaluator.class.getName());
public IntOption instanceLimitOption = new IntOption("instanceLimit", 'i',
"Maximum number of instances to test/train on (-1 = no limit).", 1000000, -1,
Integer.MAX_VALUE);
public IntOption timeLimitOption = new IntOption("timeLimit", 't',
"Maximum number of seconds to test/train for (-1 = no limit).", -1, -1,
Integer.MAX_VALUE);
public IntOption sampleFrequencyOption = new IntOption("sampleFrequency", 'f',
"How many instances between samples of the learning performance.", 100000,
0, Integer.MAX_VALUE);
public StringOption evaluationNameOption = new StringOption("evaluationName", 'n', "Identifier of the evaluation",
"Prequential_"
+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
public FileOption dumpFileOption = new FileOption("dumpFile", 'd', "File to append intermediate csv results to",
null, "csv", true);
// Default=0: no delay/waiting
public IntOption sourceDelayOption = new IntOption("sourceDelay", 'w',
"How many microseconds between injections of two instances.", 0, 0, Integer.MAX_VALUE);
// Batch size to delay the incoming stream: delay of x milliseconds after each
// batch
public IntOption batchDelayOption = new IntOption("delayBatchSize", 'b',
"The delay batch size: delay of x milliseconds after each batch ", 1, 1, Integer.MAX_VALUE);
private PrequentialSourceProcessor preqSource;
// private PrequentialSourceTopologyStarter preqStarter;
// private EntranceProcessingItem sourcePi;
private Stream sourcePiOutputStream;
private Learner classifier;
private EvaluatorProcessor evaluator;
// private ProcessingItem evaluatorPi;
// private Stream evaluatorPiInputStream;
private Topology prequentialTopology;
private TopologyBuilder builder;
public void getDescription(StringBuilder sb, int indent) {
sb.append("Prequential evaluation");
}
@Override
public void init() {
// TODO remove the if statement
// theoretically, dynamic binding will work here!
// test later!
// for now, the if statement is used by Storm
if (builder == null) {
builder = new TopologyBuilder();
logger.debug("Successfully instantiating TopologyBuilder");
builder.initTopology(evaluationNameOption.getValue());
logger.debug("Successfully initializing SAMOA topology with name {}", evaluationNameOption.getValue());
}
// instantiate PrequentialSourceProcessor and its output stream
// (sourcePiOutputStream)
preqSource = new PrequentialSourceProcessor();
preqSource.setStreamSource((InstanceStream) this.streamTrainOption.getValue());
preqSource.setMaxNumInstances(instanceLimitOption.getValue());
preqSource.setSourceDelay(sourceDelayOption.getValue());
preqSource.setDelayBatchSize(batchDelayOption.getValue());
builder.addEntranceProcessor(preqSource);
logger.debug("Successfully instantiating PrequentialSourceProcessor");
// preqStarter = new PrequentialSourceTopologyStarter(preqSource,
// instanceLimitOption.getValue());
// sourcePi = builder.createEntrancePi(preqSource, preqStarter);
// sourcePiOutputStream = builder.createStream(sourcePi);
sourcePiOutputStream = builder.createStream(preqSource);
// preqStarter.setInputStream(sourcePiOutputStream);
// instantiate classifier and connect it to sourcePiOutputStream
classifier = this.learnerOption.getValue();
classifier.init(builder, preqSource.getDataset(), 1);
builder.connectInputShuffleStream(sourcePiOutputStream, classifier.getInputProcessor());
logger.debug("Successfully instantiating Classifier");
PerformanceEvaluator evaluatorOptionValue = this.evaluatorOption.getValue();
if (!PrequentialEvaluation.isLearnerAndEvaluatorCompatible(classifier, evaluatorOptionValue)) {
evaluatorOptionValue = getDefaultPerformanceEvaluatorForLearner(classifier);
}
evaluator = new EvaluatorProcessor.Builder(evaluatorOptionValue)
.samplingFrequency(sampleFrequencyOption.getValue()).dumpFile(dumpFileOption.getFile()).build();
// evaluatorPi = builder.createPi(evaluator);
// evaluatorPi.connectInputShuffleStream(evaluatorPiInputStream);
builder.addProcessor(evaluator);
for (Stream evaluatorPiInputStream : classifier.getResultStreams()) {
builder.connectInputShuffleStream(evaluatorPiInputStream, evaluator);
}
logger.debug("Successfully instantiating EvaluatorProcessor");
prequentialTopology = builder.build();
logger.debug("Successfully building the topology");
}
@Override
public void setFactory(ComponentFactory factory) {
// TODO unify this code with init()
// for now, it's used by S4 App
// dynamic binding theoretically will solve this problem
builder = new TopologyBuilder(factory);
logger.debug("Successfully instantiating TopologyBuilder");
builder.initTopology(evaluationNameOption.getValue());
logger.debug("Successfully initializing SAMOA topology with name {}", evaluationNameOption.getValue());
}
public Topology getTopology() {
return prequentialTopology;
}
//
// @Override
// public TopologyStarter getTopologyStarter() {
// return this.preqStarter;
// }
private static boolean isLearnerAndEvaluatorCompatible(Learner learner, PerformanceEvaluator evaluator) {
return (learner instanceof RegressionLearner && evaluator instanceof RegressionPerformanceEvaluator) ||
(learner instanceof ClassificationLearner && evaluator instanceof ClassificationPerformanceEvaluator);
}
private static PerformanceEvaluator getDefaultPerformanceEvaluatorForLearner(Learner learner) {
if (learner instanceof RegressionLearner) {
return new BasicRegressionPerformanceEvaluator();
}
// Default to BasicClassificationPerformanceEvaluator for all other cases
return new BasicClassificationPerformanceEvaluator();
}
}
| |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.plugin.weblogic;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.management.MBeanServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.hq.plugin.weblogic.jmx.ApplicationQuery;
import org.hyperic.hq.product.AutoServerDetector;
import org.hyperic.hq.product.ServerControlPlugin;
import org.hyperic.hq.product.ServerDetector;
import org.hyperic.hq.product.ServerResource;
import org.hyperic.hq.plugin.weblogic.jmx.NodeManagerQuery;
import org.hyperic.hq.plugin.weblogic.jmx.ServerQuery;
import org.hyperic.hq.plugin.weblogic.jmx.ServiceQuery;
import org.hyperic.hq.plugin.weblogic.jmx.WeblogicDiscover;
import org.hyperic.hq.plugin.weblogic.jmx.WeblogicDiscoverException;
import org.hyperic.hq.plugin.weblogic.jmx.WeblogicQuery;
import org.hyperic.hq.plugin.weblogic.jmx.WeblogicRuntimeDiscoverer;
import org.hyperic.hq.product.PluginException;
import org.hyperic.hq.product.RuntimeDiscoverer;
import org.hyperic.hq.product.ServiceResource;
import org.hyperic.util.config.ConfigResponse;
import org.hyperic.sigar.SigarException;
public abstract class WeblogicDetector extends ServerDetector implements AutoServerDetector {
private static final String PTQL_QUERY =
"State.Name.eq=java,Args.-1.eq=weblogic.Server";
private static final String SCRIPT_EXT =
isWin32() ? ".cmd" : ".sh";
private static final String ADMIN_START =
"startWebLogic" + SCRIPT_EXT;
public static final String NODE_START = "bin/startManagedWebLogic" + SCRIPT_EXT;
static final String PROP_MX_SERVER =
"-Dweblogic.management.server";
private static final Log log = LogFactory.getLog(WeblogicDetector.class);
public WeblogicDetector() {
super();
setName(WeblogicProductPlugin.SERVER_NAME);
}
@Override
public RuntimeDiscoverer getRuntimeDiscoverer() {
if(WeblogicProductPlugin.NEW_DISCOVERY){
return super.getRuntimeDiscoverer();
}
return new WeblogicRuntimeDiscoverer(this);
}
//just here to override protected access.
void adjustWeblogicClassPath(String installpath) {
adjustClassPath(installpath);
}
public List getServerResources(ConfigResponse platformConfig) throws PluginException {
getLog().debug("[getServerResources] platformConfig=" + platformConfig);
List servers = new ArrayList();
List<WLSProcWithPid> procs = getServerProcessList();
List s;
for (WLSProcWithPid proc : procs) {
try {
s = discoverServer(proc);
if (s != null) {
servers.addAll(s);
}
} catch (SigarException e) {
getLog().debug(e.getMessage(), e);
throw new PluginException(e);
} catch (PluginException ex) {
getLog().debug(ex.getMessage(), ex);
throw ex;
}
}
return servers;
}
private List discoverServer(WLSProcWithPid proc) throws PluginException, SigarException {
getLog().debug("Looking at: " + proc.getPath());
File installDir = new File(proc.getPath());
File configXML = new File(proc.getPath(), "config/config.xml");
if (!configXML.exists()) { //6.1
configXML = new File(proc.getPath(), "config.xml");
}
WeblogicConfig cfg = new WeblogicConfig();
try {
cfg.read(configXML);
} catch (IOException e) {
throw new PluginException("Failed to read " + configXML + ": " + e.getMessage(), e);
} catch (Exception e) {
throw new PluginException("Failed to parse " + configXML + ": " + e.getMessage(), e);
}
WeblogicConfig.Server srvConfig = cfg.getServer(proc.getName());
getLog().debug("srvConfig=" + srvConfig);
if (srvConfig == null) {
throw new PluginException("server '" + proc.getName() + "' not found in " + configXML);
}
if (getName().indexOf(srvConfig.getVersion()) < 0) {
getLog().debug("server '" + proc.getName() + " is not a " + getName());
return null;
}
ConfigResponse productConfig =
new ConfigResponse(srvConfig.getProperties());
String[] dirs = {
proc.getName(), //8.1
"logs", //9.1
};
File wlsLog = null;
for (int i = 0; i < dirs.length; i++) {
wlsLog =
new File(installDir,
dirs[i] + File.separator + proc.getName() + ".log");
if (wlsLog.exists()) {
break;
}
}
productConfig.setValue(WeblogicLogFileTrackPlugin.PROP_FILES_SERVER,
wlsLog.toString());
ConfigResponse controlConfig = new ConfigResponse();
File script = new File(installDir, "../../" + ADMIN_START);
try {
controlConfig.setValue(ServerControlPlugin.PROP_PROGRAM, script.getCanonicalPath());
} catch (IOException ex) {
controlConfig.setValue(ServerControlPlugin.PROP_PROGRAM, script.getPath());
getLog().debug(ex);
}
boolean hasCreds = false;
//for use w/ -jar hq-product.jar or agent.properties
Properties props = getManager().getProperties();
String[] credProps = {
WeblogicMetric.PROP_ADMIN_USERNAME,
WeblogicMetric.PROP_ADMIN_PASSWORD,
WeblogicMetric.PROP_ADMIN_URL,
WeblogicMetric.PROP_JVM,};
for (int i = 0; i < credProps.length; i++) {
String key = credProps[i];
//try both ${domain}.admin.url and admin.url
String val =
props.getProperty(srvConfig.domain + "." + key,
props.getProperty(key));
if (val != null) {
productConfig.setValue(key, val);
hasCreds = true;
} else {
hasCreds = false;
}
}
populateListeningPorts(proc.getPid(), productConfig, true);
if (getLog().isDebugEnabled()) {
getLog().debug(getName() + " config: " + productConfig);
}
String installpath = getCanonicalPath(installDir.getPath() + File.separator + "servers" + File.separator + srvConfig.name);
log.debug("[discoverServer] installDir=" + installDir);
log.debug("[discoverServer] installpath=" + installpath);
if (!new File(installpath).exists()) {
installpath = getCanonicalPath(installDir.getPath());
}
List servers = new ArrayList();
ServerResource server = createServerResource(installpath);
String name = getTypeInfo().getName()
+ " " + srvConfig.domain + " " + srvConfig.name;
if (WeblogicProductPlugin.usePlatformName && WeblogicProductPlugin.NEW_DISCOVERY) {
name = getPlatformName() + " " + name;
}
server.setName(name);
setIdentifier(server,name);
log.debug("[discoverServer] identifier=" + server.getIdentifier());
setProductConfig(server, productConfig);
setControlConfig(server, controlConfig);
//force user to configure by not setting measurement config
//since we dont discover username or password.
if (hasCreds) {
server.setMeasurementConfig();
}
servers.add(server);
installpath = getInstallRoot(installpath);
if (installpath != null) {
//handle the case where agent is started before WLS
adjustClassPath(installpath);
}
return servers;
}
private static boolean isAdminDir(String path) {
if (path.startsWith("/")) {
File config =
new File(path, "config.xml.booted");
return config.exists();
} else {
return false;
}
}
private List<WLSProcWithPid> getServerProcessList() {
ArrayList<WLSProcWithPid> servers = new ArrayList<WLSProcWithPid>();
long[] pids = getPids(PTQL_QUERY);
for (int i = 0; i < pids.length; i++) {
getLog().debug("pid = '" + pids[i] + "'");
String cwd = null;
String name = null;
String[] args = getProcArgs(pids[i]);
getLog().debug("[" + pids[i] + "] args = " + Arrays.asList(args));
if (isValidProc(args)) {
getLog().debug("[" + pids[i] + "] is valid");
try {
cwd = getSigar().getProcExe(pids[i]).getCwd();
} catch (SigarException e) {
getLog().debug("[" + pids[i] + "] Error getting process info, reason: '" + e.getMessage() + "'");
}
for (int j = 0; j < args.length; j++) {
String arg = args[j];
if (arg.startsWith("-Dweblogic.Name")) {
name = arg.substring(arg.indexOf("=") + 1).trim();
} else if ((cwd == null) && arg.startsWith("-D")) {
int ix = arg.indexOf("=");
if (ix != -1) {
String path = arg.substring(ix + 1).trim();
if (isAdminDir(path)) {
cwd = path;
}
}
}
}
getLog().debug("[" + pids[i] + "] cwd = '" + cwd + "' name = '" + name + "'");
if (cwd != null) {
servers.add(new WLSProcWithPid(cwd, name,pids[i]));
}
} else {
getLog().debug("[" + pids[i] + "] is not valid");
}
}
return servers;
}
public abstract boolean isValidProc(String[] args);
private static String getInstallRoot(String installpath) {
final String jar =
"server" + File.separator
+ "lib" + File.separator
+ "weblogic.jar";
File dir = new File(installpath);
while (dir != null) {
if (new File(dir, jar).exists()) {
return dir.getAbsolutePath();
}
dir = dir.getParentFile();
}
return null;
}
public static String getRunningInstallPath() {
String installpath = null;
long[] pids = getPids(PTQL_QUERY);
for (int i = 0; i < pids.length; i++) {
String[] args = getProcArgs(pids[i]);
for (int j = 1; j < args.length; j++) {
String arg = args[j];
if (arg.startsWith("-D")) {
//e.g. -Dplatform.home=$PWD
int ix = arg.indexOf("=");
if (ix == -1) {
continue;
}
//e.g. 6.1 petstore is -Djava.security.policy==...
if (arg.startsWith("=")) {
arg = arg.substring(1, arg.length());
}
arg = arg.substring(ix + 1).trim();
if (!new File(arg).exists()) {
continue;
}
} else {
continue;
}
installpath = getInstallRoot(arg);
if (installpath != null) {
log.debug(WeblogicProductPlugin.PROP_INSTALLPATH + "="
+ installpath + " (derived from " + args[j] + ")");
break;
}
}
}
return installpath;
}
@Override
protected List discoverServices(ConfigResponse config) throws PluginException {
getLog().debug("[discoverServices] config=" + config);
List services = new ArrayList();
List aServices = new ArrayList();
try {
WeblogicDiscover discover = new WeblogicDiscover(getTypeInfo().getVersion(), config.toProperties());
MBeanServer mServer = discover.getMBeanServer();
discover.init(mServer);
NodeManagerQuery nodemgrQuery = new NodeManagerQuery();
ServerQuery serverQuery = new ServerQuery();
serverQuery.setDiscover(discover);
serverQuery.setName(config.getValue("server"));
ArrayList servers = new ArrayList();
discover.find(mServer, serverQuery, servers);
WeblogicQuery[] serviceQueries = discover.getServiceQueries();
for (int j = 0; j < serviceQueries.length; j++) {
WeblogicQuery serviceQuery = serviceQueries[j];
serviceQuery.setParent(serverQuery);
serviceQuery.setVersion(serverQuery.getVersion());
discover.find(mServer, serviceQuery, services);
}
for (int k = 0; k < services.size(); k++) {
boolean valid = true;
ServiceQuery service = (ServiceQuery) services.get(k);
if (service instanceof ApplicationQuery) {
valid = ((ApplicationQuery) service).isEAR();
}
if (valid) {
aServices.add(generateService(service));
} else {
log.debug("skipped service:" + service.getName());
}
}
} catch (WeblogicDiscoverException ex) {
getLog().debug(ex.getMessage(), ex);
}
return aServices;
}
public static ServiceResource generateService(ServiceQuery service) throws PluginException {
ServiceResource aiservice = new ServiceResource();
ConfigResponse productConfig = new ConfigResponse(service.getResourceConfig());
ConfigResponse metricConfig = new ConfigResponse();
ConfigResponse cprops = new ConfigResponse(service.getCustomProperties());
String notes = service.getDescription();
if (notes != null) {
aiservice.setDescription(notes);
}
aiservice.setType(service.getResourceName());
String name = service.getResourceFullName();
// if (usePlatformName) {
// name = GenericPlugin.getPlatformName() + " " + name;
// }
if (name.length() >= 200) {
// make sure we dont exceed service name limit
name = name.substring(0, 199);
}
aiservice.setName(name);
if (service.hasControl() && !service.isServer61()) {
ConfigResponse controlConfig = new ConfigResponse(service.getControlConfig());
aiservice.setControlConfig(controlConfig);
}
aiservice.setProductConfig(productConfig);
aiservice.setMeasurementConfig(metricConfig);
aiservice.setCustomProperties(cprops);
if (service.hasResponseTime()) {
ConfigResponse rtConfig = new ConfigResponse(service.getResponseTimeConfig());
aiservice.setResponseTimeConfig(rtConfig);
}
log.debug("discovered service: " + aiservice.getName());
return aiservice;
}
abstract void setIdentifier(ServerResource server, String name);
public class WLSProc {
private String path;
private String name;
public WLSProc(String path, String name) {
this.path = path;
this.name = name;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
protected class WLSProcWithPid extends WLSProc {
public WLSProcWithPid(String path, String name, long pid) {
super(path, name);
this.pid = pid;
}
public long getPid() {
return pid;
}
public void setPid(long pid) {
this.pid = pid;
}
protected long pid;
}
private void populateListeningPorts(long pid, ConfigResponse productConfig, boolean b) {
try {
Class du = Class.forName("org.hyperic.hq.product.DetectionUtil");
Method plp = du.getMethod("populateListeningPorts", long.class, ConfigResponse.class, boolean.class);
plp.invoke(null, pid, productConfig, b);
} catch (ClassNotFoundException ex) {
log.debug("[populateListeningPorts] Class 'DetectionUtil' not found", ex);
} catch (NoSuchMethodException ex) {
log.debug("[populateListeningPorts] Method 'populateListeningPorts' not found", ex);
} catch (Exception ex) {
log.debug("[populateListeningPorts] Problem with Method 'populateListeningPorts'", ex);
}
}
}
| |
/*
* Copyright (C) 2011 The Guava 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 com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.util.Comparator;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A generalized interval on any ordering, for internal use. Supports {@code null}. Unlike {@link
* Range}, this allows the use of an arbitrary comparator. This is designed for use in the
* implementation of subcollections of sorted collection types.
*
* <p>Whenever possible, use {@code Range} instead, which is better supported.
*
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
@ElementTypesAreNonnullByDefault
final class GeneralRange<T extends @Nullable Object> implements Serializable {
/** Converts a Range to a GeneralRange. */
static <T extends Comparable> GeneralRange<T> from(Range<T> range) {
T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null;
BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN;
T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null;
BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN;
return new GeneralRange<>(
Ordering.natural(),
range.hasLowerBound(),
lowerEndpoint,
lowerBoundType,
range.hasUpperBound(),
upperEndpoint,
upperBoundType);
}
/** Returns the whole range relative to the specified comparator. */
static <T extends @Nullable Object> GeneralRange<T> all(Comparator<? super T> comparator) {
return new GeneralRange<>(comparator, false, null, OPEN, false, null, OPEN);
}
/**
* Returns everything above the endpoint relative to the specified comparator, with the specified
* endpoint behavior.
*/
static <T extends @Nullable Object> GeneralRange<T> downTo(
Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) {
return new GeneralRange<>(comparator, true, endpoint, boundType, false, null, OPEN);
}
/**
* Returns everything below the endpoint relative to the specified comparator, with the specified
* endpoint behavior.
*/
static <T extends @Nullable Object> GeneralRange<T> upTo(
Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) {
return new GeneralRange<>(comparator, false, null, OPEN, true, endpoint, boundType);
}
/**
* Returns everything between the endpoints relative to the specified comparator, with the
* specified endpoint behavior.
*/
static <T extends @Nullable Object> GeneralRange<T> range(
Comparator<? super T> comparator,
@ParametricNullness T lower,
BoundType lowerType,
@ParametricNullness T upper,
BoundType upperType) {
return new GeneralRange<>(comparator, true, lower, lowerType, true, upper, upperType);
}
private final Comparator<? super T> comparator;
private final boolean hasLowerBound;
@CheckForNull private final T lowerEndpoint;
private final BoundType lowerBoundType;
private final boolean hasUpperBound;
@CheckForNull private final T upperEndpoint;
private final BoundType upperBoundType;
private GeneralRange(
Comparator<? super T> comparator,
boolean hasLowerBound,
@CheckForNull T lowerEndpoint,
BoundType lowerBoundType,
boolean hasUpperBound,
@CheckForNull T upperEndpoint,
BoundType upperBoundType) {
this.comparator = checkNotNull(comparator);
this.hasLowerBound = hasLowerBound;
this.hasUpperBound = hasUpperBound;
this.lowerEndpoint = lowerEndpoint;
this.lowerBoundType = checkNotNull(lowerBoundType);
this.upperEndpoint = upperEndpoint;
this.upperBoundType = checkNotNull(upperBoundType);
// Trigger any exception that the comparator would throw for the endpoints.
/*
* uncheckedCastNullableTToT is safe as long as the callers are careful to pass a "real" T
* whenever they pass `true` for the matching `has*Bound` parameter.
*/
if (hasLowerBound) {
comparator.compare(
uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint));
}
if (hasUpperBound) {
comparator.compare(
uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint));
}
if (hasLowerBound && hasUpperBound) {
int cmp =
comparator.compare(
uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(upperEndpoint));
// be consistent with Range
checkArgument(
cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint);
if (cmp == 0) {
checkArgument(lowerBoundType != OPEN || upperBoundType != OPEN);
}
}
}
Comparator<? super T> comparator() {
return comparator;
}
boolean hasLowerBound() {
return hasLowerBound;
}
boolean hasUpperBound() {
return hasUpperBound;
}
boolean isEmpty() {
// The casts are safe because of the has*Bound() checks.
return (hasUpperBound() && tooLow(uncheckedCastNullableTToT(getUpperEndpoint())))
|| (hasLowerBound() && tooHigh(uncheckedCastNullableTToT(getLowerEndpoint())));
}
boolean tooLow(@ParametricNullness T t) {
if (!hasLowerBound()) {
return false;
}
// The cast is safe because of the hasLowerBound() check.
T lbound = uncheckedCastNullableTToT(getLowerEndpoint());
int cmp = comparator.compare(t, lbound);
return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN);
}
boolean tooHigh(@ParametricNullness T t) {
if (!hasUpperBound()) {
return false;
}
// The cast is safe because of the hasUpperBound() check.
T ubound = uncheckedCastNullableTToT(getUpperEndpoint());
int cmp = comparator.compare(t, ubound);
return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN);
}
boolean contains(@ParametricNullness T t) {
return !tooLow(t) && !tooHigh(t);
}
/**
* Returns the intersection of the two ranges, or an empty range if their intersection is empty.
*/
@SuppressWarnings("nullness") // TODO(cpovirk): Add casts as needed. Will be noisy and annoying...
GeneralRange<T> intersect(GeneralRange<T> other) {
checkNotNull(other);
checkArgument(comparator.equals(other.comparator));
boolean hasLowBound = this.hasLowerBound;
T lowEnd = getLowerEndpoint();
BoundType lowType = getLowerBoundType();
if (!hasLowerBound()) {
hasLowBound = other.hasLowerBound;
lowEnd = other.getLowerEndpoint();
lowType = other.getLowerBoundType();
} else if (other.hasLowerBound()) {
int cmp = comparator.compare(getLowerEndpoint(), other.getLowerEndpoint());
if (cmp < 0 || (cmp == 0 && other.getLowerBoundType() == OPEN)) {
lowEnd = other.getLowerEndpoint();
lowType = other.getLowerBoundType();
}
}
boolean hasUpBound = this.hasUpperBound;
T upEnd = getUpperEndpoint();
BoundType upType = getUpperBoundType();
if (!hasUpperBound()) {
hasUpBound = other.hasUpperBound;
upEnd = other.getUpperEndpoint();
upType = other.getUpperBoundType();
} else if (other.hasUpperBound()) {
int cmp = comparator.compare(getUpperEndpoint(), other.getUpperEndpoint());
if (cmp > 0 || (cmp == 0 && other.getUpperBoundType() == OPEN)) {
upEnd = other.getUpperEndpoint();
upType = other.getUpperBoundType();
}
}
if (hasLowBound && hasUpBound) {
int cmp = comparator.compare(lowEnd, upEnd);
if (cmp > 0 || (cmp == 0 && lowType == OPEN && upType == OPEN)) {
// force allowed empty range
lowEnd = upEnd;
lowType = OPEN;
upType = CLOSED;
}
}
return new GeneralRange<>(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType);
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof GeneralRange) {
GeneralRange<?> r = (GeneralRange<?>) obj;
return comparator.equals(r.comparator)
&& hasLowerBound == r.hasLowerBound
&& hasUpperBound == r.hasUpperBound
&& getLowerBoundType().equals(r.getLowerBoundType())
&& getUpperBoundType().equals(r.getUpperBoundType())
&& Objects.equal(getLowerEndpoint(), r.getLowerEndpoint())
&& Objects.equal(getUpperEndpoint(), r.getUpperEndpoint());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(
comparator,
getLowerEndpoint(),
getLowerBoundType(),
getUpperEndpoint(),
getUpperBoundType());
}
@CheckForNull private transient GeneralRange<T> reverse;
/** Returns the same range relative to the reversed comparator. */
GeneralRange<T> reverse() {
GeneralRange<T> result = reverse;
if (result == null) {
result =
new GeneralRange<>(
Ordering.from(comparator).reverse(),
hasUpperBound,
getUpperEndpoint(),
getUpperBoundType(),
hasLowerBound,
getLowerEndpoint(),
getLowerBoundType());
result.reverse = this;
return this.reverse = result;
}
return result;
}
@Override
public String toString() {
return comparator
+ ":"
+ (lowerBoundType == CLOSED ? '[' : '(')
+ (hasLowerBound ? lowerEndpoint : "-\u221e")
+ ','
+ (hasUpperBound ? upperEndpoint : "\u221e")
+ (upperBoundType == CLOSED ? ']' : ')');
}
@CheckForNull
T getLowerEndpoint() {
return lowerEndpoint;
}
BoundType getLowerBoundType() {
return lowerBoundType;
}
@CheckForNull
T getUpperEndpoint() {
return upperEndpoint;
}
BoundType getUpperBoundType() {
return upperBoundType;
}
}
| |
package com.grunzke.tmprof;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.grunzke.tmprof.json.OptionsDeserializer;
import com.grunzke.tmprof.json.PlayerDeserializer;
import com.grunzke.tmprof.json.RaceDeserializer;
import com.grunzke.tmprof.json.RatingDeserializer;
public enum Ratings
{
INSTANCE;
private Map<String, Integer> ratings;
private Ratings()
{
ratings = new RatingDeserializer().read();
}
private void manualInit()
{
ratings.put("Xevoc", 1617);
ratings.put("mikaeljt", 1532);
ratings.put("demiurgsage", 1455);
ratings.put("bjolletz", 1447);
ratings.put("Fujiwara", 1443);
ratings.put("sprockitz", 1438);
ratings.put("Isobanaani", 1423);
ratings.put("Glenw", 1421);
ratings.put("le_asmo", 1412);
ratings.put("shanarkoh", 1409);
ratings.put("eephus", 1406);
ratings.put("marksickau", 1406);
ratings.put("Kin", 1400);
ratings.put("JonasD", 1397);
ratings.put("Pattern", 1397);
ratings.put("Romma", 1397);
ratings.put("Halskov", 1395);
ratings.put("toine", 1395);
ratings.put("c.love", 1387);
ratings.put("Thrar", 1384);
ratings.put("loike", 1384);
ratings.put("UOP_Champ", 1377);
ratings.put("koishi", 1373);
ratings.put("Elsuprimo", 1372);
ratings.put("eliegel", 1372);
ratings.put("Machiavelli", 1366);
ratings.put("BlueSteel", 1364);
ratings.put("retardedonkey", 1362);
ratings.put("Pelly", 1362);
ratings.put("eunck", 1361);
ratings.put("dgrazian", 1360);
ratings.put("TerraTurtle", 1360);
ratings.put("Gr3n", 1359);
ratings.put("Tawy", 1357);
ratings.put("allstar64", 1355);
ratings.put("akio", 1353);
ratings.put("jbrier", 1352);
ratings.put("Stones", 1352);
ratings.put("Ladinek", 1342);
ratings.put("jsnell", 1341);
ratings.put("LoloHelico", 1340);
ratings.put("mrfister69", 1340);
ratings.put("kikoho", 1339);
ratings.put("Isawa", 1338);
ratings.put("koleman2", 1336);
ratings.put("Mb", 1334);
ratings.put("MangeUnDindon", 1334);
ratings.put("koko615615", 1333);
ratings.put("ghostofmars", 1331);
ratings.put("Thargor", 1331);
ratings.put("SpaceTrucker", 1329);
ratings.put("Devak", 1329);
ratings.put("Roestertaube", 1329);
ratings.put("Riku", 1325);
ratings.put("KorKronus", 1325);
ratings.put("blastoch", 1325);
ratings.put("wArLoRd", 1325);
ratings.put("Stefan", 1324);
ratings.put("WOH_G64", 1324);
ratings.put("VHOORLYS", 1323);
ratings.put("Chmol", 1322);
ratings.put("wolfox", 1320);
ratings.put("watt89", 1317);
ratings.put("Yvon", 1316);
ratings.put("konush", 1315);
ratings.put("BLEE", 1315);
ratings.put("ararar", 1314);
ratings.put("GoddamnBF", 1313);
ratings.put("Jai", 1312);
ratings.put("zander", 1309);
ratings.put("Artwo", 1307);
ratings.put("onesones", 1307);
ratings.put("Silberklinge", 1305);
ratings.put("rafalimaz", 1305);
ratings.put("CTKShadow", 1304);
ratings.put("Noctua", 1303);
ratings.put("dasala", 1300);
ratings.put("asymptotech", 1299);
ratings.put("Cephalofair", 1299);
ratings.put("LaQuille", 1299);
ratings.put("rainbowjoe", 1298);
ratings.put("Vazoun", 1297);
ratings.put("affe1982", 1295);
ratings.put("veenickz", 1287);
ratings.put("keeefir", 1287);
ratings.put("rasberry", 1285);
ratings.put("Shardan", 1284);
ratings.put("tori", 1284);
ratings.put("BattleToads", 1283);
ratings.put("yamamoto", 1280);
ratings.put("Schummel", 1279);
ratings.put("hussai", 1278);
ratings.put("Given", 1278);
ratings.put("yuta", 1277);
ratings.put("victori", 1276);
ratings.put("arthur", 1276);
ratings.put("csander1", 1276);
ratings.put("entaku_p", 1275);
ratings.put("Pesto", 1274);
ratings.put("Rafael.Ramus", 1273);
ratings.put("kitty", 1273);
ratings.put("rajeevbat", 1273);
ratings.put("Alex", 1272);
ratings.put("gremar", 1272);
ratings.put("Fortuna", 1272);
ratings.put("M3lchior", 1272);
ratings.put("schloetterer", 1271);
ratings.put("ansonkit", 1271);
ratings.put("Nocturne", 1270);
ratings.put("nightlark7", 1270);
ratings.put("Morat", 1269);
ratings.put("mbsp", 1265);
ratings.put("jimh", 1264);
ratings.put("leesa", 1264);
ratings.put("JJape", 1264);
ratings.put("Brokastis.Sampionis", 1264);
ratings.put("fuguta", 1263);
ratings.put("surpriz3", 1262);
ratings.put("pyhuang", 1262);
ratings.put("PerOlander", 1261);
ratings.put("bassano", 1257);
ratings.put("Niccolo", 1257);
ratings.put("rabbit19", 1256);
ratings.put("mnkymn08", 1255);
ratings.put("no_dice", 1255);
ratings.put("Brent", 1254);
ratings.put("ttchong", 1252);
ratings.put("Orni", 1252);
ratings.put("eMps", 1252);
ratings.put("ashallue", 1251);
ratings.put("Dirrtymagic", 1250);
ratings.put("Chili", 1250);
ratings.put("otomedi", 1250);
ratings.put("GrandAt", 1249);
ratings.put("weichieh1982", 1249);
ratings.put("lsy03", 1248);
ratings.put("Fiitsch", 1247);
ratings.put("froggy", 1247);
ratings.put("zhenzhm4", 1246);
ratings.put("lcg3092", 1246);
ratings.put("armaddon", 1245);
ratings.put("brain_cloud", 1244);
ratings.put("eingewinner", 1244);
ratings.put("Salokin", 1244);
ratings.put("qqzm", 1244);
ratings.put("VG715", 1244);
ratings.put("Cortzas", 1243);
ratings.put("wackforce", 1243);
ratings.put("bjcowen", 1242);
ratings.put("gnpaolo", 1240);
ratings.put("Trantor", 1240);
ratings.put("Dashmudtz", 1240);
ratings.put("kruppy", 1239);
ratings.put("sunny", 1239);
ratings.put("Toshimoko", 1239);
ratings.put("silent", 1237);
ratings.put("shutzy", 1237);
ratings.put("moira", 1237);
ratings.put("Olli", 1237);
ratings.put("Jayne", 1236);
ratings.put("Fluxx", 1236);
ratings.put("grosiu", 1236);
ratings.put("CatMac", 1235);
ratings.put("OrionHegenomy", 1234);
ratings.put("itzamna", 1233);
ratings.put("AnythingForMarcello", 1233);
ratings.put("kahy", 1233);
ratings.put("frankchow", 1232);
ratings.put("jaen", 1232);
ratings.put("Lightblade", 1231);
ratings.put("mirumoto", 1230);
ratings.put("miked1991", 1229);
ratings.put("foxtrot2620", 1229);
ratings.put("Fatcat", 1229);
ratings.put("WarShoe", 1229);
ratings.put("paschlewwer", 1229);
ratings.put("broche", 1229);
ratings.put("bpt", 1229);
ratings.put("prodigaldax", 1229);
ratings.put("bartdevos", 1228);
ratings.put("Wildfighter", 1228);
ratings.put("gpchurchill", 1228);
ratings.put("Brains-on-ice", 1228);
ratings.put("mav", 1228);
ratings.put("magnusrk", 1227);
ratings.put("Rungan", 1227);
ratings.put("j.madrjas", 1227);
ratings.put("grant5", 1227);
ratings.put("Khal", 1227);
ratings.put("DrHades", 1225);
ratings.put("Sarquer", 1225);
ratings.put("cletus", 1225);
ratings.put("daddybear", 1225);
ratings.put("linsson", 1224);
ratings.put("sasin", 1223);
ratings.put("atreyu26", 1220);
ratings.put("Jan", 1220);
ratings.put("ShevekDelphy", 1219);
ratings.put("Geekinker", 1219);
ratings.put("Nerkatel", 1219);
ratings.put("terrarist", 1219);
ratings.put("analemma2345", 1219);
ratings.put("battleffs", 1219);
ratings.put("Jari", 1218);
ratings.put("TockTock", 1217);
ratings.put("DamageINC", 1217);
ratings.put("harubz", 1216);
ratings.put("mtanzer", 1216);
ratings.put("Sir_Gawain", 1215);
ratings.put("mjmassi", 1215);
ratings.put("BravePawn", 1213);
ratings.put("criadepaloma", 1213);
ratings.put("Qatol", 1212);
ratings.put("melendor", 1212);
ratings.put("Vilgan", 1212);
ratings.put("toucan13", 1211);
ratings.put("slugi", 1211);
ratings.put("itcouldbewirfs", 1209);
ratings.put("noelgames", 1209);
ratings.put("sense-", 1208);
ratings.put("hchao", 1208);
ratings.put("spitball", 1207);
ratings.put("randomuser", 1207);
ratings.put("robinz", 1206);
ratings.put("Koronin", 1206);
ratings.put("dingbat", 1206);
ratings.put("mahiru00", 1206);
ratings.put("Emily97", 1205);
ratings.put("yopd", 1205);
ratings.put("tasso_zh", 1205);
ratings.put("Chio", 1204);
ratings.put("enkidu", 1203);
ratings.put("telipych", 1203);
ratings.put("tucnak64", 1200);
ratings.put("Dinandino", 1200);
ratings.put("Skopajz", 1200);
ratings.put("clark.millikan", 1199);
ratings.put("Thefeds", 1199);
ratings.put("reggie79", 1198);
ratings.put("QBert", 1198);
ratings.put("Rabbits", 1198);
ratings.put("TwitchBot", 1197);
ratings.put("slapp", 1197);
ratings.put("ktk", 1197);
ratings.put("Herracek", 1196);
ratings.put("Mirror", 1196);
ratings.put("keiis", 1196);
ratings.put("mikezehnal", 1196);
ratings.put("grecocha", 1196);
ratings.put("Leco", 1195);
}
public Integer getRating(String player)
{
Integer r = ratings.get(player);
return r==null ? 0 : r;
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.annotate;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.AnnotationTooltipBuilder;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.annotate.LineAnnotationAspect;
import com.intellij.openapi.vcs.annotate.LineAnnotationAspectAdapter;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.history.VcsFileRevision;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.impl.AbstractVcsHelperImpl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.concurrency.EdtExecutorService;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsUser;
import com.intellij.vcs.log.impl.*;
import com.intellij.vcs.log.util.VcsUserUtil;
import com.intellij.vcsUtil.VcsUtil;
import git4idea.GitContentRevision;
import git4idea.GitFileRevision;
import git4idea.GitRevisionNumber;
import git4idea.GitVcs;
import git4idea.changes.GitCommittedChangeList;
import git4idea.changes.GitCommittedChangeListProvider;
import git4idea.log.GitCommitTooltipLinkHandler;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public final class GitFileAnnotation extends FileAnnotation {
private final Project myProject;
@NotNull private final VirtualFile myFile;
@NotNull private final FilePath myFilePath;
@NotNull private final GitVcs myVcs;
@Nullable private final VcsRevisionNumber myBaseRevision;
@NotNull private final List<LineInfo> myLines;
@Nullable private List<VcsFileRevision> myRevisions;
@Nullable private Object2IntMap<VcsRevisionNumber> myRevisionMap;
@NotNull private final Map<VcsRevisionNumber, String> myCommitMessageMap = new HashMap<>();
private final VcsLogApplicationSettings myLogSettings = ApplicationManager.getApplication().getService(VcsLogApplicationSettings.class);
private final LineAnnotationAspect DATE_ASPECT =
new GitAnnotationAspect(LineAnnotationAspect.DATE, VcsBundle.message("line.annotation.aspect.date"), true) {
@Override
public String doGetValue(LineInfo info) {
Date date = getDate(info);
return FileAnnotation.formatDate(date);
}
};
private final LineAnnotationAspect REVISION_ASPECT =
new GitAnnotationAspect(LineAnnotationAspect.REVISION, VcsBundle.message("line.annotation.aspect.revision"), false) {
@Override
protected String doGetValue(LineInfo lineInfo) {
return lineInfo.getRevisionNumber().getShortRev();
}
};
private final LineAnnotationAspect AUTHOR_ASPECT =
new GitAnnotationAspect(LineAnnotationAspect.AUTHOR, VcsBundle.message("line.annotation.aspect.author"), true) {
@Override
protected String doGetValue(LineInfo lineInfo) {
return VcsUserUtil.toExactString(lineInfo.getAuthorUser());
}
};
private final VcsLogUiProperties.PropertiesChangeListener myLogSettingChangeListener = this::onLogSettingChange;
public GitFileAnnotation(@NotNull Project project,
@NotNull VirtualFile file,
@Nullable VcsRevisionNumber revision,
@NotNull List<LineInfo> lines) {
super(project);
myProject = project;
myFile = file;
myFilePath = VcsUtil.getFilePath(file);
myVcs = GitVcs.getInstance(myProject);
myBaseRevision = revision;
myLines = lines;
myLogSettings.addChangeListener(myLogSettingChangeListener);
}
public <T> void onLogSettingChange(@NotNull VcsLogUiProperties.VcsLogUiProperty<T> property) {
if (property.equals(CommonUiProperties.PREFER_COMMIT_DATE)) {
reload(null);
}
}
public GitFileAnnotation(@NotNull GitFileAnnotation annotation) {
this(annotation.getProject(), annotation.getFile(), annotation.getCurrentRevision(), annotation.getLines());
}
@Override
public void dispose() {
myLogSettings.removeChangeListener(myLogSettingChangeListener);
}
@Override
public LineAnnotationAspect @NotNull [] getAspects() {
return new LineAnnotationAspect[]{REVISION_ASPECT, DATE_ASPECT, AUTHOR_ASPECT};
}
@NotNull
private Date getDate(LineInfo info) {
return Boolean.TRUE.equals(myLogSettings.get(CommonUiProperties.PREFER_COMMIT_DATE)) ? info.getCommitterDate() : info.getAuthorDate();
}
@Nullable
@Override
public String getAnnotatedContent() {
try {
ContentRevision revision = GitContentRevision.createRevision(myFilePath, myBaseRevision, myProject);
return revision.getContent();
}
catch (VcsException e) {
return null;
}
}
@Nullable
@Override
public List<VcsFileRevision> getRevisions() {
return myRevisions;
}
public void setRevisions(@NotNull List<VcsFileRevision> revisions) {
myRevisions = revisions;
myRevisionMap = new Object2IntOpenHashMap<>();
for (int i = 0; i < myRevisions.size(); i++) {
myRevisionMap.put(myRevisions.get(i).getRevisionNumber(), i);
}
}
public void setCommitMessage(@NotNull VcsRevisionNumber revisionNumber, @NotNull String message) {
myCommitMessageMap.put(revisionNumber, message);
}
@Override
public int getLineCount() {
return myLines.size();
}
@Nullable
public LineInfo getLineInfo(int lineNumber) {
if (lineNumberCheck(lineNumber)) return null;
return myLines.get(lineNumber);
}
@NlsContexts.Tooltip
@Nullable
@Override
public String getToolTip(int lineNumber) {
return getToolTip(lineNumber, false);
}
@NlsContexts.Tooltip
@Nullable
@Override
public String getHtmlToolTip(int lineNumber) {
return getToolTip(lineNumber, true);
}
@NlsContexts.Tooltip
@Nullable
private String getToolTip(int lineNumber, boolean asHtml) {
LineInfo lineInfo = getLineInfo(lineNumber);
if (lineInfo == null) return null;
AnnotationTooltipBuilder atb = new AnnotationTooltipBuilder(myProject, asHtml);
GitRevisionNumber revisionNumber = lineInfo.getRevisionNumber();
atb.appendRevisionLine(revisionNumber, it -> GitCommitTooltipLinkHandler.createLink(it.asString(), it));
atb.appendLine(VcsBundle.message("commit.description.tooltip.author", VcsUserUtil.toExactString(lineInfo.getAuthorUser())));
atb.appendLine(VcsBundle.message("commit.description.tooltip.date", DateFormatUtil.formatDateTime(getDate(lineInfo))));
if (!myFilePath.equals(lineInfo.getFilePath())) {
String path = FileUtil.getLocationRelativeToUserHome(lineInfo.getFilePath().getPresentableUrl());
atb.appendLine(VcsBundle.message("commit.description.tooltip.path", path));
}
String commitMessage = getCommitMessage(revisionNumber);
if (commitMessage == null) commitMessage = lineInfo.getSubject() + "\n...";
atb.appendCommitMessageBlock(commitMessage);
return atb.toString();
}
@NlsSafe
@Nullable
public String getCommitMessage(@NotNull VcsRevisionNumber revisionNumber) {
if (myRevisions != null && myRevisionMap != null &&
myRevisionMap.containsKey(revisionNumber)) {
VcsFileRevision fileRevision = myRevisions.get(myRevisionMap.getInt(revisionNumber));
return fileRevision.getCommitMessage();
}
return myCommitMessageMap.get(revisionNumber);
}
@Nullable
@Override
public VcsRevisionNumber getLineRevisionNumber(int lineNumber) {
LineInfo lineInfo = getLineInfo(lineNumber);
return lineInfo != null ? lineInfo.getRevisionNumber() : null;
}
@Nullable
@Override
public Date getLineDate(int lineNumber) {
LineInfo lineInfo = getLineInfo(lineNumber);
return lineInfo != null ? getDate(lineInfo) : null;
}
private boolean lineNumberCheck(int lineNumber) {
return myLines.size() <= lineNumber || lineNumber < 0;
}
@NotNull
public List<LineInfo> getLines() {
return myLines;
}
/**
* Revision annotation aspect implementation
*/
private abstract class GitAnnotationAspect extends LineAnnotationAspectAdapter {
GitAnnotationAspect(@NonNls String id, @NlsContexts.ListItem String displayName, boolean showByDefault) {
super(id, displayName, showByDefault);
}
@Override
public String getValue(int lineNumber) {
if (lineNumberCheck(lineNumber)) {
return "";
}
else {
return doGetValue(myLines.get(lineNumber));
}
}
protected abstract String doGetValue(LineInfo lineInfo);
@Override
protected void showAffectedPaths(int lineNum) {
if (lineNum >= 0 && lineNum < myLines.size()) {
LineInfo info = myLines.get(lineNum);
VirtualFile root = ProjectLevelVcsManager.getInstance(myProject).getVcsRootFor(myFilePath);
if (root == null) return;
CompletableFuture<Boolean> shownInLog;
if (ModalityState.current() == ModalityState.NON_MODAL &&
Registry.is("vcs.blame.show.affected.files.in.log")) {
Hash hash = HashImpl.build(info.getRevisionNumber().asString());
shownInLog = VcsLogNavigationUtil.jumpToRevisionAsync(myProject, root, hash, info.getFilePath());
}
else {
shownInLog = CompletableFuture.completedFuture(false); // can't use log tabs in modal dialogs (ex: commit, merge)
}
shownInLog.thenAcceptAsync(success -> {
if (!success) {
AbstractVcsHelperImpl.loadAndShowCommittedChangesDetails(myProject, info.getRevisionNumber(), myFilePath, false,
() -> getRevisionsChangesProvider().getChangesIn(lineNum));
}
}, EdtExecutorService.getInstance());
}
}
}
static class CommitInfo {
@NotNull private final Project myProject;
@NotNull private final GitRevisionNumber myRevision;
@NotNull private final FilePath myFilePath;
@Nullable private final GitRevisionNumber myPreviousRevision;
@Nullable private final FilePath myPreviousFilePath;
@NotNull private final Date myCommitterDate;
@NotNull private final Date myAuthorDate;
@NotNull private final VcsUser myAuthor;
@NotNull private final String mySubject;
CommitInfo(@NotNull Project project,
@NotNull GitRevisionNumber revision,
@NotNull FilePath path,
@NotNull Date committerDate,
@NotNull Date authorDate,
@NotNull VcsUser author,
@NotNull String subject,
@Nullable GitRevisionNumber previousRevision,
@Nullable FilePath previousPath) {
myProject = project;
myRevision = revision;
myFilePath = path;
myPreviousRevision = previousRevision;
myPreviousFilePath = previousPath;
myCommitterDate = committerDate;
myAuthorDate = authorDate;
myAuthor = author;
mySubject = subject;
}
@NotNull
public GitRevisionNumber getRevisionNumber() {
return myRevision;
}
@NotNull
public FilePath getFilePath() {
return myFilePath;
}
@NotNull
public VcsFileRevision getFileRevision() {
return new GitFileRevision(myProject, myFilePath, myRevision);
}
@Nullable
public VcsFileRevision getPreviousFileRevision() {
if (myPreviousRevision == null || myPreviousFilePath == null) return null;
return new GitFileRevision(myProject, myPreviousFilePath, myPreviousRevision);
}
@NotNull
public Date getCommitterDate() {
return myCommitterDate;
}
@NotNull
public Date getAuthorDate() {
return myAuthorDate;
}
@NotNull
public @Nls String getAuthor() {
return myAuthor.getName();
}
@NotNull
public VcsUser getAuthorUser() {
return myAuthor;
}
@NotNull
public @Nls String getSubject() {
return mySubject;
}
}
public static class LineInfo {
@NotNull private final CommitInfo myCommitInfo;
private final int myLineNumber;
private final int myOriginalLineNumber;
LineInfo(@NotNull CommitInfo commitInfo, int lineNumber, int originalLineNumber) {
this.myCommitInfo = commitInfo;
this.myLineNumber = lineNumber;
this.myOriginalLineNumber = originalLineNumber;
}
public int getLineNumber() {
return myLineNumber;
}
public int getOriginalLineNumber() {
return myOriginalLineNumber;
}
@NotNull
public GitRevisionNumber getRevisionNumber() {
return myCommitInfo.getRevisionNumber();
}
@NotNull
public FilePath getFilePath() {
return myCommitInfo.getFilePath();
}
@NotNull
public VcsFileRevision getFileRevision() {
return myCommitInfo.getFileRevision();
}
@Nullable
public VcsFileRevision getPreviousFileRevision() {
return myCommitInfo.getPreviousFileRevision();
}
@NotNull
public Date getCommitterDate() {
return myCommitInfo.getCommitterDate();
}
@NotNull
public Date getAuthorDate() {
return myCommitInfo.getAuthorDate();
}
@NotNull
public @Nls String getAuthor() {
return myCommitInfo.getAuthor();
}
@NotNull
public VcsUser getAuthorUser() {
return myCommitInfo.getAuthorUser();
}
@NlsSafe
@NotNull
public String getSubject() {
return myCommitInfo.getSubject();
}
}
@NotNull
@Override
public VirtualFile getFile() {
return myFile;
}
@Nullable
@Override
public VcsRevisionNumber getCurrentRevision() {
return myBaseRevision;
}
@Override
public VcsKey getVcsKey() {
return GitVcs.getKey();
}
@Override
public boolean isBaseRevisionChanged(@NotNull VcsRevisionNumber number) {
if (!myFile.isInLocalFileSystem()) return false;
final VcsRevisionNumber currentCurrentRevision = myVcs.getDiffProvider().getCurrentRevision(myFile);
return myBaseRevision != null && ! myBaseRevision.equals(currentCurrentRevision);
}
@Nullable
@Override
public CurrentFileRevisionProvider getCurrentFileRevisionProvider() {
return (lineNumber) -> {
LineInfo lineInfo = getLineInfo(lineNumber);
return lineInfo != null ? lineInfo.getFileRevision() : null;
};
}
@Nullable
@Override
public PreviousFileRevisionProvider getPreviousFileRevisionProvider() {
return new PreviousFileRevisionProvider() {
@Nullable
@Override
public VcsFileRevision getPreviousRevision(int lineNumber) {
LineInfo lineInfo = getLineInfo(lineNumber);
if (lineInfo == null) return null;
VcsFileRevision previousFileRevision = lineInfo.getPreviousFileRevision();
if (previousFileRevision != null) return previousFileRevision;
GitRevisionNumber revisionNumber = lineInfo.getRevisionNumber();
if (myRevisions != null && myRevisionMap != null &&
myRevisionMap.containsKey(revisionNumber)) {
int index = myRevisionMap.getInt(revisionNumber);
if (index + 1 < myRevisions.size()) {
return myRevisions.get(index + 1);
}
}
return null;
}
@Nullable
@Override
public VcsFileRevision getLastRevision() {
if (myBaseRevision instanceof GitRevisionNumber) {
return new GitFileRevision(myProject, myFilePath, (GitRevisionNumber)myBaseRevision);
}
else {
return ContainerUtil.getFirstItem(getRevisions());
}
}
};
}
@Nullable
@Override
public AuthorsMappingProvider getAuthorsMappingProvider() {
Map<VcsRevisionNumber, String> authorsMap = new HashMap<>();
for (int i = 0; i < getLineCount(); i++) {
LineInfo lineInfo = getLineInfo(i);
if (lineInfo == null) continue;
if (!authorsMap.containsKey(lineInfo.getRevisionNumber())) {
authorsMap.put(lineInfo.getRevisionNumber(), lineInfo.getAuthor());
}
}
return () -> authorsMap;
}
@Nullable
@Override
public RevisionsOrderProvider getRevisionsOrderProvider() {
ContainerUtil.KeyOrderedMultiMap<Date, VcsRevisionNumber> dates = new ContainerUtil.KeyOrderedMultiMap<>();
for (int i = 0; i < getLineCount(); i++) {
LineInfo lineInfo = getLineInfo(i);
if (lineInfo == null) continue;
VcsRevisionNumber number = lineInfo.getRevisionNumber();
Date date = lineInfo.getCommitterDate();
dates.putValue(date, number);
}
List<List<VcsRevisionNumber>> orderedRevisions = new ArrayList<>();
NavigableSet<Date> orderedDates = dates.navigableKeySet();
for (Date date : orderedDates.descendingSet()) {
Collection<VcsRevisionNumber> revisionNumbers = dates.get(date);
orderedRevisions.add(new ArrayList<>(revisionNumbers));
}
return () -> orderedRevisions;
}
/**
* Do not use {@link CommittedChangesProvider#getOneList} to avoid unnecessary rename detections (as we know FilePath already)
*/
@NotNull
@Override
public RevisionChangesProvider getRevisionsChangesProvider() {
return (lineNumber) -> {
LineInfo lineInfo = getLineInfo(lineNumber);
if (lineInfo == null) return null;
GitRepository repository = GitRepositoryManager.getInstance(myProject).getRepositoryForFile(lineInfo.getFilePath());
if (repository == null) return null;
GitCommittedChangeList changeList =
GitCommittedChangeListProvider.getCommittedChangeList(myProject, repository.getRoot(), lineInfo.getRevisionNumber());
return Pair.create(changeList, lineInfo.getFilePath());
};
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.internal.admin.remote;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.CacheCallback;
import com.gemstone.gemfire.cache.CacheListener;
import com.gemstone.gemfire.cache.CacheLoader;
import com.gemstone.gemfire.cache.CacheLoaderException;
import com.gemstone.gemfire.cache.CacheWriter;
import com.gemstone.gemfire.cache.CacheWriterException;
import com.gemstone.gemfire.cache.CustomEvictionAttributes;
import com.gemstone.gemfire.cache.CustomExpiry;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.Declarable;
import com.gemstone.gemfire.cache.DiskWriteAttributes;
import com.gemstone.gemfire.cache.EntryEvent;
import com.gemstone.gemfire.cache.EvictionAttributes;
import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.LoaderHelper;
import com.gemstone.gemfire.cache.MembershipAttributes;
import com.gemstone.gemfire.cache.MirrorType;
import com.gemstone.gemfire.cache.PartitionAttributes;
import com.gemstone.gemfire.cache.Region.Entry;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionEvent;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.SubscriptionAttributes;
import com.gemstone.gemfire.compression.CompressionException;
import com.gemstone.gemfire.compression.Compressor;
import com.gemstone.gemfire.internal.InternalDataSerializer;
import com.gemstone.gemfire.internal.Version;
import com.gemstone.gemfire.internal.cache.EvictionAttributesImpl;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
/**
* Provides an implementation of RegionAttributes that can be used from a VM
* remote from the vm that created the cache.
*/
public class RemoteRegionAttributes implements RegionAttributes,
DataSerializable {
private static final long serialVersionUID = -4989613295006261809L;
private String cacheLoaderDesc;
private String cacheWriterDesc;
private String capacityControllerDesc;
private String[] cacheListenerDescs;
private Class keyConstraint;
private Class valueConstraint;
private ExpirationAttributes rTtl;
private ExpirationAttributes rIdleTimeout;
private ExpirationAttributes eTtl;
private String customEttlDesc;
private ExpirationAttributes eIdleTimeout;
private String customEIdleDesc;
private DataPolicy dataPolicy;
private Scope scope;
private boolean statsEnabled;
private boolean ignoreJTA;
private boolean isLockGrantor;
private int concurrencyLevel;
private boolean concurrencyChecksEnabled;
private float loadFactor;
private int initialCapacity;
private boolean earlyAck;
private boolean multicastEnabled;
private boolean enableGateway;
private String gatewayHubId;
private boolean enableSubscriptionConflation;
private boolean publisher;
private boolean enableAsyncConflation;
private DiskWriteAttributes diskWriteAttributes;
private File[] diskDirs;
private int[] diskSizes;
private boolean indexMaintenanceSynchronous;
private PartitionAttributes partitionAttributes;
private MembershipAttributes membershipAttributes;
private SubscriptionAttributes subscriptionAttributes;
private EvictionAttributesImpl evictionAttributes = new EvictionAttributesImpl();
private boolean cloningEnable;
private String poolName;
private String diskStoreName;
private boolean isDiskSynchronous;
private String[] gatewaySendersDescs;
private boolean isGatewaySenderEnabled = false;
private String[] asyncEventQueueDescs;
private String hdfsStoreName;
private boolean hdfsWriteOnly;
private String compressorDesc;
private boolean offHeap;
/**
* constructs a new default RemoteRegionAttributes.
*/
public RemoteRegionAttributes(RegionAttributes attr) {
this.cacheLoaderDesc = getDesc(attr.getCacheLoader());
this.cacheWriterDesc = getDesc(attr.getCacheWriter());
this.cacheListenerDescs = getDescs(attr.getCacheListeners());
this.keyConstraint = attr.getKeyConstraint();
this.valueConstraint = attr.getValueConstraint();
this.rTtl = attr.getRegionTimeToLive();
this.rIdleTimeout = attr.getRegionIdleTimeout();
this.eTtl = attr.getEntryTimeToLive();
this.customEttlDesc = getDesc(attr.getCustomEntryTimeToLive());
this.eIdleTimeout = attr.getEntryIdleTimeout();
this.customEIdleDesc = getDesc(attr.getCustomEntryIdleTimeout());
this.dataPolicy = attr.getDataPolicy();
this.scope = attr.getScope();
this.statsEnabled = attr.getStatisticsEnabled();
this.ignoreJTA = attr.getIgnoreJTA();
this.concurrencyLevel = attr.getConcurrencyLevel();
this.concurrencyChecksEnabled = attr.getConcurrencyChecksEnabled();
this.loadFactor = attr.getLoadFactor();
this.initialCapacity = attr.getInitialCapacity();
this.earlyAck = attr.getEarlyAck();
this.multicastEnabled = attr.getMulticastEnabled();
// this.enableGateway = attr.getEnableGateway();
// this.gatewayHubId = attr.getGatewayHubId();
this.enableSubscriptionConflation = attr.getEnableSubscriptionConflation();
this.publisher = attr.getPublisher();
this.enableAsyncConflation = attr.getEnableAsyncConflation();
this.diskStoreName = attr.getDiskStoreName();
if (this.diskStoreName == null) {
this.diskWriteAttributes = attr.getDiskWriteAttributes();
this.diskDirs = attr.getDiskDirs();
this.diskSizes = attr.getDiskDirSizes();
} else {
this.diskWriteAttributes = null;
this.diskDirs = null;
this.diskSizes = null;
}
this.partitionAttributes = attr.getPartitionAttributes();
this.membershipAttributes = attr.getMembershipAttributes();
this.subscriptionAttributes = attr.getSubscriptionAttributes();
this.cloningEnable = attr.getCloningEnabled();
this.poolName = attr.getPoolName();
this.isDiskSynchronous = attr.isDiskSynchronous();
this.gatewaySendersDescs = getDescs(attr.getGatewaySenderIds().toArray());
this.asyncEventQueueDescs = getDescs(attr.getAsyncEventQueueIds().toArray());
this.hdfsStoreName = attr.getHDFSStoreName();
this.hdfsWriteOnly = attr.getHDFSWriteOnly();
this.compressorDesc = getDesc(attr.getCompressor());
this.offHeap = attr.getOffHeap();
}
/**
* For use only by DataExternalizable mechanism
*/
public RemoteRegionAttributes() {
}
public CacheLoader getCacheLoader() {
return cacheLoaderDesc.equals("") ? null : new RemoteCacheLoader(
cacheLoaderDesc);
}
public CacheWriter getCacheWriter() {
return cacheWriterDesc.equals("") ? null : new RemoteCacheWriter(
cacheWriterDesc);
}
public Class getKeyConstraint() {
return keyConstraint;
}
public Class getValueConstraint() {
return valueConstraint;
}
public ExpirationAttributes getRegionTimeToLive() {
return rTtl;
}
public ExpirationAttributes getRegionIdleTimeout() {
return rIdleTimeout;
}
public ExpirationAttributes getEntryTimeToLive() {
return eTtl;
}
public CustomExpiry getCustomEntryTimeToLive() {
return customEttlDesc.equals("") ? null : new RemoteCustomExpiry(
customEttlDesc);
}
public ExpirationAttributes getEntryIdleTimeout() {
return eIdleTimeout;
}
public CustomExpiry getCustomEntryIdleTimeout() {
return customEIdleDesc.equals("") ? null : new RemoteCustomExpiry(
customEIdleDesc);
}
public String getPoolName() {
return poolName;
}
public Scope getScope() {
return scope;
}
public CacheListener getCacheListener() {
CacheListener[] listeners = getCacheListeners();
if (listeners.length == 0) {
return null;
} else if (listeners.length == 1) {
return listeners[0];
} else {
throw new IllegalStateException(LocalizedStrings.RemoteRegionAttributes_MORE_THAN_ONE_CACHE_LISTENER_EXISTS.toLocalizedString());
}
}
private static final CacheListener[] EMPTY_LISTENERS = new CacheListener[0];
public CacheListener[] getCacheListeners() {
if (this.cacheListenerDescs == null || this.cacheListenerDescs.length == 0) {
return EMPTY_LISTENERS;
} else {
CacheListener[] result = new CacheListener[this.cacheListenerDescs.length];
for (int i=0; i < result.length; i++) {
result[i] = new RemoteCacheListener(this.cacheListenerDescs[i]);
}
return result;
}
}
public int getInitialCapacity() {
return initialCapacity;
}
public float getLoadFactor() {
return loadFactor;
}
public int getConcurrencyLevel() {
return concurrencyLevel;
}
public boolean getConcurrencyChecksEnabled() {
return this.concurrencyChecksEnabled;
}
public boolean getStatisticsEnabled() {
return statsEnabled;
}
public boolean getIgnoreJTA() {
return ignoreJTA;
}
public boolean isLockGrantor() {
return this.isLockGrantor;
}
public boolean getPersistBackup() {
return getDataPolicy().withPersistence();
}
public boolean getEarlyAck() {
return this.earlyAck;
}
public boolean getMulticastEnabled() {
return this.multicastEnabled;
}
public boolean getEnableGateway() {
return this.enableGateway;
}
public boolean getEnableWAN() { // deprecated in 5.0
return this.enableGateway;
}
public String getGatewayHubId() {
return this.gatewayHubId;
}
/*
* @deprecated as of prPersistSprint1
*/
@Deprecated
public boolean getPublisher() {
return this.publisher;
}
public boolean getEnableConflation() { // deprecated in 5.0
return getEnableSubscriptionConflation();
}
public boolean getEnableBridgeConflation() { // deprecated in 5.7
return getEnableSubscriptionConflation();
}
public boolean getEnableSubscriptionConflation() {
return this.enableSubscriptionConflation;
}
public boolean getEnableAsyncConflation() {
return this.enableAsyncConflation;
}
public DiskWriteAttributes getDiskWriteAttributes() {
return this.diskWriteAttributes;
}
public File[] getDiskDirs() {
return this.diskDirs;
}
public int[] getDiskDirSizes() {
return this.diskSizes;
}
public MirrorType getMirrorType() {
//checkReadiness();
if (this.dataPolicy.isNormal() || this.dataPolicy.isPreloaded()
|| this.dataPolicy.isEmpty() || this.dataPolicy.withPartitioning()) {
return MirrorType.NONE;
} else if (this.dataPolicy.withReplication()) {
return MirrorType.KEYS_VALUES;
} else {
throw new IllegalStateException(LocalizedStrings.RemoteRegionAttributes_NO_MIRROR_TYPE_CORRESPONDS_TO_DATA_POLICY_0.toLocalizedString(this.dataPolicy));
}
}
public DataPolicy getDataPolicy() {
//checkReadiness();
return this.dataPolicy;
}
public PartitionAttributes getPartitionAttributes() {
return this.partitionAttributes;
}
public MembershipAttributes getMembershipAttributes() {
return this.membershipAttributes;
}
public SubscriptionAttributes getSubscriptionAttributes() {
return this.subscriptionAttributes;
}
public Compressor getCompressor() {
return compressorDesc.equals("") ? null : new RemoteCompressor(
compressorDesc);
}
public boolean getOffHeap() {
return this.offHeap;
}
public void toDataPre_GFE_8_0_0_0(DataOutput out) throws IOException {
DataSerializer.writeString(this.cacheLoaderDesc, out);
DataSerializer.writeString(this.cacheWriterDesc, out);
DataSerializer.writeStringArray(this.cacheListenerDescs, out);
DataSerializer.writeString(this.capacityControllerDesc, out);
DataSerializer.writeObject(this.keyConstraint, out);
DataSerializer.writeObject(this.valueConstraint, out);
DataSerializer.writeObject(this.rTtl, out);
DataSerializer.writeObject(this.rIdleTimeout, out);
DataSerializer.writeObject(this.eTtl, out);
DataSerializer.writeString(this.customEttlDesc, out);
DataSerializer.writeObject(this.eIdleTimeout, out);
DataSerializer.writeString(this.customEIdleDesc, out);
DataSerializer.writeObject(this.dataPolicy, out);
DataSerializer.writeObject(this.scope, out);
out.writeBoolean(this.statsEnabled);
out.writeBoolean(this.ignoreJTA);
out.writeInt(this.concurrencyLevel);
out.writeFloat(this.loadFactor);
out.writeInt(this.initialCapacity);
out.writeBoolean(this.earlyAck);
out.writeBoolean(this.multicastEnabled);
out.writeBoolean(this.enableGateway);
DataSerializer.writeString(this.gatewayHubId, out);
out.writeBoolean(this.enableSubscriptionConflation);
out.writeBoolean(this.publisher);
out.writeBoolean(this.enableAsyncConflation);
DataSerializer.writeObject(this.diskWriteAttributes, out);
DataSerializer.writeObject(this.diskDirs, out);
DataSerializer.writeObject(this.diskSizes, out);
out.writeBoolean(this.indexMaintenanceSynchronous);
DataSerializer.writeObject(this.partitionAttributes, out);
DataSerializer.writeObject(this.membershipAttributes, out);
DataSerializer.writeObject(this.subscriptionAttributes, out);
DataSerializer.writeObject(this.evictionAttributes, out);
out.writeBoolean(this.cloningEnable);
DataSerializer.writeString(this.diskStoreName, out);
out.writeBoolean(this.isDiskSynchronous);
DataSerializer.writeStringArray(this.gatewaySendersDescs, out);
out.writeBoolean(this.isGatewaySenderEnabled);
out.writeBoolean(this.concurrencyChecksEnabled);
}
public void toDataPre_GFE_9_0_0_0(DataOutput out) throws IOException {
DataSerializer.writeString(this.cacheLoaderDesc, out);
DataSerializer.writeString(this.cacheWriterDesc, out);
DataSerializer.writeStringArray(this.cacheListenerDescs, out);
DataSerializer.writeString(this.capacityControllerDesc, out);
DataSerializer.writeObject(this.keyConstraint, out);
DataSerializer.writeObject(this.valueConstraint, out);
DataSerializer.writeObject(this.rTtl, out);
DataSerializer.writeObject(this.rIdleTimeout, out);
DataSerializer.writeObject(this.eTtl, out);
DataSerializer.writeString(this.customEttlDesc, out);
DataSerializer.writeObject(this.eIdleTimeout, out);
DataSerializer.writeString(this.customEIdleDesc, out);
DataSerializer.writeObject(this.dataPolicy, out);
DataSerializer.writeObject(this.scope, out);
out.writeBoolean(this.statsEnabled);
out.writeBoolean(this.ignoreJTA);
out.writeInt(this.concurrencyLevel);
out.writeFloat(this.loadFactor);
out.writeInt(this.initialCapacity);
out.writeBoolean(this.earlyAck);
out.writeBoolean(this.multicastEnabled);
if (InternalDataSerializer.getVersionForDataStream(out).compareTo(
Version.CURRENT) < 0) {
out.writeBoolean(this.enableGateway);
DataSerializer.writeString(this.gatewayHubId, out);
}
out.writeBoolean(this.enableSubscriptionConflation);
out.writeBoolean(this.publisher);
out.writeBoolean(this.enableAsyncConflation);
DataSerializer.writeObject(this.diskWriteAttributes, out);
DataSerializer.writeObject(this.diskDirs, out);
DataSerializer.writeObject(this.diskSizes, out);
out.writeBoolean(this.indexMaintenanceSynchronous);
DataSerializer.writeObject(this.partitionAttributes, out);
DataSerializer.writeObject(this.membershipAttributes, out);
DataSerializer.writeObject(this.subscriptionAttributes, out);
DataSerializer.writeObject(this.evictionAttributes, out);
out.writeBoolean(this.cloningEnable);
DataSerializer.writeString(this.diskStoreName, out);
out.writeBoolean(this.isDiskSynchronous);
DataSerializer.writeStringArray(this.gatewaySendersDescs, out);
out.writeBoolean(this.isGatewaySenderEnabled);
out.writeBoolean(this.concurrencyChecksEnabled);
DataSerializer.writeString(this.compressorDesc, out);
}
public void toData(DataOutput out) throws IOException {
toDataPre_GFE_9_0_0_0(out);
out.writeBoolean(this.offHeap);
DataSerializer.writeString(this.hdfsStoreName, out);
}
public void fromDataPre_GFE_8_0_0_0(DataInput in) throws IOException, ClassNotFoundException {
this.cacheLoaderDesc = DataSerializer.readString(in);
this.cacheWriterDesc = DataSerializer.readString(in);
this.cacheListenerDescs = DataSerializer.readStringArray(in);
this.capacityControllerDesc = DataSerializer.readString(in);
this.keyConstraint = (Class) DataSerializer.readObject(in);
this.valueConstraint = (Class) DataSerializer.readObject(in);
this.rTtl = (ExpirationAttributes) DataSerializer.readObject(in);
this.rIdleTimeout = (ExpirationAttributes) DataSerializer.readObject(in);
this.eTtl = (ExpirationAttributes) DataSerializer.readObject(in);
this.customEttlDesc = DataSerializer.readString(in);
this.eIdleTimeout = (ExpirationAttributes) DataSerializer.readObject(in);
this.customEIdleDesc = DataSerializer.readString(in);
this.dataPolicy = (DataPolicy) DataSerializer.readObject(in);
this.scope = (Scope) DataSerializer.readObject(in);
this.statsEnabled = in.readBoolean();
this.ignoreJTA = in.readBoolean();
this.concurrencyLevel = in.readInt();
this.loadFactor = in.readFloat();
this.initialCapacity = in.readInt();
this.earlyAck = in.readBoolean();
this.multicastEnabled = in.readBoolean();
this.enableGateway = in.readBoolean();
this.gatewayHubId = DataSerializer.readString(in);
this.enableSubscriptionConflation = in.readBoolean();
this.publisher = in.readBoolean();
this.enableAsyncConflation = in.readBoolean();
this.diskWriteAttributes = (DiskWriteAttributes) DataSerializer.readObject(in);
this.diskDirs = (File[]) DataSerializer.readObject(in);
this.diskSizes = (int[] )DataSerializer.readObject(in);
this.indexMaintenanceSynchronous = in.readBoolean();
this.partitionAttributes = (PartitionAttributes) DataSerializer
.readObject(in);
this.membershipAttributes = (MembershipAttributes) DataSerializer
.readObject(in);
this.subscriptionAttributes = (SubscriptionAttributes) DataSerializer
.readObject(in);
this.evictionAttributes = (EvictionAttributesImpl) DataSerializer.readObject(in);
this.cloningEnable = in.readBoolean();
this.diskStoreName = DataSerializer.readString(in);
this.isDiskSynchronous = in.readBoolean();
this.gatewaySendersDescs = DataSerializer.readStringArray(in);
this.isGatewaySenderEnabled = in.readBoolean();
this.concurrencyChecksEnabled = in.readBoolean();
}
public void fromDataPre_GFE_9_0_0_0(DataInput in) throws IOException, ClassNotFoundException {
this.cacheLoaderDesc = DataSerializer.readString(in);
this.cacheWriterDesc = DataSerializer.readString(in);
this.cacheListenerDescs = DataSerializer.readStringArray(in);
this.capacityControllerDesc = DataSerializer.readString(in);
this.keyConstraint = (Class) DataSerializer.readObject(in);
this.valueConstraint = (Class) DataSerializer.readObject(in);
this.rTtl = (ExpirationAttributes) DataSerializer.readObject(in);
this.rIdleTimeout = (ExpirationAttributes) DataSerializer.readObject(in);
this.eTtl = (ExpirationAttributes) DataSerializer.readObject(in);
this.customEttlDesc = DataSerializer.readString(in);
this.eIdleTimeout = (ExpirationAttributes) DataSerializer.readObject(in);
this.customEIdleDesc = DataSerializer.readString(in);
this.dataPolicy = (DataPolicy) DataSerializer.readObject(in);
this.scope = (Scope) DataSerializer.readObject(in);
this.statsEnabled = in.readBoolean();
this.ignoreJTA = in.readBoolean();
this.concurrencyLevel = in.readInt();
this.loadFactor = in.readFloat();
this.initialCapacity = in.readInt();
this.earlyAck = in.readBoolean();
this.multicastEnabled = in.readBoolean();
if (InternalDataSerializer.getVersionForDataStream(in).compareTo(
Version.CURRENT) < 0) {
this.enableGateway = in.readBoolean();
this.gatewayHubId = DataSerializer.readString(in);
}
this.enableSubscriptionConflation = in.readBoolean();
this.publisher = in.readBoolean();
this.enableAsyncConflation = in.readBoolean();
this.diskWriteAttributes = (DiskWriteAttributes) DataSerializer.readObject(in);
this.diskDirs = (File[]) DataSerializer.readObject(in);
this.diskSizes = (int[] )DataSerializer.readObject(in);
this.indexMaintenanceSynchronous = in.readBoolean();
this.partitionAttributes = (PartitionAttributes) DataSerializer
.readObject(in);
this.membershipAttributes = (MembershipAttributes) DataSerializer
.readObject(in);
this.subscriptionAttributes = (SubscriptionAttributes) DataSerializer
.readObject(in);
this.evictionAttributes = (EvictionAttributesImpl) DataSerializer.readObject(in);
this.cloningEnable = in.readBoolean();
this.diskStoreName = DataSerializer.readString(in);
this.isDiskSynchronous = in.readBoolean();
this.gatewaySendersDescs = DataSerializer.readStringArray(in);
this.isGatewaySenderEnabled = in.readBoolean();
this.concurrencyChecksEnabled = in.readBoolean();
this.compressorDesc = DataSerializer.readString(in);
}
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
fromDataPre_GFE_9_0_0_0(in);
this.offHeap = in.readBoolean();
this.hdfsStoreName = DataSerializer.readString(in);
}
private String[] getDescs(Object[] l) {
if (l == null) {
return new String[0];
} else {
String[] result = new String[l.length];
for (int i=0; i < l.length; i++) {
result[i] = getDesc(l[i]);
}
return result;
}
}
private String getDesc(Object o) {
if (o == null) {
return "";
}
else if (o instanceof RemoteCacheCallback) {
return ((RemoteCacheCallback) o).toString();
}
else {
return o.getClass().getName();
}
}
public boolean getIndexMaintenanceSynchronous() {
return this.indexMaintenanceSynchronous;
}
/**
* A remote representation of a cache callback
*/
private abstract static class RemoteCacheCallback implements CacheCallback {
/** The description of this callback */
private final String desc;
/**
* Creates a new <code>RemoteCacheCallback</code> with the given
* description.
*/
protected RemoteCacheCallback(String desc) {
this.desc = desc;
}
@Override
public final String toString() {
return desc;
}
public final void close() {
}
}
private static class RemoteCacheListener extends RemoteCacheCallback
implements CacheListener {
public RemoteCacheListener(String desc) {
super(desc);
}
public void afterCreate(EntryEvent event) {
}
public void afterUpdate(EntryEvent event) {
}
public void afterInvalidate(EntryEvent event) {
}
public void afterDestroy(EntryEvent event) {
}
public void afterRegionInvalidate(RegionEvent event) {
}
public void afterRegionDestroy(RegionEvent event) {
}
public void afterRegionClear(RegionEvent event) {
}
public void afterRegionCreate(RegionEvent event) {
}
public void afterRegionLive(RegionEvent event) {
}
}
private static class RemoteCacheWriter extends RemoteCacheCallback implements
CacheWriter {
public RemoteCacheWriter(String desc) {
super(desc);
}
public void beforeUpdate(EntryEvent event) throws CacheWriterException {
}
public void beforeCreate(EntryEvent event) throws CacheWriterException {
}
public void beforeDestroy(EntryEvent event) throws CacheWriterException {
}
public void beforeRegionDestroy(RegionEvent event)
throws CacheWriterException {
}
public void beforeRegionClear(RegionEvent event)
throws CacheWriterException {
}
}
private static class RemoteCustomExpiry extends RemoteCacheCallback
implements CustomExpiry, Declarable {
public RemoteCustomExpiry(String desc) {
super(desc);
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.CustomExpiry#getExpiry(com.gemstone.gemfire.cache.Region.Entry)
*/
public ExpirationAttributes getExpiry(Entry entry) {
return null;
}
/* (non-Javadoc)
* @see com.gemstone.gemfire.cache.Declarable#init(java.util.Properties)
*/
public void init(Properties props) {
}
}
private static class RemoteCacheLoader extends RemoteCacheCallback implements
CacheLoader {
public RemoteCacheLoader(String desc) {
super(desc);
}
public Object load(LoaderHelper helper) throws CacheLoaderException {
return null;
}
}
private static class RemoteCompressor extends RemoteCacheCallback implements
Compressor {
public RemoteCompressor(String desc) {
super(desc);
}
public byte[] compress(byte[] input) {
return null;
}
public byte[] decompress(byte[] input) {
return null;
}
}
public EvictionAttributes getEvictionAttributes()
{
return this.evictionAttributes;
}
/**
* {@inheritDoc}
*/
@Override
public CustomEvictionAttributes getCustomEvictionAttributes() {
// TODO: HDFS: no support for custom eviction attributes from remote yet
return null;
}
public boolean getCloningEnabled() {
// TODO Auto-generated method stub
return this.cloningEnable;
}
public String getDiskStoreName() {
return this.diskStoreName;
}
public String getHDFSStoreName() {
return this.hdfsStoreName;
}
public boolean getHDFSWriteOnly() {
return this.hdfsWriteOnly;
}
public boolean isDiskSynchronous() {
return this.isDiskSynchronous;
}
public boolean isGatewaySenderEnabled() {
return this.isGatewaySenderEnabled;
}
public Set<String> getGatewaySenderIds() {
if (this.gatewaySendersDescs == null
|| this.gatewaySendersDescs.length == 0) {
return Collections.EMPTY_SET;
}
else {
Set<String> senderIds = new HashSet<String>();
String[] result = new String[this.gatewaySendersDescs.length];
for (int i = 0; i < result.length; i++) {
result[i] = new String(this.gatewaySendersDescs[i]);
senderIds.add(result[i]);
}
return senderIds;
}
}
public Set<String> getAsyncEventQueueIds() {
if (this.asyncEventQueueDescs == null
|| this.asyncEventQueueDescs.length == 0) {
return Collections.EMPTY_SET;
}
else {
Set<String> asyncEventQueues = new HashSet<String>();
String[] result = new String[this.asyncEventQueueDescs.length];
for (int i = 0; i < result.length; i++) {
result[i] = new String(this.asyncEventQueueDescs[i]);
asyncEventQueues.add(result[i]);
}
return asyncEventQueues;
}
}
}
| |
/*******************************************************************************
* 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.wink.common.internal.http;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.RuntimeDelegate;
import javax.ws.rs.ext.RuntimeDelegate.HeaderDelegate;
import org.apache.wink.common.internal.utils.MediaTypeUtils;
/**
* Represents a HTTP Accept header (see 14.1 of RFC 2616).
*/
public class Accept {
private static HeaderDelegate<Accept> doNotDirectlyAccess = null;
public static synchronized HeaderDelegate<Accept> getAcceptHeaderDelegate() {
if (doNotDirectlyAccess == null) {
RuntimeDelegate delegate = RuntimeDelegate.getInstance();
doNotDirectlyAccess = delegate.createHeaderDelegate(Accept.class);
}
return doNotDirectlyAccess;
}
private List<MediaType> mediaTypes;
private List<ValuedMediaType> valuedMediaTypes;
private List<ValuedMediaType> sortedValuedMediaTypes;
private List<MediaType> sortedMediaTypes;
public Accept(List<MediaType> mediaTypes) {
this.mediaTypes = mediaTypes;
if (mediaTypes.isEmpty()) {
throw new IllegalArgumentException();
}
this.valuedMediaTypes = new LinkedList<ValuedMediaType>();
for (MediaType mt : mediaTypes) {
this.valuedMediaTypes.add(new ValuedMediaType(mt));
}
this.sortedValuedMediaTypes = sort(new LinkedList<ValuedMediaType>(this.valuedMediaTypes));
sortedMediaTypes = new LinkedList<MediaType>();
for (ValuedMediaType vmt : sortedValuedMediaTypes) {
sortedMediaTypes.add(vmt.getMediaType());
}
}
private List<ValuedMediaType> sort(List<ValuedMediaType> types) {
// sort the accept media types.
// use the reverseOrder() method because sort()
// will sort in ascending order and we want descending order
Collections.sort(types, Collections.reverseOrder());
return types;
}
/**
* Get an unmodifiable list of the valued media types in the accept header
*
* @return an unmodifiable list of the valued media types
*/
public List<ValuedMediaType> getValuedMediaTypes() {
return Collections.unmodifiableList(valuedMediaTypes);
}
/**
* Get a sorted unmodifiable list of the valued media types in the accept
* header
*
* @return a sorted unmodifiable list of the valued media types
*/
public List<ValuedMediaType> getSortedValuedMediaTypes() {
return Collections.unmodifiableList(sortedValuedMediaTypes);
}
/**
* Get an unmodifiable list of the media types in the accept header
*
* @return an unmodifiable list of the accept media types
*/
public List<MediaType> getMediaTypes() {
return mediaTypes;
}
/**
* Get a sorted unmodifiable list of the valued media types in the accept
* header
*
* @return a sorted unmodifiable list of the valued media types
*/
public List<MediaType> getSortedMediaTypes() {
return Collections.unmodifiableList(sortedMediaTypes);
}
/**
* Is media type acceptable by this Accept header
*
* @param mt a media type to check for acceptance
* @return true if acceptable, false otherwise
*/
public boolean isAcceptable(MediaType mt) {
boolean accpetable = false;
for (ValuedMediaType vmt : valuedMediaTypes) {
if (vmt.isCompatible(mt)) {
if (vmt.getQ() == 0) {
return false;
}
accpetable = true;
}
}
return accpetable;
}
/**
* Creates a new instance of Accept by parsing the supplied string.
*
* @param value the accept string
* @return the newly created Accept
* @throws IllegalArgumentException if the supplied string cannot be parsed
*/
public static Accept valueOf(String value) throws IllegalArgumentException {
return getAcceptHeaderDelegate().fromString(value);
}
/**
* Convert the accept to a string suitable for use as the value of the
* corresponding HTTP header.
*
* @return a stringified accept
*/
@Override
public String toString() {
return getAcceptHeaderDelegate().toString(this);
}
/**
* Represents a media type along with its q value.
*/
public static class ValuedMediaType implements Comparable<ValuedMediaType> {
private double q;
private MediaType mediaType;
public ValuedMediaType(MediaType mediaType) {
double q = 1;
String qStr = mediaType.getParameters().get("q"); //$NON-NLS-1$
if (qStr != null) {
q = Double.parseDouble(qStr);
}
init(mediaType, q);
}
public ValuedMediaType(MediaType mediaType, double q) {
init(mediaType, q);
}
private void init(MediaType mediaType, double q) {
if (mediaType == null) {
throw new NullPointerException("mediaType"); //$NON-NLS-1$
}
if (q < 0 || q > 1) {
throw new IllegalArgumentException(String.valueOf(q));
}
this.mediaType = mediaType;
// strip digits after the first 3
this.q = ((double)((int)(q * 1000))) / 1000;
// if the result q is different than the initial q, then create a
// new MediaType
// with the stripped q value
if (this.q != q) {
Map<String, String> parameters = new LinkedHashMap<String, String>();
parameters.putAll(mediaType.getParameters());
parameters.put("q", Double.toString(this.q)); //$NON-NLS-1$
this.mediaType =
new MediaType(mediaType.getType(), mediaType.getSubtype(), parameters);
}
}
public double getQ() {
return q;
}
public MediaType getMediaType() {
return mediaType;
}
public boolean isCompatible(MediaType other) {
return mediaType.isCompatible(other);
}
public String toString() {
return mediaType.toString();
}
public int compareTo(ValuedMediaType o) {
int ret = Double.compare(q, o.q);
if (ret != 0) {
return ret;
}
return MediaTypeUtils.compareTo(mediaType, o.mediaType);
}
}
}
| |
/*******************************************************************************
* 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.ofbiz.base.start;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ofbiz.base.start.Start.ServerState;
/**
* The StartupControlPanel controls OFBiz by executing high level
* functions such as init, start and stop on the server. The bulk
* of the startup sequence logic resides in this class.
*/
final class StartupControlPanel {
public static final String module = StartupControlPanel.class.getName();
/**
* Initialize OFBiz by:
* - setting high level JVM and OFBiz system properties
* - creating a Config object holding startup configuration parameters
*
* @param ofbizCommands commands passed by the user to OFBiz on start
* @return config OFBiz configuration
*/
static Config init(List<StartupCommand> ofbizCommands) {
Config config = null;
try {
loadGlobalOfbizSystemProperties("ofbiz.system.props");
config = new Config(ofbizCommands);
} catch (StartupException e) {
fullyTerminateSystem(e);
}
return config;
}
/**
* Execute the startup sequence for OFBiz
*/
static void start(Config config,
AtomicReference<ServerState> serverState,
List<StartupCommand> ofbizCommands) throws StartupException {
//TODO loaders should be converted to a single loader
List<StartupLoader> loaders = new ArrayList<>();
Thread adminServer = createAdminServer(config, serverState, loaders);
createLogDirectoryIfMissing(config);
createRuntimeShutdownHook(config, loaders, serverState);
loadStartupLoaders(config, loaders, ofbizCommands, serverState);
printStartupMessage(config);
executeShutdownAfterLoadIfConfigured(config, loaders, serverState, adminServer);
}
/**
* Print OFBiz startup message only if the OFBiz server is not scheduled for shutdown.
* @param config contains parameters for system startup
*/
private static void printStartupMessage(Config config) {
if (!config.shutdownAfterLoad) {
String lineSeparator = System.lineSeparator();
System.out.println(lineSeparator + " ____ __________ _" +
lineSeparator + " / __ \\/ ____/ __ )(_)___" +
lineSeparator + " / / / / /_ / __ / /_ /" +
lineSeparator + "/ /_/ / __/ / /_/ / / / /_" +
lineSeparator + "\\____/_/ /_____/_/ /___/ is started and ready." +
lineSeparator);
}
}
/**
* Shutdown the OFBiz server. This method is invoked in one of the
* following ways:
*
* - Manually if requested by the client AdminClient
* - Automatically if Config.shutdownAfterLoad is set to true
*/
static void stop(List<StartupLoader> loaders, AtomicReference<ServerState> serverState, Thread adminServer) {
shutdownServer(loaders, serverState, adminServer);
System.exit(0);
}
/**
* Properly exit from the system when a StartupException cannot or
* should not be handled except by exiting the system.
*
* A proper system exit is achieved by:
*
* - Printing the stack trace for users to see what happened
* - Executing the shutdown hooks (if existing) through System.exit
* - Terminating any lingering threads (if existing) through System.exit
* - Providing an exit code that is not 0 to signal to the build system
* or user of failure to execute.
*
* @param e The startup exception that cannot / should not be handled
* except by terminating the system
*/
static void fullyTerminateSystem(StartupException e) {
e.printStackTrace();
System.exit(1);
}
private static void shutdownServer(List<StartupLoader> loaders, AtomicReference<ServerState> serverState, Thread adminServer) {
ServerState currentState;
do {
currentState = serverState.get();
if (currentState == ServerState.STOPPING) {
return;
}
} while (!serverState.compareAndSet(currentState, ServerState.STOPPING));
// The current thread was the one that successfully changed the state;
// continue with further processing.
synchronized (loaders) {
// Unload in reverse order
for (int i = loaders.size(); i > 0; i--) {
StartupLoader loader = loaders.get(i - 1);
try {
loader.unload();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (adminServer != null && adminServer.isAlive()) {
adminServer.interrupt();
}
}
private static void loadGlobalOfbizSystemProperties(String globalOfbizPropertiesFileName) throws StartupException {
String systemProperties = System.getProperty(globalOfbizPropertiesFileName);
if (systemProperties != null) {
try (FileInputStream stream = new FileInputStream(systemProperties)) {
System.getProperties().load(stream);
} catch (IOException e) {
throw new StartupException("Couldn't load global system props", e);
}
}
}
private static Thread createAdminServer(
Config config,
AtomicReference<ServerState> serverState,
List<StartupLoader> loaders) throws StartupException {
Thread adminServer = null;
if (config.adminPort > 0) {
adminServer = new AdminServer(loaders, serverState, config);
adminServer.start();
} else {
System.out.println("Admin socket not configured; set to port 0");
}
return adminServer;
}
private static void createLogDirectoryIfMissing(Config config) {
File logDir = new File(config.logDir);
if (!logDir.exists()) {
if (logDir.mkdir()) {
System.out.println("Created OFBiz log dir [" + logDir.getAbsolutePath() + "]");
}
}
}
private static void createRuntimeShutdownHook(
Config config,
List<StartupLoader> loaders,
AtomicReference<ServerState> serverState) {
if (config.useShutdownHook) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
shutdownServer(loaders, serverState, this);
}
});
} else {
System.out.println("Shutdown hook disabled");
}
}
private static void loadStartupLoaders(Config config,
List<StartupLoader> loaders,
List<StartupCommand> ofbizCommands,
AtomicReference<ServerState> serverState) throws StartupException {
String startupLoaderName = "org.apache.ofbiz.base.container.ContainerLoader";
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
synchronized (loaders) {
if (serverState.get() == ServerState.STOPPING) {
return;
}
try {
Class<?> loaderClass = classloader.loadClass(startupLoaderName);
StartupLoader loader = (StartupLoader) loaderClass.newInstance();
loaders.add(loader); // add before loading, so unload can occur if error during loading
loader.load(config, ofbizCommands);
} catch (ReflectiveOperationException e) {
throw new StartupException(e);
}
}
serverState.compareAndSet(ServerState.STARTING, ServerState.RUNNING);
}
private static void executeShutdownAfterLoadIfConfigured(
Config config,
List<StartupLoader> loaders,
AtomicReference<ServerState> serverState,
Thread adminServer) {
if (config.shutdownAfterLoad) {
stop(loaders, serverState, adminServer);
}
}
}
| |
/*
* 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.tinkerpop.gremlin.process.traversal.dsl.graph;
import org.apache.tinkerpop.gremlin.process.computer.Computer;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.remote.RemoteConnection;
import org.apache.tinkerpop.gremlin.process.remote.traversal.strategy.decoration.RemoteStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.Bytecode;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddEdgeStartStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddVertexStartStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.IoStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.InjectStep;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.RequirementsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* A {@code GraphTraversalSource} is the primary DSL of the Gremlin traversal machine.
* It provides access to all the configurations and steps for Turing complete graph computing.
* Any DSL can be constructed based on the methods of both {@code GraphTraversalSource} and {@link GraphTraversal}.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphTraversalSource implements TraversalSource {
protected transient RemoteConnection connection;
protected final Graph graph;
protected TraversalStrategies strategies;
protected Bytecode bytecode = new Bytecode();
////////////////
public static final class Symbols {
private Symbols() {
// static fields only
}
public static final String withBulk = "withBulk";
public static final String withPath = "withPath";
}
////////////////
@Override
public Optional<Class> getAnonymousTraversalClass() {
return Optional.of(__.class);
}
public GraphTraversalSource(final Graph graph, final TraversalStrategies traversalStrategies) {
this.graph = graph;
this.strategies = traversalStrategies;
}
public GraphTraversalSource(final Graph graph) {
this(graph, TraversalStrategies.GlobalCache.getStrategies(graph.getClass()));
}
public GraphTraversalSource(final RemoteConnection connection) {
this(EmptyGraph.instance(), TraversalStrategies.GlobalCache.getStrategies(EmptyGraph.class).clone());
this.connection = connection;
this.strategies.addStrategies(new RemoteStrategy(connection));
}
@Override
public TraversalStrategies getStrategies() {
return this.strategies;
}
@Override
public Graph getGraph() {
return this.graph;
}
@Override
public Bytecode getBytecode() {
return this.bytecode;
}
@SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
public GraphTraversalSource clone() {
try {
final GraphTraversalSource clone = (GraphTraversalSource) super.clone();
clone.strategies = this.strategies.clone();
clone.bytecode = this.bytecode.clone();
return clone;
} catch (final CloneNotSupportedException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
//// CONFIGURATIONS
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource with(final String key) {
return (GraphTraversalSource) TraversalSource.super.with(key);
}
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource with(final String key, final Object value) {
return (GraphTraversalSource) TraversalSource.super.with(key, value);
}
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource withStrategies(final TraversalStrategy... traversalStrategies) {
return (GraphTraversalSource) TraversalSource.super.withStrategies(traversalStrategies);
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings({"unchecked"})
public GraphTraversalSource withoutStrategies(final Class<? extends TraversalStrategy>... traversalStrategyClasses) {
return (GraphTraversalSource) TraversalSource.super.withoutStrategies(traversalStrategyClasses);
}
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource withComputer(final Computer computer) {
return (GraphTraversalSource) TraversalSource.super.withComputer(computer);
}
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource withComputer(final Class<? extends GraphComputer> graphComputerClass) {
return (GraphTraversalSource) TraversalSource.super.withComputer(graphComputerClass);
}
/**
* {@inheritDoc}
*/
@Override
public GraphTraversalSource withComputer() {
return (GraphTraversalSource) TraversalSource.super.withComputer();
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSideEffect(final String key, final Supplier<A> initialValue, final BinaryOperator<A> reducer) {
return (GraphTraversalSource) TraversalSource.super.withSideEffect(key, initialValue, reducer);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSideEffect(final String key, final A initialValue, final BinaryOperator<A> reducer) {
return (GraphTraversalSource) TraversalSource.super.withSideEffect(key, initialValue, reducer);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSideEffect(final String key, final A initialValue) {
return (GraphTraversalSource) TraversalSource.super.withSideEffect(key, initialValue);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSideEffect(final String key, final Supplier<A> initialValue) {
return (GraphTraversalSource) TraversalSource.super.withSideEffect(key, initialValue);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, splitOperator, mergeOperator);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final A initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, splitOperator, mergeOperator);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final A initialValue) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final Supplier<A> initialValue) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, splitOperator);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final A initialValue, final UnaryOperator<A> splitOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, splitOperator);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final Supplier<A> initialValue, final BinaryOperator<A> mergeOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, mergeOperator);
}
/**
* {@inheritDoc}
*/
@Override
public <A> GraphTraversalSource withSack(final A initialValue, final BinaryOperator<A> mergeOperator) {
return (GraphTraversalSource) TraversalSource.super.withSack(initialValue, mergeOperator);
}
public GraphTraversalSource withBulk(final boolean useBulk) {
if (useBulk)
return this;
final GraphTraversalSource clone = this.clone();
RequirementsStrategy.addRequirements(clone.getStrategies(), TraverserRequirement.ONE_BULK);
clone.bytecode.addSource(Symbols.withBulk, useBulk);
return clone;
}
public GraphTraversalSource withPath() {
final GraphTraversalSource clone = this.clone();
RequirementsStrategy.addRequirements(clone.getStrategies(), TraverserRequirement.PATH);
clone.bytecode.addSource(Symbols.withPath);
return clone;
}
//// SPAWNS
/**
* Spawns a {@link GraphTraversal} by adding a vertex with the specified label. If the {@code label} is
* {@code null} then it will default to {@link Vertex#DEFAULT_LABEL}.
*/
public GraphTraversal<Vertex, Vertex> addV(final String label) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.addV, label);
final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new AddVertexStartStep(traversal, label));
}
/**
* Spawns a {@link GraphTraversal} by adding a vertex with the label as determined by a {@link Traversal}. If the
* {@code vertexLabelTraversal} is {@code null} then it will default to {@link Vertex#DEFAULT_LABEL}.
*/
public GraphTraversal<Vertex, Vertex> addV(final Traversal<?, String> vertexLabelTraversal) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.addV, vertexLabelTraversal);
final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new AddVertexStartStep(traversal, vertexLabelTraversal));
}
/**
* Spawns a {@link GraphTraversal} by adding a vertex with the default label.
*/
public GraphTraversal<Vertex, Vertex> addV() {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.addV);
final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new AddVertexStartStep(traversal, (String)null));
}
/**
* Spawns a {@link GraphTraversal} by adding a edge with the specified label.
*/
public GraphTraversal<Edge, Edge> addE(final String label) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.addE, label);
final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new AddEdgeStartStep(traversal, label));
}
/**
* Spawns a {@link GraphTraversal} by adding a edge with a label as specified by the provided {@link Traversal}.
*/
public GraphTraversal<Edge, Edge> addE(final Traversal<?, String> edgeLabelTraversal) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.addE, edgeLabelTraversal);
final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new AddEdgeStartStep(traversal, edgeLabelTraversal));
}
/**
* Spawns a {@link GraphTraversal} starting it with arbitrary values.
*/
public <S> GraphTraversal<S, S> inject(S... starts) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.inject, starts);
final GraphTraversal.Admin<S, S> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new InjectStep<S>(traversal, starts));
}
/**
* Spawns a {@link GraphTraversal} starting with all vertices or some subset of vertices as specified by their
* unique identifier.
*/
public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.V, vertexIds);
final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new GraphStep<>(traversal, Vertex.class, true, vertexIds));
}
/**
* Spawns a {@link GraphTraversal} starting with all edges or some subset of edges as specified by their unique
* identifier.
*/
public GraphTraversal<Edge, Edge> E(final Object... edgesIds) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.E, edgesIds);
final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new GraphStep<>(traversal, Edge.class, true, edgesIds));
}
/**
* Performs a read or write based operation on the {@link Graph} backing this {@code GraphTraversalSource}. This
* step can be accompanied by the {@link GraphTraversal#with(String, Object)} modulator for further configuration
* and must be accompanied by a {@link GraphTraversal#read()} or {@link GraphTraversal#write()} modulator step
* which will terminate the traversal.
*
* @param file the name of file for which the read or write will apply - note that the context of how this
* parameter is used is wholly dependent on the implementation
* @return the traversal with the {@link IoStep} added
* @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#io-step" target="_blank">Reference Documentation - IO Step</a>
* @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#read-step" target="_blank">Reference Documentation - Read Step</a>
* @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#write-step" target="_blank">Reference Documentation - Write Step</a>
* @since 3.4.0
*/
public <S> GraphTraversal<S, S> io(final String file) {
final GraphTraversalSource clone = this.clone();
clone.bytecode.addStep(GraphTraversal.Symbols.io, file);
final GraphTraversal.Admin<S,S> traversal = new DefaultGraphTraversal<>(clone);
return traversal.addStep(new IoStep<S>(traversal, file));
}
/**
* Proxies calls through to the underlying {@link Graph#tx()}.
*/
public Transaction tx() {
return this.graph.tx();
}
/**
* If there is an underlying {@link RemoteConnection} it will be closed by this method.
*/
@Override
public void close() throws Exception {
if (connection != null) connection.close();
}
@Override
public String toString() {
return StringFactory.traversalSourceString(this);
}
}
| |
package com.thecrafter.loveyoumore;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
import com.thecrafter.loveyoumore.audio.AudioHandler;
import com.thecrafter.loveyoumore.audio.AudioWrapper;
import com.thecrafter.loveyoumore.util.RandomIntGenerator;
import java.io.IOException;
import java.util.Vector;
public class MainActivity extends Activity {
private AudioHandler mAudioHandler;
private AudioHandler mAudioHandler2;
private String[] mMsgArray;
private RandomIntGenerator mMsgIndexGenerator;
private Toast mToast; // Shared toast to show simple messages
private MediaPlayer mClickSoundPlayer; // Media player for onClick sounds
// Animations
private Animation mBumpAnimation;
private Animation mRotateAnimation;
private Animation mFadeAnimation;
// Modes
private enum Mode {
MUSIC1,
TEXT1,
MUSIC2
}
private Mode mMode = Mode.MUSIC1;
private void nextMode() {
Mode next;
switch (mMode) {
case MUSIC1: next = Mode.TEXT1; break;
case TEXT1: next = Mode.MUSIC2; break;
case MUSIC2: next = Mode.MUSIC1; break;
default: next = Mode.MUSIC1;
}
mMode = next;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init onClick Sound Player
mClickSoundPlayer = MediaPlayer.create(this, R.raw.buttonclicksound);
// Init animations
mBumpAnimation = AnimationUtils.loadAnimation(this, R.anim.heart_scaleup_anim);
mRotateAnimation = AnimationUtils.loadAnimation(this, R.anim.heart_rotate_anim);
mFadeAnimation = AnimationUtils.loadAnimation(this, R.anim.heart_fade_anim);
// Create audio vectors and fill them with sound resources
Vector<AudioWrapper> audioVector = new Vector<>();
audioVector.add(new AudioWrapper(this, R.raw.msg1));
audioVector.add(new AudioWrapper(this, R.raw.msg2));
audioVector.add(new AudioWrapper(this, R.raw.msg3));
audioVector.add(new AudioWrapper(this, R.raw.msg4));
audioVector.add(new AudioWrapper(this, R.raw.msg5));
audioVector.add(new AudioWrapper(this, R.raw.msg6));
audioVector.add(new AudioWrapper(this, R.raw.msg7));
audioVector.add(new AudioWrapper(this, R.raw.msg8));
audioVector.add(new AudioWrapper(this, R.raw.msg9));
audioVector.add(new AudioWrapper(this, R.raw.msg10));
audioVector.add(new AudioWrapper(this, R.raw.msg11));
audioVector.add(new AudioWrapper(this, R.raw.msg12));
audioVector.add(new AudioWrapper(this, R.raw.msg13));
audioVector.add(new AudioWrapper(this, R.raw.msg14));
audioVector.add(new AudioWrapper(this, R.raw.msg15));
audioVector.add(new AudioWrapper(this, R.raw.msg16));
audioVector.add(new AudioWrapper(this, R.raw.msg17));
audioVector.add(new AudioWrapper(this, R.raw.msg18));
audioVector.add(new AudioWrapper(this, R.raw.msg19));
audioVector.add(new AudioWrapper(this, R.raw.msg20));
Vector<AudioWrapper> audioVector2 = new Vector<>();
audioVector2.add(new AudioWrapper(this, R.raw.msg21));
audioVector2.add(new AudioWrapper(this, R.raw.msg22));
audioVector2.add(new AudioWrapper(this, R.raw.msg23));
audioVector2.add(new AudioWrapper(this, R.raw.msg24));
audioVector2.add(new AudioWrapper(this, R.raw.msg25));
audioVector2.add(new AudioWrapper(this, R.raw.msg26));
audioVector2.add(new AudioWrapper(this, R.raw.msg27));
audioVector2.add(new AudioWrapper(this, R.raw.msg28));
audioVector2.add(new AudioWrapper(this, R.raw.msg29));
audioVector2.add(new AudioWrapper(this, R.raw.msg30));
audioVector2.add(new AudioWrapper(this, R.raw.msg31));
audioVector2.add(new AudioWrapper(this, R.raw.msg32));
audioVector2.add(new AudioWrapper(this, R.raw.msg33));
audioVector2.add(new AudioWrapper(this, R.raw.msg34));
audioVector2.add(new AudioWrapper(this, R.raw.msg35));
audioVector2.add(new AudioWrapper(this, R.raw.msg36));
audioVector2.add(new AudioWrapper(this, R.raw.msg37));
audioVector2.add(new AudioWrapper(this, R.raw.msg38));
audioVector2.add(new AudioWrapper(this, R.raw.msg39));
// Pass the vector to audio handlers
mAudioHandler = new AudioHandler(audioVector, this);
mAudioHandler2 = new AudioHandler(audioVector2, this);
// Get message array
mMsgArray = getResources().getStringArray(R.array.msg_array);
// Init RandomIntGenerator
mMsgIndexGenerator = new RandomIntGenerator(
mMsgArray.length - 1,
((mMsgArray.length - 1) * 2) / 3);
// Set initial image
ImageView heartImage = (ImageView)findViewById(R.id.heart_img);
heartImage.setImageResource(R.drawable.heart);
heartImage.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// Vibrate for 50 millisecond
Vibrator vibe = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(50);
ImageView heartImage = (ImageView) findViewById(R.id.heart_img);
// Change mode
nextMode();
// Change image
switch (mMode) {
case MUSIC1:
heartImage.setImageResource(R.drawable.heart);
break;
case MUSIC2:
heartImage.setImageResource(R.drawable.heart_yellow);
break;
case TEXT1:
heartImage.setImageResource(R.drawable.heart_purple);
break;
}
return true;
}
});
}
public void onImageClick(View v) {
switch (mMode) {
case MUSIC1: {
// Start bumping animation for heart image
v.startAnimation(mBumpAnimation);
// Update music state
mAudioHandler.update();
break;
}
case MUSIC2: {
v.startAnimation(mFadeAnimation);
// Update music state
mAudioHandler2.update();
break;
}
case TEXT1: {
// Play a System Sound
mClickSoundPlayer.stop();
try {
mClickSoundPlayer.prepare();
}
catch (IOException e){
System.out.println(e.toString());
}
mClickSoundPlayer.seekTo(0);
mClickSoundPlayer.start();
// Start rotate animation for heart image
v.startAnimation(mRotateAnimation);
// Show the next message
if(mToast != null)
mToast.cancel();
mToast = Toast.makeText(this, mMsgArray[mMsgIndexGenerator.getNextInt()], Toast.LENGTH_LONG);
mToast.show();
// Update the next message
mMsgIndexGenerator.updateNextInt();
break;
}
}
}
}
| |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.internal.operators.maybe;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong;
import io.reactivex.annotations.Nullable;
import org.reactivestreams.Subscriber;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.subscriptions.*;
import io.reactivex.internal.util.BackpressureHelper;
/**
* Maps a success value into an Iterable and streams it back as a Flowable.
*
* @param <T> the source value type
* @param <R> the element type of the Iterable
*/
public final class MaybeFlatMapIterableFlowable<T, R> extends Flowable<R> {
final MaybeSource<T> source;
final Function<? super T, ? extends Iterable<? extends R>> mapper;
public MaybeFlatMapIterableFlowable(MaybeSource<T> source,
Function<? super T, ? extends Iterable<? extends R>> mapper) {
this.source = source;
this.mapper = mapper;
}
@Override
protected void subscribeActual(Subscriber<? super R> s) {
source.subscribe(new FlatMapIterableObserver<T, R>(s, mapper));
}
static final class FlatMapIterableObserver<T, R>
extends BasicIntQueueSubscription<R>
implements MaybeObserver<T> {
private static final long serialVersionUID = -8938804753851907758L;
final Subscriber<? super R> actual;
final Function<? super T, ? extends Iterable<? extends R>> mapper;
final AtomicLong requested;
Disposable d;
volatile Iterator<? extends R> it;
volatile boolean cancelled;
boolean outputFused;
FlatMapIterableObserver(Subscriber<? super R> actual,
Function<? super T, ? extends Iterable<? extends R>> mapper) {
this.actual = actual;
this.mapper = mapper;
this.requested = new AtomicLong();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
Iterator<? extends R> iterator;
boolean has;
try {
iterator = mapper.apply(value).iterator();
has = iterator.hasNext();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
actual.onError(ex);
return;
}
if (!has) {
actual.onComplete();
return;
}
this.it = iterator;
drain();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
actual.onComplete();
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
BackpressureHelper.add(requested, n);
drain();
}
}
@Override
public void cancel() {
cancelled = true;
d.dispose();
d = DisposableHelper.DISPOSED;
}
void fastPath(Subscriber<? super R> a, Iterator<? extends R> iterator) {
for (;;) {
if (cancelled) {
return;
}
R v;
try {
v = iterator.next();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
a.onNext(v);
if (cancelled) {
return;
}
boolean b;
try {
b = iterator.hasNext();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
if (!b) {
a.onComplete();
return;
}
}
}
void drain() {
if (getAndIncrement() != 0) {
return;
}
Subscriber<? super R> a = actual;
Iterator<? extends R> iterator = this.it;
if (outputFused && iterator != null) {
a.onNext(null);
a.onComplete();
return;
}
int missed = 1;
for (;;) {
if (iterator != null) {
long r = requested.get();
if (r == Long.MAX_VALUE) {
fastPath(a, iterator);
return;
}
long e = 0L;
while (e != r) {
if (cancelled) {
return;
}
R v;
try {
v = ObjectHelper.requireNonNull(iterator.next(), "The iterator returned a null value");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
a.onNext(v);
if (cancelled) {
return;
}
e++;
boolean b;
try {
b = iterator.hasNext();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
a.onError(ex);
return;
}
if (!b) {
a.onComplete();
return;
}
}
if (e != 0L) {
BackpressureHelper.produced(requested, e);
}
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
if (iterator == null) {
iterator = it;
}
}
}
@Override
public int requestFusion(int mode) {
if ((mode & ASYNC) != 0) {
outputFused = true;
return ASYNC;
}
return NONE;
}
@Override
public void clear() {
it = null;
}
@Override
public boolean isEmpty() {
return it == null;
}
@Nullable
@Override
public R poll() throws Exception {
Iterator<? extends R> iterator = it;
if (iterator != null) {
R v = ObjectHelper.requireNonNull(iterator.next(), "The iterator returned a null value");
if (!iterator.hasNext()) {
it = null;
}
return v;
}
return null;
}
}
}
| |
/*
Copyright 2021 The Kubernetes 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 io.kubernetes.client.openapi;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.gsonfire.GsonFireBuilder;
import io.kubernetes.client.gson.V1StatusPreProcessor;
import io.kubernetes.client.openapi.models.V1Status;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Map;
import okio.ByteString;
public class JSON {
private Gson gson;
private boolean isLenientOnJson = false;
private static final DateTimeFormatter RFC3339MICRO_FORMATTER =
new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 6, 6, true)
.optionalEnd()
.appendLiteral("Z")
.toFormatter();
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter =
new OffsetDateTimeTypeAdapter(RFC3339MICRO_FORMATTER);
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
public static GsonBuilder createGson() {
GsonFireBuilder fireBuilder = new GsonFireBuilder();
GsonBuilder builder =
fireBuilder
.registerPreProcessor(V1Status.class, new V1StatusPreProcessor())
.createGsonBuilder();
return builder;
}
private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
JsonElement element = readElement.getAsJsonObject().get(discriminatorField);
if (null == element) {
throw new IllegalArgumentException(
"missing discriminator field: <" + discriminatorField + ">");
}
return element.getAsString();
}
/**
* Returns the Java class that implements the OpenAPI schema for the specified discriminator
* value.
*
* @param classByDiscriminatorValue The map of discriminator values to Java classes.
* @param discriminatorValue The value of the OpenAPI discriminator in the input data.
* @return The Java class that implements the OpenAPI schema
*/
private static Class getClassByDiscriminator(
Map classByDiscriminatorValue, String discriminatorValue) {
Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue);
if (null == clazz) {
throw new IllegalArgumentException(
"cannot determine model class of name: <" + discriminatorValue + ">");
}
return clazz;
}
public JSON() {
gson =
createGson()
.registerTypeAdapter(Date.class, dateTypeAdapter)
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
.registerTypeAdapter(byte[].class, byteArrayAdapter)
.create();
}
/**
* Get Gson.
*
* @return Gson
*/
public Gson getGson() {
return gson;
}
/**
* Set Gson.
*
* @param gson Gson
* @return JSON
*/
public JSON setGson(Gson gson) {
this.gson = gson;
return this;
}
public JSON setLenientOnJson(boolean lenientOnJson) {
isLenientOnJson = lenientOnJson;
return this;
}
/**
* Serialize the given Java object into JSON string.
*
* @param obj Object
* @return String representation of the JSON
*/
public String serialize(Object obj) {
return gson.toJson(obj);
}
/**
* Deserialize the given JSON string to Java object.
*
* @param <T> Type
* @param body The JSON string
* @param returnType The type to deserialize into
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see
// https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
return gson.fromJson(body, returnType);
}
} catch (JsonParseException e) {
// Fallback processing when failed to parse JSON form response body:
// return the response body string directly for the String return type;
if (returnType.equals(String.class)) {
return (T) body;
} else {
throw (e);
}
}
}
/** Gson TypeAdapter for Byte Array type */
public class ByteArrayAdapter extends TypeAdapter<byte[]> {
@Override
public void write(JsonWriter out, byte[] value) throws IOException {
boolean oldHtmlSafe = out.isHtmlSafe();
out.setHtmlSafe(false);
if (value == null) {
out.nullValue();
} else {
out.value(ByteString.of(value).base64());
}
out.setHtmlSafe(oldHtmlSafe);
}
@Override
public byte[] read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String bytesAsBase64 = in.nextString();
ByteString byteString = ByteString.decodeBase64(bytesAsBase64);
return byteString.toByteArray();
}
}
}
/** Gson TypeAdapter for JSR310 OffsetDateTime type */
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
private DateTimeFormatter formatter;
public OffsetDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public OffsetDateTime read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
if (date.endsWith("+0000")) {
date = date.substring(0, date.length() - 5) + "Z";
}
try {
return OffsetDateTime.parse(date, formatter);
} catch (DateTimeParseException e) {
// backward-compatibility for ISO8601 timestamp format
return OffsetDateTime.parse(date, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
}
}
}
/** Gson TypeAdapter for JSR310 LocalDate type */
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
public LocalDateTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE);
}
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
public void setFormat(DateTimeFormatter dateFormat) {
this.formatter = dateFormat;
}
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
if (date == null) {
out.nullValue();
} else {
out.value(formatter.format(date));
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
return LocalDate.parse(date, formatter);
}
}
}
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
return this;
}
/**
* Gson TypeAdapter for java.sql.Date type If the dateFormat is null, a simple "yyyy-MM-dd" format
* will be used (more efficient than SimpleDateFormat).
*/
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
private DateFormat dateFormat;
public SqlDateTypeAdapter() {}
public SqlDateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, java.sql.Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date> {
private DateFormat dateFormat;
public DateTypeAdapter() {}
public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException {
if (date == null) {
out.nullValue();
} else {
String value;
if (dateFormat != null) {
value = dateFormat.format(date);
} else {
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException {
try {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} catch (IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
}
public JSON setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
}
| |
package org.bbottema.javareflection;
import lombok.experimental.UtilityClass;
import org.bbottema.javareflection.model.MethodModifier;
import org.bbottema.javareflection.util.ExternalClassLoader;
import org.bbottema.javareflection.valueconverter.IncompatibleTypeException;
import org.bbottema.javareflection.valueconverter.ValueConversionHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static org.bbottema.javareflection.LookupCaches.CLASS_CACHE;
import static org.bbottema.javareflection.util.MiscUtil.trustedNullableCast;
/**
* Utility with convenience methods that operate on the class level.
* <ul>
* <li>With this helper class you can locate and/or load classes. An advanced <code>Class</code> lookup ({@link #locateClass(String, boolean,
* ClassLoader)}), that allows a full scan (to try all
* packages known) and an optional {@link ExternalClassLoader} instance that is able to actually compile a .java file on the fly and load its compile
* .class file</li>
* <li>create a new instance while handling all the exceptions</li>
* <li>find fields or assign values to fields, using casting, autoboxing or type conversions</li>
* <li>simply give back a list of field / method names</li>
* </ul>
*/
@UtilityClass
@SuppressWarnings("WeakerAccess")
public final class ClassUtils {
/**
* Searches the JVM and optionally all of its packages
*
* @param className The name of the class to locate.
* @param fullscan Whether a full scan through all available java packages is required.
* @param classLoader Optional user-provided classloader.
* @return The <code>Class</code> reference if found or <code>null</code> otherwise.
*/
@Nullable
@SuppressWarnings({"WeakerAccess", "unchecked"})
public static <T> Class<T> locateClass(final String className, final boolean fullscan, @Nullable final ClassLoader classLoader) {
final String cacheKey = className + fullscan;
if (CLASS_CACHE.containsKey(cacheKey)) {
return (Class<T>) CLASS_CACHE.get(cacheKey);
}
Class<?> _class;
if (fullscan) {
_class = locateClass(className, null, classLoader);
} else {
// try standard package used for most common classes
_class = locateClass(className, "java.lang", classLoader);
if (_class == null) {
_class = locateClass(className, "java.util", classLoader);
}
if (_class == null) {
_class = locateClass(className, "java.math", classLoader);
}
}
CLASS_CACHE.put(cacheKey, _class);
return (Class<T>) _class;
}
@Nullable
@SuppressWarnings({"WeakerAccess", "unchecked"})
public static <T> Class<T> locateClass(final String className, @Nullable final String inPackage, @Nullable final ClassLoader classLoader) {
final String cacheKey = className + inPackage;
if (CLASS_CACHE.containsKey(cacheKey)) {
return (Class<T>) CLASS_CACHE.get(cacheKey);
}
Class<?> _class = locateClass(className, classLoader);
if (_class == null) {
_class = PackageUtils.scanPackagesForClass(className, inPackage, classLoader);
}
CLASS_CACHE.put(cacheKey, _class);
return (Class<T>) _class;
}
/**
* This function dynamically tries to locate a class. First it searches the class-cache list, then it tries to get it from the Virtual Machine
* using {@code Class.forName(String)}.
*
* @param fullClassName The <code>Class</code> that needs to be found.
* @param classLoader Optional user-provided classloader.
* @return The {@code Class} object found from cache or VM.
*/
@SuppressWarnings({"WeakerAccess", "unchecked"})
@Nullable
public static <T> Class<T> locateClass(final String fullClassName, @Nullable final ClassLoader classLoader) {
try {
Class<?> _class = null;
if (classLoader != null) {
_class = classLoader.loadClass(fullClassName);
}
if (_class == null) {
_class = Class.forName(fullClassName);
}
return (Class<T>) _class;
} catch (final ClassNotFoundException e) {
return null;
}
}
/**
* Simply calls {@link Class#newInstance()} and hides the exception handling boilerplate code.
*
* @param _class The datatype for which we need to create a new instance of.
* @param <T> Type used to parameterize the return instance.
* @return A new parameterized instance of the given type.
*/
@NotNull
@SuppressWarnings("WeakerAccess")
public static <T> T newInstanceSimple(final Class<T> _class) {
try {
return _class.getConstructor().newInstance();
} catch (SecurityException e) {
throw new RuntimeException("unable to invoke parameterless constructor; security problem", e);
} catch (InstantiationException e) {
throw new RuntimeException("unable to complete instantiation of object", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("unable to access parameterless constructor", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("unable to invoke parameterless constructor", e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("unable to find parameterless constructor (not public?)", e);
}
}
/**
* Gets value from the field returned by {@link #solveField(Object, String)}.;
*/
@Nullable
@SuppressWarnings("WeakerAccess")
public static <T> T solveFieldValue(final Object object, final String fieldName) {
final Field field = solveField(object, fieldName);
if (field == null) {
throw new RuntimeException(new NoSuchFieldException());
}
field.setAccessible(true);
try {
return trustedNullableCast(field.get(object));
} catch (IllegalAccessException e) {
throw new RuntimeException("Was unable to retrieve value from field %s", e);
}
}
/**
* Delegates to {@link #solveField(Class, String)} by using the class of given object <code>object</code> or if <code>object</code> itself if it ss a class.
*/
@Nullable
@SuppressWarnings("WeakerAccess")
public static Field solveField(final Object object, final String fieldName) {
return object.getClass().equals(Class.class)
? solveField((Class<?>) object, fieldName) // Java static field
: solveField(object.getClass(), fieldName); // Java instance field
}
/**
* Returns a field from the given Class that goes by the name of <code>fieldName</code>. Will search for fields on implemented interfaces and superclasses.
*
* @param _class The reference to the Class to fetch the field from.
* @param fieldName The identifier or name of the member field/property.
* @return The value of the <code>Field</code>.
*/
@Nullable
@SuppressWarnings("WeakerAccess")
public static Field solveField(final Class<?> _class, final String fieldName) {
Field resolvedField = null;
try {
resolvedField = _class.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
for (int i = 0; resolvedField == null && i < _class.getInterfaces().length; i++) {
resolvedField = solveField(_class.getInterfaces()[i], fieldName);
}
for (Class<?> superclass = _class.getSuperclass(); resolvedField == null && superclass != null; superclass = superclass.getSuperclass()) {
resolvedField = solveField(superclass, fieldName);
}
}
return resolvedField;
}
/**
* Assigns a value to a field <code>id</code> on the given object <code>o</code>. If a simple assignment fails, a common conversion will be
* attempted.
*
* @param o The object to find the field on.
* @param property The name of the field we're assigning the value to.
* @param value The value to assign to the field, may be converted to the field's type through common conversion.
* @return The actual value that was assigned (the original or the converted value).
* @throws IllegalAccessException Thrown by {@link Field#set(Object, Object)}
* @throws NoSuchFieldException Thrown if the {@link Field} could not be found, even after trying to convert the value to the target type.
* @see ValueConversionHelper#convert(Object, Class)
*/
@Nullable
@SuppressWarnings("WeakerAccess")
public static Object assignToField(final Object o, final String property, final Object value) throws IllegalAccessException, NoSuchFieldException {
final Field field = solveField(o, property);
if (field != null) {
field.setAccessible(true);
Object assignedValue = value;
try {
field.set(o, value);
} catch (final IllegalArgumentException ie) {
try {
assignedValue = ValueConversionHelper.convert(value, field.getType());
} catch (IncompatibleTypeException e) {
throw new NoSuchFieldException(e.getMessage());
}
field.set(o, assignedValue);
}
return assignedValue;
} else {
throw new NoSuchFieldException();
}
}
/**
* Returns a list of names that represent the fields on an <code>Object</code>.
*
* @param subject The <code>Object</code> who's properties/fields need to be reflected.
* @return A list of names that represent the fields on the given <code>Object</code>.
*/
@NotNull
@SuppressWarnings("WeakerAccess")
public static Collection<String> collectPropertyNames(final Object subject) {
final Collection<String> properties = new LinkedHashSet<>();
final Field[] fields = subject.getClass().getFields();
for (final Field f : fields) {
properties.add(f.getName());
}
return properties;
}
/**
* @return Returns the result of {@link #collectMethods(Class, Class, EnumSet)} mapped to the method names.
*/
@SuppressWarnings("WeakerAccess")
public static Set<String> collectMethodNames(Class<?> dataType, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers) {
Set<String> methodNames = new HashSet<>();
for (Method m : collectMethods(dataType, boundaryMarker, methodModifiers)) {
methodNames.add(m.getName());
}
return methodNames;
}
/**
* @return The result of {@link #collectMethodsMappingToName(Class, Class, EnumSet)} filtered on method name.
*/
@SuppressWarnings("WeakerAccess")
public static List<Method> collectMethodsByName(final Class<?> type, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers, final String methodName) {
LinkedHashMap<String, List<Method>> methodsByName = collectMethodsMappingToName(type, boundaryMarker, methodModifiers);
return methodsByName.containsKey(methodName) ? methodsByName.get(methodName) : new ArrayList<Method>();
}
/**
* @return Whether {@link #collectMethodsMappingToName(Class, Class, EnumSet)} contains a method with the given name.
*/
@SuppressWarnings("WeakerAccess")
public static boolean hasMethodByName(final Class<?> type, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers, final String methodName) {
LinkedHashMap<String, List<Method>> methodsByName = collectMethodsMappingToName(type, boundaryMarker, methodModifiers);
return methodsByName.containsKey(methodName) && !methodsByName.get(methodName).isEmpty();
}
/**
* @return The first result of {@link #collectMethodsByName(Class, Class, EnumSet, String)}.
* <strong>Note: </strong> methods are ordered in groups (see {@link #collectMethods(Class, Class, EnumSet)})).
*/
@Nullable
@SuppressWarnings("WeakerAccess")
public static Method findFirstMethodByName(final Class<?> type, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers, final String methodName) {
List<Method> methods = collectMethodsByName(type, boundaryMarker, methodModifiers, methodName);
return methods.isEmpty() ? null : methods.iterator().next();
}
/**
* @return The result of {@link #collectMethods(Class, Class, EnumSet)} filtered on method name,
* ordered in groups (see {@link #collectMethods(Class, Class, EnumSet)})).
*/
@SuppressWarnings("WeakerAccess")
public static LinkedHashMap<String, List<Method>> collectMethodsMappingToName(Class<?> type, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers) {
LinkedHashMap<String, List<Method>> methodsMappedToName = new LinkedHashMap<>();
for (Method method : collectMethods(type, boundaryMarker, methodModifiers)) {
if (!methodsMappedToName.containsKey(method.getName())) {
methodsMappedToName.put(method.getName(), new ArrayList<Method>());
}
methodsMappedToName.get(method.getName()).add(method);
}
return methodsMappedToName;
}
/**
* Returns a list of names that represent the methods on an <code>Object</code>.
* <p>
* Methods are ordered by their declaring type in the inheritance chain, but unordered for methods of the same type.
* In other words, considering type A, B and C each with methods 1, 2 and 3, the methods might be ordered as follows:
* {@code [A2,A1,B1,B2,C2,C1]}.
*
* @param methodModifiers List of method modifiers that will match any method that has one of them.
* @param boundaryMarker Optional type to limit (including) how far back up the inheritance chain we go for discovering methods.
* @return Returns a list with methods, either {@link Method}s.
*/
@SuppressWarnings("WeakerAccess")
public static List<Method> collectMethods(Class<?> dataType, Class<?> boundaryMarker, EnumSet<MethodModifier> methodModifiers) {
final List<Method> allMethods = new ArrayList<>();
for (Method declaredMethod : dataType.getDeclaredMethods()) {
if (MethodModifier.meetsModifierRequirements(declaredMethod, methodModifiers)) {
allMethods.add(declaredMethod);
}
}
for (Class<?> implementedInterface : dataType.getInterfaces()) {
allMethods.addAll(collectMethods(implementedInterface, boundaryMarker, methodModifiers));
}
if (dataType != boundaryMarker && dataType.getSuperclass() != null) {
allMethods.addAll(collectMethods(dataType.getSuperclass(), boundaryMarker, methodModifiers));
}
return allMethods;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.engine.impl.request;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.sling.api.request.RequestProgressTracker;
/**
* The <code>SlingRequestProgressTracker</code> class provides the
* functionality to track the progress of request processing. Instances of this
* class are provided through the
* {@link org.apache.sling.api.SlingHttpServletRequest#getRequestProgressTracker()}
* method.
* <p>
* The following functionality is provided:
* <ol>
* <li>Track the progress of request processing through the
* {@link #log(String)} and {@link #log(String, Object...)} methods.
* <li>Ability to measure and track processing times of parts of request
* processing through the {@link #startTimer(String)} and
* {@link #logTimer(String)} methods.
* <li>Dumping the recording messages through the
* {@link #dump(PrintWriter)} method.
* <li>Resetting the tracker through the {@link #reset()} method.
* </ol>
* <p>
* <b>Tracking Request Processing</b>
* <p>
* As the request being processed, certain steps may be tracked by calling
* either of the <code>log</code> methods. A tracking entry consists of a time
* stamp managed by this class, and a tracking message noting the actual step being
* tracked.
* <p>
* <b>Timing Processing Steps</b>
* </p>
* Certain steps during request processing may need to be timed in that the time
* required for processing should be recorded. Instances of this class maintain
* a map of named timers. Each timer is started (initialized or reset) by
* calling the {@link #startTimer(String)} method. This method just records the
* starting time of the named timer.
* <p>
* To record the number of milliseconds ellapsed since a timer has been started,
* the {@link #logTimer(String)} method may be called. This method logs the
* tracking entry with message
* consisting of the name of the timer and the number of milliseconds ellapsed
* since the timer was last {@link #startTimer(String) started}. The
* {@link #logTimer(String)} method may be called multiple times to record
* several timed steps.
* <p>
* Additional information can be logged using the {@link #logTimer(String, String, Object...)}
* method.
* <p>
* Calling the {@link #startTimer(String)} method with the name of timer which
* already exists, resets the start time of the named timer to the current
* system time.
* <p>
* <b>Dumping Tracking Entries</b>
* <p>
* The {@link #dump(PrintWriter)} methods writes all tracking entries to the given
* <code>PrintWriter</code>. Each entry is written on a single line
* consisting of the following fields:
* <ol>
* <li>The number of milliseconds since the last {@link #reset()} (or creation)
* of this timer.
* <li>The absolute time of the timer in parenthesis.
* <li>The entry message
* </ol>
*/
public class SlingRequestProgressTracker implements RequestProgressTracker {
/**
* The name of the timer tracking the processing time of the complete
* process.
*/
private static final String REQUEST_PROCESSING_TIMER = "Request Processing";
/** Prefix for log messages */
private static final String LOG_PREFIX = "LOG ";
/** Prefix for comment messages */
private static final String COMMENT_PREFIX = "COMMENT ";
/** TIMER_END format explanation */
private static final String TIMER_END_FORMAT = "{<elapsed msec>,<timer name>} <optional message>";
/** The leading millisecond number is left-padded with white-space to this width. */
private static final int PADDING_WIDTH = 7;
/**
* The system time at creation of this instance or the last {@link #reset()}.
*/
private long processingStart;
/**
* The system time when {@link #done()} was called or -1 while processing is in progress.
*/
private long processingEnd;
/**
* The list of tracking entries.
*/
private final List<TrackingEntry> entries = new ArrayList<TrackingEntry>();
/**
* Map of named timers indexed by timer name storing the system time of
* start of the respective timer.
*/
private final Map<String, Long> namedTimerEntries = new HashMap<String, Long>();
/**
* Creates a new request progress tracker.
*/
public SlingRequestProgressTracker() {
reset();
}
/**
* Resets this timer by removing all current entries and timers and adds an
* initial timer entry
*/
public void reset() {
// remove all entries
entries.clear();
namedTimerEntries.clear();
// enter initial messages
processingStart = startTimerInternal(REQUEST_PROCESSING_TIMER);
processingEnd = -1;
entries.add(new TrackingEntry(COMMENT_PREFIX + "timer_end format is " + TIMER_END_FORMAT));
}
/**
* @see org.apache.sling.api.request.RequestProgressTracker#getMessages()
*/
public Iterator<String> getMessages() {
return new Iterator<String>() {
private final Iterator<TrackingEntry> entryIter = entries.iterator();
public boolean hasNext() {
return entryIter.hasNext();
}
public String next() {
// throws NoSuchElementException if no entries any more
final TrackingEntry entry = entryIter.next();
final long offset = entry.getTimeStamp() - getTimeStamp();
return formatMessage(offset, entry.getMessage());
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
private String formatMessage(long offset, String message) {
// Set exact length to avoid array copies within StringBuilder
final StringBuilder sb = new StringBuilder(PADDING_WIDTH + 1 + message.length() + 1);
final String offsetStr = Long.toString(offset);
for (int i = PADDING_WIDTH - offsetStr.length(); i > 0; i--) {
sb.append(' ');
}
sb.append(offsetStr).append(' ').append(message).append('\n');
return sb.toString();
}
/**
* Dumps the process timer entries to the given writer, one entry per line.
* See the class comments for the rough format of each message line.
*/
public void dump(final PrintWriter writer) {
logTimer(REQUEST_PROCESSING_TIMER,
"Dumping SlingRequestProgressTracker Entries");
final StringBuilder sb = new StringBuilder();
final Iterator<String> messages = getMessages();
while (messages.hasNext()) {
sb.append(messages.next());
}
writer.print(sb.toString());
}
/** Creates an entry with the given message. */
public void log(String message) {
entries.add(new TrackingEntry(LOG_PREFIX + message));
}
/** Creates an entry with the given entry tag and message */
public void log(String format, Object... args) {
String message = MessageFormat.format(format, args);
entries.add(new TrackingEntry(LOG_PREFIX + message));
}
/**
* Starts a named timer. If a timer of the same name already exists, it is
* reset to the current time.
*/
public void startTimer(String name) {
startTimerInternal(name);
}
/**
* Start the named timer and returns the start time in milliseconds.
* Logs a message with format
* <pre>
* TIMER_START{<name>} <optional message>
* </pre>
*/
private long startTimerInternal(String name) {
long timer = System.currentTimeMillis();
namedTimerEntries.put(name, timer);
entries.add(new TrackingEntry(timer, "TIMER_START{" + name + "}"));
return timer;
}
/**
* Log a timer entry, including start, end and elapsed time.
*/
public void logTimer(String name) {
if (namedTimerEntries.containsKey(name)) {
logTimerInternal(name, null, namedTimerEntries.get(name));
}
}
/**
* Log a timer entry, including start, end and elapsed time.
*/
public void logTimer(String name, String format, Object... args) {
if (namedTimerEntries.containsKey(name)) {
logTimerInternal(name, MessageFormat.format(format, args), namedTimerEntries.get(name));
}
}
/**
* Log a timer entry, including start, end and elapsed time using TIMER_END_FORMAT
*/
private void logTimerInternal(String name, String msg, long startTime) {
final StringBuilder sb = new StringBuilder();
sb.append("TIMER_END{");
sb.append(System.currentTimeMillis() - startTime);
sb.append(',');
sb.append(name);
sb.append('}');
if(msg != null) {
sb.append(' ');
sb.append(msg);
}
entries.add(new TrackingEntry(sb.toString()));
}
public void done() {
if(processingEnd != -1) return;
logTimer(REQUEST_PROCESSING_TIMER, REQUEST_PROCESSING_TIMER);
processingEnd = System.currentTimeMillis();
}
private long getTimeStamp() {
return processingStart;
}
public long getDuration() {
if (processingEnd != -1) {
return processingEnd - processingStart;
}
return System.currentTimeMillis() - processingStart;
}
/** Process tracker entry keeping timestamp, tag and message */
private static class TrackingEntry {
// creation time stamp
private final long timeStamp;
// tracking message
private final String message;
TrackingEntry(String message) {
this.timeStamp = System.currentTimeMillis();
this.message = message;
}
TrackingEntry(long timeStamp, String message) {
this.timeStamp = timeStamp;
this.message = message;
}
long getTimeStamp() {
return timeStamp;
}
String getMessage() {
return message;
}
}
}
| |
package gappsockets.client.socksproxyserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.logging.Level;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.MessageProp;
import gappsockets.client.api.ApiService;
import gappsockets.client.api.ErrorHandler;
import gappsockets.client.api.GAppSocketService;
import gappsockets.client.config.AuthMethod;
import gappsockets.client.config.AuthMethods;
import gappsockets.client.config.Config;
import gappsockets.client.config.PasswordHash;
import gappsockets.client.config.User;
import gappsockets.common.socks.AddressType;
import gappsockets.common.socks.ClientMethodSelectionMessage;
import gappsockets.common.socks.Method;
import gappsockets.common.socks.Reply;
import gappsockets.common.socks.ServerMethodSelectionMessage;
import gappsockets.common.socks.SocksReply;
import gappsockets.common.socks.SocksRequest;
import gappsockets.common.socks.Version;
import gappsockets.common.socks.gssapiauth.Message;
import gappsockets.common.socks.gssapiauth.MessageType;
import gappsockets.common.socks.usernamepasswordauth.UsernamePasswordRequest;
import gappsockets.common.socks.usernamepasswordauth.UsernamePasswordResponse;
import gappsockets.common.util.Bytes;
final class Worker implements Runnable {
private static interface DatagramSocketFactory {
DatagramSocket createDatagramSocket() throws SocketException;
}
private static final class DefaultDatagramSocketFactory implements DatagramSocketFactory {
public DefaultDatagramSocketFactory() { }
@Override
public DatagramSocket createDatagramSocket() throws SocketException {
return new DatagramSocket();
}
}
private static final class ErrorHandlerImpl implements ErrorHandler {
public static final ErrorHandlerImpl INSTANCE = new ErrorHandlerImpl();
private ErrorHandlerImpl() { }
@Override
public void handleError(final Throwable t) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in executing GAppSocket",
t);
}
}
private static final class GSSDatagramSocket extends DatagramSocket {
private final GSSContext gssContext;
private final MessageProp messageProp;
public GSSDatagramSocket(
final GSSContext context,
final MessageProp prop) throws SocketException {
this.gssContext = context;
this.messageProp = prop;
}
@Override
public void receive(final DatagramPacket p) throws IOException {
super.receive(p);
byte[] data = p.getData();
Message message = Message.newInstance(data);
byte[] token = message.getToken();
MessageProp prop = new MessageProp(
this.messageProp.getQOP(), this.messageProp.getPrivacy());
try {
token = this.gssContext.unwrap(token, 0, token.length, prop);
} catch (GSSException e) {
throw new IOException(e);
}
p.setData(token);
}
@Override
public void send(final DatagramPacket p) throws IOException {
byte[] data = p.getData();
byte[] token;
MessageProp prop = new MessageProp(
this.messageProp.getQOP(), this.messageProp.getPrivacy());
try {
token = this.gssContext.wrap(data, 0, data.length, prop);
} catch (GSSException e) {
throw new IOException(e);
}
Message message = Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.ENCAPSULATED_USER_DATA,
token);
p.setData(message.toByteArray());
super.send(p);
}
}
private static final class GSSDatagramSocketFactory implements DatagramSocketFactory {
private final GSSContext gssContext;
private final MessageProp messageProp;
public GSSDatagramSocketFactory(
final GSSContext context, final MessageProp prop) {
this.gssContext = context;
this.messageProp = prop;
}
@Override
public DatagramSocket createDatagramSocket() throws SocketException {
return new GSSDatagramSocket(this.gssContext, this.messageProp);
}
}
private static final class GSSSocket extends Socket {
private static enum ProtectionLevel {
NONE(0),
LEVEL_1(1),
LEVEL_2(2),
LEVEL_3(3);
public static ProtectionLevel valueOf(final int i) {
for (ProtectionLevel protectionLevel : ProtectionLevel.values()) {
if (protectionLevel.intValue() == i) {
return protectionLevel;
}
}
throw new IllegalArgumentException(
"no value of the specified int: " + Integer.toString(i));
}
private final int intValue;
private ProtectionLevel(final int iValue) {
this.intValue = iValue;
}
public int intValue() {
return this.intValue;
}
}
private final GSSContext gssContext;
private InputStream inputStream;
private MessageProp messageProp;
private OutputStream outputStream;
private final Socket socket;
public GSSSocket(final GSSContext context, final Socket sock) {
this.gssContext = context;
this.inputStream = null;
this.messageProp = null;
this.outputStream = null;
this.socket = sock;
}
@Override
public void close() throws IOException {
try {
this.gssContext.dispose();
} catch (GSSException e) {
throw new IOException(e);
}
if (this.inputStream != null) {
this.inputStream.close();
}
if (this.outputStream != null) {
this.outputStream.close();
}
this.socket.close();
}
public void doHandshake() throws GSSException, IOException {
InputStream inStream = this.socket.getInputStream();
OutputStream outStream = this.socket.getOutputStream();
byte[] token = null;
while (!this.gssContext.isEstablished()) {
Message message = Message.newInstanceFrom(inStream);
token = message.getToken();
try {
token = this.gssContext.acceptSecContext(token, 0, token.length);
} catch (GSSException e) {
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.ABORT,
null).toByteArray());
outStream.flush();
throw e;
}
if (token == null) {
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.AUTHENTICATION,
new byte[] { }).toByteArray());
outStream.flush();
} else {
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.AUTHENTICATION,
token).toByteArray());
outStream.flush();
}
}
Message message = Message.newInstanceFrom(inStream);
token = message.getToken();
MessageProp prop = new MessageProp(0, false);
try {
token = this.gssContext.unwrap(token, 0, token.length,
new MessageProp(prop.getQOP(), prop.getPrivacy()));
} catch (GSSException e) {
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.ABORT,
null).toByteArray());
outStream.flush();
throw e;
}
ProtectionLevel protectionLevel = ProtectionLevel.valueOf(
Bytes.unsigned(token[0]));
ProtectionLevel protectionLevelChoice = null;
switch (protectionLevel) {
case NONE:
protectionLevelChoice = ProtectionLevel.NONE;
break;
case LEVEL_1:
protectionLevelChoice = ProtectionLevel.LEVEL_1;
break;
case LEVEL_2:
protectionLevelChoice = ProtectionLevel.LEVEL_2;
break;
case LEVEL_3:
protectionLevelChoice = ProtectionLevel.LEVEL_2;
break;
}
token = new byte[] { (byte) protectionLevelChoice.intValue() };
try {
token = this.gssContext.wrap(token, 0, token.length,
new MessageProp(prop.getQOP(), prop.getPrivacy()));
} catch (GSSException e) {
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.ABORT,
null).toByteArray());
outStream.flush();
throw e;
}
outStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.PROTECTION_LEVEL_NEGOTIATION,
token).toByteArray());
outStream.flush();
if (this.socket.isClosed()) {
throw new SocketException("client socket closed due to client "
+ "finding choice of protection level unacceptable");
}
boolean privacyState = false;
switch (protectionLevelChoice) {
case NONE:
return;
case LEVEL_1:
break;
case LEVEL_2:
privacyState = true;
break;
case LEVEL_3:
throw new AssertionError("protection level 3 not supported");
}
this.messageProp = new MessageProp(0, privacyState);
this.inputStream = new GSSUnwrappedInputStream(
this.gssContext, this.messageProp, inStream);
this.outputStream = new GSSWrappedOutputStream(
this.gssContext, this.messageProp, outStream);
}
public GSSContext getGSSContext() {
return this.gssContext;
}
@Override
public InputStream getInputStream() throws IOException {
if (this.inputStream == null) {
return this.socket.getInputStream();
}
return this.inputStream;
}
public MessageProp getMessageProp() {
if (this.messageProp == null) {
return null;
}
return new MessageProp(this.messageProp.getQOP(), this.messageProp.getPrivacy());
}
@Override
public OutputStream getOutputStream() throws IOException {
if (this.outputStream == null) {
return this.socket.getOutputStream();
}
return this.outputStream;
}
@Override
public boolean isClosed() {
return this.socket.isClosed();
}
}
private static final class GSSUnwrappedInputStream extends InputStream {
private byte[] buffer;
private final GSSContext gssContext;
private final InputStream inputStream;
private final MessageProp messageProp;
public GSSUnwrappedInputStream(
final GSSContext context,
final MessageProp prop,
final InputStream inStream) {
this.buffer = new byte[] { };
this.gssContext = context;
this.inputStream = inStream;
this.messageProp = prop;
}
@Override
public void close() throws IOException {
this.buffer = new byte[] { };
}
@Override
public int read() throws IOException {
if (this.buffer.length == 0) {
Message message = Message.newInstanceFrom(this.inputStream);
byte[] token = message.getToken();
MessageProp prop = new MessageProp(
this.messageProp.getQOP(), this.messageProp.getPrivacy());
try {
token = this.gssContext.unwrap(token, 0, token.length, prop);
} catch (GSSException e) {
throw new IOException(e);
}
this.buffer = Arrays.copyOf(token, token.length);
}
int b = this.buffer[0];
this.buffer = Arrays.copyOfRange(this.buffer, 1, this.buffer.length);
return b;
}
}
private static final class GSSWrappedOutputStream extends OutputStream {
private static final int MAX_BUFFER_SIZE = Message.MAX_TOKEN_LENGTH;
private byte[] buffer;
private final GSSContext gssContext;
private final MessageProp messageProp;
private final OutputStream outputStream;
public GSSWrappedOutputStream(
final GSSContext context,
final MessageProp prop,
final OutputStream outStream) {
this.buffer = new byte[] { };
this.gssContext = context;
this.messageProp = prop;
this.outputStream = outStream;
}
@Override
public void close() throws IOException {
this.buffer = new byte[] { };
}
@Override
public void flush() throws IOException {
byte[] token;
MessageProp prop = new MessageProp(
this.messageProp.getQOP(), this.messageProp.getPrivacy());
try {
token = this.gssContext.wrap(this.buffer, 0, this.buffer.length, prop);
} catch (GSSException e) {
throw new IOException(e);
}
this.buffer = new byte[] { };
this.outputStream.write(Message.newInstance(
gappsockets.common.socks.gssapiauth.Version.V1,
MessageType.ENCAPSULATED_USER_DATA,
token).toByteArray());
this.outputStream.flush();
}
@Override
public void write(final int b) throws IOException {
if (this.buffer.length == MAX_BUFFER_SIZE) {
this.flush();
}
this.buffer = Arrays.copyOf(this.buffer, this.buffer.length + 1);
this.buffer[this.buffer.length - 1] = (byte) b;
}
}
private static final int HALF_SECOND = 500;
private static final int TCP_SERVER_SO_TIMEOUT = 60000; // 1 minute
private static final int UDP_SO_TIMEOUT = 60000; // 1 minute
private static void writeThenFlush(
final byte[] b, final OutputStream out) throws IOException {
out.write(b);
out.flush();
}
private final ApiService apiService;
private InputStream clientInputStream;
private OutputStream clientOutputStream;
private Socket clientSocket;
private final Config config;
private DatagramSocketFactory datagramSocketFactory;
public Worker(
final Socket clientSock,
final Config conf,
final ApiService service) {
this.apiService = service;
this.clientInputStream = null;
this.clientOutputStream = null;
this.clientSocket = clientSock;
this.config = conf;
this.datagramSocketFactory = new DefaultDatagramSocketFactory();
}
private boolean authenticateUsingGssapiAuth() throws IOException, GSSException {
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
GSSSocket gssSocket = new GSSSocket(context, this.clientSocket);
gssSocket.doHandshake();
this.clientInputStream = gssSocket.getInputStream();
this.clientOutputStream = gssSocket.getOutputStream();
this.clientSocket = gssSocket;
this.datagramSocketFactory = new GSSDatagramSocketFactory(
gssSocket.getGSSContext(), gssSocket.getMessageProp());
return true;
}
private boolean authenticateUsingUsernamePasswordAuth() throws IOException {
UsernamePasswordRequest usernamePasswordReq = null;
UsernamePasswordResponse usernamePasswordResp = null;
try {
usernamePasswordReq = UsernamePasswordRequest.newInstanceFrom(
this.clientInputStream);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing username/password request",
e);
usernamePasswordResp = UsernamePasswordResponse.newInstance(
gappsockets.common.socks.usernamepasswordauth.Version.V1,
(byte) 0x01);
this.writeThenFlush(usernamePasswordResp.toByteArray());
return false;
}
User user = this.config.getUsers().getLast(
usernamePasswordReq.getUsername());
if (user == null) {
usernamePasswordResp = UsernamePasswordResponse.newInstance(
gappsockets.common.socks.usernamepasswordauth.Version.V1,
(byte) 0x01);
this.writeThenFlush(usernamePasswordResp.toByteArray());
return false;
}
PasswordHash passwordHash = user.getPasswordHash();
PasswordHash otherPasswordHash = PasswordHash.newInstance(
usernamePasswordReq.getPassword(), passwordHash.getSalt());
if (!passwordHash.equals(otherPasswordHash)) {
usernamePasswordResp = UsernamePasswordResponse.newInstance(
gappsockets.common.socks.usernamepasswordauth.Version.V1,
(byte) 0x01);
this.writeThenFlush(usernamePasswordResp.toByteArray());
return false;
}
usernamePasswordResp = UsernamePasswordResponse.newInstance(
gappsockets.common.socks.usernamepasswordauth.Version.V1,
UsernamePasswordResponse.STATUS_SUCCESS);
this.writeThenFlush(usernamePasswordResp.toByteArray());
return true;
}
private void doBind(final SocksRequest socksReq) throws IOException {
if (this.apiService != null) {
this.doBindUsingGAppSockets(socksReq);
return;
}
SocksReply socksRep = null;
int desiredDestinationPort = socksReq.getDesiredDestinationPort();
ServerSocketFactory factory = ServerSocketFactory.getDefault();
ServerSocket serverSocket = null;
try {
serverSocket = factory.createServerSocket(desiredDestinationPort);
serverSocket.setSoTimeout(TCP_SERVER_SO_TIMEOUT);
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in creating incoming socket",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
String serverBoundAddress = serverSocket.getInetAddress().getHostAddress();
AddressType addressType = AddressType.get(serverBoundAddress);
int serverBoundPort = serverSocket.getLocalPort();
socksRep = SocksReply.newInstance(
Version.V5,
Reply.SUCCEEDED,
addressType,
serverBoundAddress,
serverBoundPort);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (IOException e) {
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
} finally {
serverSocket.close();
if (socksRep != null && socksRep.getReply().equals(
Reply.GENERAL_SOCKS_SERVER_FAILURE)) {
return;
}
}
serverBoundAddress = socket.getInetAddress().getHostAddress();
addressType = AddressType.get(serverBoundAddress);
serverBoundPort = socket.getPort();
socksRep = SocksReply.newInstance(
Version.V5,
Reply.SUCCEEDED,
addressType,
serverBoundAddress,
serverBoundPort);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
try {
this.passData(socket);
} finally {
if (!socket.isClosed()) {
socket.close();
}
}
}
private void doBindUsingGAppSockets(
final SocksRequest socksReq) throws IOException {
SocksReply socksRep = null;
GAppSocketService gAppSocketService =
this.apiService.newGAppSocketService();
try {
gAppSocketService.start(ErrorHandlerImpl.INSTANCE);
gAppSocketService.putInput(socksReq.toByteArray());
byte[] b = gAppSocketService.getOutput();
try {
socksRep = SocksReply.newInstance(b);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing SOCKS reply",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
if (socksRep.getReply().equals(Reply.SUCCEEDED)) {
b = gAppSocketService.getOutput();
try {
socksRep = SocksReply.newInstance(b);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing SOCKS reply",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
if (socksRep.getReply().equals(Reply.SUCCEEDED)) {
this.passData(gAppSocketService);
}
}
} finally {
if (!gAppSocketService.isStopped()) {
gAppSocketService.stop();
}
}
}
private void doConnect(final SocksRequest socksReq) throws IOException {
if (this.apiService != null) {
this.doConnectUsingGAppSockets(socksReq);
return;
}
SocksReply socksRep = null;
SocketFactory socketFactory = SocketFactory.getDefault();
Socket serverSocket = null;
try {
serverSocket = socketFactory.createSocket(
socksReq.getDesiredDestinationAddress(),
socksReq.getDesiredDestinationPort());
} catch (UnknownHostException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in creating outgoing socket",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.HOST_UNREACHABLE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in creating outgoing socket",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
String serverBoundAddress = serverSocket.getInetAddress().getHostAddress();
AddressType addressType = AddressType.get(serverBoundAddress);
int serverBoundPort = serverSocket.getPort();
socksRep = SocksReply.newInstance(
Version.V5,
Reply.SUCCEEDED,
addressType,
serverBoundAddress,
serverBoundPort);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
try {
this.passData(serverSocket);
} finally {
if (!serverSocket.isClosed()) {
serverSocket.close();
}
}
}
private void doConnectUsingGAppSockets(
final SocksRequest socksReq) throws IOException {
SocksReply socksRep = null;
GAppSocketService gAppSocketService =
this.apiService.newGAppSocketService();
try {
gAppSocketService.start(ErrorHandlerImpl.INSTANCE);
gAppSocketService.putInput(socksReq.toByteArray());
byte[] b = gAppSocketService.getOutput();
try {
socksRep = SocksReply.newInstance(b);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing SOCKS reply",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
if (socksRep.getReply().equals(Reply.SUCCEEDED)) {
this.passData(gAppSocketService);
}
} finally {
if (!gAppSocketService.isStopped()) {
gAppSocketService.stop();
}
}
}
private void doUdpAssociate(final SocksRequest socksReq) throws IOException {
if (this.apiService != null) {
this.doUdpAssociateUsingGAppSockets(socksReq);
return;
}
SocksReply socksRep = null;
String desiredDestinationAddress = socksReq.getDesiredDestinationAddress();
int desiredDestinationPort = socksReq.getDesiredDestinationPort();
DatagramSocket serverSock = null;
try {
serverSock = new DatagramSocket();
serverSock.setSoTimeout(UDP_SO_TIMEOUT);
} catch (SocketException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting UDP association",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
DatagramSocket clientSock = null;
try {
clientSock = this.datagramSocketFactory.createDatagramSocket();
clientSock.setSoTimeout(UDP_SO_TIMEOUT);
} catch (SocketException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting UDP association",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
if (!serverSock.isClosed()) {
serverSock.close();
}
return;
}
String serverBoundAddress = clientSock.getLocalAddress().getHostAddress();
AddressType addressType = AddressType.get(serverBoundAddress);
int serverBoundPort = clientSock.getLocalPort();
socksRep = SocksReply.newInstance(
Version.V5,
Reply.SUCCEEDED,
addressType,
serverBoundAddress,
serverBoundPort);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
UdpRelayServer udpRelayServer = new UdpRelayServer(
clientSock,
serverSock,
desiredDestinationAddress,
desiredDestinationPort);
try {
udpRelayServer.start();
while (!this.clientSocket.isClosed()
&& !udpRelayServer.isStopped()) {
try {
Thread.sleep(HALF_SECOND);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting UDP association",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
} finally {
if (!udpRelayServer.isStopped()) {
udpRelayServer.stop();
}
if (!clientSock.isClosed()) {
clientSock.close();
}
if (!serverSock.isClosed()) {
serverSock.close();
}
}
}
private void doUdpAssociateUsingGAppSockets(
final SocksRequest socksReq) throws IOException {
SocksReply socksRep = null;
GAppSocketService gAppSocketService =
this.apiService.newGAppSocketService();
try {
gAppSocketService.start(ErrorHandlerImpl.INSTANCE);
gAppSocketService.putInput(socksReq.toByteArray());
byte[] b = gAppSocketService.getOutput();
try {
socksRep = SocksReply.newInstance(b);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing SOCKS reply",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
LoggerHolder.LOGGER.fine(socksRep.toString());
if (!socksRep.getReply().equals(Reply.SUCCEEDED)) {
this.writeThenFlush(socksRep.toByteArray());
} else {
DatagramSocket clientSock = null;
try {
clientSock = this.datagramSocketFactory.createDatagramSocket();
clientSock.setSoTimeout(UDP_SO_TIMEOUT);
} catch (SocketException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting UDP association",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
String serverBoundAddress = clientSock.getLocalAddress().getHostAddress();
AddressType addressType = AddressType.get(serverBoundAddress);
int serverBoundPort = clientSock.getLocalPort();
socksRep = SocksReply.newInstance(
Version.V5,
Reply.SUCCEEDED,
addressType,
serverBoundAddress,
serverBoundPort);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
UdpToGAppRelayServer udpToGAppRelayServer =
new UdpToGAppRelayServer(
clientSock,
gAppSocketService);
try {
udpToGAppRelayServer.start();
while (!this.clientSocket.isClosed()
&& !udpToGAppRelayServer.isStopped()) {
try {
Thread.sleep(HALF_SECOND);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting UDP association",
e);
socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
} finally {
if (!udpToGAppRelayServer.isStopped()) {
udpToGAppRelayServer.stop();
}
if (!clientSock.isClosed()) {
clientSock.close();
}
}
}
} finally {
if (!gAppSocketService.isStopped()) {
gAppSocketService.stop();
}
}
}
private void passData(final GAppSocketService gAppSocketService) {
TcpToGAppRelayServer tcpToGAppRelayServer = new TcpToGAppRelayServer(
this.clientSocket, gAppSocketService);
try {
tcpToGAppRelayServer.start();
while (!tcpToGAppRelayServer.isStopped()) {
try {
Thread.sleep(HALF_SECOND);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting to pass data",
e);
} finally {
if (!tcpToGAppRelayServer.isStopped()) {
tcpToGAppRelayServer.stop();
}
}
}
private void passData(final Socket serverSocket) {
TcpRelayServer tcpRelayServer = new TcpRelayServer(
this.clientSocket, serverSocket);
try {
tcpRelayServer.start();
while (!tcpRelayServer.isStopped()) {
try {
Thread.sleep(HALF_SECOND);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in starting to pass data",
e);
} finally {
if (!tcpRelayServer.isStopped()) {
tcpRelayServer.stop();
}
}
}
public void run() {
try {
try {
this.clientInputStream = this.clientSocket.getInputStream();
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in getting input stream for client",
e);
return;
}
try {
this.clientOutputStream = this.clientSocket.getOutputStream();
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in getting output stream for client",
e);
return;
}
ClientMethodSelectionMessage cmsm = null;
try {
cmsm = ClientMethodSelectionMessage.newInstanceFrom(
this.clientInputStream);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing method selection message from client",
e);
return;
}
LoggerHolder.LOGGER.fine(cmsm.toString());
Method method = null;
AuthMethods authMethods = this.config.getAuthMethods();
for (AuthMethod authMethod : authMethods.toList()) {
Method meth = authMethod.getMethod();
if (cmsm.getMethods().contains(meth)) {
method = meth;
break;
}
}
if (method == null) {
method = Method.NO_ACCEPTABLE_METHODS;
}
ServerMethodSelectionMessage smsm =
ServerMethodSelectionMessage.newInstance(Version.V5, method);
LoggerHolder.LOGGER.fine(smsm.toString());
this.writeThenFlush(smsm.toByteArray());
switch (method) {
case NO_AUTHENTICATION_REQUIRED:
// No need to do anything
break;
case GSSAPI:
if (!this.authenticateUsingGssapiAuth()) { return; }
break;
case USERNAME_PASSWORD:
if (!this.authenticateUsingUsernamePasswordAuth()) { return; }
break;
case NO_ACCEPTABLE_METHODS:
return;
}
SocksRequest socksReq = null;
try {
socksReq = SocksRequest.newInstanceFrom(this.clientInputStream);
} catch (IllegalArgumentException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error in parsing SOCKS request",
e);
SocksReply socksRep = SocksReply.newInstance(
Version.V5,
Reply.GENERAL_SOCKS_SERVER_FAILURE,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
return;
}
LoggerHolder.LOGGER.fine(socksReq.toString());
switch (socksReq.getCommand()) {
case BIND:
this.doBind(socksReq);
break;
case CONNECT:
this.doConnect(socksReq);
break;
case UDP_ASSOCIATE:
this.doUdpAssociate(socksReq);
break;
default:
SocksReply socksRep = SocksReply.newInstance(
Version.V5,
Reply.COMMAND_NOT_SUPPORTED,
AddressType.IP_V4_ADDRESS,
AddressType.IP_V4_ADDRESS.getAddressOfAllZeroes(),
0);
LoggerHolder.LOGGER.fine(socksRep.toString());
this.writeThenFlush(socksRep.toByteArray());
break;
}
} catch (Throwable t) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Internal server error",
t);
} finally {
if (!this.clientSocket.isClosed()) {
try {
this.clientSocket.close();
} catch (IOException e) {
LoggerHolder.LOGGER.log(
Level.WARNING,
"Error upon closing connection to client",
e);
}
}
}
}
private void writeThenFlush(final byte[] b) throws IOException {
writeThenFlush(b, this.clientOutputStream);
}
}
| |
/*
* 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.activemq.store.memory;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.SubscriptionInfo;
import org.apache.activemq.store.MessageRecoveryListener;
import org.apache.activemq.store.MessageStoreStatistics;
import org.apache.activemq.store.MessageStoreSubscriptionStatistics;
import org.apache.activemq.store.TopicMessageStore;
import org.apache.activemq.util.LRUCache;
import org.apache.activemq.util.SubscriptionKey;
public class MemoryTopicMessageStore extends MemoryMessageStore implements TopicMessageStore {
private Map<SubscriptionKey, SubscriptionInfo> subscriberDatabase;
private Map<SubscriptionKey, MemoryTopicSub> topicSubMap;
private final Map<MessageId, Message> originalMessageTable;
public MemoryTopicMessageStore(ActiveMQDestination destination) {
this(destination, new MemoryTopicMessageStoreLRUCache(100, 100, 0.75f, false), makeSubscriptionInfoMap());
// Set the messageStoreStatistics after the super class is initialized
// so that the stats can be properly updated on cache eviction
MemoryTopicMessageStoreLRUCache cache = (MemoryTopicMessageStoreLRUCache) originalMessageTable;
cache.setMessageStoreStatistics(messageStoreStatistics);
}
public MemoryTopicMessageStore(ActiveMQDestination destination, Map<MessageId, Message> messageTable,
Map<SubscriptionKey, SubscriptionInfo> subscriberDatabase) {
super(destination, messageTable);
this.subscriberDatabase = subscriberDatabase;
this.topicSubMap = makeSubMap();
// this is only necessary so that messageStoreStatistics can be set if
// necessary We need the original reference since messageTable is wrapped
// in a synchronized map in the parent class
this.originalMessageTable = messageTable;
}
protected static Map<SubscriptionKey, SubscriptionInfo> makeSubscriptionInfoMap() {
return Collections.synchronizedMap(new HashMap<SubscriptionKey, SubscriptionInfo>());
}
protected static Map<SubscriptionKey, MemoryTopicSub> makeSubMap() {
return Collections.synchronizedMap(new HashMap<SubscriptionKey, MemoryTopicSub>());
}
@Override
public synchronized void addMessage(ConnectionContext context, Message message) throws IOException {
super.addMessage(context, message);
for (MemoryTopicSub sub : topicSubMap.values()) {
sub.addMessage(message.getMessageId(), message);
}
}
@Override
public synchronized void acknowledge(ConnectionContext context, String clientId, String subscriptionName, MessageId messageId, MessageAck ack) throws IOException {
super.removeMessage(messageId);
SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName);
MemoryTopicSub sub = topicSubMap.get(key);
if (sub != null) {
sub.removeMessage(messageId);
}
}
@Override
public synchronized SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException {
return subscriberDatabase.get(new SubscriptionKey(clientId, subscriptionName));
}
@Override
public synchronized void addSubscription(SubscriptionInfo info, boolean retroactive) throws IOException {
SubscriptionKey key = new SubscriptionKey(info);
MemoryTopicSub sub = new MemoryTopicSub(key);
topicSubMap.put(key, sub);
if (retroactive) {
for (Map.Entry<MessageId, Message> entry : messageTable.entrySet()) {
sub.addMessage(entry.getKey(), entry.getValue());
}
}
subscriberDatabase.put(key, info);
}
@Override
public synchronized void deleteSubscription(String clientId, String subscriptionName) {
SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName);
subscriberDatabase.remove(key);
MemoryTopicSub subscription = topicSubMap.get(key);
if (subscription != null) {
List<Message> storedMessages = subscription.getStoredMessages();
for (Message message : storedMessages) {
try {
acknowledge(null, key.getClientId(), key.getSubscriptionName(), message.getMessageId(), null);
} catch (IOException e) {
}
}
}
subscriberDatabase.remove(key);
topicSubMap.remove(key);
}
@Override
public synchronized void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) throws Exception {
MemoryTopicSub sub = topicSubMap.get(new SubscriptionKey(clientId, subscriptionName));
if (sub != null) {
sub.recoverSubscription(listener);
}
}
@Override
public synchronized void delete() {
super.delete();
subscriberDatabase.clear();
topicSubMap.clear();
}
@Override
public SubscriptionInfo[] getAllSubscriptions() throws IOException {
return subscriberDatabase.values().toArray(new SubscriptionInfo[subscriberDatabase.size()]);
}
@Override
public synchronized int getMessageCount(String clientId, String subscriberName) throws IOException {
int result = 0;
MemoryTopicSub sub = topicSubMap.get(new SubscriptionKey(clientId, subscriberName));
if (sub != null) {
result = sub.size();
}
return result;
}
@Override
public synchronized long getMessageSize(String clientId, String subscriberName) throws IOException {
long result = 0;
MemoryTopicSub sub = topicSubMap.get(new SubscriptionKey(clientId, subscriberName));
if (sub != null) {
result = sub.messageSize();
}
return result;
}
@Override
public synchronized void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, MessageRecoveryListener listener) throws Exception {
MemoryTopicSub sub = this.topicSubMap.get(new SubscriptionKey(clientId, subscriptionName));
if (sub != null) {
sub.recoverNextMessages(maxReturned, listener);
}
}
@Override
public void resetBatching(String clientId, String subscriptionName) {
MemoryTopicSub sub = topicSubMap.get(new SubscriptionKey(clientId, subscriptionName));
if (sub != null) {
sub.resetBatching();
}
}
// Disabled for the memory store, can be enabled later if necessary
private final MessageStoreSubscriptionStatistics stats = new MessageStoreSubscriptionStatistics(false);
@Override
public MessageStoreSubscriptionStatistics getMessageStoreSubStatistics() {
return stats;
}
/**
* Since we initialize the store with a LRUCache in some cases, we need to
* account for cache evictions when computing the message store statistics.
*
*/
private static class MemoryTopicMessageStoreLRUCache extends LRUCache<MessageId, Message> {
private static final long serialVersionUID = -342098639681884413L;
private MessageStoreStatistics messageStoreStatistics;
public MemoryTopicMessageStoreLRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) {
super(initialCapacity, maximumCacheSize, loadFactor, accessOrder);
}
public void setMessageStoreStatistics(MessageStoreStatistics messageStoreStatistics) {
this.messageStoreStatistics = messageStoreStatistics;
}
@Override
protected void onCacheEviction(Map.Entry<MessageId, Message> eldest) {
decMessageStoreStatistics(messageStoreStatistics, eldest.getValue());
// We aren't tracking this anymore so remove our reference to it.
eldest.getValue().decrementReferenceCount();
}
}
}
| |
/*
* Copyright 2004,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.rampart;
import org.apache.axis2.context.MessageContext;
import org.apache.neethi.Policy;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.conversation.ConversationConstants;
import javax.xml.namespace.QName;
import java.util.ArrayList;
public class AsymmetricBindingBuilderTest extends MessageBuilderTestBase {
public void testAsymmBinding() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-1.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.WSSE_NS, WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingServerSide() {
try {
MessageContext ctx = getMsgCtx();
ctx.setServerSide(true);
String policyXml = "test-resources/policy/rampart-asymm-binding-1.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingWithSigDK() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-2-sig-dk.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.WSSE_NS, WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingWithDK() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-3-dk.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.WSSE_NS, WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingWithDKEncrBeforeSig() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-4-dk-ebs.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.REF_LIST_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingEncrBeforeSig() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-5-ebs.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(WSConstants.WSSE_NS, WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.REF_LIST_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingTripleDesRSA15() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-6-3des-r15.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(WSConstants.WSSE_NS, WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testAsymmBindingTripleDesRSA15DK() {
try {
MessageContext ctx = getMsgCtx();
String policyXml = "test-resources/policy/rampart-asymm-binding-7-3des-r15-DK.xml";
Policy policy = this.loadPolicy(policyXml);
ctx.setProperty(RampartMessageData.KEY_RAMPART_POLICY, policy);
MessageBuilder builder = new MessageBuilder();
builder.build(ctx);
ArrayList list = new ArrayList();
list.add(new QName(WSConstants.WSU_NS, WSConstants.TIMESTAMP_TOKEN_LN));
list.add(new QName(WSConstants.WSSE_NS,WSConstants.BINARY_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.ENC_KEY_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.ENC_NS, WSConstants.REF_LIST_LN));
list.add(new QName(ConversationConstants.WSC_NS_05_02, ConversationConstants.DERIVED_KEY_TOKEN_LN));
list.add(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN));
this.verifySecHeader(list.iterator(), ctx.getEnvelope());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| |
/*
* Copyright (C) 2015 Willi Ye
*
* 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.kunalkene1797.blackboxkit.fragments.kernel;
import android.os.Bundle;
import com.kunalkene1797.blackboxkit.R;
import com.kunalkene1797.blackboxkit.elements.DAdapter;
import com.kunalkene1797.blackboxkit.elements.DividerCardView;
import com.kunalkene1797.blackboxkit.elements.PopupCardItem;
import com.kunalkene1797.blackboxkit.elements.SeekBarCardView;
import com.kunalkene1797.blackboxkit.elements.SwitchCardView;
import com.kunalkene1797.blackboxkit.fragments.RecyclerViewFragment;
import com.kunalkene1797.blackboxkit.utils.kernel.CPU;
import com.kunalkene1797.blackboxkit.utils.kernel.CPUHotplug;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by willi on 06.02.15.
*/
public class CPUHotplugFragment extends RecyclerViewFragment implements
SwitchCardView.DSwitchCard.OnDSwitchCardListener,
PopupCardItem.DPopupCard.OnDPopupCardListener, SeekBarCardView.DSeekBarCardView.OnDSeekBarCardListener {
private SwitchCardView.DSwitchCard mMpdecisionCard;
private SwitchCardView.DSwitchCard mIntelliPlugCard;
private PopupCardItem.DPopupCard mIntelliPlugProfileCard;
private SwitchCardView.DSwitchCard mIntelliPlugEcoCard;
private SwitchCardView.DSwitchCard mIntelliPlugTouchBoostCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugHysteresisCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugThresholdCard;
private PopupCardItem.DPopupCard mIntelliPlugScreenOffMaxCard;
private SwitchCardView.DSwitchCard mIntelliPlugDebugCard;
private SwitchCardView.DSwitchCard mIntelliPlugSuspendCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugCpusBoostedCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugMinCpusOnlineCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugMaxCpusOnlineCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugMaxCpusOnlineSuspCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugSuspendDeferTimeCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugDeferSamplingCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugBoostLockDurationCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugDownLockDurationCard;
private SeekBarCardView.DSeekBarCardView mIntelliPlugFShiftCard;
private SwitchCardView.DSwitchCard mBluPlugCard;
private SwitchCardView.DSwitchCard mBluPlugPowersaverModeCard;
private SeekBarCardView.DSeekBarCardView mBluPlugMinOnlineCard;
private SeekBarCardView.DSeekBarCardView mBluPlugMaxOnlineCard;
private SeekBarCardView.DSeekBarCardView mBluPlugMaxCoresScreenOffCard;
private PopupCardItem.DPopupCard mBluPlugMaxFreqScreenOffCard;
private SeekBarCardView.DSeekBarCardView mBluPlugUpThresholdCard;
private SeekBarCardView.DSeekBarCardView mBluPlugUpTimerCntCard;
private SeekBarCardView.DSeekBarCardView mBluPlugDownTimerCntCard;
private SwitchCardView.DSwitchCard mMsmHotplugEnabledCard;
private SwitchCardView.DSwitchCard mMsmHotplugDebugMaskCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugMinCpusOnlineCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugMaxCpusOnlineCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugCpusBoostedCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugCpusOnlineSuspCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugBoostLockDurationCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugDownLockDurationCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugHistorySizeCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugUpdateRateCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugFastLaneLoadCard;
private PopupCardItem.DPopupCard mMsmHotplugFastLaneMinFreqCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugOfflineLoadCard;
private SwitchCardView.DSwitchCard mMsmHotplugIoIsBusyCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugSuspendMaxCpusCard;
private PopupCardItem.DPopupCard mMsmHotplugSuspendFreqCard;
private SeekBarCardView.DSeekBarCardView mMsmHotplugSuspendDeferTimeCard;
private SwitchCardView.DSwitchCard mMakoHotplugEnableCard;
private SeekBarCardView.DSeekBarCardView mMakoCoreOnTouchCard;
private PopupCardItem.DPopupCard mMakoHotplugCpuFreqUnplugLimitCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugFirstLevelCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugHighLoadCounterCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugLoadThresholdCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugMaxLoadCounterCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugMinTimeCpuOnlineCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugMinCoresOnlineCard;
private SeekBarCardView.DSeekBarCardView mMakoHotplugTimerCard;
private PopupCardItem.DPopupCard mMakoSuspendFreqCard;
private SwitchCardView.DSwitchCard mMBHotplugEnableCard;
private SwitchCardView.DSwitchCard mMBHotplugScroffSingleCoreCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugMinCpusCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugMaxCpusCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugMaxCpusOnlineSuspCard;
private PopupCardItem.DPopupCard mMBHotplugIdleFreqCard;
private SwitchCardView.DSwitchCard mMBHotplugBoostEnableCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugBoostTimeCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugCpusBoostedCard;
private PopupCardItem.DPopupCard[] mMBHotplugBoostFreqsCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugStartDelayCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugDelayCard;
private SeekBarCardView.DSeekBarCardView mMBHotplugPauseCard;
private SwitchCardView.DSwitchCard mAlucardHotplugEnableCard;
private SwitchCardView.DSwitchCard mAlucardHotplugHpIoIsBusyCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugSamplingRateCard;
private SwitchCardView.DSwitchCard mAlucardHotplugSuspendCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugMinCpusOnlineCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugMaxCoresLimitCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugMaxCoresLimitSleepCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugCpuDownRateCard;
private SeekBarCardView.DSeekBarCardView mAlucardHotplugCpuUpRateCard;
private SwitchCardView.DSwitchCard mThunderPlugEnableCard;
private SeekBarCardView.DSeekBarCardView mThunderPlugSuspendCpusCard;
private PopupCardItem.DPopupCard mThunderPlugEnduranceLevelCard;
private SeekBarCardView.DSeekBarCardView mThunderPlugSamplingRateCard;
private SeekBarCardView.DSeekBarCardView mThunderPlugLoadThresholdCard;
private SwitchCardView.DSwitchCard mThunderPlugTouchBoostCard;
private SwitchCardView.DSwitchCard mZenDecisionEnableCard;
private SeekBarCardView.DSeekBarCardView mZenDecisionWakeWaitTimeCard;
private SeekBarCardView.DSeekBarCardView mZenDecisionBatThresholdIgnoreCard;
private SwitchCardView.DSwitchCard mAutoSmpEnableCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpCpufreqDownCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpCpufreqUpCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpCycleDownCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpCycleUpCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpDelayCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpMaxCpusCard;
private SeekBarCardView.DSeekBarCardView mAutoSmpMinCpusCard;
private SwitchCardView.DSwitchCard mAutoSmpScroffSingleCoreCard;
@Override
public void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
if (CPUHotplug.hasMpdecision()) mpdecisionInit();
if (CPUHotplug.hasIntelliPlug()) intelliPlugInit();
if (CPUHotplug.hasBluPlug()) bluPlugInit();
if (CPUHotplug.hasMsmHotplug()) msmHotplugInit();
if (CPUHotplug.hasMakoHotplug()) makoHotplugInit();
if (CPUHotplug.hasMBHotplug()) mbHotplugInit();
if (CPUHotplug.hasAlucardHotplug()) alucardHotplugInit();
if (CPUHotplug.hasThunderPlug()) thunderPlugInit();
if (CPUHotplug.hasZenDecision()) zenDecisionInit();
if (CPUHotplug.hasAutoSmp()) autoSmpInit();
}
private void mpdecisionInit() {
mMpdecisionCard = new SwitchCardView.DSwitchCard();
mMpdecisionCard.setTitle(getString(R.string.mpdecision));
mMpdecisionCard.setDescription(getString(R.string.mpdecision_summary));
mMpdecisionCard.setChecked(CPUHotplug.isMpdecisionActive());
mMpdecisionCard.setOnDSwitchCardListener(this);
addView(mMpdecisionCard);
}
private void intelliPlugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasIntelliPlugEnable()) {
mIntelliPlugCard = new SwitchCardView.DSwitchCard();
mIntelliPlugCard.setTitle(getString(R.string.intelliplug));
mIntelliPlugCard.setDescription(getString(R.string.intelliplug_summary));
mIntelliPlugCard.setChecked(CPUHotplug.isIntelliPlugActive());
mIntelliPlugCard.setOnDSwitchCardListener(this);
views.add(mIntelliPlugCard);
}
if (CPUHotplug.hasIntelliPlugProfile()) {
mIntelliPlugProfileCard = new PopupCardItem.DPopupCard(CPUHotplug.getIntelliPlugProfileMenu(getActivity()));
mIntelliPlugProfileCard.setTitle(getString(R.string.profile));
mIntelliPlugProfileCard.setDescription(getString(R.string.profile_summary));
mIntelliPlugProfileCard.setItem(CPUHotplug.getIntelliPlugProfile());
mIntelliPlugProfileCard.setOnDPopupCardListener(this);
views.add(mIntelliPlugProfileCard);
}
if (CPUHotplug.hasIntelliPlugEco()) {
mIntelliPlugEcoCard = new SwitchCardView.DSwitchCard();
mIntelliPlugEcoCard.setTitle(getString(R.string.eco_mode));
mIntelliPlugEcoCard.setDescription(getString(R.string.eco_mode_summary));
mIntelliPlugEcoCard.setChecked(CPUHotplug.isIntelliPlugEcoActive());
mIntelliPlugEcoCard.setOnDSwitchCardListener(this);
views.add(mIntelliPlugEcoCard);
}
if (CPUHotplug.hasIntelliPlugTouchBoost()) {
mIntelliPlugTouchBoostCard = new SwitchCardView.DSwitchCard();
mIntelliPlugTouchBoostCard.setTitle(getString(R.string.touch_boost));
mIntelliPlugTouchBoostCard.setDescription(getString(R.string.touch_boost_summary));
mIntelliPlugTouchBoostCard.setChecked(CPUHotplug.isIntelliPlugTouchBoostActive());
mIntelliPlugTouchBoostCard.setOnDSwitchCardListener(this);
views.add(mIntelliPlugTouchBoostCard);
}
if (CPUHotplug.hasIntelliPlugHysteresis()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 17; i++)
list.add(String.valueOf(i));
mIntelliPlugHysteresisCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugHysteresisCard.setTitle(getString(R.string.hysteresis));
mIntelliPlugHysteresisCard.setDescription(getString(R.string.hysteresis_summary));
mIntelliPlugHysteresisCard.setProgress(CPUHotplug.getIntelliPlugHysteresis());
mIntelliPlugHysteresisCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugHysteresisCard);
}
if (CPUHotplug.hasIntelliPlugThresold()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 1001; i++)
list.add(String.valueOf(i));
mIntelliPlugThresholdCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugThresholdCard.setTitle(getString(R.string.threshold));
mIntelliPlugThresholdCard.setProgress(CPUHotplug.getIntelliPlugThresold());
mIntelliPlugThresholdCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugThresholdCard);
}
if (CPUHotplug.hasIntelliPlugScreenOffMax() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mIntelliPlugScreenOffMaxCard = new PopupCardItem.DPopupCard(list);
mIntelliPlugScreenOffMaxCard.setTitle(getString(R.string.cpu_max_screen_off_freq));
mIntelliPlugScreenOffMaxCard.setDescription(getString(R.string.cpu_max_screen_off_freq_summary));
mIntelliPlugScreenOffMaxCard.setItem(CPUHotplug.getIntelliPlugScreenOffMax());
mIntelliPlugScreenOffMaxCard.setOnDPopupCardListener(this);
views.add(mIntelliPlugScreenOffMaxCard);
}
if (CPUHotplug.hasIntelliPlugDebug()) {
mIntelliPlugDebugCard = new SwitchCardView.DSwitchCard();
mIntelliPlugDebugCard.setTitle(getString(R.string.debug));
mIntelliPlugDebugCard.setDescription(getString(R.string.debug_summary));
mIntelliPlugDebugCard.setChecked(CPUHotplug.isIntelliPlugDebugActive());
mIntelliPlugDebugCard.setOnDSwitchCardListener(this);
views.add(mIntelliPlugDebugCard);
}
if (CPUHotplug.hasIntelliPlugSuspend()) {
mIntelliPlugSuspendCard = new SwitchCardView.DSwitchCard();
mIntelliPlugSuspendCard.setTitle(getString(R.string.suspend));
mIntelliPlugSuspendCard.setDescription(getString(R.string.suspend_summary));
mIntelliPlugSuspendCard.setChecked(CPUHotplug.isIntelliPlugSuspendActive());
mIntelliPlugSuspendCard.setOnDSwitchCardListener(this);
views.add(mIntelliPlugSuspendCard);
}
if (CPUHotplug.hasIntelliPlugCpusBoosted()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mIntelliPlugCpusBoostedCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugCpusBoostedCard.setTitle(getString(R.string.cpus_boosted));
mIntelliPlugCpusBoostedCard.setDescription(getString(R.string.cpus_boosted_summary));
mIntelliPlugCpusBoostedCard.setProgress(CPUHotplug.getIntelliPlugCpusBoosted() - 1);
mIntelliPlugCpusBoostedCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugCpusBoostedCard);
}
if (CPUHotplug.hasIntelliPlugMinCpusOnline()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mIntelliPlugMinCpusOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugMinCpusOnlineCard.setTitle(getString(R.string.min_cpu_online));
mIntelliPlugMinCpusOnlineCard.setDescription(getString(R.string.min_cpu_online_summary));
mIntelliPlugMinCpusOnlineCard.setProgress(CPUHotplug.getIntelliPlugMinCpusOnline() - 1);
mIntelliPlugMinCpusOnlineCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugMinCpusOnlineCard);
}
if (CPUHotplug.hasIntelliPlugMaxCpusOnline()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mIntelliPlugMaxCpusOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugMaxCpusOnlineCard.setTitle(getString(R.string.max_cpu_online));
mIntelliPlugMaxCpusOnlineCard.setDescription(getString(R.string.max_cpu_online_summary));
mIntelliPlugMaxCpusOnlineCard.setProgress(CPUHotplug.getIntelliPlugMaxCpusOnline() - 1);
mIntelliPlugMaxCpusOnlineCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugMaxCpusOnlineCard);
}
if (CPUHotplug.hasIntelliPlugMaxCpusOnlineSusp()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mIntelliPlugMaxCpusOnlineSuspCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugMaxCpusOnlineSuspCard.setTitle(getString(R.string.max_cores_screen_off));
mIntelliPlugMaxCpusOnlineSuspCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mIntelliPlugMaxCpusOnlineSuspCard.setProgress(CPUHotplug.getIntelliPlugMaxCpusOnlineSusp() - 1);
mIntelliPlugMaxCpusOnlineSuspCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugMaxCpusOnlineSuspCard);
}
if (CPUHotplug.hasIntelliPlugSuspendDeferTime()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 501; i++)
list.add((i * 10) + getString(R.string.ms));
mIntelliPlugSuspendDeferTimeCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugSuspendDeferTimeCard.setTitle(getString(R.string.suspend_defer_time));
mIntelliPlugSuspendDeferTimeCard.setProgress(list.indexOf(String.valueOf(
CPUHotplug.getIntelliPlugSuspendDeferTime())));
mIntelliPlugSuspendDeferTimeCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugSuspendDeferTimeCard);
}
if (CPUHotplug.hasIntelliPlugDeferSampling()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 1001; i++)
list.add(i + getString(R.string.ms));
mIntelliPlugDeferSamplingCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugDeferSamplingCard.setTitle(getString(R.string.defer_sampling));
mIntelliPlugDeferSamplingCard.setProgress(CPUHotplug.getIntelliPlugDeferSampling());
mIntelliPlugDeferSamplingCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugDeferSamplingCard);
}
if (CPUHotplug.hasIntelliPlugBoostLockDuration()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 5001; i++)
list.add(i + getString(R.string.ms));
mIntelliPlugBoostLockDurationCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugBoostLockDurationCard.setTitle(getString(R.string.boost_lock_duration));
mIntelliPlugBoostLockDurationCard.setDescription(getString(R.string.boost_lock_duration_summary));
mIntelliPlugBoostLockDurationCard.setProgress(CPUHotplug.getIntelliPlugBoostLockDuration() - 1);
mIntelliPlugBoostLockDurationCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugBoostLockDurationCard);
}
if (CPUHotplug.hasIntelliPlugDownLockDuration()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 5001; i++)
list.add(i + getString(R.string.ms));
mIntelliPlugDownLockDurationCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugDownLockDurationCard.setTitle(getString(R.string.down_lock_duration));
mIntelliPlugDownLockDurationCard.setDescription(getString(R.string.down_lock_duration_summary));
mIntelliPlugDownLockDurationCard.setProgress(CPUHotplug.getIntelliPlugDownLockDuration() - 1);
mIntelliPlugDownLockDurationCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugDownLockDurationCard);
}
if (CPUHotplug.hasIntelliPlugFShift()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 4; i++)
list.add(String.valueOf(i));
mIntelliPlugFShiftCard = new SeekBarCardView.DSeekBarCardView(list);
mIntelliPlugFShiftCard.setTitle(getString(R.string.fshift));
mIntelliPlugFShiftCard.setProgress(CPUHotplug.getIntelliPlugFShift());
mIntelliPlugFShiftCard.setOnDSeekBarCardListener(this);
views.add(mIntelliPlugFShiftCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mIntelliPlugDividerCard = new DividerCardView.DDividerCard();
mIntelliPlugDividerCard.setText(getString(R.string.intelliplug));
addView(mIntelliPlugDividerCard);
addAllViews(views);
}
}
private void bluPlugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasBluPlugEnable()) {
mBluPlugCard = new SwitchCardView.DSwitchCard();
mBluPlugCard.setTitle(getString(R.string.blu_plug));
mBluPlugCard.setDescription(getString(R.string.blu_plug_summary));
mBluPlugCard.setChecked(CPUHotplug.isBluPlugActive());
mBluPlugCard.setOnDSwitchCardListener(this);
views.add(mBluPlugCard);
}
if (CPUHotplug.hasBluPlugPowersaverMode()) {
mBluPlugPowersaverModeCard = new SwitchCardView.DSwitchCard();
mBluPlugPowersaverModeCard.setTitle(getString(R.string.powersaver_mode));
mBluPlugPowersaverModeCard.setDescription(getString(R.string.powersaver_mode_summary));
mBluPlugPowersaverModeCard.setChecked(CPUHotplug.isBluPlugPowersaverModeActive());
mBluPlugPowersaverModeCard.setOnDSwitchCardListener(this);
views.add(mBluPlugPowersaverModeCard);
}
if (CPUHotplug.hasBluPlugMinOnline()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mBluPlugMinOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugMinOnlineCard.setTitle(getString(R.string.min_cpu_online));
mBluPlugMinOnlineCard.setDescription(getString(R.string.min_cpu_online_summary));
mBluPlugMinOnlineCard.setProgress(CPUHotplug.getBluPlugMinOnline() - 1);
mBluPlugMinOnlineCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugMinOnlineCard);
}
if (CPUHotplug.hasBluPlugMaxOnline()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mBluPlugMaxOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugMaxOnlineCard.setTitle(getString(R.string.max_cpu_online));
mBluPlugMaxOnlineCard.setDescription(getString(R.string.max_cpu_online_summary));
mBluPlugMaxOnlineCard.setProgress(CPUHotplug.getBluPlugMaxOnline() - 1);
mBluPlugMaxOnlineCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugMaxOnlineCard);
}
if (CPUHotplug.hasBluPlugMaxCoresScreenOff()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < CPU.getCoreCount(); i++)
list.add(String.valueOf(i + 1));
mBluPlugMaxCoresScreenOffCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugMaxCoresScreenOffCard.setTitle(getString(R.string.max_cores_screen_off));
mBluPlugMaxCoresScreenOffCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mBluPlugMaxCoresScreenOffCard.setProgress(CPUHotplug.getBluPlugMaxCoresScreenOff() - 1);
mBluPlugMaxCoresScreenOffCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugMaxCoresScreenOffCard);
}
if (CPUHotplug.hasBluPlugMaxFreqScreenOff() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mBluPlugMaxFreqScreenOffCard = new PopupCardItem.DPopupCard(list);
mBluPlugMaxFreqScreenOffCard.setTitle(getString(R.string.cpu_max_screen_off_freq));
mBluPlugMaxFreqScreenOffCard.setDescription(getString(R.string.cpu_max_screen_off_freq_summary));
mBluPlugMaxFreqScreenOffCard.setItem(CPUHotplug.getBluPlugMaxFreqScreenOff());
mBluPlugMaxFreqScreenOffCard.setOnDPopupCardListener(this);
views.add(mBluPlugMaxFreqScreenOffCard);
}
if (CPUHotplug.hasBluPlugUpThreshold()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(i + "%");
mBluPlugUpThresholdCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugUpThresholdCard.setTitle(getString(R.string.up_threshold));
mBluPlugUpThresholdCard.setDescription(getString(R.string.up_threshold_summary));
mBluPlugUpThresholdCard.setProgress(CPUHotplug.getBluPlugUpThreshold());
mBluPlugUpThresholdCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugUpThresholdCard);
}
if (CPUHotplug.hasBluPlugUpTimerCnt()) {
List<String> list = new ArrayList<>();
for (float i = 0; i < 21; i++)
list.add(String.valueOf(i / (float) 2).replace(".0", ""));
mBluPlugUpTimerCntCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugUpTimerCntCard.setTitle(getString(R.string.up_timer_cnt));
mBluPlugUpTimerCntCard.setDescription(getString(R.string.up_timer_cnt_summary));
mBluPlugUpTimerCntCard.setProgress(CPUHotplug.getBluPlugUpTimerCnt());
mBluPlugUpTimerCntCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugUpTimerCntCard);
}
if (CPUHotplug.hasBluPlugDownTimerCnt()) {
List<String> list = new ArrayList<>();
for (float i = 0; i < 21; i++)
list.add(String.valueOf(i / (float) 2).replace(".0", ""));
mBluPlugDownTimerCntCard = new SeekBarCardView.DSeekBarCardView(list);
mBluPlugDownTimerCntCard.setTitle(getString(R.string.down_timer_cnt));
mBluPlugDownTimerCntCard.setDescription(getString(R.string.down_timer_cnt_summary));
mBluPlugDownTimerCntCard.setProgress(CPUHotplug.getBluPlugDownTimerCnt());
mBluPlugDownTimerCntCard.setOnDSeekBarCardListener(this);
views.add(mBluPlugDownTimerCntCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mBluPlugDividerCard = new DividerCardView.DDividerCard();
mBluPlugDividerCard.setText(getString(R.string.blu_plug));
addView(mBluPlugDividerCard);
addAllViews(views);
}
}
private void msmHotplugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasMsmHotplugEnable()) {
mMsmHotplugEnabledCard = new SwitchCardView.DSwitchCard();
mMsmHotplugEnabledCard.setTitle(getString(R.string.msm_hotplug));
mMsmHotplugEnabledCard.setDescription(getString(R.string.msm_hotplug_summary));
mMsmHotplugEnabledCard.setChecked(CPUHotplug.isMsmHotplugActive());
mMsmHotplugEnabledCard.setOnDSwitchCardListener(this);
views.add(mMsmHotplugEnabledCard);
}
if (CPUHotplug.hasMsmHotplugDebugMask()) {
mMsmHotplugDebugMaskCard = new SwitchCardView.DSwitchCard();
mMsmHotplugDebugMaskCard.setTitle(getString(R.string.debug_mask));
mMsmHotplugDebugMaskCard.setDescription(getString(R.string.debug_mask_summary));
mMsmHotplugDebugMaskCard.setChecked(CPUHotplug.isMsmHotplugDebugMaskActive());
mMsmHotplugDebugMaskCard.setOnDSwitchCardListener(this);
views.add(mMsmHotplugDebugMaskCard);
}
if (CPUHotplug.hasMsmHotplugMinCpusOnline()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMsmHotplugMinCpusOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugMinCpusOnlineCard.setTitle(getString(R.string.min_cpu_online));
mMsmHotplugMinCpusOnlineCard.setDescription(getString(R.string.min_cpu_online_summary));
mMsmHotplugMinCpusOnlineCard.setProgress(CPUHotplug.getMsmHotplugMinCpusOnline() - 1);
mMsmHotplugMinCpusOnlineCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugMinCpusOnlineCard);
}
if (CPUHotplug.hasMsmHotplugMaxCpusOnline()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMsmHotplugMaxCpusOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugMaxCpusOnlineCard.setTitle(getString(R.string.max_cpu_online));
mMsmHotplugMaxCpusOnlineCard.setDescription(getString(R.string.max_cpu_online_summary));
mMsmHotplugMaxCpusOnlineCard.setProgress(CPUHotplug.getMsmHotplugMaxCpusOnline() - 1);
mMsmHotplugMaxCpusOnlineCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugMaxCpusOnlineCard);
}
if (CPUHotplug.hasMsmHotplugCpusBoosted()) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMsmHotplugCpusBoostedCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugCpusBoostedCard.setTitle(getString(R.string.cpus_boosted));
mMsmHotplugCpusBoostedCard.setDescription(getString(R.string.cpus_boosted_summary));
mMsmHotplugCpusBoostedCard.setProgress(CPUHotplug.getMsmHotplugCpusBoosted());
mMsmHotplugCpusBoostedCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugCpusBoostedCard);
}
if (CPUHotplug.hasMsmHotplugMaxCpusOnlineSusp()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMsmHotplugCpusOnlineSuspCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugCpusOnlineSuspCard.setTitle(getString(R.string.max_cores_screen_off));
mMsmHotplugCpusOnlineSuspCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mMsmHotplugCpusOnlineSuspCard.setProgress(CPUHotplug.getMsmHotplugMaxCpusOnlineSusp() - 1);
mMsmHotplugCpusOnlineSuspCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugCpusOnlineSuspCard);
}
if (CPUHotplug.hasMsmHotplugBoostLockDuration()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 5001; i++)
list.add(String.valueOf(i));
mMsmHotplugBoostLockDurationCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugBoostLockDurationCard.setTitle(getString(R.string.boost_lock_duration));
mMsmHotplugBoostLockDurationCard.setDescription(getString(R.string.boost_lock_duration_summary));
mMsmHotplugBoostLockDurationCard.setProgress(CPUHotplug.getMsmHotplugBoostLockDuration() - 1);
mMsmHotplugBoostLockDurationCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugBoostLockDurationCard);
}
if (CPUHotplug.hasMsmHotplugDownLockDuration()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 5001; i++)
list.add(String.valueOf(i));
mMsmHotplugDownLockDurationCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugDownLockDurationCard.setTitle(getString(R.string.down_lock_duration));
mMsmHotplugDownLockDurationCard.setDescription(getString(R.string.down_lock_duration_summary));
mMsmHotplugDownLockDurationCard.setProgress(CPUHotplug.getMsmHotplugDownLockDuration() - 1);
mMsmHotplugDownLockDurationCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugDownLockDurationCard);
}
if (CPUHotplug.hasMsmHotplugHistorySize()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 61; i++)
list.add(String.valueOf(i));
mMsmHotplugHistorySizeCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugHistorySizeCard.setTitle(getString(R.string.history_size));
mMsmHotplugHistorySizeCard.setDescription(getString(R.string.history_size_summary));
mMsmHotplugHistorySizeCard.setProgress(CPUHotplug.getMsmHotplugHistorySize() - 1);
mMsmHotplugHistorySizeCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugHistorySizeCard);
}
if (CPUHotplug.hasMsmHotplugUpdateRate()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 61; i++)
list.add(String.valueOf(i));
mMsmHotplugUpdateRateCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugUpdateRateCard.setTitle(getString(R.string.update_rate));
mMsmHotplugUpdateRateCard.setDescription(getString(R.string.update_rate_summary));
mMsmHotplugUpdateRateCard.setProgress(CPUHotplug.getMsmHotplugUpdateRate());
mMsmHotplugUpdateRateCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugUpdateRateCard);
}
if (CPUHotplug.hasMsmHotplugFastLaneLoad()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 401; i++)
list.add(String.valueOf(i));
mMsmHotplugFastLaneLoadCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugFastLaneLoadCard.setTitle(getString(R.string.fast_lane_load));
mMsmHotplugFastLaneLoadCard.setDescription(getString(R.string.fast_lane_load_summary));
mMsmHotplugFastLaneLoadCard.setProgress(CPUHotplug.getMsmHotplugFastLaneLoad());
mMsmHotplugFastLaneLoadCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugFastLaneLoadCard);
}
if (CPUHotplug.hasMsmHotplugFastLaneMinFreq() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMsmHotplugFastLaneMinFreqCard = new PopupCardItem.DPopupCard(list);
mMsmHotplugFastLaneMinFreqCard.setTitle(getString(R.string.fast_lane_min_freq));
mMsmHotplugFastLaneMinFreqCard.setDescription(getString(R.string.fast_lane_min_freq_summary));
mMsmHotplugFastLaneMinFreqCard.setItem((CPUHotplug.getMsmHotplugFastLaneMinFreq() / 1000) + getString(R.string.mhz));
mMsmHotplugFastLaneMinFreqCard.setOnDPopupCardListener(this);
views.add(mMsmHotplugFastLaneMinFreqCard);
}
if (CPUHotplug.hasMsmHotplugOfflineLoad()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(String.valueOf(i));
mMsmHotplugOfflineLoadCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugOfflineLoadCard.setTitle(getString(R.string.offline_load));
mMsmHotplugOfflineLoadCard.setDescription(getString(R.string.offline_load_summary));
mMsmHotplugOfflineLoadCard.setProgress(CPUHotplug.getMsmHotplugOfflineLoad());
mMsmHotplugOfflineLoadCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugOfflineLoadCard);
}
if (CPUHotplug.hasMsmHotplugIoIsBusy()) {
mMsmHotplugIoIsBusyCard = new SwitchCardView.DSwitchCard();
mMsmHotplugIoIsBusyCard.setTitle(getString(R.string.io_is_busy));
mMsmHotplugIoIsBusyCard.setDescription(getString(R.string.io_is_busy_summary));
mMsmHotplugIoIsBusyCard.setChecked(CPUHotplug.isMsmHotplugIoIsBusyActive());
mMsmHotplugIoIsBusyCard.setOnDSwitchCardListener(this);
views.add(mMsmHotplugIoIsBusyCard);
}
if (CPUHotplug.hasMsmHotplugSuspendMaxCpus()) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMsmHotplugSuspendMaxCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugSuspendMaxCpusCard.setTitle(getString(R.string.max_cores_screen_off));
mMsmHotplugSuspendMaxCpusCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mMsmHotplugSuspendMaxCpusCard.setProgress(CPUHotplug.getMsmHotplugSuspendMaxCpus());
mMsmHotplugSuspendMaxCpusCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugSuspendMaxCpusCard);
}
if (CPUHotplug.hasMsmHotplugSuspendFreq() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMsmHotplugSuspendFreqCard = new PopupCardItem.DPopupCard(list);
mMsmHotplugSuspendFreqCard.setTitle(getString(R.string.cpu_max_screen_off_freq));
mMsmHotplugSuspendFreqCard.setDescription(getString(R.string.cpu_max_screen_off_freq_summary));
mMsmHotplugSuspendFreqCard.setItem((CPUHotplug.getMsmHotplugSuspendFreq() / 1000) + getString(R.string.mhz));
mMsmHotplugSuspendFreqCard.setOnDPopupCardListener(this);
views.add(mMsmHotplugSuspendFreqCard);
}
if (CPUHotplug.hasMsmHotplugSuspendDeferTime()) {
List<String> list = new ArrayList<>();
for (int i = 0; i <= 5001; i += 10)
list.add(String.valueOf(i));
mMsmHotplugSuspendDeferTimeCard = new SeekBarCardView.DSeekBarCardView(list);
mMsmHotplugSuspendDeferTimeCard.setTitle(getString(R.string.defer_time));
mMsmHotplugSuspendDeferTimeCard.setProgress(CPUHotplug.getMsmHotplugSuspendDeferTime());
mMsmHotplugSuspendDeferTimeCard.setOnDSeekBarCardListener(this);
views.add(mMsmHotplugSuspendDeferTimeCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mMsmHotplugDividerCard = new DividerCardView.DDividerCard();
mMsmHotplugDividerCard.setText(getString(R.string.msm_hotplug));
addView(mMsmHotplugDividerCard);
addAllViews(views);
}
}
private void makoHotplugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasMakoHotplugEnable()) {
mMakoHotplugEnableCard = new SwitchCardView.DSwitchCard();
mMakoHotplugEnableCard.setTitle(getString(R.string.mako_hotplug));
mMakoHotplugEnableCard.setDescription(getString(R.string.mako_hotplug_summary));
mMakoHotplugEnableCard.setChecked(CPUHotplug.isMakoHotplugActive());
mMakoHotplugEnableCard.setOnDSwitchCardListener(this);
views.add(mMakoHotplugEnableCard);
}
if (CPUHotplug.hasMakoHotplugCoresOnTouch()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMakoCoreOnTouchCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoCoreOnTouchCard.setTitle(getString(R.string.cores_on_touch));
mMakoCoreOnTouchCard.setDescription(getString(R.string.cores_on_touch_summary));
mMakoCoreOnTouchCard.setProgress(CPUHotplug.getMakoHotplugCoresOnTouch() - 1);
mMakoCoreOnTouchCard.setOnDSeekBarCardListener(this);
views.add(mMakoCoreOnTouchCard);
}
if (CPUHotplug.hasMakoHotplugCpuFreqUnplugLimit() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMakoHotplugCpuFreqUnplugLimitCard = new PopupCardItem.DPopupCard(list);
mMakoHotplugCpuFreqUnplugLimitCard.setDescription(getString(R.string.cpu_freq_unplug_limit));
mMakoHotplugCpuFreqUnplugLimitCard.setItem((CPUHotplug.getMakoHotplugCpuFreqUnplugLimit() / 1000)
+ getString(R.string.mhz));
mMakoHotplugCpuFreqUnplugLimitCard.setOnDPopupCardListener(this);
views.add(mMakoHotplugCpuFreqUnplugLimitCard);
}
if (CPUHotplug.hasMakoHotplugFirstLevel()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(i + "%");
mMakoHotplugFirstLevelCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugFirstLevelCard.setTitle(getString(R.string.first_level));
mMakoHotplugFirstLevelCard.setDescription(getString(R.string.first_level_summary));
mMakoHotplugFirstLevelCard.setProgress(CPUHotplug.getMakoHotplugFirstLevel());
mMakoHotplugFirstLevelCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugFirstLevelCard);
}
if (CPUHotplug.hasMakoHotplugHighLoadCounter()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(String.valueOf(i));
mMakoHotplugHighLoadCounterCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugHighLoadCounterCard.setTitle(getString(R.string.high_load_counter));
mMakoHotplugHighLoadCounterCard.setProgress(CPUHotplug.getMakoHotplugHighLoadCounter());
mMakoHotplugHighLoadCounterCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugHighLoadCounterCard);
}
if (CPUHotplug.hasMakoHotplugLoadThreshold()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(i + "%");
mMakoHotplugLoadThresholdCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugLoadThresholdCard.setTitle(getString(R.string.load_threshold));
mMakoHotplugLoadThresholdCard.setDescription(getString(R.string.load_threshold_summary));
mMakoHotplugLoadThresholdCard.setProgress(CPUHotplug.getMakoHotplugLoadThreshold());
mMakoHotplugLoadThresholdCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugLoadThresholdCard);
}
if (CPUHotplug.hasMakoHotplugMaxLoadCounter()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(String.valueOf(i));
mMakoHotplugMaxLoadCounterCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugMaxLoadCounterCard.setTitle(getString(R.string.max_load_counter));
mMakoHotplugMaxLoadCounterCard.setProgress(CPUHotplug.getMakoHotplugMaxLoadCounter());
mMakoHotplugMaxLoadCounterCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugMaxLoadCounterCard);
}
if (CPUHotplug.hasMakoHotplugMinTimeCpuOnline()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(String.valueOf(i));
mMakoHotplugMinTimeCpuOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugMinTimeCpuOnlineCard.setTitle(getString(R.string.min_time_cpu_online));
mMakoHotplugMinTimeCpuOnlineCard.setProgress(CPUHotplug.getMakoHotplugMinTimeCpuOnline());
mMakoHotplugMinTimeCpuOnlineCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugMinTimeCpuOnlineCard);
}
if (CPUHotplug.hasMakoHotplugMinCoresOnline()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMakoHotplugMinCoresOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugMinCoresOnlineCard.setTitle(getString(R.string.min_cpu_online));
mMakoHotplugMinCoresOnlineCard.setDescription(getString(R.string.min_cpu_online_summary));
mMakoHotplugMinCoresOnlineCard.setProgress(CPUHotplug.getMakoHotplugMinCoresOnline() - 1);
mMakoHotplugMinCoresOnlineCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugMinCoresOnlineCard);
}
if (CPUHotplug.hasMakoHotplugTimer()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++)
list.add(String.valueOf(i));
mMakoHotplugTimerCard = new SeekBarCardView.DSeekBarCardView(list);
mMakoHotplugTimerCard.setTitle(getString(R.string.timer));
mMakoHotplugTimerCard.setProgress(CPUHotplug.getMakoHotplugTimer());
mMakoHotplugTimerCard.setOnDSeekBarCardListener(this);
views.add(mMakoHotplugTimerCard);
}
if (CPUHotplug.hasMakoHotplugSuspendFreq() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMakoSuspendFreqCard = new PopupCardItem.DPopupCard(list);
mMakoSuspendFreqCard.setTitle(getString(R.string.cpu_max_screen_off_freq));
mMakoSuspendFreqCard.setDescription(getString(R.string.cpu_max_screen_off_freq_summary));
mMakoSuspendFreqCard.setItem((CPUHotplug.getMakoHotplugSuspendFreq() / 1000) + getString(R.string.mhz));
mMakoSuspendFreqCard.setOnDPopupCardListener(this);
views.add(mMakoSuspendFreqCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mMakoHotplugDividerCard = new DividerCardView.DDividerCard();
mMakoHotplugDividerCard.setText(getString(R.string.mako_hotplug));
addView(mMakoHotplugDividerCard);
addAllViews(views);
}
}
private void mbHotplugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasMBGHotplugEnable()) {
mMBHotplugEnableCard = new SwitchCardView.DSwitchCard();
mMBHotplugEnableCard.setTitle(CPUHotplug.getMBName(getActivity()));
mMBHotplugEnableCard.setDescription(getString(R.string.mb_hotplug_summary));
mMBHotplugEnableCard.setChecked(CPUHotplug.isMBHotplugActive());
mMBHotplugEnableCard.setOnDSwitchCardListener(this);
views.add(mMBHotplugEnableCard);
}
if (CPUHotplug.hasMBHotplugScroffSingleCore()) {
mMBHotplugScroffSingleCoreCard = new SwitchCardView.DSwitchCard();
mMBHotplugScroffSingleCoreCard.setTitle(getString(R.string.screen_off_single_core));
mMBHotplugScroffSingleCoreCard.setDescription(getString(R.string.screen_off_single_core_summary));
mMBHotplugScroffSingleCoreCard.setChecked(CPUHotplug.isMBHotplugScroffSingleCoreActive());
mMBHotplugScroffSingleCoreCard.setOnDSwitchCardListener(this);
views.add(mMBHotplugScroffSingleCoreCard);
}
if (CPUHotplug.hasMBHotplugMinCpus()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMBHotplugMinCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugMinCpusCard.setTitle(getString(R.string.min_cpu_online));
mMBHotplugMinCpusCard.setDescription(getString(R.string.min_cpu_online_summary));
mMBHotplugMinCpusCard.setProgress(CPUHotplug.getMBHotplugMinCpus() - 1);
mMBHotplugMinCpusCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugMinCpusCard);
}
if (CPUHotplug.hasMBHotplugMaxCpus()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMBHotplugMaxCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugMaxCpusCard.setTitle(getString(R.string.max_cpu_online));
mMBHotplugMaxCpusCard.setDescription(getString(R.string.max_cpu_online_summary));
mMBHotplugMaxCpusCard.setProgress(CPUHotplug.getMBHotplugMaxCpus() - 1);
mMBHotplugMaxCpusCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugMaxCpusCard);
}
if (CPUHotplug.hasMBHotplugMaxCpusOnlineSusp()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMBHotplugMaxCpusOnlineSuspCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugMaxCpusOnlineSuspCard.setTitle(getString(R.string.max_cores_screen_off));
mMBHotplugMaxCpusOnlineSuspCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mMBHotplugMaxCpusOnlineSuspCard.setProgress(CPUHotplug.getMBHotplugMaxCpusOnlineSusp() - 1);
mMBHotplugMaxCpusOnlineSuspCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugMaxCpusOnlineSuspCard);
}
if (CPUHotplug.hasMBHotplugIdleFreq() && CPU.getFreqs() != null) {
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMBHotplugIdleFreqCard = new PopupCardItem.DPopupCard(list);
mMBHotplugIdleFreqCard.setTitle(getString(R.string.idle_frequency));
mMBHotplugIdleFreqCard.setDescription(getString(R.string.idle_frequency_summary));
mMBHotplugIdleFreqCard.setItem((CPUHotplug.getMBHotplugIdleFreq() / 1000) + getString(R.string.mhz));
mMBHotplugIdleFreqCard.setOnDPopupCardListener(this);
views.add(mMBHotplugIdleFreqCard);
}
if (CPUHotplug.hasMBHotplugBoostEnable()) {
mMBHotplugBoostEnableCard = new SwitchCardView.DSwitchCard();
mMBHotplugBoostEnableCard.setTitle(getString(R.string.touch_boost));
mMBHotplugBoostEnableCard.setDescription(getString(R.string.touch_boost_summary));
mMBHotplugBoostEnableCard.setChecked(CPUHotplug.isMBHotplugBoostActive());
mMBHotplugBoostEnableCard.setOnDSwitchCardListener(this);
views.add(mMBHotplugBoostEnableCard);
}
if (CPUHotplug.hasMBHotplugBoostTime()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 51; i++)
list.add((i * 100) + getString(R.string.ms));
mMBHotplugBoostTimeCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugBoostTimeCard.setTitle(getString(R.string.touch_boost_time));
mMBHotplugBoostTimeCard.setProgress(CPUHotplug.getMBHotplugBoostTime() / 100);
mMBHotplugBoostTimeCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugBoostTimeCard);
}
if (CPUHotplug.hasMBHotplugCpusBoosted()) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mMBHotplugCpusBoostedCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugCpusBoostedCard.setTitle(getString(R.string.cpus_boosted));
mMBHotplugCpusBoostedCard.setDescription(getString(R.string.cpus_boosted_summary));
mMBHotplugCpusBoostedCard.setProgress(CPUHotplug.getMBHotplugCpusBoosted());
mMBHotplugCpusBoostedCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugCpusBoostedCard);
}
if (CPUHotplug.hasMBHotplugBoostFreqs() && CPU.getFreqs() != null) {
List<Integer> freqs = CPUHotplug.getMBHotplugBoostFreqs();
List<String> list = new ArrayList<>();
for (int freq : CPU.getFreqs())
list.add((freq / 1000) + getString(R.string.mhz));
mMBHotplugBoostFreqsCard = new PopupCardItem.DPopupCard[freqs.size()];
for (int i = 0; i < freqs.size(); i++) {
mMBHotplugBoostFreqsCard[i] = new PopupCardItem.DPopupCard(list);
mMBHotplugBoostFreqsCard[i].setDescription(getString(R.string.boost_frequecy_core, i));
mMBHotplugBoostFreqsCard[i].setItem((freqs.get(i) / 1000) + getString(R.string.mhz));
mMBHotplugBoostFreqsCard[i].setOnDPopupCardListener(this);
views.add(mMBHotplugBoostFreqsCard[i]);
}
}
if (CPUHotplug.hasMBHotplugStartDelay()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 51; i++)
list.add((i * 1000) + getString(R.string.ms));
mMBHotplugStartDelayCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugStartDelayCard.setTitle(getString(R.string.start_delay));
mMBHotplugStartDelayCard.setDescription(getString(R.string.start_delay_summary));
mMBHotplugStartDelayCard.setProgress(CPUHotplug.getMBHotplugStartDelay() / 1000);
mMBHotplugStartDelayCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugStartDelayCard);
}
if (CPUHotplug.hasMBHotplugDelay()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 201; i++)
list.add(String.valueOf(i));
mMBHotplugDelayCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugDelayCard.setTitle(getString(R.string.delay));
mMBHotplugDelayCard.setDescription(getString(R.string.delay_summary));
mMBHotplugDelayCard.setProgress(CPUHotplug.getMBHotplugDelay());
mMBHotplugDelayCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugDelayCard);
}
if (CPUHotplug.hasMBHotplugPause()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 51; i++)
list.add((i * 1000) + getString(R.string.ms));
mMBHotplugPauseCard = new SeekBarCardView.DSeekBarCardView(list);
mMBHotplugPauseCard.setTitle(getString(R.string.pause));
mMBHotplugPauseCard.setDescription(getString(R.string.pause_summary));
mMBHotplugPauseCard.setProgress(CPUHotplug.getMBHotplugPause() / 1000);
mMBHotplugPauseCard.setOnDSeekBarCardListener(this);
views.add(mMBHotplugPauseCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mMBHotplugDividerCard = new DividerCardView.DDividerCard();
mMBHotplugDividerCard.setText(CPUHotplug.getMBName(getActivity()));
addView(mMBHotplugDividerCard);
addAllViews(views);
}
}
private void alucardHotplugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasAlucardHotplugEnable()) {
mAlucardHotplugEnableCard = new SwitchCardView.DSwitchCard();
mAlucardHotplugEnableCard.setTitle(getString(R.string.alucard_hotplug));
mAlucardHotplugEnableCard.setDescription(getString(R.string.alucard_hotplug_summary));
mAlucardHotplugEnableCard.setChecked(CPUHotplug.isAlucardHotplugActive());
mAlucardHotplugEnableCard.setOnDSwitchCardListener(this);
views.add(mAlucardHotplugEnableCard);
}
if (CPUHotplug.hasAlucardHotplugHpIoIsBusy()) {
mAlucardHotplugHpIoIsBusyCard = new SwitchCardView.DSwitchCard();
mAlucardHotplugHpIoIsBusyCard.setTitle(getString(R.string.io_is_busy));
mAlucardHotplugHpIoIsBusyCard.setDescription(getString(R.string.io_is_busy_summary));
mAlucardHotplugHpIoIsBusyCard.setChecked(CPUHotplug.isAlucardHotplugHpIoIsBusyActive());
mAlucardHotplugHpIoIsBusyCard.setOnDSwitchCardListener(this);
views.add(mAlucardHotplugHpIoIsBusyCard);
}
if (CPUHotplug.hasAlucardHotplugSamplingRate()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 101; i++)
list.add(i + "%");
mAlucardHotplugSamplingRateCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugSamplingRateCard.setTitle(getString(R.string.sampling_rate));
mAlucardHotplugSamplingRateCard.setProgress(CPUHotplug.getAlucardHotplugSamplingRate() - 1);
mAlucardHotplugSamplingRateCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugSamplingRateCard);
}
if (CPUHotplug.hasAlucardHotplugSuspend()) {
mAlucardHotplugSuspendCard = new SwitchCardView.DSwitchCard();
mAlucardHotplugSuspendCard.setTitle(getString(R.string.suspend));
mAlucardHotplugSuspendCard.setDescription(getString(R.string.suspend_summary));
mAlucardHotplugSuspendCard.setChecked(CPUHotplug.isAlucardHotplugSuspendActive());
mAlucardHotplugSuspendCard.setOnDSwitchCardListener(this);
views.add(mAlucardHotplugSuspendCard);
}
if (CPUHotplug.hasAlucardHotplugMinCpusOnline()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mAlucardHotplugMinCpusOnlineCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugMinCpusOnlineCard.setTitle(getString(R.string.min_cpu_online));
mAlucardHotplugMinCpusOnlineCard.setDescription(getString(R.string.min_cpu_online_summary));
mAlucardHotplugMinCpusOnlineCard.setProgress(CPUHotplug.getAlucardHotplugMinCpusOnline() - 1);
mAlucardHotplugMinCpusOnlineCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugMinCpusOnlineCard);
}
if (CPUHotplug.hasAlucardHotplugMaxCoresLimit()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mAlucardHotplugMaxCoresLimitCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugMaxCoresLimitCard.setTitle(getString(R.string.max_cpu_online));
mAlucardHotplugMaxCoresLimitCard.setDescription(getString(R.string.max_cpu_online_summary));
mAlucardHotplugMaxCoresLimitCard.setProgress(CPUHotplug.getAlucardHotplugMaxCoresLimit() - 1);
mAlucardHotplugMaxCoresLimitCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugMaxCoresLimitCard);
}
if (CPUHotplug.hasAlucardHotplugMaxCoresLimitSleep()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++)
list.add(String.valueOf(i));
mAlucardHotplugMaxCoresLimitSleepCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugMaxCoresLimitSleepCard.setTitle(getString(R.string.max_cores_screen_off));
mAlucardHotplugMaxCoresLimitSleepCard.setDescription(getString(R.string.max_cores_screen_off_summary));
mAlucardHotplugMaxCoresLimitSleepCard.setProgress(CPUHotplug.getAlucardHotplugMaxCoresLimitSleep() - 1);
mAlucardHotplugMaxCoresLimitSleepCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugMaxCoresLimitSleepCard);
}
if (CPUHotplug.hasAlucardHotplugCpuDownRate()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 101; i++)
list.add(i + "%");
mAlucardHotplugCpuDownRateCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugCpuDownRateCard.setTitle(getString(R.string.cpu_down_rate));
mAlucardHotplugCpuDownRateCard.setProgress(CPUHotplug.getAlucardHotplugCpuDownRate() - 1);
mAlucardHotplugCpuDownRateCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugCpuDownRateCard);
}
if (CPUHotplug.hasAlucardHotplugCpuUpRate()) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 101; i++)
list.add(i + "%");
mAlucardHotplugCpuUpRateCard = new SeekBarCardView.DSeekBarCardView(list);
mAlucardHotplugCpuUpRateCard.setTitle(getString(R.string.cpu_up_rate));
mAlucardHotplugCpuUpRateCard.setProgress(CPUHotplug.getAlucardHotplugCpuUpRate() - 1);
mAlucardHotplugCpuUpRateCard.setOnDSeekBarCardListener(this);
views.add(mAlucardHotplugCpuUpRateCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mAlucardDividerCard = new DividerCardView.DDividerCard();
mAlucardDividerCard.setText(getString(R.string.alucard_hotplug));
addView(mAlucardDividerCard);
addAllViews(views);
}
}
private void thunderPlugInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasThunderPlugEnable()) {
mThunderPlugEnableCard = new SwitchCardView.DSwitchCard();
mThunderPlugEnableCard.setTitle(getString(R.string.thunderplug));
mThunderPlugEnableCard.setDescription(getString(R.string.thunderplug_summary));
mThunderPlugEnableCard.setChecked(CPUHotplug.isThunderPlugActive());
mThunderPlugEnableCard.setOnDSwitchCardListener(this);
views.add(mThunderPlugEnableCard);
}
if (CPUHotplug.hasThunderPlugSuspendCpus()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++) list.add(String.valueOf(i));
mThunderPlugSuspendCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mThunderPlugSuspendCpusCard.setTitle(getString(R.string.min_cores_screen_off));
mThunderPlugSuspendCpusCard.setDescription(getString(R.string.min_cores_screen_off_summary));
mThunderPlugSuspendCpusCard.setProgress(CPUHotplug.getThunderPlugSuspendCpus() - 1);
mThunderPlugSuspendCpusCard.setOnDSeekBarCardListener(this);
views.add(mThunderPlugSuspendCpusCard);
}
if (CPUHotplug.hasThunderPlugEnduranceLevel()) {
mThunderPlugEnduranceLevelCard = new PopupCardItem.DPopupCard(new ArrayList<>(Arrays
.asList(getResources().getStringArray(R.array.thunderplug_endurance_level_items))));
mThunderPlugEnduranceLevelCard.setTitle(getString(R.string.endurance_level));
mThunderPlugEnduranceLevelCard.setDescription(getString(R.string.endurance_level_summary));
mThunderPlugEnduranceLevelCard.setItem(CPUHotplug.getThunderPlugEnduranceLevel());
mThunderPlugEnduranceLevelCard.setOnDPopupCardListener(this);
views.add(mThunderPlugEnduranceLevelCard);
}
if (CPUHotplug.hasThunderPlugSamplingRate()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 51; i++) list.add(String.valueOf(i * 50 + 100));
mThunderPlugSamplingRateCard = new SeekBarCardView.DSeekBarCardView(list);
mThunderPlugSamplingRateCard.setTitle(getString(R.string.sampling_rate));
mThunderPlugSamplingRateCard.setProgress(CPUHotplug.getThunderPlugSamplingRate() / 50);
mThunderPlugSamplingRateCard.setOnDSeekBarCardListener(this);
views.add(mThunderPlugSamplingRateCard);
}
if (CPUHotplug.hasThunderPlugLoadThreshold()) {
List<String> list = new ArrayList<>();
for (int i = 11; i < 101; i++) list.add(String.valueOf(i));
mThunderPlugLoadThresholdCard = new SeekBarCardView.DSeekBarCardView(list);
mThunderPlugLoadThresholdCard.setTitle(getString(R.string.load_threshold));
mThunderPlugLoadThresholdCard.setDescription(getString(R.string.load_threshold_summary));
mThunderPlugLoadThresholdCard.setProgress(CPUHotplug.getThunderPlugLoadThreshold() - 11);
mThunderPlugLoadThresholdCard.setOnDSeekBarCardListener(this);
views.add(mThunderPlugLoadThresholdCard);
}
if (CPUHotplug.hasThunderPlugTouchBoost()) {
mThunderPlugTouchBoostCard = new SwitchCardView.DSwitchCard();
mThunderPlugTouchBoostCard.setTitle(getString(R.string.touch_boost));
mThunderPlugTouchBoostCard.setDescription(getString(R.string.touch_boost_summary));
mThunderPlugTouchBoostCard.setChecked(CPUHotplug.isThunderPlugTouchBoostActive());
mThunderPlugTouchBoostCard.setOnDSwitchCardListener(this);
views.add(mThunderPlugTouchBoostCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mThunderPlugDividerCard = new DividerCardView.DDividerCard();
mThunderPlugDividerCard.setText(getString(R.string.thunderplug));
addView(mThunderPlugDividerCard);
addAllViews(views);
}
}
private void zenDecisionInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasZenDecisionEnable()) {
mZenDecisionEnableCard = new SwitchCardView.DSwitchCard();
mZenDecisionEnableCard.setTitle(getString(R.string.zen_decision));
mZenDecisionEnableCard.setDescription(getString(R.string.zen_decision_summary));
mZenDecisionEnableCard.setChecked(CPUHotplug.isZenDecisionActive());
mZenDecisionEnableCard.setOnDSwitchCardListener(this);
views.add(mZenDecisionEnableCard);
}
if (CPUHotplug.hasZenDecisionWakeWaitTime()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 61; i++) list.add((i * 1000) + getString(R.string.ms));
mZenDecisionWakeWaitTimeCard = new SeekBarCardView.DSeekBarCardView(list);
mZenDecisionWakeWaitTimeCard.setTitle(getString(R.string.wake_wait_time));
mZenDecisionWakeWaitTimeCard.setDescription(getString(R.string.wake_wait_time_summary));
mZenDecisionWakeWaitTimeCard.setProgress(CPUHotplug.getZenDecisionWakeWaitTime() / 1000);
mZenDecisionWakeWaitTimeCard.setOnDSeekBarCardListener(this);
views.add(mZenDecisionWakeWaitTimeCard);
}
if (CPUHotplug.hasZenDecisionBatThresholdIgnore()) {
List<String> list = new ArrayList<>();
list.add(getString(R.string.disabled));
for (int i = 1; i < 101; i++) list.add(i + "%");
mZenDecisionBatThresholdIgnoreCard = new SeekBarCardView.DSeekBarCardView(list);
mZenDecisionBatThresholdIgnoreCard.setTitle(getString(R.string.bat_threshold_ignore));
mZenDecisionBatThresholdIgnoreCard.setDescription(getString(R.string.bat_threshold_ignore_summary));
mZenDecisionBatThresholdIgnoreCard.setProgress(CPUHotplug.getZenDecisionBatThresholdIgnore());
mZenDecisionBatThresholdIgnoreCard.setOnDSeekBarCardListener(this);
views.add(mZenDecisionBatThresholdIgnoreCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mZenDecisionDividerCard = new DividerCardView.DDividerCard();
mZenDecisionDividerCard.setText(getString(R.string.zen_decision));
addView(mZenDecisionDividerCard);
addAllViews(views);
}
}
private void autoSmpInit() {
List<DAdapter.DView> views = new ArrayList<>();
if (CPUHotplug.hasAutoSmpEnable()) {
mAutoSmpEnableCard = new SwitchCardView.DSwitchCard();
mAutoSmpEnableCard.setTitle(getString(R.string.autosmp));
mAutoSmpEnableCard.setDescription(getString(R.string.autosmp_summary));
mAutoSmpEnableCard.setChecked(CPUHotplug.isAutoSmpActive());
mAutoSmpEnableCard.setOnDSwitchCardListener(this);
views.add(mAutoSmpEnableCard);
}
if (CPUHotplug.hasAutoSmpCpufreqDown()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++) list.add(i + "%");
mAutoSmpCpufreqDownCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpCpufreqDownCard.setTitle(getString(R.string.downrate_limits));
mAutoSmpCpufreqDownCard.setProgress(CPUHotplug.getAutoSmpCpufreqDown());
mAutoSmpCpufreqDownCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpCpufreqDownCard);
}
if (CPUHotplug.hasAutoSmpCpufreqUp()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 101; i++) list.add(i + "%");
mAutoSmpCpufreqUpCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpCpufreqUpCard.setTitle(getString(R.string.uprate_limits));
mAutoSmpCpufreqUpCard.setProgress(CPUHotplug.getAutoSmpCpufreqUp());
mAutoSmpCpufreqUpCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpCpufreqUpCard);
}
if (CPUHotplug.hasAutoSmpCycleDown()) {
List<String> list = new ArrayList<>();
for (int i = 0; i <= CPU.getCoreCount(); i++) list.add(String.valueOf(i));
mAutoSmpCycleDownCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpCycleDownCard.setTitle(getString(R.string.cycle_down));
mAutoSmpCycleDownCard.setDescription(getString(R.string.cycle_down_summary));
mAutoSmpCycleDownCard.setProgress(CPUHotplug.getAutoSmpCycleDown());
mAutoSmpCycleDownCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpCycleDownCard);
}
if (CPUHotplug.hasAutoSmpCycleUp()) {
List<String> list = new ArrayList<>();
for (int i = 0; i <= CPU.getCoreCount(); i++) list.add(String.valueOf(i));
mAutoSmpCycleUpCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpCycleUpCard.setTitle(getString(R.string.cycle_up));
mAutoSmpCycleUpCard.setDescription(getString(R.string.cycle_up_summary));
mAutoSmpCycleUpCard.setProgress(CPUHotplug.getAutoSmpCycleUp());
mAutoSmpCycleUpCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpCycleUpCard);
}
if (CPUHotplug.hasAutoSmpDelay()) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 501; i++) list.add(i + getString(R.string.ms));
mAutoSmpDelayCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpDelayCard.setTitle(getString(R.string.delay));
mAutoSmpDelayCard.setDescription(getString(R.string.delay_summary));
mAutoSmpDelayCard.setProgress(CPUHotplug.getAutoSmpDelay());
mAutoSmpDelayCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpDelayCard);
}
if (CPUHotplug.hasAutoSmpMaxCpus()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++) list.add(String.valueOf(i));
mAutoSmpMaxCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpMaxCpusCard.setTitle(getString(R.string.max_cpu_online));
mAutoSmpMaxCpusCard.setDescription(getString(R.string.max_cpu_online_summary));
mAutoSmpMaxCpusCard.setProgress(CPUHotplug.getAutoSmpMaxCpus() - 1);
mAutoSmpMaxCpusCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpMaxCpusCard);
}
if (CPUHotplug.hasAutoSmpMinCpus()) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= CPU.getCoreCount(); i++) list.add(String.valueOf(i));
mAutoSmpMinCpusCard = new SeekBarCardView.DSeekBarCardView(list);
mAutoSmpMinCpusCard.setTitle(getString(R.string.min_cpu_online));
mAutoSmpMinCpusCard.setDescription(getString(R.string.min_cpu_online_summary));
mAutoSmpMinCpusCard.setProgress(CPUHotplug.getAutoSmpMinCpus() - 1);
mAutoSmpMinCpusCard.setOnDSeekBarCardListener(this);
views.add(mAutoSmpMinCpusCard);
}
if (CPUHotplug.hasAutoSmpScroffSingleCore()) {
mAutoSmpScroffSingleCoreCard = new SwitchCardView.DSwitchCard();
mAutoSmpScroffSingleCoreCard.setTitle(getString(R.string.screen_off_single_core));
mAutoSmpScroffSingleCoreCard.setDescription(getString(R.string.screen_off_single_core_summary));
mAutoSmpScroffSingleCoreCard.setChecked(CPUHotplug.isAutoSmpScroffSingleCoreActive());
mAutoSmpScroffSingleCoreCard.setOnDSwitchCardListener(this);
views.add(mAutoSmpScroffSingleCoreCard);
}
if (views.size() > 0) {
DividerCardView.DDividerCard mAutoSmpDividerCard = new DividerCardView.DDividerCard();
mAutoSmpDividerCard.setText(getString(R.string.autosmp));
addView(mAutoSmpDividerCard);
addAllViews(views);
}
}
@Override
public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) {
if (dSwitchCard == mMpdecisionCard)
CPUHotplug.activateMpdecision(checked, getActivity());
else if (dSwitchCard == mIntelliPlugCard)
CPUHotplug.activateIntelliPlug(checked, getActivity());
else if (dSwitchCard == mIntelliPlugEcoCard)
CPUHotplug.activateIntelliPlugEco(checked, getActivity());
else if (dSwitchCard == mIntelliPlugTouchBoostCard)
CPUHotplug.activateIntelliPlugTouchBoost(checked, getActivity());
else if (dSwitchCard == mIntelliPlugDebugCard)
CPUHotplug.activateIntelliPlugDebug(checked, getActivity());
else if (dSwitchCard == mIntelliPlugSuspendCard)
CPUHotplug.activateIntelliPlugSuspend(checked, getActivity());
else if (dSwitchCard == mBluPlugCard)
CPUHotplug.activateBluPlug(checked, getActivity());
else if (dSwitchCard == mBluPlugPowersaverModeCard)
CPUHotplug.activateBluPlugPowersaverMode(checked, getActivity());
else if (dSwitchCard == mMsmHotplugEnabledCard)
CPUHotplug.activateMsmHotplug(checked, getActivity());
else if (dSwitchCard == mMsmHotplugDebugMaskCard)
CPUHotplug.activateMsmHotplugDebugMask(checked, getActivity());
else if (dSwitchCard == mMsmHotplugIoIsBusyCard)
CPUHotplug.activateMsmHotplugIoIsBusy(checked, getActivity());
else if (dSwitchCard == mMakoHotplugEnableCard)
CPUHotplug.activateMakoHotplug(checked, getActivity());
else if (dSwitchCard == mMBHotplugEnableCard)
CPUHotplug.activateMBHotplug(checked, getActivity());
else if (dSwitchCard == mMBHotplugScroffSingleCoreCard)
CPUHotplug.activateMBHotplugScroffSingleCore(checked, getActivity());
else if (dSwitchCard == mMBHotplugBoostEnableCard)
CPUHotplug.activateMBHotplugBoost(checked, getActivity());
else if (dSwitchCard == mAlucardHotplugEnableCard)
CPUHotplug.activateAlucardHotplug(checked, getActivity());
else if (dSwitchCard == mAlucardHotplugHpIoIsBusyCard)
CPUHotplug.activateAlucardHotplugHpIoIsBusy(checked, getActivity());
else if (dSwitchCard == mAlucardHotplugSuspendCard)
CPUHotplug.activateAlucardHotplugSuspend(checked, getActivity());
else if (dSwitchCard == mThunderPlugEnableCard)
CPUHotplug.activateThunderPlug(checked, getActivity());
else if (dSwitchCard == mThunderPlugTouchBoostCard)
CPUHotplug.activateThunderPlugTouchBoost(checked, getActivity());
else if (dSwitchCard == mZenDecisionEnableCard)
CPUHotplug.activateZenDecision(checked, getActivity());
else if (dSwitchCard == mAutoSmpEnableCard)
CPUHotplug.activateAutoSmp(checked, getActivity());
else if (dSwitchCard == mAutoSmpScroffSingleCoreCard)
CPUHotplug.activateAutoSmpScroffSingleCoreActive(checked, getActivity());
}
@Override
public void onItemSelected(PopupCardItem.DPopupCard dPopupCard, int position) {
if (dPopupCard == mIntelliPlugProfileCard)
CPUHotplug.setIntelliPlugProfile(position, getActivity());
else if (dPopupCard == mIntelliPlugScreenOffMaxCard)
CPUHotplug.setIntelliPlugScreenOffMax(position, getActivity());
else if (dPopupCard == mBluPlugMaxFreqScreenOffCard)
CPUHotplug.setBluPlugMaxFreqScreenOff(position, getActivity());
else if (dPopupCard == mMsmHotplugFastLaneMinFreqCard)
CPUHotplug.setMsmHotplugFastLaneMinFreq(CPU.getFreqs().get(position), getActivity());
else if (dPopupCard == mMsmHotplugSuspendFreqCard)
CPUHotplug.setMsmHotplugSuspendFreq(CPU.getFreqs().get(position), getActivity());
else if (dPopupCard == mMakoHotplugCpuFreqUnplugLimitCard)
CPUHotplug.setMakoHotplugCpuFreqUnplugLimit(CPU.getFreqs().get(position), getActivity());
else if (dPopupCard == mMakoSuspendFreqCard)
CPUHotplug.setMakoHotplugSuspendFreq(CPU.getFreqs().get(position), getActivity());
else if (dPopupCard == mMBHotplugIdleFreqCard)
CPUHotplug.setMBHotplugIdleFreq(CPU.getFreqs().get(position), getActivity());
else if (dPopupCard == mThunderPlugEnduranceLevelCard)
CPUHotplug.setThunderPlugEnduranceLevel(position, getActivity());
else {
for (int i = 0; i < mMBHotplugBoostFreqsCard.length; i++)
if (dPopupCard == mMBHotplugBoostFreqsCard[i]) {
CPUHotplug.setMBHotplugBoostFreqs(i, CPU.getFreqs().get(position), getActivity());
return;
}
}
}
@Override
public void onChanged(SeekBarCardView.DSeekBarCardView dSeekBarCardView, int position) {
}
@Override
public void onStop(SeekBarCardView.DSeekBarCardView dSeekBarCardView, int position) {
if (dSeekBarCardView == mIntelliPlugHysteresisCard)
CPUHotplug.setIntelliPlugHysteresis(position, getActivity());
else if (dSeekBarCardView == mIntelliPlugThresholdCard)
CPUHotplug.setIntelliPlugThresold(position, getActivity());
else if (dSeekBarCardView == mIntelliPlugCpusBoostedCard)
CPUHotplug.setIntelliPlugCpusBoosted(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugMinCpusOnlineCard)
CPUHotplug.setIntelliPlugMinCpusOnline(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugMaxCpusOnlineCard)
CPUHotplug.setIntelliPlugMaxCpusOnline(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugMaxCpusOnlineSuspCard)
CPUHotplug.setIntelliPlugMaxCpusOnlineSusp(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugSuspendDeferTimeCard)
CPUHotplug.setIntelliPlugSuspendDeferTime(position * 10, getActivity());
else if (dSeekBarCardView == mIntelliPlugDeferSamplingCard)
CPUHotplug.setIntelliPlugDeferSampling(position, getActivity());
else if (dSeekBarCardView == mIntelliPlugBoostLockDurationCard)
CPUHotplug.setIntelliPlugBoostLockDuration(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugDownLockDurationCard)
CPUHotplug.setIntelliPlugDownLockDuration(position + 1, getActivity());
else if (dSeekBarCardView == mIntelliPlugFShiftCard)
CPUHotplug.setIntelliPlugFShift(position, getActivity());
else if (dSeekBarCardView == mBluPlugMinOnlineCard)
CPUHotplug.setBluPlugMinOnline(position + 1, getActivity());
else if (dSeekBarCardView == mBluPlugMaxOnlineCard)
CPUHotplug.setBluPlugMaxOnline(position + 1, getActivity());
else if (dSeekBarCardView == mBluPlugMaxCoresScreenOffCard)
CPUHotplug.setBluPlugMaxCoresScreenOff(position + 1, getActivity());
else if (dSeekBarCardView == mBluPlugUpThresholdCard)
CPUHotplug.setBluPlugUpThreshold(position, getActivity());
else if (dSeekBarCardView == mBluPlugUpTimerCntCard)
CPUHotplug.setBluPlugUpTimerCnt(position, getActivity());
else if (dSeekBarCardView == mBluPlugDownTimerCntCard)
CPUHotplug.setBluPlugDownTimerCnt(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugMinCpusOnlineCard)
CPUHotplug.setMsmHotplugMinCpusOnline(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugMaxCpusOnlineCard)
CPUHotplug.setMsmHotplugMaxCpusOnline(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugCpusBoostedCard)
CPUHotplug.setMsmHotplugCpusBoosted(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugCpusOnlineSuspCard)
CPUHotplug.setMsmHotplugMaxCpusOnlineSusp(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugBoostLockDurationCard)
CPUHotplug.setMsmHotplugBoostLockDuration(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugDownLockDurationCard)
CPUHotplug.setMsmHotplugDownLockDuration(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugHistorySizeCard)
CPUHotplug.setMsmHotplugHistorySize(position + 1, getActivity());
else if (dSeekBarCardView == mMsmHotplugUpdateRateCard)
CPUHotplug.setMsmHotplugUpdateRate(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugFastLaneLoadCard)
CPUHotplug.setMsmHotplugFastLaneLoad(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugOfflineLoadCard)
CPUHotplug.setMsmHotplugOfflineLoad(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugSuspendMaxCpusCard)
CPUHotplug.setMsmHotplugSuspendMaxCpus(position, getActivity());
else if (dSeekBarCardView == mMsmHotplugSuspendDeferTimeCard)
CPUHotplug.setMsmHotplugSuspendDeferTime(position, getActivity());
else if (dSeekBarCardView == mMakoCoreOnTouchCard)
CPUHotplug.setMakoHotplugCoresOnTouch(position + 1, getActivity());
else if (dSeekBarCardView == mMakoHotplugFirstLevelCard)
CPUHotplug.setMakoHotplugFirstLevel(position, getActivity());
else if (dSeekBarCardView == mMakoHotplugHighLoadCounterCard)
CPUHotplug.setMakoHotplugHighLoadCounter(position, getActivity());
else if (dSeekBarCardView == mMakoHotplugLoadThresholdCard)
CPUHotplug.setMakoHotplugLoadThreshold(position, getActivity());
else if (dSeekBarCardView == mMakoHotplugMaxLoadCounterCard)
CPUHotplug.setMakoHotplugMaxLoadCounter(position, getActivity());
else if (dSeekBarCardView == mMakoHotplugMinTimeCpuOnlineCard)
CPUHotplug.setMakoHotplugMinTimeCpuOnline(position, getActivity());
else if (dSeekBarCardView == mMakoHotplugMinCoresOnlineCard)
CPUHotplug.setMakoHotplugMinCoresOnline(position + 1, getActivity());
else if (dSeekBarCardView == mMakoHotplugTimerCard)
CPUHotplug.setMakoHotplugTimer(position, getActivity());
else if (dSeekBarCardView == mMBHotplugMinCpusCard)
CPUHotplug.setMBHotplugMinCpus(position + 1, getActivity());
else if (dSeekBarCardView == mMBHotplugMaxCpusCard)
CPUHotplug.setMBHotplugMaxCpus(position + 1, getActivity());
else if (dSeekBarCardView == mMBHotplugMaxCpusOnlineSuspCard)
CPUHotplug.setMBHotplugMaxCpusOnlineSusp(position + 1, getActivity());
else if (dSeekBarCardView == mMBHotplugBoostTimeCard)
CPUHotplug.setMBHotplugBoostTime(position * 100, getActivity());
else if (dSeekBarCardView == mMBHotplugCpusBoostedCard)
CPUHotplug.setMBHotplugCpusBoosted(position, getActivity());
else if (dSeekBarCardView == mMBHotplugStartDelayCard)
CPUHotplug.setMBHotplugStartDelay(position * 1000, getActivity());
else if (dSeekBarCardView == mMBHotplugDelayCard)
CPUHotplug.setMBHotplugDelay(position, getActivity());
else if (dSeekBarCardView == mMBHotplugPauseCard)
CPUHotplug.setMBHotplugPause(position * 1000, getActivity());
else if (dSeekBarCardView == mAlucardHotplugSamplingRateCard)
CPUHotplug.setAlucardHotplugSamplingRate(position + 1, getActivity());
else if (dSeekBarCardView == mAlucardHotplugMinCpusOnlineCard)
CPUHotplug.setAlucardHotplugMinCpusOnline(position + 1, getActivity());
else if (dSeekBarCardView == mAlucardHotplugMaxCoresLimitCard)
CPUHotplug.setAlucardHotplugMaxCoresLimit(position + 1, getActivity());
else if (dSeekBarCardView == mAlucardHotplugMaxCoresLimitSleepCard)
CPUHotplug.setAlucardHotplugMaxCoresLimitSleep(position + 1, getActivity());
else if (dSeekBarCardView == mAlucardHotplugCpuDownRateCard)
CPUHotplug.setAlucardHotplugCpuDownRate(position + 1, getActivity());
else if (dSeekBarCardView == mAlucardHotplugCpuUpRateCard)
CPUHotplug.setAlucardHotplugCpuUpRate(position + 1, getActivity());
else if (dSeekBarCardView == mThunderPlugSuspendCpusCard)
CPUHotplug.setThunderPlugSuspendCpus(position + 1, getActivity());
else if (dSeekBarCardView == mThunderPlugSamplingRateCard)
CPUHotplug.setThunderPlugSamplingRate(position * 50, getActivity());
else if (dSeekBarCardView == mThunderPlugLoadThresholdCard)
CPUHotplug.setThunderPlugLoadThreshold(position + 11, getActivity());
else if (dSeekBarCardView == mZenDecisionWakeWaitTimeCard)
CPUHotplug.setZenDecisionWakeWaitTime(position * 1000, getActivity());
else if (dSeekBarCardView == mZenDecisionBatThresholdIgnoreCard)
CPUHotplug.setZenDecisionBatThresholdIgnore(position, getActivity());
else if (dSeekBarCardView == mAutoSmpCpufreqDownCard)
CPUHotplug.setAutoSmpCpufreqDown(position, getActivity());
else if (dSeekBarCardView == mAutoSmpCpufreqUpCard)
CPUHotplug.setAutoSmpCpufreqUp(position, getActivity());
else if (dSeekBarCardView == mAutoSmpCycleDownCard)
CPUHotplug.setAutoSmpCycleDown(position, getActivity());
else if (dSeekBarCardView == mAutoSmpCycleUpCard)
CPUHotplug.setAutoSmpCycleUp(position, getActivity());
else if (dSeekBarCardView == mAutoSmpDelayCard)
CPUHotplug.setAutoSmpDelay(position, getActivity());
else if (dSeekBarCardView == mAutoSmpMaxCpusCard)
CPUHotplug.setAutoSmpMaxCpus(position + 1, getActivity());
else if (dSeekBarCardView == mAutoSmpMinCpusCard)
CPUHotplug.setAutoSmpMinCpus(position + 1, getActivity());
}
}
| |
package org.jolokia.docker.maven;
/*
* Copyright 2009-2014 Roland Huss Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.StringUtils;
import org.jolokia.docker.maven.access.DockerAccess;
import org.jolokia.docker.maven.access.DockerAccessException;
import org.jolokia.docker.maven.access.PortMapping;
import org.jolokia.docker.maven.access.log.LogCallback;
import org.jolokia.docker.maven.access.log.LogGetHandle;
import org.jolokia.docker.maven.config.ImageConfiguration;
import org.jolokia.docker.maven.config.LogConfiguration;
import org.jolokia.docker.maven.config.RunImageConfiguration;
import org.jolokia.docker.maven.config.WaitConfiguration;
import org.jolokia.docker.maven.log.LogDispatcher;
import org.jolokia.docker.maven.service.QueryService;
import org.jolokia.docker.maven.service.RunService;
import org.jolokia.docker.maven.util.StartOrderResolver;
import org.jolokia.docker.maven.util.Timestamp;
import org.jolokia.docker.maven.util.WaitUtil;
/**
* Goal for creating and starting a docker container. This goal evaluates the image configuration
*
* @author roland
* @goal start
* @phase pre-integration-test
*/
public class StartMojo extends AbstractDockerMojo {
/**
* @parameter property = "docker.showLogs"
*/
private String showLogs;
/**
* @parameter property = "docker.follow" default-value = "false"
*/
protected boolean follow;
/**
* {@inheritDoc}
*/
@Override
public synchronized void executeInternal(final DockerAccess dockerAccess) throws DockerAccessException, MojoExecutionException {
getPluginContext().put(CONTEXT_KEY_START_CALLED, true);
Properties projProperties = project.getProperties();
QueryService queryService = serviceHub.getQueryService();
RunService runService = serviceHub.getRunService();
LogDispatcher dispatcher = getLogDispatcher(dockerAccess);
PortMapping.PropertyWriteHelper portMappingPropertyWriteHelper = new PortMapping.PropertyWriteHelper(portPropertyFile);
boolean success = false;
try {
for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getImages())) {
final ImageConfiguration imageConfig = (ImageConfiguration) resolvable;
// Still to check: How to work with linking, volumes, etc ....
//String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry);
String imageName = imageConfig.getName();
checkImageWithAutoPull(dockerAccess, imageName,
getConfiguredRegistry(imageConfig),imageConfig.getBuildConfiguration() == null);
RunImageConfiguration runConfig = imageConfig.getRunConfiguration();
PortMapping portMapping = runService.getPortMapping(runConfig, projProperties);
String containerId = runService.createAndStartContainer(imageConfig, portMapping, projProperties);
if (showLogs(imageConfig)) {
dispatcher.trackContainerLog(containerId, getContainerLogSpec(containerId, imageConfig));
}
portMappingPropertyWriteHelper.add(portMapping, runConfig.getPortPropertyFile());
// Wait if requested
waitIfRequested(dockerAccess,imageConfig, projProperties, containerId);
}
if (follow) {
runService.addShutdownHookForStoppingContainers(keepContainer,removeVolumes);
wait();
}
portMappingPropertyWriteHelper.write();
success = true;
} catch (InterruptedException e) {
log.warn("Interrupted");
Thread.currentThread().interrupt();
throw new MojoExecutionException("interrupted", e);
} catch (IOException e) {
throw new MojoExecutionException("I/O Error",e);
} finally {
if (!success) {
log.error("Error occurred during container startup, shutting down...");
runService.stopStartedContainers(keepContainer, removeVolumes);
}
}
}
// ========================================================================================================
private void waitIfRequested(DockerAccess docker, ImageConfiguration imageConfig, Properties projectProperties, String containerId) throws MojoExecutionException {
RunImageConfiguration runConfig = imageConfig.getRunConfiguration();
WaitConfiguration wait = runConfig.getWaitConfiguration();
if (wait != null) {
ArrayList<WaitUtil.WaitChecker> checkers = new ArrayList<>();
ArrayList<String> logOut = new ArrayList<>();
if (wait.getUrl() != null) {
String waitUrl = StrSubstitutor.replace(wait.getUrl(), projectProperties);
WaitConfiguration.HttpConfiguration httpConfig = wait.getHttp();
if (httpConfig != null) {
checkers.add(new WaitUtil.HttpPingChecker(waitUrl, httpConfig.getMethod(), httpConfig.getStatus()));
} else {
checkers.add(new WaitUtil.HttpPingChecker(waitUrl));
}
logOut.add("on url " + waitUrl);
}
if (wait.getLog() != null) {
checkers.add(getLogWaitChecker(wait.getLog(), docker, containerId));
logOut.add("on log out '" + wait.getLog() + "'");
}
try {
long waited = WaitUtil.wait(wait.getTime(), checkers.toArray(new WaitUtil.WaitChecker[0]));
log.info(imageConfig.getDescription() + ": Waited " + StringUtils.join(logOut.toArray(), " and ") + " " + waited + " ms");
} catch (TimeoutException exp) {
String desc = imageConfig.getDescription() + ": Timeout after " + wait.getTime() + " ms while waiting " +
StringUtils.join(logOut.toArray(), " and ");
log.error(desc);
throw new MojoExecutionException(desc);
}
}
}
private WaitUtil.WaitChecker getLogWaitChecker(final String logPattern, final DockerAccess docker, final String containerId) {
return new WaitUtil.WaitChecker() {
boolean first = true;
LogGetHandle logHandle;
boolean detected = false;
@Override
public boolean check() {
if (first) {
final Pattern pattern = Pattern.compile(logPattern);
logHandle = docker.getLogAsync(containerId, new LogCallback() {
@Override
public void log(int type, Timestamp timestamp, String txt) throws LogCallback.DoneException {
if (pattern.matcher(txt).find()) {
detected = true;
throw new LogCallback.DoneException();
}
}
@Override
public void error(String error) {
log.error(error);
}
});
first = false;
}
return detected;
}
@Override
public void cleanUp() {
if (logHandle != null) {
logHandle.finish();
}
}
};
}
protected boolean showLogs(ImageConfiguration imageConfig) {
if (showLogs != null) {
if (showLogs.equalsIgnoreCase("true")) {
return true;
} else if (showLogs.equalsIgnoreCase("false")) {
return false;
} else {
return matchesConfiguredImages(showLogs, imageConfig);
}
}
RunImageConfiguration runConfig = imageConfig.getRunConfiguration();
if (runConfig != null) {
LogConfiguration logConfig = runConfig.getLog();
if (logConfig != null) {
return logConfig.isEnabled();
} else {
// Default is to show logs if "follow" is true
return follow;
}
}
return false;
}
}
| |
/*
* Copyright 2017-present, Yudong (Dom) Wang
*
* 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.wisdom.tool.util;
import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.codec.Charsets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.wisdom.tool.constant.RESTConst;
import org.wisdom.tool.gui.util.UIUtil;
import org.wisdom.tool.model.ErrCode;
import org.wisdom.tool.model.HttpHist;
import org.wisdom.tool.model.HttpHists;
import org.wisdom.tool.model.HttpReq;
import org.wisdom.tool.model.HttpRsp;
import org.wisdom.tool.thread.RESTThdPool;
import org.wisdom.tool.thread.TestThd;
/**
* @ClassName: TestUtil
* @Description: Test utility
* @Author: Yudong (Dom) Wang
* @Email: wisdomtool@outlook.com
* @Date: 2017-7-17 PM 1:11:29
* @Version: WisdomTool RESTClient V1.2
*/
public final class TestUtil
{
private static Logger log = LogManager.getLogger(TestUtil.class);
/**
*
* @Title: run
* @Description: Run test cases
* @param @param hists
* @param @return
* @return void
* @throws
*/
public static void runTest(HttpHists hists)
{
if (null == hists || CollectionUtils.isEmpty(hists.getHists()))
{
return;
}
List<HttpHist> histLst = hists.getHists();
hists.setTotal(histLst.size());
for (HttpHist hist : histLst)
{
if (hists.isStop())
{
hists.reset();
return;
}
if (null == hist.getReq() || null == hist.getRsp())
{
hist.setCause(RESTUtil.getCause(ErrCode.BAD_CASE).toString());
hists.countErr();
continue;
}
HttpReq req = hist.getReq();
HttpRsp rsp = RESTClient.getInstance().exec(req);
RESTUtil.result(hists, hist, rsp);
}
report(hists);
}
/**
*
* @Title: report
* @Description: Save test result to report
* @param @param hists
* @return void
* @throws
*/
private static synchronized void report(HttpHists hists)
{
try
{
// Update JS
InputStream is = RESTUtil.getInputStream(RESTConst.REPORT_JS);
String jsTxt = IOUtils.toString(is, Charsets.UTF_8);
jsTxt = jsTxt.replaceFirst(RESTConst.LABEL_REPORT_DATA, RESTUtil.tojsonText(hists));
FileUtils.write(new File(RESTUtil.replacePath(RESTConst.REPORT_JS)), jsTxt, Charsets.UTF_8);
RESTUtil.close(is);
// Update HTML
is = RESTUtil.getInputStream(RESTConst.REPORT_HTML);
String htmlTxt = IOUtils.toString(is, Charsets.UTF_8);
htmlTxt = htmlTxt.replaceFirst(RESTConst.LABEL_TOTAL, String.valueOf(hists.getTotal()));
htmlTxt = htmlTxt.replaceFirst(RESTConst.LABEL_PASSES, String.valueOf(hists.getPasses()));
htmlTxt = htmlTxt.replaceFirst(RESTConst.LABEL_FAILURES, String.valueOf(hists.getFailures()));
htmlTxt = htmlTxt.replaceFirst(RESTConst.LABEL_ERRORS, String.valueOf(hists.getErrors()));
FileUtils.write(new File(RESTUtil.replacePath(RESTConst.REPORT_HTML)), htmlTxt, Charsets.UTF_8);
RESTUtil.close(is);
// Copy file
is = RESTUtil.getInputStream(RESTConst.REPORT_JQUERY);
FileUtils.copyInputStreamToFile(is, new File(RESTUtil.replacePath(RESTConst.REPORT_JQUERY)));
RESTUtil.close(is);
is = RESTUtil.getInputStream(RESTConst.REPORT_CSS);
FileUtils.copyInputStreamToFile(is, new File(RESTUtil.replacePath(RESTConst.REPORT_CSS)));
RESTUtil.close(is);
is = RESTUtil.getInputStream(RESTConst.LOGO);
String rpath = RESTUtil.getPath(RESTConst.REPORT);
String logoPath = StringUtils.replaceOnce(RESTConst.LOGO, RESTConst.WISDOM_TOOL, rpath);
FileUtils.copyInputStreamToFile(is, new File(logoPath));
RESTUtil.close(is);
try
{
// Open test report
Desktop.getDesktop().open(new File(RESTUtil.replacePath(RESTConst.REPORT_HTML)));
}
catch(Exception e)
{
UIUtil.showMessage(RESTConst.MSG_REPORT, RESTConst.TEST_REPORT);
}
}
catch(Throwable e)
{
log.error("Failed to generate report.", e);
}
}
/**
*
* @Title : open
* @Description: Open test report
* @Param : @param path
* @Param : @param msg
* @Param : @param title
* @Return : void
* @Throws :
*/
public static void open(String path, final String msg, final String title)
{
File rf = new File(RESTUtil.replacePath(path));
if (!rf.exists())
{
return;
}
try
{
Desktop.getDesktop().open(rf);
}
catch(Exception e)
{
UIUtil.showMessage(msg, title);
}
}
/**
*
* @Title : progress
* @Description: Display progress
* @Param : @param hists
* @Return : void
* @Throws :
*/
public static void progress(HttpHists hists)
{
int done = 0;
int preDone = 0;
int progress = 0;
System.out.print(RESTConst.TEST_CASE + ".\r\nCompleted --> ");
while (progress < hists.getTotal())
{
progress = hists.progress();
done = Math.min(progress, hists.getTotal()) * 100 / hists.getTotal();
if (done != preDone)
{
System.out.print(done + "%");
for (int i = 0; i <= String.valueOf(done).length(); i++)
{
System.out.print("\b");
}
}
preDone = done;
RESTUtil.sleep(RESTConst.TIME_100MS);
}
System.out.println("\r\n" + RESTConst.DONE);
}
/**
*
* @Title : apiTest
* @Description: test API
* @Param : @param hists
* @Return : void
* @Throws :
*/
public static void apiTest(HttpHists hists)
{
Thread testThrd = new TestThd(hists);
testThrd.setName(RESTConst.TEST_THREAD);
RESTThdPool.getInstance().getPool().submit(testThrd);
RESTUtil.sleep(RESTConst.TIME_100MS);
TestUtil.progress(hists);
}
}
| |
/*
* Copyright 2015 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigtable.mapreduce;
import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import com.google.cloud.bigtable.hbase.BigtableOptionsFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2;
import org.apache.hadoop.hbase.mapreduce.KeyValueSortReducer;
import org.apache.hadoop.hbase.mapreduce.ResultSerialization;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Import data written by {@link org.apache.hadoop.hbase.mapreduce.Export}.
*
* @author sduskis
* @version $Id: $Id
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class Import extends Configured implements Tool {
private static final Log LOG = LogFactory.getLog(Import.class);
static final String NAME = "import";
/** Constant <code>CF_RENAME_PROP="HBASE_IMPORTER_RENAME_CFS"</code> */
public static final String CF_RENAME_PROP = "HBASE_IMPORTER_RENAME_CFS";
/** Constant <code>BULK_OUTPUT_CONF_KEY="import.bulk.output"</code> */
public static final String BULK_OUTPUT_CONF_KEY = "import.bulk.output";
/** Constant <code>FILTER_CLASS_CONF_KEY="import.filter.class"</code> */
public static final String FILTER_CLASS_CONF_KEY = "import.filter.class";
/** Constant <code>FILTER_ARGS_CONF_KEY="import.filter.args"</code> */
public static final String FILTER_ARGS_CONF_KEY = "import.filter.args";
/** Constant <code>TABLE_NAME="import.table.name"</code> */
public static final String TABLE_NAME = "import.table.name";
private static final String JOB_NAME_CONF_KEY = "mapreduce.job.name";
/** A mapper that just writes out KeyValues. */
public static class KeyValueImporter extends TableMapper<ImmutableBytesWritable, KeyValue> {
private Map<byte[], byte[]> cfRenameMap;
private Filter filter;
/**
* @param row The current table row key.
* @param value The columns.
* @param context The current context.
* @throws IOException When something is broken with the data.
*/
@SuppressWarnings("deprecation")
@Override
public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException {
try {
if (LOG.isTraceEnabled()) {
LOG.trace(
"Considering the row." + Bytes.toString(row.get(), row.getOffset(), row.getLength()));
}
if (filter == null || !filter.filterRowKey(row.get(), row.getOffset(), row.getLength())) {
for (Cell kv : value.rawCells()) {
kv = filterKv(filter, kv);
// skip if we filtered it out
if (kv == null) continue;
// TODO get rid of ensureKeyValue
context.write(row, KeyValueUtil.ensureKeyValue(convertKv(kv, cfRenameMap)));
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("map process was interrupted", e);
}
}
@Override
public void setup(Context context) {
cfRenameMap = createCfRenameMap(context.getConfiguration());
filter = instantiateFilter(context.getConfiguration());
}
}
/** Write table content out to files. */
public static class Importer extends TableMapper<ImmutableBytesWritable, Mutation> {
private Map<byte[], byte[]> cfRenameMap;
private Filter filter;
private Durability durability;
/**
* @param row The current table row key.
* @param value The columns.
* @param context The current context.
* @throws IOException When something is broken with the data.
*/
@Override
public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException {
try {
writeResult(row, value, context);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("map process was interrupted", e);
}
}
private void writeResult(ImmutableBytesWritable key, Result result, Context context)
throws IOException, InterruptedException {
Put put = null;
Delete delete = null;
if (LOG.isTraceEnabled()) {
LOG.trace(
"Considering the row." + Bytes.toString(key.get(), key.getOffset(), key.getLength()));
}
if (filter == null || !filter.filterRowKey(key.get(), key.getOffset(), key.getLength())) {
processKV(key, result, context, put, delete);
}
}
protected void processKV(
ImmutableBytesWritable key, Result result, Context context, Put put, Delete delete)
throws IOException, InterruptedException {
for (Cell kv : result.rawCells()) {
kv = filterKv(filter, kv);
// skip if we filter it out
if (kv == null) continue;
kv = convertKv(kv, cfRenameMap);
// Deletes and Puts are gathered and written when finished
/*
* If there are sequence of mutations and tombstones in an Export, and after Import the same
* sequence should be restored as it is. If we combine all Delete tombstones into single
* request then there is chance of ignoring few DeleteFamily tombstones, because if we
* submit multiple DeleteFamily tombstones in single Delete request then we are maintaining
* only newest in hbase table and ignoring other. Check - HBASE-12065
*/
if (CellUtil.isDeleteFamily(kv)) {
Delete deleteFamily = new Delete(key.get());
deleteFamily.addDeleteMarker(kv);
if (durability != null) {
deleteFamily.setDurability(durability);
}
context.write(key, deleteFamily);
} else if (CellUtil.isDelete(kv)) {
if (delete == null) {
delete = new Delete(key.get());
}
delete.addDeleteMarker(kv);
} else {
if (put == null) {
put = new Put(key.get());
}
addPutToKv(put, kv);
}
}
if (put != null) {
if (durability != null) {
put.setDurability(durability);
}
context.write(key, put);
}
if (delete != null) {
if (durability != null) {
delete.setDurability(durability);
}
context.write(key, delete);
}
}
protected void addPutToKv(Put put, Cell kv) throws IOException {
put.add(kv);
}
@Override
public void setup(Context context) {
Configuration conf = context.getConfiguration();
cfRenameMap = createCfRenameMap(conf);
filter = instantiateFilter(conf);
}
}
/**
* Create a {@link org.apache.hadoop.hbase.filter.Filter} to apply to all incoming keys ({@link
* KeyValue KeyValues}) to optionally not include in the job output
*
* @param conf {@link org.apache.hadoop.conf.Configuration} from which to load the filter
* @return the filter to use for the task, or <tt>null</tt> if no filter to should be used
* @throws java.lang.IllegalArgumentException if the filter is misconfigured
*/
public static Filter instantiateFilter(Configuration conf) {
// get the filter, if it was configured
Class<? extends Filter> filterClass = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
if (filterClass == null) {
LOG.debug("No configured filter class, accepting all keyvalues.");
return null;
}
LOG.debug("Attempting to create filter:" + filterClass);
String[] filterArgs = conf.getStrings(FILTER_ARGS_CONF_KEY);
ArrayList<byte[]> quotedArgs = toQuotedByteArrays(filterArgs);
try {
Method m = filterClass.getMethod("createFilterFromArguments", ArrayList.class);
return (Filter) m.invoke(null, quotedArgs);
} catch (IllegalAccessException e) {
LOG.error("Couldn't instantiate filter!", e);
throw new RuntimeException(e);
} catch (SecurityException e) {
LOG.error("Couldn't instantiate filter!", e);
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
LOG.error("Couldn't instantiate filter!", e);
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
LOG.error("Couldn't instantiate filter!", e);
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
LOG.error("Couldn't instantiate filter!", e);
throw new RuntimeException(e);
}
}
private static ArrayList<byte[]> toQuotedByteArrays(String... stringArgs) {
ArrayList<byte[]> quotedArgs = new ArrayList<byte[]>();
for (String stringArg : stringArgs) {
// all the filters' instantiation methods expected quoted args since they are coming from
// the shell, so add them here, though it shouldn't really be needed :-/
quotedArgs.add(Bytes.toBytes("'" + stringArg + "'"));
}
return quotedArgs;
}
/**
* Attempt to filter out the keyvalue
*
* @param kv {@link org.apache.hadoop.hbase.KeyValue} on which to apply the filter
* @return <tt>null</tt> if the key should not be written, otherwise returns the original {@link
* org.apache.hadoop.hbase.KeyValue}
* @param filter a {@link org.apache.hadoop.hbase.filter.Filter} object.
* @throws java.io.IOException if any.
*/
public static Cell filterKv(Filter filter, Cell kv) throws IOException {
// apply the filter and skip this kv if the filter doesn't apply
if (filter != null) {
Filter.ReturnCode code = filter.filterKeyValue(kv);
if (LOG.isTraceEnabled()) {
LOG.trace("Filter returned:" + code + " for the key value:" + kv);
}
// if its not an accept type, then skip this kv
if (!(code.equals(Filter.ReturnCode.INCLUDE)
|| code.equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) {
return null;
}
}
return kv;
}
// helper: create a new KeyValue based on CF rename map
private static Cell convertKv(Cell kv, Map<byte[], byte[]> cfRenameMap) {
if (cfRenameMap != null) {
// If there's a rename mapping for this CF, create a new KeyValue
byte[] newCfName = cfRenameMap.get(CellUtil.cloneFamily(kv));
if (newCfName != null) {
kv =
new KeyValue(
kv.getRowArray(), // row buffer
kv.getRowOffset(), // row offset
kv.getRowLength(), // row length
newCfName, // CF buffer
0, // CF offset
newCfName.length, // CF length
kv.getQualifierArray(), // qualifier buffer
kv.getQualifierOffset(), // qualifier offset
kv.getQualifierLength(), // qualifier length
kv.getTimestamp(), // timestamp
KeyValue.Type.codeToType(kv.getTypeByte()), // KV Type
kv.getValueArray(), // value buffer
kv.getValueOffset(), // value offset
kv.getValueLength()); // value length
}
}
return kv;
}
// helper: make a map from sourceCfName to destCfName by parsing a config key
private static Map<byte[], byte[]> createCfRenameMap(Configuration conf) {
Map<byte[], byte[]> cfRenameMap = null;
String allMappingsPropVal = conf.get(CF_RENAME_PROP);
if (allMappingsPropVal != null) {
// The conf value format should be sourceCf1:destCf1,sourceCf2:destCf2,...
String[] allMappings = allMappingsPropVal.split(",");
for (String mapping : allMappings) {
if (cfRenameMap == null) {
cfRenameMap = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR);
}
String[] srcAndDest = mapping.split(":");
if (srcAndDest.length != 2) {
continue;
}
cfRenameMap.put(srcAndDest[0].getBytes(), srcAndDest[1].getBytes());
}
}
return cfRenameMap;
}
/**
* Sets a configuration property with key {@link #CF_RENAME_PROP} in conf that tells the mapper
* how to rename column families.
*
* <p>Alternately, instead of calling this function, you could set the configuration key {@link
* #CF_RENAME_PROP} yourself. The value should look like
*
* <pre>srcCf1:destCf1,srcCf2:destCf2,....</pre>
*
* . This would have the same effect on the mapper behavior.
*
* @param conf the Configuration in which the {@link #CF_RENAME_PROP} key will be set
* @param renameMap a mapping from source CF names to destination CF names
*/
public static void configureCfRenaming(Configuration conf, Map<String, String> renameMap) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : renameMap.entrySet()) {
String sourceCf = entry.getKey();
String destCf = entry.getValue();
if (sourceCf.contains(":")
|| sourceCf.contains(",")
|| destCf.contains(":")
|| destCf.contains(",")) {
throw new IllegalArgumentException(
"Illegal character in CF names: " + sourceCf + ", " + destCf);
}
if (sb.length() != 0) {
sb.append(",");
}
sb.append(sourceCf + ":" + destCf);
}
conf.set(CF_RENAME_PROP, sb.toString());
}
/**
* Add a Filter to be instantiated on import
*
* @param conf Configuration to update (will be passed to the job)
* @param clazz {@link org.apache.hadoop.hbase.filter.Filter} subclass to instantiate on the
* server.
* @param filterArgs List of arguments to pass to the filter on instantiation
*/
public static void addFilterAndArguments(
Configuration conf, Class<? extends Filter> clazz, List<String> filterArgs) {
conf.set(Import.FILTER_CLASS_CONF_KEY, clazz.getName());
conf.setStrings(Import.FILTER_ARGS_CONF_KEY, filterArgs.toArray(new String[filterArgs.size()]));
}
/**
* Sets up the actual job.
*
* @param conf The current configuration.
* @param args The command line parameters.
* @return The newly created job.
* @throws java.io.IOException When setting up the job fails.
*/
public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException {
conf.setIfUnset(
"hbase.client.connection.impl", BigtableConfiguration.getConnectionClass().getName());
conf.setIfUnset(BigtableOptionsFactory.BIGTABLE_RPC_TIMEOUT_MS_KEY, "60000");
TableName tableName = TableName.valueOf(args[0]);
conf.set(TABLE_NAME, tableName.getNameAsString());
Path inputDir = new Path(args[1]);
Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
job.setJarByClass(Importer.class);
FileInputFormat.setInputPaths(job, inputDir);
// Randomize the splits to avoid hot spotting a single tablet server
job.setInputFormatClass(ShuffledSequenceFileInputFormat.class);
// Give the mappers enough work to do otherwise each split will be dominated by spinup time
ShuffledSequenceFileInputFormat.setMinInputSplitSize(job, 1L * 1024 * 1024 * 1024);
String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
// make sure we get the filter in the jars
try {
Class<? extends Filter> filter = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
if (filter != null) {
TableMapReduceUtil.addDependencyJars(conf, filter);
}
} catch (Exception e) {
throw new IOException(e);
}
if (hfileOutPath != null) {
job.setMapperClass(KeyValueImporter.class);
try (Connection conn = ConnectionFactory.createConnection(conf);
Table table = conn.getTable(tableName);
RegionLocator regionLocator = conn.getRegionLocator(tableName)) {
job.setReducerClass(KeyValueSortReducer.class);
Path outputDir = new Path(hfileOutPath);
FileOutputFormat.setOutputPath(job, outputDir);
job.setMapOutputKeyClass(ImmutableBytesWritable.class);
job.setMapOutputValueClass(KeyValue.class);
HFileOutputFormat2.configureIncrementalLoad(job, table, regionLocator);
}
} else {
// No reducers. Just write straight to table. Call initTableReducerJob
// because it sets up the TableOutputFormat.
job.setMapperClass(Importer.class);
// TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job);
TableMapReduceUtil.initTableReducerJob(
tableName.getNameAsString(), null, job, null, null, null, null, false);
job.setNumReduceTasks(0);
}
return job;
}
/*
* @param errorMsg Error message. Can be null.
*/
private static void usage(final String errorMsg) {
if (errorMsg != null && errorMsg.length() > 0) {
System.err.println("ERROR: " + errorMsg);
}
System.err.println("Usage: Import [options] <tablename> <inputdir>");
System.err.println(" Mandatory properties:");
System.err.println(" -D " + BigtableOptionsFactory.PROJECT_ID_KEY + "=<bigtable project id>");
System.err.println(
" -D " + BigtableOptionsFactory.INSTANCE_ID_KEY + "=<bigtable instance id>");
System.err.println(
" To apply a generic org.apache.hadoop.hbase.filter.Filter to the input, use");
System.err.println(" -D" + FILTER_CLASS_CONF_KEY + "=<name of filter class>");
System.err.println(" -D" + FILTER_ARGS_CONF_KEY + "=<comma separated list of args for filter");
System.err.println(
" NOTE: The filter will be applied BEFORE doing key renames via the "
+ CF_RENAME_PROP
+ " property. Futher, filters will only use the"
+ " Filter#filterRowKey(byte[] buffer, int offset, int length) method to identify "
+ " whether the current row needs to be ignored completely for processing and "
+ " Filter#filterKeyValue(KeyValue) method to determine if the KeyValue should be added;"
+ " Filter.ReturnCode#INCLUDE and #INCLUDE_AND_NEXT_COL will be considered as including"
+ " the KeyValue.");
System.err.println(
" -D "
+ JOB_NAME_CONF_KEY
+ "=jobName - use the specified mapreduce job name for the import");
System.err.println(
"For performance consider the following options:\n"
+ " -Dmapreduce.map.speculative=false\n"
+ " -Dmapreduce.reduce.speculative=false\n");
}
/** {@inheritDoc} */
@Override
public int run(String[] args) throws Exception {
String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
if (otherArgs.length < 2) {
usage("Wrong number of arguments: " + otherArgs.length);
return -1;
}
if (getConf().get(BigtableOptionsFactory.PROJECT_ID_KEY) == null) {
usage("Must specify the property " + BigtableOptionsFactory.PROJECT_ID_KEY);
return -1;
}
if (getConf().get(BigtableOptionsFactory.INSTANCE_ID_KEY) == null) {
usage("Must specify the property" + BigtableOptionsFactory.INSTANCE_ID_KEY);
return -1;
}
String inputVersionString = System.getProperty(ResultSerialization.IMPORT_FORMAT_VER);
if (inputVersionString != null) {
getConf().set(ResultSerialization.IMPORT_FORMAT_VER, inputVersionString);
}
Job job = createSubmittableJob(getConf(), otherArgs);
return (job.waitForCompletion(true) ? 0 : 1);
}
/**
* Main entry point.
*
* @param args The command line parameters.
* @throws java.lang.Exception When running the job fails.
*/
public static void main(String[] args) throws Exception {
System.exit(ToolRunner.run(HBaseConfiguration.create(), new Import(), args));
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.09.09 at 01:22:27 PM CEST
//
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* <p>Java class for card.type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="card.type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attGroup ref="{http://www.w3.org/1998/Math/MathML}card.attlist"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "card.type", namespace = "http://www.w3.org/1998/Math/MathML")
public class CardType {
@XmlAttribute
protected String encoding;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String definitionURL;
@XmlAttribute(name = "class")
@XmlSchemaType(name = "NMTOKENS")
protected List<String> clazz;
@XmlAttribute
protected String style;
@XmlAttribute
@XmlIDREF
@XmlSchemaType(name = "IDREF")
protected Object xref;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anySimpleType")
protected String href;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
/**
* Gets the value of the definitionURL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefinitionURL() {
return definitionURL;
}
/**
* Sets the value of the definitionURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefinitionURL(String value) {
this.definitionURL = value;
}
/**
* Gets the value of the clazz property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clazz property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClazz().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getClazz() {
if (clazz == null) {
clazz = new ArrayList<String>();
}
return this.clazz;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the xref property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getXref() {
return xref;
}
/**
* Sets the value of the xref property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setXref(Object value) {
this.xref = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| |
/*
* 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.teavm.classlib.java.util;
import java.io.Serializable;
import java.util.Arrays;
import org.teavm.classlib.impl.tz.DateTimeZone;
import org.teavm.classlib.impl.tz.DateTimeZoneProvider;
import org.teavm.classlib.impl.tz.FixedDateTimeZone;
import org.teavm.classlib.impl.unicode.CLDRHelper;
/**
* {@code TimeZone} represents a time zone offset, taking into account
* daylight savings.
* <p>
* Typically, you get a {@code TimeZone} using {@code getDefault}
* which creates a {@code TimeZone} based on the time zone where the
* program is running. For example, for a program running in Japan,
* {@code getDefault} creates a {@code TimeZone} object based on
* Japanese Standard Time.
* <p>
* You can also get a {@code TimeZone} using {@code getTimeZone}
* along with a time zone ID. For instance, the time zone ID for the U.S.
* Pacific Time zone is "America/Los_Angeles". So, you can get a U.S. Pacific
* Time {@code TimeZone} object with the following: <blockquote>
*
* <pre>
* TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
* </pre>
*
* </blockquote> You can use the {@code getAvailableIDs} method to iterate
* through all the supported time zone IDs. You can then choose a supported ID
* to get a {@code TimeZone}. If the time zone you want is not
* represented by one of the supported IDs, then you can create a custom time
* zone ID with the following syntax: <blockquote>
*
* <pre>
* GMT[+|-]hh[[:]mm]
* </pre>
*
* </blockquote> For example, you might specify GMT+14:00 as a custom time zone
* ID. The {@code TimeZone} that is returned when you specify a custom
* time zone ID does not include daylight savings time.
* <p>
* For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such
* as "PST", "CTT", "AST") are also supported. However, <strong>their use is
* deprecated</strong> because the same abbreviation is often used for multiple
* time zones (for example, "CST" could be U.S. "Central Standard Time" and
* "China Standard Time"), and the Java platform can then only recognize one of
* them.
* <p>
* Please note the type returned by factory methods, i.e. {@code getDefault()}
* and {@code getTimeZone(String)}, is implementation dependent, so it may
* introduce serialization incompatibility issues between different
* implementations.
*
* @see GregorianCalendar
* @see TSimpleTimeZone
*/
public abstract class TTimeZone implements Serializable, Cloneable {
private static final long serialVersionUID = 3581463369166924961L;
/**
* The SHORT display name style.
*/
public static final int SHORT = 0;
/**
* The LONG display name style.
*/
public static final int LONG = 1;
private static TTimeZone defaultTz;
static TTimeZone GMT = new TIANATimeZone(new FixedDateTimeZone("GMT", 0, 0));
private String id;
/**
* Constructs a new instance of this class.
*/
public TTimeZone() {
}
TTimeZone(String id) {
this.id = id;
}
/**
* Returns a new {@code TimeZone} with the same ID, {@code rawOffset} and daylight savings
* time rules as this {@code TimeZone}.
*
* @return a shallow copy of this {@code TimeZone}.
* @see java.lang.Cloneable
*/
@Override
public Object clone() {
try {
TTimeZone zone = (TTimeZone) super.clone();
return zone;
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Gets the available time zone IDs. Any one of these IDs can be passed to
* {@code get()} to create the corresponding {@code TimeZone} instance.
*
* @return an array of time zone ID strings.
*/
public static String[] getAvailableIDs() {
return DateTimeZoneProvider.getIds();
}
/**
* Gets the available time zone IDs which match the specified offset from
* GMT. Any one of these IDs can be passed to {@code get()} to create the corresponding
* {@code TimeZone} instance.
*
* @param offset
* the offset from GMT in milliseconds.
* @return an array of time zone ID strings.
*/
public static String[] getAvailableIDs(int offset) {
String[] all = DateTimeZoneProvider.getIds();
String[] result = new String[all.length];
int i = 0;
for (String id : all) {
DateTimeZone jodaTz = DateTimeZoneProvider.getTimeZone(id);
if (jodaTz.getStandardOffset(System.currentTimeMillis()) == offset) {
result[i++] = id;
}
}
return Arrays.copyOf(result, i);
}
/**
* Gets the default time zone.
*
* @return the default time zone.
*/
public static TTimeZone getDefault() {
if (defaultTz == null) {
defaultTz = new TIANATimeZone(DateTimeZoneProvider.detectTimezone());
}
return (TTimeZone) defaultTz.clone();
}
/**
* Gets the LONG name for this {@code TimeZone} for the default {@code Locale} in standard
* time. If the name is not available, the result is in the format
* {@code GMT[+-]hh:mm}.
*
* @return the {@code TimeZone} name.
*/
public final String getDisplayName() {
return getDisplayName(false, LONG, TLocale.getDefault());
}
/**
* Gets the LONG name for this {@code TimeZone} for the specified {@code Locale} in standard
* time. If the name is not available, the result is in the format
* {@code GMT[+-]hh:mm}.
*
* @param locale
* the {@code Locale}.
* @return the {@code TimeZone} name.
*/
public final String getDisplayName(TLocale locale) {
return getDisplayName(false, LONG, locale);
}
/**
* Gets the specified style of name ({@code LONG} or {@code SHORT}) for this {@code TimeZone} for
* the default {@code Locale} in either standard or daylight time as specified. If
* the name is not available, the result is in the format {@code GMT[+-]hh:mm}.
*
* @param daylightTime
* {@code true} for daylight time, {@code false} for standard
* time.
* @param style
* either {@code LONG} or {@code SHORT}.
* @return the {@code TimeZone} name.
*/
public final String getDisplayName(boolean daylightTime, int style) {
return getDisplayName(daylightTime, style, TLocale.getDefault());
}
/**
* Gets the specified style of name ({@code LONG} or {@code SHORT}) for this {@code TimeZone} for
* the specified {@code Locale} in either standard or daylight time as specified. If
* the name is not available, the result is in the format {@code GMT[+-]hh:mm}.
*
* @param daylightTime
* {@code true} for daylight time, {@code false} for standard
* time.
* @param style
* either LONG or SHORT.
* @param locale
* either {@code LONG} or {@code SHORT}.
* @return the {@code TimeZone} name.
*/
public String getDisplayName(boolean daylightTime, int style, TLocale locale) {
String name = CLDRHelper.getTimeZoneName(locale.getLanguage(), locale.getCountry(), id);
if (name == null) {
name = id;
}
return name;
}
/**
* Gets the ID of this {@code TimeZone}.
*
* @return the time zone ID string.
*/
public String getID() {
return id;
}
/**
* Gets the daylight savings offset in milliseconds for this {@code TimeZone}.
* <p>
* This implementation returns 3600000 (1 hour), or 0 if the time zone does
* not observe daylight savings.
* <p>
* Subclasses may override to return daylight savings values other than 1
* hour.
* <p>
*
* @return the daylight savings offset in milliseconds if this {@code TimeZone}
* observes daylight savings, zero otherwise.
*/
public int getDSTSavings() {
if (useDaylightTime()) {
return 3600000;
}
return 0;
}
/**
* Gets the offset from GMT of this {@code TimeZone} for the specified date. The
* offset includes daylight savings time if the specified date is within the
* daylight savings time period.
*
* @param time
* the date in milliseconds since January 1, 1970 00:00:00 GMT
* @return the offset from GMT in milliseconds.
*/
public int getOffset(long time) {
return inDaylightTime(new TDate(time)) ? getRawOffset() + getDSTSavings() : getRawOffset();
}
/**
* Gets the offset from GMT of this {@code TimeZone} for the specified date and
* time. The offset includes daylight savings time if the specified date and
* time are within the daylight savings time period.
*
* @param era
* the {@code GregorianCalendar} era, either {@code GregorianCalendar.BC} or
* {@code GregorianCalendar.AD}.
* @param year
* the year.
* @param month
* the {@code Calendar} month.
* @param day
* the day of the month.
* @param dayOfWeek
* the {@code Calendar} day of the week.
* @param time
* the time of day in milliseconds.
* @return the offset from GMT in milliseconds.
*/
abstract public int getOffset(int era, int year, int month, int day,
int dayOfWeek, int time);
/**
* Gets the offset for standard time from GMT for this {@code TimeZone}.
*
* @return the offset from GMT in milliseconds.
*/
abstract public int getRawOffset();
/**
* Gets the {@code TimeZone} with the specified ID.
*
* @param name
* a time zone string ID.
* @return the {@code TimeZone} with the specified ID or null if no {@code TimeZone} with
* the specified ID exists.
*/
public static TTimeZone getTimeZone(String name) {
DateTimeZone jodaZone = DateTimeZoneProvider.getTimeZone(name);
if (jodaZone != null) {
return new TIANATimeZone(jodaZone);
}
if (name.startsWith("GMT") && name.length() > 3) {
char sign = name.charAt(3);
if (sign == '+' || sign == '-') {
int[] position = new int[1];
String formattedName = formatTimeZoneName(name, 4);
int hour = parseNumber(formattedName, 4, position);
if (hour < 0 || hour > 23) {
return (TTimeZone) GMT.clone();
}
int index = position[0];
if (index != -1) {
int raw = hour * 3600000;
if (index < formattedName.length()
&& formattedName.charAt(index) == ':') {
int minute = parseNumber(formattedName, index + 1,
position);
if (position[0] == -1 || minute < 0 || minute > 59) {
return (TTimeZone) GMT.clone();
}
raw += minute * 60000;
} else if (hour >= 30 || index > 6) {
raw = (hour / 100 * 3600000) + (hour % 100 * 60000);
}
if (sign == '-') {
raw = -raw;
}
return new TIANATimeZone(new FixedDateTimeZone(formattedName, raw, raw));
}
}
}
return (TTimeZone) GMT.clone();
}
private static String formatTimeZoneName(String name, int offset) {
StringBuilder buf = new StringBuilder();
int index = offset, length = name.length();
buf.append(name.substring(0, offset));
while (index < length) {
if (Character.digit(name.charAt(index), 10) != -1) {
buf.append(name.charAt(index));
if ((length - (index + 1)) == 2) {
buf.append(':');
}
} else if (name.charAt(index) == ':') {
buf.append(':');
}
index++;
}
if (buf.toString().indexOf(":") == -1) {
buf.append(':');
buf.append("00");
}
if (buf.toString().indexOf(":") == 5) {
buf.insert(4, '0');
}
return buf.toString();
}
/**
* Returns whether the specified {@code TimeZone} has the same raw offset as this
* {@code TimeZone}.
*
* @param zone
* a {@code TimeZone}.
* @return {@code true} when the {@code TimeZone} have the same raw offset, {@code false}
* otherwise.
*/
public boolean hasSameRules(TTimeZone zone) {
if (zone == null) {
return false;
}
return getRawOffset() == zone.getRawOffset();
}
/**
* Returns whether the specified {@code Date} is in the daylight savings time period for
* this {@code TimeZone}.
*
* @param time
* a {@code Date}.
* @return {@code true} when the {@code Date} is in the daylight savings time period, {@code false}
* otherwise.
*/
abstract public boolean inDaylightTime(TDate time);
private static int parseNumber(String string, int offset, int[] position) {
int index = offset, length = string.length(), digit, result = 0;
while (index < length
&& (digit = Character.digit(string.charAt(index), 10)) != -1) {
index++;
result = result * 10 + digit;
}
position[0] = index == offset ? -1 : index;
return result;
}
/**
* Sets the default time zone. If passed {@code null}, then the next
* time {@link #getDefault} is called, the default time zone will be
* determined. This behavior is slightly different than the canonical
* description of this method, but it follows the spirit of it.
*
* @param timezone
* a {@code TimeZone} object.
*/
public static void setDefault(TTimeZone timezone) {
defaultTz = timezone != null ? (TTimeZone)timezone.clone() : null;
}
/**
* Sets the ID of this {@code TimeZone}.
*
* @param name
* a string which is the time zone ID.
*/
public void setID(String name) {
if (name == null) {
throw new NullPointerException();
}
id = name;
}
/**
* Sets the offset for standard time from GMT for this {@code TimeZone}.
*
* @param offset
* the offset from GMT in milliseconds.
*/
abstract public void setRawOffset(int offset);
/**
* Returns whether this {@code TimeZone} has a daylight savings time period.
*
* @return {@code true} if this {@code TimeZone} has a daylight savings time period, {@code false}
* otherwise.
*/
abstract public boolean useDaylightTime();
/**
* Gets the name and the details of the user-selected TimeZone on the
* device.
*
* @param tzinfo
* int array of 10 elements to be filled with the TimeZone
* information. Once filled, the contents of the array are
* formatted as follows: tzinfo[0] -> the timezone offset;
* tzinfo[1] -> the dst adjustment; tzinfo[2] -> the dst start
* hour; tzinfo[3] -> the dst start day of week; tzinfo[4] -> the
* dst start week of month; tzinfo[5] -> the dst start month;
* tzinfo[6] -> the dst end hour; tzinfo[7] -> the dst end day of
* week; tzinfo[8] -> the dst end week of month; tzinfo[9] -> the
* dst end month;
* @param isCustomTimeZone
* boolean array of size 1 that indicates if a timezone match is
* found
* @return the name of the TimeZone or null if error occurs in native
* method.
*/
private static native String getCustomTimeZone(int[] tzinfo,
boolean[] isCustomTimeZone);
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != TTimeZone.class) {
return false;
}
TTimeZone other = (TTimeZone)obj;
return this.id.equals(other.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
| |
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.olddriver.ui.transitions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import java.util.List;
import com.olddriver.R;
import com.olddriver.util.AnimUtils;
import static android.view.View.MeasureSpec.makeMeasureSpec;
/**
* A transition between a FAB & another surface using a circular reveal moving along an arc.
* <p>
* See: https://www.google.com/design/spec/motion/transforming-material.html#transforming-material-radial-transformation
*/
public class FabTransform extends Transition {
private static final String EXTRA_FAB_COLOR = "EXTRA_FAB_COLOR";
private static final String EXTRA_FAB_ICON_RES_ID = "EXTRA_FAB_ICON_RES_ID";
private static final long DEFAULT_DURATION = 240L;
private static final String PROP_BOUNDS = "plaid:fabTransform:bounds";
private static final String[] TRANSITION_PROPERTIES = {
PROP_BOUNDS
};
private final int color;
private final int icon;
public FabTransform(@ColorInt int fabColor, @DrawableRes int fabIconResId) {
color = fabColor;
icon = fabIconResId;
setPathMotion(new GravityArcMotion());
setDuration(DEFAULT_DURATION);
}
public FabTransform(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = null;
try {
a = context.obtainStyledAttributes(attrs, R.styleable.FabTransform);
if (!a.hasValue(R.styleable.FabTransform_fabColor)
|| !a.hasValue(R.styleable.FabTransform_fabIcon)) {
throw new IllegalArgumentException("Must provide both color & icon.");
}
color = a.getColor(R.styleable.FabTransform_fabColor, Color.TRANSPARENT);
icon = a.getResourceId(R.styleable.FabTransform_fabIcon, 0);
setPathMotion(new GravityArcMotion());
if (getDuration() < 0) {
setDuration(DEFAULT_DURATION);
}
} finally {
a.recycle();
}
}
/**
* Configure {@code intent} with the extras needed to initialize this transition.
*/
public static void addExtras(@NonNull Intent intent, @ColorInt int fabColor,
@DrawableRes int fabIconResId) {
intent.putExtra(EXTRA_FAB_COLOR, fabColor);
intent.putExtra(EXTRA_FAB_ICON_RES_ID, fabIconResId);
}
/**
* Create a {@link FabTransform} from the supplied {@code activity} extras and set as its
* shared element enter/return transition.
*/
public static boolean setup(@NonNull Activity activity, @Nullable View target) {
final Intent intent = activity.getIntent();
if (!intent.hasExtra(EXTRA_FAB_COLOR) || !intent.hasExtra(EXTRA_FAB_ICON_RES_ID)) {
return false;
}
final int color = intent.getIntExtra(EXTRA_FAB_COLOR, Color.TRANSPARENT);
final int icon = intent.getIntExtra(EXTRA_FAB_ICON_RES_ID, -1);
final FabTransform sharedEnter = new FabTransform(color, icon);
if (target != null) {
sharedEnter.addTarget(target);
}
activity.getWindow().setSharedElementEnterTransition(sharedEnter);
return true;
}
@Override
public String[] getTransitionProperties() {
return TRANSITION_PROPERTIES;
}
@Override
public void captureStartValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
@Override
public void captureEndValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
@Override
public Animator createAnimator(final ViewGroup sceneRoot,
final TransitionValues startValues,
final TransitionValues endValues) {
if (startValues == null || endValues == null) return null;
final Rect startBounds = (Rect) startValues.values.get(PROP_BOUNDS);
final Rect endBounds = (Rect) endValues.values.get(PROP_BOUNDS);
final boolean fromFab = endBounds.width() > startBounds.width();
final View view = endValues.view;
final Rect dialogBounds = fromFab ? endBounds : startBounds;
final Rect fabBounds = fromFab ? startBounds : endBounds;
final Interpolator fastOutSlowInInterpolator =
AnimUtils.getFastOutSlowInInterpolator(sceneRoot.getContext());
final long duration = getDuration();
final long halfDuration = duration / 2;
final long twoThirdsDuration = duration * 2 / 3;
if (!fromFab) {
// Force measure / layout the dialog back to it's original bounds
view.measure(
makeMeasureSpec(startBounds.width(), View.MeasureSpec.EXACTLY),
makeMeasureSpec(startBounds.height(), View.MeasureSpec.EXACTLY));
view.layout(startBounds.left, startBounds.top, startBounds.right, startBounds.bottom);
}
final int translationX = startBounds.centerX() - endBounds.centerX();
final int translationY = startBounds.centerY() - endBounds.centerY();
if (fromFab) {
view.setTranslationX(translationX);
view.setTranslationY(translationY);
}
// Add a color overlay to fake appearance of the FAB
final ColorDrawable fabColor = new ColorDrawable(color);
fabColor.setBounds(0, 0, dialogBounds.width(), dialogBounds.height());
if (!fromFab) fabColor.setAlpha(0);
view.getOverlay().add(fabColor);
// Add an icon overlay again to fake the appearance of the FAB
final Drawable fabIcon =
ContextCompat.getDrawable(sceneRoot.getContext(), icon).mutate();
final int iconLeft = (dialogBounds.width() - fabIcon.getIntrinsicWidth()) / 2;
final int iconTop = (dialogBounds.height() - fabIcon.getIntrinsicHeight()) / 2;
fabIcon.setBounds(iconLeft, iconTop,
iconLeft + fabIcon.getIntrinsicWidth(),
iconTop + fabIcon.getIntrinsicHeight());
if (!fromFab) fabIcon.setAlpha(0);
view.getOverlay().add(fabIcon);
// Circular clip from/to the FAB size
final Animator circularReveal;
if (fromFab) {
circularReveal = ViewAnimationUtils.createCircularReveal(view,
view.getWidth() / 2,
view.getHeight() / 2,
startBounds.width() / 2,
(float) Math.hypot(endBounds.width() / 2, endBounds.width() / 2));
circularReveal.setInterpolator(
AnimUtils.getFastOutLinearInInterpolator(sceneRoot.getContext()));
} else {
circularReveal = ViewAnimationUtils.createCircularReveal(view,
view.getWidth() / 2,
view.getHeight() / 2,
(float) Math.hypot(startBounds.width() / 2, startBounds.width() / 2),
endBounds.width() / 2);
circularReveal.setInterpolator(
AnimUtils.getLinearOutSlowInInterpolator(sceneRoot.getContext()));
// Persist the end clip i.e. stay at FAB size after the reveal has run
circularReveal.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
final int left = (view.getWidth() - fabBounds.width()) / 2;
final int top = (view.getHeight() - fabBounds.height()) / 2;
outline.setOval(
left, top, left + fabBounds.width(), top + fabBounds.height());
view.setClipToOutline(true);
}
});
}
});
}
circularReveal.setDuration(duration);
// Translate to end position along an arc
final Animator translate = ObjectAnimator.ofFloat(
view,
View.TRANSLATION_X,
View.TRANSLATION_Y,
fromFab ? getPathMotion().getPath(translationX, translationY, 0, 0)
: getPathMotion().getPath(0, 0, -translationX, -translationY));
translate.setDuration(duration);
translate.setInterpolator(fastOutSlowInInterpolator);
// Fade contents of non-FAB view in/out
List<Animator> fadeContents = null;
if (view instanceof ViewGroup) {
final ViewGroup vg = ((ViewGroup) view);
fadeContents = new ArrayList<>(vg.getChildCount());
for (int i = vg.getChildCount() - 1; i >= 0; i--) {
final View child = vg.getChildAt(i);
final Animator fade =
ObjectAnimator.ofFloat(child, View.ALPHA, fromFab ? 1f : 0f);
if (fromFab) {
child.setAlpha(0f);
}
fade.setDuration(twoThirdsDuration);
fade.setInterpolator(fastOutSlowInInterpolator);
fadeContents.add(fade);
}
}
// Fade in/out the fab color & icon overlays
final Animator colorFade = ObjectAnimator.ofInt(fabColor, "alpha", fromFab ? 0 : 255);
final Animator iconFade = ObjectAnimator.ofInt(fabIcon, "alpha", fromFab ? 0 : 255);
if (!fromFab) {
colorFade.setStartDelay(halfDuration);
iconFade.setStartDelay(halfDuration);
}
colorFade.setDuration(halfDuration);
iconFade.setDuration(halfDuration);
colorFade.setInterpolator(fastOutSlowInInterpolator);
iconFade.setInterpolator(fastOutSlowInInterpolator);
// Work around issue with elevation shadows. At the end of the return transition the shared
// element's shadow is drawn twice (by each activity) which is jarring. This workaround
// still causes the shadow to snap, but it's better than seeing it double drawn.
Animator elevation = null;
if (!fromFab) {
elevation = ObjectAnimator.ofFloat(view, View.TRANSLATION_Z, -view.getElevation());
elevation.setDuration(duration);
elevation.setInterpolator(fastOutSlowInInterpolator);
}
// Run all animations together
final AnimatorSet transition = new AnimatorSet();
transition.playTogether(circularReveal, translate, colorFade, iconFade);
transition.playTogether(fadeContents);
if (elevation != null) transition.play(elevation);
if (fromFab) {
transition.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Clean up
view.getOverlay().clear();
}
});
}
return new AnimUtils.NoPauseAnimator(transition);
}
private void captureValues(TransitionValues transitionValues) {
final View view = transitionValues.view;
if (view == null || view.getWidth() <= 0 || view.getHeight() <= 0) return;
transitionValues.values.put(PROP_BOUNDS, new Rect(view.getLeft(), view.getTop(),
view.getRight(), view.getBottom()));
}
}
| |
/*
* Copyright 2006-2007 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.openspaces.utest.core;
import com.gigaspaces.client.*;
import com.gigaspaces.internal.client.spaceproxy.ISpaceProxy;
import com.j_spaces.core.IJSpace;
import com.j_spaces.core.LeaseContext;
import com.j_spaces.core.client.ReadModifiers;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import org.jmock.core.Constraint;
import org.openspaces.core.DefaultGigaSpace;
import org.openspaces.core.exception.ExceptionTranslator;
import org.openspaces.core.transaction.TransactionProvider;
import org.springframework.transaction.TransactionDefinition;
/**
* A set of mock tests verifies that the correct {@link com.j_spaces.core.IJSpace} API is called as
* a result of {@link org.openspaces.core.DefaultGigaSpace} execution.
*
* @author kimchy
*/
public class DefaultGigaSpacesTests extends MockObjectTestCase {
private DefaultGigaSpace gs;
private Mock mockIJSpace;
private Mock mockTxProvider;
private Mock mockExTranslator;
protected void setUp() throws Exception {
mockIJSpace = mock(ISpaceProxy.class);
mockTxProvider = mock(TransactionProvider.class);
mockExTranslator = mock(ExceptionTranslator.class);
mockIJSpace.expects(once()).method("getReadModifiers").will(returnValue(0));
gs = new DefaultGigaSpace((IJSpace) mockIJSpace.proxy(), (TransactionProvider) mockTxProvider.proxy(),
(ExceptionTranslator) mockExTranslator.proxy(), TransactionDefinition.ISOLATION_DEFAULT);
}
public void testReadOperation() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("read").with(same(template), NULL, eq(0l), eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.read(template);
assertEquals(retVal, actualRetVal);
}
public void testReadOperationWithDefaultReadModifiers() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("read").with(same(template), NULL, eq(0l), eq(ReadModifiers.READ_COMMITTED | com.gigaspaces.client.ReadModifiers.FIFO.getCode()))
.will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultReadModifiers(com.gigaspaces.client.ReadModifiers.FIFO);
Object actualRetVal = gs.read(template);
assertEquals(retVal, actualRetVal);
}
public void testReadOperationWithDefaultReadModifiersAndIsolationLevelOverride() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("read").with(same(template), NULL, eq(0l), eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultReadModifiers(com.gigaspaces.client.ReadModifiers.DIRTY_READ);
Object actualRetVal = gs.read(template);
assertEquals(retVal, actualRetVal);
}
public void testReadOperationWithDefaultTimeout() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once())
.method("read")
.with(same(template), NULL, eq(10l), eq(ReadModifiers.READ_COMMITTED))
.will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultReadTimeout(10l);
Object actualRetVal = gs.read(template);
assertEquals(retVal, actualRetVal);
}
public void testReadOperationWithTimeoutParameter() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once())
.method("read")
.with(same(template), NULL, eq(11l), eq(ReadModifiers.READ_COMMITTED))
.will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.read(template, 11l);
assertEquals(retVal, actualRetVal);
}
public void testReadIfExistsOperation() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("readIfExists").with(same(template), NULL, eq(0l),
eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.readIfExists(template);
assertEquals(retVal, actualRetVal);
}
public void testReadIfExistsOperationWithDefaultTimeout() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("readIfExists").with(same(template), NULL, eq(10l),
eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultReadTimeout(10l);
Object actualRetVal = gs.readIfExists(template);
assertEquals(retVal, actualRetVal);
}
public void testReadIfExistsOperationWithTimeoutParameter() {
Object template = new Object();
Object retVal = new Object();
mockIJSpace.expects(once()).method("readIfExists").with(same(template), NULL, eq(11l),
eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.readIfExists(template, 11l);
assertEquals(retVal, actualRetVal);
}
public void testReadMultipleOperation() {
Object template = new Object();
Object[] retVal = new Object[] { new Object(), new Object() };
mockIJSpace.expects(once()).method("readMultiple").with(same(template), NULL, eq(2),
eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.readMultiple(template, 2);
assertEquals(retVal, actualRetVal);
}
public void testReadMultipleNoLimitOperation() {
Object template = new Object();
Object[] retVal = new Object[] { new Object(), new Object(), new Object(), new Object()};
mockIJSpace.expects(once()).method("readMultiple").with(same(template), NULL, eq(Integer.MAX_VALUE),
eq(ReadModifiers.READ_COMMITTED)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(
returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
Object actualRetVal = gs.readMultiple(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeOperation() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(0l),
eq(0),
same(false)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.take(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeOperationWithDefaultTimeout() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(10l),
eq(0),
same(false)};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultTakeTimeout(10l);
Object actualRetVal = gs.take(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeOperationWithTimeoutParameter() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(11l),
eq(0),
same(false)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.take(template, 11l);
assertEquals(retVal, actualRetVal);
}
public void testTakeIfExistsOperation() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(0l),
eq(0),
eq(Boolean.TRUE)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.takeIfExists(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeIfExistsOperationWithDefaultTimeout() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(10l),
eq(0),
eq(Boolean.TRUE)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultTakeTimeout(10l);
Object actualRetVal = gs.takeIfExists(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeIfExistsOperationWithTimeoutParameter() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(11l),
eq(0),
eq(Boolean.TRUE)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.takeIfExists(template, 11l);
assertEquals(retVal, actualRetVal);
}
public void testTakeWithDefaultTakeModifiers() {
Object template = new Object();
Object retVal = new Object();
Constraint[] constraints = new Constraint[] {
same(template),
NULL,
eq(11l),
eq(TakeModifiers.MEMORY_ONLY_SEARCH.getCode()),
eq(Boolean.TRUE)
};
mockIJSpace.expects(once()).method("take").with(constraints).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultTakeModifiers(TakeModifiers.MEMORY_ONLY_SEARCH);
Object actualRetVal = gs.takeIfExists(template, 11l);
assertEquals(retVal, actualRetVal);
}
public void testTakeMultipleNoLimit() {
Object template = new Object();
Object[] retVal = new Object[] { new Object(), new Object(), new Object(), new Object()};
mockIJSpace.expects(once()).method("takeMultiple").with(same(template), NULL, eq(Integer.MAX_VALUE), eq(0)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.takeMultiple(template);
assertEquals(retVal, actualRetVal);
}
public void testTakeMultiple() {
Object template = new Object();
Object[] retVal = new Object[] { new Object(), new Object() };
mockIJSpace.expects(once()).method("takeMultiple").with(same(template), NULL, eq(2), eq(0)).will(returnValue(retVal));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
Object actualRetVal = gs.takeMultiple(template, 2);
assertEquals(retVal, actualRetVal);
}
@SuppressWarnings("unchecked")
public void testWriteOperation() {
Object entry = new Object();
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
Constraint[] constraints = new Constraint[] {
same(entry),
NULL,
eq(Long.MAX_VALUE),
eq(0l),
eq(WriteModifiers.NONE.getCode())
};
mockIJSpace.expects(once()).method("write").with(constraints).will(returnValue(leaseContext));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
LeaseContext<Object> actualLeaseContext = gs.write(entry);
assertEquals(leaseContext, actualLeaseContext);
}
@SuppressWarnings("unchecked")
public void testWriteOperationWithDefaultLease() {
Object entry = new Object();
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
Constraint[] constraints = new Constraint[] {
same(entry),
NULL,
eq(10l),
eq(0l),
eq(WriteModifiers.NONE.getCode())
};
mockIJSpace.expects(once()).method("write").with(constraints).will(returnValue(leaseContext));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultWriteLease(10l);
LeaseContext actualLeaseContext = gs.write(entry);
assertEquals(leaseContext, actualLeaseContext);
}
@SuppressWarnings("unchecked")
public void testWriteOperationWithLeaseParameter() {
Object entry = new Object();
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
Constraint[] constraints = new Constraint[] {
same(entry),
NULL,
eq(10l),
eq(0l),
eq(WriteModifiers.NONE.getCode())
};
mockIJSpace.expects(once()).method("write").with(constraints).will(returnValue(leaseContext));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
LeaseContext<Object> actualLeaseContext = gs.write(entry, 10l);
assertEquals(leaseContext, actualLeaseContext);
}
@SuppressWarnings("unchecked")
public void testWriteOperationWithLeaseTimeoutModifiersParameters() {
Object entry = new Object();
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
mockIJSpace.expects(once())
.method("write")
.with(new Constraint[] { same(entry), NULL, eq(10l), eq(2l), eq(3) })
.will(returnValue(leaseContext));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
LeaseContext actualLeaseContext = gs.write(entry, 10l, 2l, 3);
assertEquals(leaseContext, actualLeaseContext);
}
@SuppressWarnings("unchecked")
public void testWriteOperationWithDefaultWriteModifiers() {
Object entry = new Object();
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
Constraint[] constraints = new Constraint[] {
same(entry),
NULL,
eq(Long.MAX_VALUE),
eq(0l),
eq(WriteModifiers.ONE_WAY.getCode())
};
mockIJSpace.expects(once()).method("write").with(constraints).will(returnValue(leaseContext));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultWriteModifiers(WriteModifiers.ONE_WAY);
LeaseContext actualLeaseContext = gs.write(entry);
assertEquals(leaseContext, actualLeaseContext);
}
@SuppressWarnings("unchecked")
public void testWriteMultipleOperationWithWriteModifiersParam() {
Object entry1 = new Object();
Object entry2 = new Object();
Object[] entries = new Object[] { entry1, entry2 };
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
LeaseContext<Object>[] leaseContexts = new LeaseContext[] { leaseContext, leaseContext };
Constraint[] constraints = new Constraint[] {
same(entries),
NULL,
eq(Long.MAX_VALUE),
eq(null),
eq(0L),
eq(WriteModifiers.ONE_WAY.getCode())
};
mockIJSpace.expects(once()).method("writeMultiple").with(constraints).will(returnValue(leaseContexts));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultWriteModifiers(WriteModifiers.MEMORY_ONLY_SEARCH);
LeaseContext<Object>[] actualLeaseContexts = gs.writeMultiple(entries, WriteModifiers.ONE_WAY);
assertEquals(leaseContexts, actualLeaseContexts);
}
@SuppressWarnings("unchecked")
public void testWriteMultipleOperationWithDefaultWriteModifiers() {
Object entry1 = new Object();
Object entry2 = new Object();
Object[] entries = new Object[] { entry1, entry2 };
Mock mockLeaseContext = mock(LeaseContext.class);
LeaseContext<Object> leaseContext = (LeaseContext<Object>) mockLeaseContext.proxy();
LeaseContext<Object>[] leaseContexts = new LeaseContext[] { leaseContext, leaseContext };
Constraint[] constraints = new Constraint[] {
same(entries),
NULL,
eq(Long.MAX_VALUE),
eq(null),
eq(0L),
eq(WriteModifiers.ONE_WAY.getCode())
};
mockIJSpace.expects(once()).method("writeMultiple").with(constraints).will(returnValue(leaseContexts));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultWriteModifiers(WriteModifiers.ONE_WAY);
LeaseContext<Object>[] actualLeaseContexts = gs.writeMultiple(entries);
assertEquals(leaseContexts, actualLeaseContexts);
}
public void testClearWithDefaultModifiers() {
Object entry1 = new Object();
Constraint[] constraints = new Constraint[] {
same(entry1),
NULL,
eq(ClearModifiers.MEMORY_ONLY_SEARCH.getCode())
};
mockIJSpace.expects(once()).method("clear").with(constraints).will(returnValue(0));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultClearModifiers(ClearModifiers.MEMORY_ONLY_SEARCH);
gs.clear(entry1);
}
public void testCountWithDefaultModifiers() {
int expectedCount = 2;
Object entry1 = new Object();
Constraint[] constraints = new Constraint[] {
same(entry1),
NULL,
eq(CountModifiers.MEMORY_ONLY_SEARCH.add(CountModifiers.READ_COMMITTED).getCode())
};
mockIJSpace.expects(once()).method("count").with(constraints).will(returnValue(expectedCount));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultCountModifiers(CountModifiers.MEMORY_ONLY_SEARCH);
int count = gs.count(entry1);
assertEquals(expectedCount, count);
}
public void testCountWithDefaultModifiersIsolationLevelOverride() {
int expectedCount = 2;
Object entry1 = new Object();
Constraint[] constraints = new Constraint[] {
same(entry1),
NULL,
eq(CountModifiers.READ_COMMITTED.getCode())
};
mockIJSpace.expects(once()).method("count").with(constraints).will(returnValue(expectedCount));
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
mockTxProvider.expects(once()).method("getCurrentTransactionIsolationLevel").with(eq(gs)).will(returnValue(TransactionDefinition.ISOLATION_READ_COMMITTED));
gs.setDefaultCountModifiers(CountModifiers.DIRTY_READ);
int count = gs.count(entry1);
assertEquals(expectedCount, count);
}
public void testChangeWithDefaultModifiers() {
Object entry1 = new Object();
Constraint[] constraints = new Constraint[] {
same(entry1),
NULL,
NULL,
eq(0l),
same(ChangeModifiers.RETURN_DETAILED_RESULTS)
};
mockIJSpace.expects(once()).method("change").with(constraints);
mockTxProvider.expects(once()).method("getCurrentTransaction").with(eq(gs), eq(gs.getSpace()));
gs.setDefaultChangeModifiers(ChangeModifiers.RETURN_DETAILED_RESULTS);
gs.change(entry1, null);
}
}
| |
package de.hub.emffrag.fragmentation;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import de.hub.emffrag.datastore.StringKeyType;
import de.hub.emffrag.model.emffrag.IndexedMap;
import de.hub.emffrag.testmodels.testmodel.TestObject;
import de.hub.emffrag.testmodels.testmodel.frag.meta.TestModelFactory;
public class IndexedMapTests extends AbstractFragmentationTests {
protected IndexedMap<String, TestObject> testIndex;
@Before
public void indexInitialization() {
testIndex = TestModelFactory.eINSTANCE.createTestObjectIndex();
}
protected void assertFragmentsIndex() {
model.assertFragmentsIndex(0l, 3l);
}
protected void assertIdIndex(boolean plusOne) {
model.assertIdIndex(0l, plusOne ? 4l : 3l);
}
@Test
public void addObjectsToMapTest() {
root.getContents().add(testIndex);
root.getContents().add(object1);
object1.getFragmentedContents().add(object2);
object1.getRegularContents().add(object3);
testIndex.put("1", object1);
testIndex.put("2", object2);
testIndex.put("3", object3);
model.save(null);
reinitializeModel();
testIndex = assertTestIndex(0);
assertIndex(testIndex, "1", "3");
assertIndexedObject(testIndex, "1");
assertIndexedObject(testIndex, "2");
assertIndexedObject(testIndex, "3");
assertFragmentsIndex();
assertIdIndex(false);
model.assertIndexClassIndex(testIndex, "1", "3", StringKeyType.instance);
}
@Test
public void iteratorTest() {
addObjectsToMapTest();
Iterator<TestObject> iterator = testIndex.iterator();
assertIterator(iterator, 3);
}
@Test
public void boundedIteratorTest1() {
performBoundedIteratorTest("0", "4", 3);
}
@Test
public void boundedIteratorTest2() {
performBoundedIteratorTest("1", "4", 3);
}
@Test
public void boundedIteratorTest3() {
performBoundedIteratorTest("0", "3", 3);
}
@Test
public void boundedIteratorTest4() {
performBoundedIteratorTest("1", "3", 3);
}
@Test
public void boundedIteratorTest5() {
performBoundedIteratorTest("0", "2", 2);
}
@Test
public void boundedIteratorTest6() {
performBoundedIteratorTest("2", "3", 2);
}
@Test
public void boundedIteratorTest7() {
performBoundedIteratorTest("1", "2", 2);
}
@Test
public void boundedIteratorTest8() {
performBoundedIteratorTest("2", "2", 1);
}
@Test
public void boundedIteratorTest9() {
performBoundedIteratorTest("3", "3", 1);
}
private void performBoundedIteratorTest(String first, String last, int size) {
addObjectsToMapTest();
Iterator<TestObject> iterator = testIndex.iterator(first, last);
assertIterator(iterator, size);
}
@Test
public void removeObjectsFromMapTest() {
addObjectsToMapTest();
testIndex.remove("2");
assertIndexedObject(testIndex, "1");
Assert.assertNull("Object is not null.", testIndex.exact("2"));
assertIndexedObject(testIndex, "3");
assertIterator(testIndex.iterator(), 2);
assertFragmentsIndex();
assertIdIndex(false);
model.assertIndexClassIndex(testIndex, "1", "3", StringKeyType.instance);
}
@Test
public void nextValueTests1() {
addObjectsToMapTest();
object1 = testIndex.next("1");
assertObject(object1);
Assert.assertEquals("Next gives wrong object.", testIndex.exact("1"), object1);
}
@Test
public void nextValueTests2() {
addObjectsToMapTest();
object1 = testIndex.next("0");
assertObject(object1);
Assert.assertEquals("Next gives wrong object.", testIndex.exact("1"), object1);
}
@Test
public void nextValueTests3() {
removeObjectsFromMapTest();
object1 = testIndex.next("2");
assertObject(object1);
Assert.assertEquals("Next gives wrong object.", testIndex.exact("3"), object1);
}
@Test
public void nextValueTests4() {
addObjectsToMapTest();
object1 = testIndex.next("4");
Assert.assertNull("Value that should not exist is there.", object1);
}
@Test
public void putValueTest1() {
performPutValueTest("4", "1", "4", 4);
}
@Test
public void putValueTest2() {
performPutValueTest("0", "0", "3", 4);;
}
@Test
public void putValueTest3() {
performPutValueTest("1", "1", "3", 3);
}
@Test
public void putValueTest4() {
performPutValueTest("1a", "1", "3", 4);
}
private void performPutValueTest(String key, String firstKey, String lastKey, int size) {
addObjectsToMapTest();
TestObject testObject = Assertions.createTestObject(4);
object1 = testIndex.exact("1");
object1.getRegularContents().add(testObject);
testIndex.put(key, testObject);
model.save(null);
reinitializeModel();
testIndex = assertTestIndex(0);
assertIndex(testIndex, firstKey, lastKey);
assertObject(testIndex.exact(key));
assertIterator(testIndex.iterator(), size);
assertFragmentsIndex();
assertIdIndex(true);
model.assertIndexClassIndex(testIndex, firstKey, lastKey, StringKeyType.instance);
}
protected void assertIterator(Iterator<TestObject> iterator, int size) {
Assert.assertTrue("Iterator is emtpy.", iterator.hasNext() || size == 0);
int i = 0;
while (iterator.hasNext()) {
assertObject(iterator.next());
i++;
}
Assert.assertEquals("Iterator has the wrong size.", size, i);
}
@SuppressWarnings("unchecked")
protected IndexedMap<String,TestObject> assertTestIndex(int index) {
Assert.assertTrue(root.getContents().size() > index);
Assert.assertTrue(root.getContents().get(index) instanceof IndexedMap);
IndexedMap<String,TestObject> contents = (IndexedMap<String,TestObject>) root.getContents().get(index);
Assert.assertTrue(((FObjectImpl)contents).fInternalObject().eResource() instanceof Fragment);
return contents;
}
protected void assertObject(Object value) {
Assert.assertNotNull("Value is null.", value);
Assert.assertTrue("Value has wrong type.", value instanceof TestObject);
Assert.assertTrue("Value is broken", ((TestObject)value).getName().startsWith("testValue"));
}
protected void assertIndexedObject(IndexedMap<String, TestObject> index, String key) {
TestObject value = index.exact(key);
assertObject(value);
}
protected void assertIndex(IndexedMap<String, TestObject> index, String firstKey, String lastKey) {
Assert.assertNotNull("Index is null.", index);
Assert.assertEquals("Wrong first key.", firstKey, index.getFirstKey());
Assert.assertEquals("Wrong last key.", lastKey, index.getLastKey());
}
}
| |
package me.xwang1024.sifResExplorer.model;
import java.util.Arrays;
public class Unit {
private int id;
private int unitNo;
private String name;
private String eponym;
private Card[] card; // normal, idolize normal, idolize rankMax, idolize
// bondMax, idolize doubleMax
private String[] avatar; // normal, idolize
private String[] cg; // normal, idolize
private String rarity;
private String attribute;
private UnitSkill unitSkill;
private String skillName;
private String skillEffect;
private String skillTrigger;
private LeaderSkill leaderSkill;
private String leaderSkillType;
private String message;
private int stamina;
private int smile;
private int pure;
private int cool;
private int rankupCost;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUnitNo() {
return unitNo;
}
public void setUnitNo(int unitNo) {
this.unitNo = unitNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEponym() {
return eponym;
}
public void setEponym(String eponym) {
this.eponym = eponym;
}
public Card[] getCard() {
return card;
}
public void setCard(Card[] card) {
this.card = card;
}
public String[] getAvatar() {
return avatar;
}
public void setAvatar(String[] avatar) {
this.avatar = avatar;
}
public String[] getCg() {
return cg;
}
public void setCg(String[] cg) {
this.cg = cg;
}
public String getRarity() {
return rarity;
}
public void setRarity(String rarity) {
this.rarity = rarity;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public UnitSkill getUnitSkill() {
return unitSkill;
}
public void setUnitSkill(UnitSkill unitSkill) {
this.unitSkill = unitSkill;
}
public LeaderSkill getLeaderSkill() {
return leaderSkill;
}
public void setLeaderSkill(LeaderSkill leaderSkill) {
this.leaderSkill = leaderSkill;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStamina() {
return stamina;
}
public void setStamina(int stamina) {
this.stamina = stamina;
}
public int getSmile() {
return smile;
}
public void setSmile(int smile) {
this.smile = smile;
}
public int getPure() {
return pure;
}
public void setPure(int pure) {
this.pure = pure;
}
public int getCool() {
return cool;
}
public void setCool(int cool) {
this.cool = cool;
}
public int getRankupCost() {
return rankupCost;
}
public void setRankupCost(int rankupCost) {
this.rankupCost = rankupCost;
}
public String getLeaderSkillType() {
return leaderSkillType;
}
public void setLeaderSkillType(String leaderSkillType) {
this.leaderSkillType = leaderSkillType;
}
public String getSkillEffect() {
return skillEffect;
}
public void setSkillEffect(String skillEffect) {
this.skillEffect = skillEffect;
}
public String getSkillTrigger() {
return skillTrigger;
}
public void setSkillTrigger(String skillTrigger) {
this.skillTrigger = skillTrigger;
}
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
@Override
public String toString() {
return "Unit [id=" + id + ", unitNo=" + unitNo + ", name=" + name + ", eponym=" + eponym
+ ", card=" + Arrays.toString(card) + ", avatar=" + Arrays.toString(avatar)
+ ", cg=" + Arrays.toString(cg) + ", rarity=" + rarity + ", attribute=" + attribute
+ ", unitSkill=" + unitSkill + ", skillName=" + skillName + ", skillEffect="
+ skillEffect + ", skillTrigger=" + skillTrigger + ", leaderSkill=" + leaderSkill
+ ", leaderSkillType=" + leaderSkillType + ", message=" + message + ", stamina="
+ stamina + ", smile=" + smile + ", pure=" + pure + ", cool=" + cool
+ ", rankupCost=" + rankupCost + "]";
}
public String toFlatString() {
return id + " " + unitNo + " " + name + " " + eponym + " " + Arrays.toString(card) + " "
+ Arrays.toString(avatar) + " " + Arrays.toString(cg) + " " + rarity + " "
+ attribute + " " + unitSkill + " " + skillName + " " + skillEffect + " "
+ skillTrigger + " " + leaderSkill + " " + leaderSkillType + " " + message + " "
+ stamina + " " + smile + " " + pure + " " + cool + " " + rankupCost;
}
}
| |
/**
*
* 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.airavata.cloud.test;
import org.apache.airavata.cloud.intf.CloudInterface;
import org.apache.airavata.cloud.intf.impl.OpenstackIntfImpl;
import org.apache.airavata.cloud.util.Constants;
import org.junit.Ignore;
import org.junit.Test;
import org.openstack4j.model.compute.Keypair;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Router;
import org.openstack4j.model.network.RouterInterface;
import org.openstack4j.model.network.Subnet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Scanner;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CloudIntfTest {
/** The properties. */
private String propertiesFile = "test_data.properties";
private Properties properties;
// Initializing Logger
private Logger logger = LoggerFactory.getLogger(CloudIntfTest.class);
public CloudIntfTest() {
try {
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(propertiesFile);
if(inputStream != null) {
properties = new Properties();
properties.load(inputStream);
}
else {
throw new FileNotFoundException("property file: " + propertiesFile + " not found!");
}
}
catch(Exception ex) {
ex.printStackTrace();
// TODO: Check with the team on how to handle exceptions.
}
}
/**
* Test that will create keypair, create server with keypair, delete server, delete keypair.
*/
@Test
@Ignore
public void jetstreamCreateDeleteServerTest() {
try {
CloudInterface cloudIntf = new OpenstackIntfImpl("jetstream_openrc.properties");
// Sample data. This can be determined by the inputs from Airavata.
String imageId = properties.getProperty("jetstream_imageId");
String flavorId = properties.getProperty("jetstream_flavorId");
// Delay in milliseconds used for waiting for server create and delete.
Integer delay = 30000;
/* Create Keypair */
String publicKeyFile = properties.getProperty("publicKeyFile");
String keyPairName = "testKey";
Scanner fileScan = new Scanner(new FileInputStream(publicKeyFile));
String publicKey = fileScan.nextLine();
Keypair kp = (Keypair) cloudIntf.getKeyPair(keyPairName);
if(kp == null) {
kp = (Keypair) cloudIntf.createKeyPair(keyPairName, publicKey);
}
logger.info("Keypair created/ retrieved: " + kp.getFingerprint());
/* Create Server */
Server newServer = (Server) cloudIntf.createServer("AiravataTest", imageId, flavorId, kp.getName());
logger.info("Server Created: " + newServer.getId());
/* Wait 30 seconds until server is active */
logger.info("Waiting for instance to go ACTIVE...");
Thread.sleep(delay);
/* Associate floating ip */
cloudIntf.addFloatingIP(newServer.getId());
/* Delete Server */
cloudIntf.deleteServer(newServer.getId());
logger.info("Server deleted: " + newServer.getId());
/* Wait 30 seconds until server is terminated */
logger.info("Waiting for instance to terminate...");
Thread.sleep(delay);
/* Delete Keypair */
cloudIntf.deleteKeyPair(kp.getName());
logger.info("Keypair deleted: " + kp.getName());
Server deleted = (Server) cloudIntf.getServer(newServer.getId());
assertTrue(newServer != null && deleted == null);
}
catch( Exception ex ) {
ex.printStackTrace();
fail();
}
}
/**
* Jetstream create delete network test.
*/
@Test
@Ignore
public void jetstreamCreateDeleteNetworkTest() {
try {
CloudInterface cloudIntf = new OpenstackIntfImpl("jetstream_openrc.properties");
/* fetch sample data from properties file */
String networkName = properties.getProperty("jetstream_network_name");
String subnetCIDR = properties.getProperty("jetstream_subnet_cidr");
Integer ipVersion = Integer.valueOf(properties.getProperty("jetstream_ip_version",
Constants.OS_IP_VERSION_DEFAULT.toString()));
String externalGateway = properties.getProperty("jetstream_public_network_name");
/* build router and subnet names */
String subnetName = "subnet-" + networkName;
String routerName = "router-" + networkName;
/* create network */
logger.info("Creating network with name = " + networkName);
Network network = (Network) cloudIntf.createNetwork(networkName);
assertTrue(network != null && network.getName().equals(networkName));
/* create subnet for network */
logger.info("Creating subnet with name = " + subnetName + ", and CIDR = " + subnetCIDR + ", and version = " + ipVersion);
Subnet subnet = (Subnet) cloudIntf.createSubnet(subnetName, networkName, subnetCIDR, ipVersion);
assertTrue(subnet != null
&& subnet.getName().equals(subnetName)
&& subnet.getCidr().equals(subnetCIDR)
&& subnet.getIpVersion().getVersion() == ipVersion.intValue());
/* create router for external gateway */
logger.info("Creating router with name = " + routerName + ", and external gateway = " + externalGateway);
Router router = (Router) cloudIntf.createRouter(routerName, externalGateway);
assertTrue(router != null && router.getName().equals(routerName));
/* create router-subnet interface */
logger.info("Creating interface between router = " + routerName + ", and subnet = " + subnetName);
RouterInterface iface = (RouterInterface) cloudIntf.createRouterSubnetInterface(routerName, subnetName);
assertTrue(iface != null && iface.getSubnetId().equals(subnet.getId()));
/* delete router-subnet interface */
logger.info("Deleting interface between router = " + routerName + ", and subnet = " + subnetName);
cloudIntf.deleteRouterSubnetInterface(routerName, subnetName);
/* delete router for external gateway */
logger.info("Creating router with name = " + routerName);
cloudIntf.deleteRouter(routerName);
/* delete subnet for network */
logger.info("Creating subnet with name = " + subnetName);
cloudIntf.deleteSubnet(subnetName);
/* delete network */
logger.info("Deleting network with name = " + networkName);
cloudIntf.deleteNetwork(networkName);
} catch( Exception ex ) {
ex.printStackTrace();
fail();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.test.randomwalk.security;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.NamespaceNotFoundException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.impl.thrift.SecurityErrorCode;
import org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.Credentials;
import org.apache.accumulo.core.security.NamespacePermission;
import org.apache.accumulo.core.security.SystemPermission;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.core.security.thrift.TCredentials;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.server.security.SecurityOperation;
import org.apache.accumulo.server.security.handler.Authenticator;
import org.apache.accumulo.server.security.handler.Authorizor;
import org.apache.accumulo.server.security.handler.PermissionHandler;
import org.apache.accumulo.test.randomwalk.Environment;
import org.apache.accumulo.test.randomwalk.State;
import org.apache.hadoop.fs.FileSystem;
import org.apache.log4j.Logger;
/**
*
*/
public class WalkingSecurity extends SecurityOperation implements Authorizor, Authenticator, PermissionHandler {
State state = null;
Environment env = null;
protected final static Logger log = Logger.getLogger(WalkingSecurity.class);
private static final String tableName = "SecurityTableName";
private static final String namespaceName = "SecurityNamespaceName";
private static final String userName = "UserName";
private static final String userPass = "UserPass";
private static final String userExists = "UserExists";
private static final String tableExists = "TableExists";
private static final String namespaceExists = "NamespaceExists";
private static final String connector = "UserConnection";
private static final String authsMap = "authorizationsCountMap";
private static final String lastKey = "lastMutationKey";
private static final String filesystem = "securityFileSystem";
private static WalkingSecurity instance = null;
public WalkingSecurity(Authorizor author, Authenticator authent, PermissionHandler pm, String instanceId) {
super(author, authent, pm, instanceId);
}
public WalkingSecurity(State state2, Environment env2) {
super(env2.getInstance().getInstanceID());
this.state = state2;
this.env = env2;
authorizor = this;
authenticator = this;
permHandle = this;
}
public static WalkingSecurity get(State state, Environment env) {
if (instance == null || instance.state != state) {
instance = new WalkingSecurity(state, env);
state.set(tableExists, Boolean.toString(false));
state.set(namespaceExists, Boolean.toString(false));
state.set(authsMap, new HashMap<String,Integer>());
}
return instance;
}
@Override
public void initialize(String instanceId, boolean initialize) {
throw new UnsupportedOperationException("nope");
}
@Override
public boolean validSecurityHandlers(Authenticator one, PermissionHandler two) {
return this.getClass().equals(one.getClass()) && this.getClass().equals(two.getClass());
}
@Override
public boolean validSecurityHandlers(Authenticator one, Authorizor two) {
return this.getClass().equals(one.getClass()) && this.getClass().equals(two.getClass());
}
@Override
public boolean validSecurityHandlers(Authorizor one, PermissionHandler two) {
return this.getClass().equals(one.getClass()) && this.getClass().equals(two.getClass());
}
@Override
public void initializeSecurity(TCredentials rootuser, String token) throws ThriftSecurityException {
throw new UnsupportedOperationException("nope");
}
@Override
public void changeAuthorizations(String user, Authorizations authorizations) throws AccumuloSecurityException {
state.set(user + "_auths", authorizations);
state.set("Auths-" + user + '-' + "time", System.currentTimeMillis());
}
@Override
public Authorizations getCachedUserAuthorizations(String user) throws AccumuloSecurityException {
return (Authorizations) state.get(user + "_auths");
}
public boolean ambiguousAuthorizations(String userName) {
Long setTime = state.getLong("Auths-" + userName + '-' + "time");
if (setTime == null)
throw new RuntimeException("WTF? Auths-" + userName + '-' + "time is null");
if (System.currentTimeMillis() < (setTime + 1000))
return true;
return false;
}
@Override
public void initUser(String user) throws AccumuloSecurityException {
changeAuthorizations(user, new Authorizations());
}
@Override
public Set<String> listUsers() throws AccumuloSecurityException {
Set<String> userList = new TreeSet<String>();
for (String user : new String[] {getSysUserName(), getTabUserName()}) {
if (userExists(user))
userList.add(user);
}
return userList;
}
@Override
public boolean authenticateUser(String principal, AuthenticationToken token) {
PasswordToken pass = (PasswordToken) state.get(principal + userPass);
boolean ret = pass.equals(token);
return ret;
}
@Override
public void createUser(String principal, AuthenticationToken token) throws AccumuloSecurityException {
state.set(principal + userExists, Boolean.toString(true));
changePassword(principal, token);
cleanUser(principal);
}
@Override
public void dropUser(String user) throws AccumuloSecurityException {
state.set(user + userExists, Boolean.toString(false));
cleanUser(user);
if (user.equals(getTabUserName()))
state.set("table" + connector, null);
}
@Override
public void changePassword(String principal, AuthenticationToken token) throws AccumuloSecurityException {
state.set(principal + userPass, token);
state.set(principal + userPass + "time", System.currentTimeMillis());
}
@Override
public boolean userExists(String user) {
return Boolean.parseBoolean(state.getString(user + userExists));
}
@Override
public boolean hasSystemPermission(String user, SystemPermission permission) throws AccumuloSecurityException {
boolean res = Boolean.parseBoolean(state.getString("Sys-" + user + '-' + permission.name()));
return res;
}
@Override
public boolean hasCachedSystemPermission(String user, SystemPermission permission) throws AccumuloSecurityException {
return hasSystemPermission(user, permission);
}
@Override
public boolean hasTablePermission(String user, String table, TablePermission permission) throws AccumuloSecurityException, TableNotFoundException {
return Boolean.parseBoolean(state.getString("Tab-" + user + '-' + permission.name()));
}
@Override
public boolean hasCachedTablePermission(String user, String table, TablePermission permission) throws AccumuloSecurityException, TableNotFoundException {
return hasTablePermission(user, table, permission);
}
@Override
public boolean hasNamespacePermission(String user, String namespace, NamespacePermission permission) throws AccumuloSecurityException,
NamespaceNotFoundException {
return Boolean.parseBoolean(state.getString("Nsp-" + user + '-' + permission.name()));
}
@Override
public boolean hasCachedNamespacePermission(String user, String namespace, NamespacePermission permission) throws AccumuloSecurityException,
NamespaceNotFoundException {
return hasNamespacePermission(user, namespace, permission);
}
@Override
public void grantSystemPermission(String user, SystemPermission permission) throws AccumuloSecurityException {
setSysPerm(state, user, permission, true);
}
@Override
public void revokeSystemPermission(String user, SystemPermission permission) throws AccumuloSecurityException {
setSysPerm(state, user, permission, false);
}
@Override
public void grantTablePermission(String user, String table, TablePermission permission) throws AccumuloSecurityException, TableNotFoundException {
setTabPerm(state, user, permission, table, true);
}
private static void setSysPerm(State state, String userName, SystemPermission tp, boolean value) {
log.debug((value ? "Gave" : "Took") + " the system permission " + tp.name() + (value ? " to" : " from") + " user " + userName);
state.set("Sys-" + userName + '-' + tp.name(), Boolean.toString(value));
}
private void setTabPerm(State state, String userName, TablePermission tp, String table, boolean value) {
if (table.equals(userName))
throw new RuntimeException("This is also fucked up");
log.debug((value ? "Gave" : "Took") + " the table permission " + tp.name() + (value ? " to" : " from") + " user " + userName);
state.set("Tab-" + userName + '-' + tp.name(), Boolean.toString(value));
if (tp.equals(TablePermission.READ) || tp.equals(TablePermission.WRITE))
state.set("Tab-" + userName + '-' + tp.name() + '-' + "time", System.currentTimeMillis());
}
@Override
public void revokeTablePermission(String user, String table, TablePermission permission) throws AccumuloSecurityException, TableNotFoundException {
setTabPerm(state, user, permission, table, false);
}
@Override
public void grantNamespacePermission(String user, String namespace, NamespacePermission permission) throws AccumuloSecurityException,
NamespaceNotFoundException {
setNspPerm(state, user, permission, namespace, true);
}
private void setNspPerm(State state, String userName, NamespacePermission tnp, String namespace, boolean value) {
if (namespace.equals(userName))
throw new RuntimeException("I don't even know");
log.debug((value ? "Gave" : "Took") + " the table permission " + tnp.name() + (value ? " to" : " from") + " user " + userName);
state.set("Nsp-" + userName + '-' + tnp.name(), Boolean.toString(value));
if (tnp.equals(NamespacePermission.READ) || tnp.equals(NamespacePermission.WRITE))
state.set("Nsp-" + userName + '-' + tnp.name() + '-' + "time", System.currentTimeMillis());
}
@Override
public void revokeNamespacePermission(String user, String namespace, NamespacePermission permission) throws AccumuloSecurityException,
NamespaceNotFoundException {
setNspPerm(state, user, permission, namespace, false);
}
@Override
public void cleanTablePermissions(String table) throws AccumuloSecurityException, TableNotFoundException {
for (String user : new String[] {getSysUserName(), getTabUserName()}) {
for (TablePermission tp : TablePermission.values()) {
revokeTablePermission(user, table, tp);
}
}
state.set(tableExists, Boolean.toString(false));
}
@Override
public void cleanNamespacePermissions(String namespace) throws AccumuloSecurityException, NamespaceNotFoundException {
for (String user : new String[] {getSysUserName(), getNspUserName()}) {
for (NamespacePermission tnp : NamespacePermission.values()) {
revokeNamespacePermission(user, namespace, tnp);
}
}
state.set(namespaceExists, Boolean.toString(false));
}
@Override
public void cleanUser(String user) throws AccumuloSecurityException {
if (getTableExists())
for (TablePermission tp : TablePermission.values())
try {
revokeTablePermission(user, getTableName(), tp);
} catch (TableNotFoundException e) {}
for (SystemPermission sp : SystemPermission.values())
revokeSystemPermission(user, sp);
}
public String getTabUserName() {
return state.getString("table" + userName);
}
public String getSysUserName() {
return state.getString("system" + userName);
}
public String getNspUserName() {
return state.getString("namespace" + userName);
}
public void setTabUserName(String name) {
state.set("table" + userName, name);
state.set(name + userExists, Boolean.toString(false));
}
public void setNspUserName(String name) {
state.set("namespace" + userName, name);
state.set(name + userExists, Boolean.toString(false));
}
public void setSysUserName(String name) {
state.set("system" + userName, name);
}
public String getTableName() {
return state.getString(tableName);
}
public String getNamespaceName() {
return state.getString(namespaceName);
}
public boolean getTableExists() {
return Boolean.parseBoolean(state.getString(tableExists));
}
public boolean getNamespaceExists() {
return Boolean.parseBoolean(state.getString(namespaceExists));
}
public TCredentials getSysCredentials() {
return new Credentials(getSysUserName(), getSysToken()).toThrift(this.env.getInstance());
}
public TCredentials getTabCredentials() {
return new Credentials(getTabUserName(), getTabToken()).toThrift(this.env.getInstance());
}
public AuthenticationToken getSysToken() {
return new PasswordToken(getSysPassword());
}
public AuthenticationToken getTabToken() {
return new PasswordToken(getTabPassword());
}
public byte[] getUserPassword(String user) {
Object obj = state.get(user + userPass);
if (obj instanceof PasswordToken) {
return ((PasswordToken) obj).getPassword();
}
return null;
}
public byte[] getSysPassword() {
Object obj = state.get(getSysUserName() + userPass);
if (obj instanceof PasswordToken) {
return ((PasswordToken) obj).getPassword();
}
return null;
}
public byte[] getTabPassword() {
Object obj = state.get(getTabUserName() + userPass);
if (obj instanceof PasswordToken) {
return ((PasswordToken) obj).getPassword();
}
return null;
}
public boolean userPassTransient(String user) {
return System.currentTimeMillis() - state.getLong(user + userPass + "time") < 1000;
}
public void setTableName(String tName) {
state.set(tableName, tName);
}
public void setNamespaceName(String nsName) {
state.set(namespaceName, nsName);
}
@Override
public void initTable(String table) throws AccumuloSecurityException {
state.set(tableExists, Boolean.toString(true));
state.set(tableName, table);
}
public String[] getAuthsArray() {
return new String[] {"Fishsticks", "PotatoSkins", "Ribs", "Asparagus", "Paper", "Towels", "Lint", "Brush", "Celery"};
}
public boolean inAmbiguousZone(String userName, TablePermission tp) {
if (tp.equals(TablePermission.READ) || tp.equals(TablePermission.WRITE)) {
Long setTime = state.getLong("Tab-" + userName + '-' + tp.name() + '-' + "time");
if (setTime == null)
throw new RuntimeException("WTF? Tab-" + userName + '-' + tp.name() + '-' + "time is null");
if (System.currentTimeMillis() < (setTime + 1000))
return true;
}
return false;
}
@SuppressWarnings("unchecked")
public Map<String,Integer> getAuthsMap() {
return (Map<String,Integer>) state.get(authsMap);
}
public String getLastKey() {
return state.getString(lastKey);
}
public void increaseAuthMap(String s, int increment) {
Integer curVal = getAuthsMap().get(s);
if (curVal == null) {
curVal = Integer.valueOf(0);
getAuthsMap().put(s, curVal);
}
curVal += increment;
}
public FileSystem getFs() {
FileSystem fs = null;
try {
fs = (FileSystem) state.get(filesystem);
} catch (RuntimeException re) {}
if (fs == null) {
try {
fs = FileSystem.get(CachedConfiguration.getInstance());
} catch (IOException e) {
throw new RuntimeException(e);
}
state.set(filesystem, fs);
}
return fs;
}
@Override
public boolean canAskAboutUser(TCredentials credentials, String user) throws ThriftSecurityException {
try {
return super.canAskAboutUser(credentials, user);
} catch (ThriftSecurityException tse) {
if (tse.getCode().equals(SecurityErrorCode.PERMISSION_DENIED))
return false;
throw tse;
}
}
@Override
public boolean validTokenClass(String tokenClass) {
return tokenClass.equals(PasswordToken.class.getName());
}
public static void clearInstance() {
instance = null;
}
@Override
public Set<Class<? extends AuthenticationToken>> getSupportedTokenTypes() {
Set<Class<? extends AuthenticationToken>> cs = new HashSet<Class<? extends AuthenticationToken>>();
cs.add(PasswordToken.class);
return cs;
}
@Override
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException {
Collection<ByteBuffer> userauths = getCachedUserAuthorizations(user).getAuthorizationsBB();
for (ByteBuffer auth : auths)
if (!userauths.contains(auth))
return false;
return true;
}
}
| |
/*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.mongodb.core.engine.metadata;
import static com.stratio.connector.mongodb.core.configuration.CustomMongoIndexType.COMPOUND;
import static com.stratio.connector.mongodb.core.configuration.CustomMongoIndexType.GEOSPATIAL_FLAT;
import static com.stratio.connector.mongodb.core.configuration.CustomMongoIndexType.GEOSPATIAL_SPHERE;
import static com.stratio.connector.mongodb.core.configuration.IndexOptions.COMPOUND_FIELDS;
import static com.stratio.connector.mongodb.core.configuration.IndexOptions.INDEX_TYPE;
import static com.stratio.connector.mongodb.core.configuration.IndexOptions.SPARSE;
import static com.stratio.connector.mongodb.core.configuration.IndexOptions.UNIQUE;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.stratio.connector.mongodb.core.configuration.CustomMongoIndexType;
import com.stratio.connector.mongodb.core.exceptions.MongoValidationException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.metadata.ColumnMetadata;
import com.stratio.crossdata.common.metadata.IndexMetadata;
import com.stratio.crossdata.common.metadata.IndexType;
import com.stratio.crossdata.common.statements.structures.BooleanSelector;
import com.stratio.crossdata.common.statements.structures.Selector;
import com.stratio.crossdata.common.statements.structures.StringSelector;
/**
* The Class IndexUtils.
*
*/
public final class IndexUtils {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(IndexUtils.class);
private IndexUtils() {
}
/**
* Retrieves the index options specified and returns them in the Mongo format.
*
* @param indexMetadata
* the index metadata
* @return the mongo index options
* @throws MongoValidationException
* if any option specified is not supported
*/
public static DBObject getCustomOptions(IndexMetadata indexMetadata) throws MongoValidationException {
DBObject indexOptionsDBObject = new BasicDBObject();
String indexName = indexMetadata.getName().getName();
Map<String, Selector> options = SelectorOptionsUtils.processOptions(indexMetadata.getOptions());
if (options != null) {
Selector boolSelector = options.get(SPARSE.getOptionName());
if (boolSelector != null) {
indexOptionsDBObject.put("sparse", ((BooleanSelector) boolSelector).getValue());
}
boolSelector = options.get(UNIQUE.getOptionName());
if (boolSelector != null) {
indexOptionsDBObject.put("unique", ((BooleanSelector) boolSelector).getValue());
}
}
if (indexName != null && !indexName.trim().isEmpty()) {
indexOptionsDBObject.put("name", indexName);
}
return indexOptionsDBObject;
}
/**
* Creates the Mongo index based on the index metadata options.
*
* @param indexMetadata
* the index metadata
* @return the Mongo index
* @throws MongoValidationException
* the unsupported exception
*/
public static DBObject getIndexDBObject(IndexMetadata indexMetadata) throws MongoValidationException {
IndexType indexType = indexMetadata.getType();
DBObject indexDBObject = new BasicDBObject();
if (indexType == IndexType.DEFAULT) {
for (ColumnMetadata columnMeta : indexMetadata.getColumns().values()) {
indexDBObject.put(columnMeta.getName().getName(), 1);
}
} else if (indexType == IndexType.FULL_TEXT) {
for (ColumnMetadata columnMeta : indexMetadata.getColumns().values()) {
indexDBObject.put(columnMeta.getName().getName(), "text");
}
} else if (indexMetadata.getType() == IndexType.CUSTOM) {
indexDBObject = getCustomIndexDBObject(indexMetadata);
} else {
String msg = "Index type " + indexMetadata.getType().toString() + " is not supported";
LOGGER.error(msg);
throw new MongoValidationException(msg);
}
return indexDBObject;
}
private static DBObject getCustomIndexDBObject(IndexMetadata indexMetadata) throws MongoValidationException {
DBObject indexDBObject = new BasicDBObject();
Map<String, Selector> options = SelectorOptionsUtils.processOptions(indexMetadata.getOptions());
if (options == null) {
String msg = "The custom index must have an index type and fields";
LOGGER.debug(msg);
throw new MongoValidationException(msg);
}
Selector selector = options.get(INDEX_TYPE.getOptionName());
if (selector == null) {
String msg = "The custom index must have an index type";
LOGGER.debug(msg);
throw new MongoValidationException(msg);
}
String indexType = ((StringSelector) selector).getValue().trim();
String[] fields = getCustomIndexDBObjectFields(options, indexType, indexMetadata);
// Create the index specified
if (COMPOUND.getIndexType().equals(indexType)) {
for (String field : fields) {
String[] fieldInfo = field.split(":");
if (fieldInfo.length != 2) {
String msg = "Format error. The fields in a compound index must be: fieldname:asc|desc [, field2:desc ...] ";
LOGGER.debug(msg);
throw new MongoValidationException(msg);
}
int order = fieldInfo[1].trim().equals("asc") ? 1 : -1;
indexDBObject.put(fieldInfo[0], order);
}
} else {
if (fields.length != 1) {
String msg = "The " + indexType + " index must have a single field";
LOGGER.debug(msg);
throw new MongoValidationException(msg);
}
String mongoIndexType;
if (CustomMongoIndexType.HASHED.getIndexType().equals(indexType)) {
mongoIndexType = "hashed";
} else if (GEOSPATIAL_SPHERE.getIndexType().equals(indexType)) {
mongoIndexType = "2dsphere";
} else if (GEOSPATIAL_FLAT.getIndexType().equals(indexType)) {
mongoIndexType = "2d";
} else {
throw new MongoValidationException("Index " + indexType + " is not supported");
}
indexDBObject.put(fields[0], mongoIndexType);
}
return indexDBObject;
}
/**
* Utility for the custom index type. Parse the compound fields value.
*
* @param options
* the options
* @param indexType
* the index type
* @param indexMetadata
* the index metadata
* @return the index fields
* @throws MongoValidationException
* if the fields are malformed
*/
private static String[] getCustomIndexDBObjectFields(Map<String, Selector> options, String indexType,
IndexMetadata indexMetadata) throws MongoValidationException {
String[] fields = null;
Selector selector = options.get(COMPOUND_FIELDS.getOptionName());
if (COMPOUND.getIndexType().equals(indexType)) {
if (selector != null) {
fields = ((StringSelector) selector).getValue().split(",");
} else {
throw new MongoValidationException("The compound index must have 1 o more fields");
}
} else {
int i = 0;
fields = new String[indexMetadata.getColumns().size()];
for (ColumnMetadata colMetadata : indexMetadata.getColumns().values()) {
fields[i++] = colMetadata.getName().getName();
}
}
return fields;
}
/**
* Drop index with the mongo default name. The name is created based on the corresponding index type.
*
* @param indexMetadata
* the index metadata
* @param db
* the db
* @throws ExecutionException
* if an error exist when running the db command
*/
public static void dropIndexWithDefaultName(IndexMetadata indexMetadata, DB db) throws ExecutionException {
if (indexMetadata.getType() == IndexType.DEFAULT) {
DBObject indexDBObject = new BasicDBObject();
for (ColumnMetadata columnMeta : indexMetadata.getColumns().values()) {
indexDBObject.put(columnMeta.getName().getName(), 1);
}
try {
db.getCollection(indexMetadata.getName().getTableName().getName()).dropIndex(indexDBObject);
} catch (Exception e) {
LOGGER.error("Error dropping the index with " + indexDBObject + " :" + e.getMessage());
throw new ExecutionException(e.getMessage(), e);
}
} else if (indexMetadata.getType() == IndexType.FULL_TEXT) {
String defaultTextIndexName;
StringBuffer strBuf = new StringBuffer();
int colNumber = 0;
int columnSize = indexMetadata.getColumns().size();
for (ColumnMetadata columnMeta : indexMetadata.getColumns().values()) {
strBuf.append(columnMeta.getName().getName()).append("_");
if (++colNumber != columnSize) {
strBuf.append("_");
}
}
defaultTextIndexName = strBuf.toString();
try {
db.getCollection(indexMetadata.getName().getTableName().getName()).dropIndex(defaultTextIndexName);
} catch (Exception e) {
LOGGER.error("Error dropping the index " + defaultTextIndexName + " :" + e.getMessage());
throw new ExecutionException(e.getMessage(), e);
}
} else {
throw new MongoValidationException("Dropping without the index name is not supported for the index type: "
+ indexMetadata.getType().toString());
}
}
}
| |
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.runtime.api.impl;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.delegate.invocation.DefaultDelegateInterceptor;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.persistence.entity.VariableInstance;
import org.activiti.spring.process.model.Extension;
import org.activiti.spring.process.model.VariableDefinition;
public class ExpressionResolverHelper {
private static ObjectMapper objectMapper = new ObjectMapper();
private static void initializeExpressionResolver() {
ProcessEngineConfigurationImpl processEngineConfiguration = mock(ProcessEngineConfigurationImpl.class);
Context.setProcessEngineConfiguration(processEngineConfiguration);
given(processEngineConfiguration.getExpressionManager()).willReturn(new ExpressionManager());
given(processEngineConfiguration.getDelegateInterceptor()).willReturn(new DefaultDelegateInterceptor());
}
public static ExpressionResolver initContext(DelegateExecution execution,
Extension extensions) {
initializeExpressionResolver();
Map<String, Object> variables = convertToStringObjectMap(extensions.getProperties());
setExecutionVariables(execution, variables);
return new ExpressionResolver(new ExpressionManager(),
objectMapper, new DefaultDelegateInterceptor());
}
public static void setExecutionVariables(DelegateExecution execution, Map<String, Object> variables) {
given(execution.getVariables()).willReturn(variables);
given(execution.getVariablesLocal()).willReturn(variables);
for (String key : variables.keySet()) {
given(execution.hasVariable(key)).willReturn(true);
VariableInstance var = getVariableInstance(key,
variables.get(key));
given(execution.getVariableInstance(key)).willReturn(var);
given(execution.getVariable(key)).willReturn(variables.get(key));
}
}
private static Map<String, Object> convertToStringObjectMap(
Map<String, VariableDefinition> sourceMap) {
Map<String, Object> result = new HashMap<>();
sourceMap.forEach((key,
value) -> result.put(value.getName(),
value.getValue()));
return result;
}
private static VariableInstance getVariableInstance(String key,
Object value) {
VariableInstance var = new VariableInstance() {
@Override
public void setRevision(int revision) {
}
@Override
public int getRevisionNext() {
return 0;
}
@Override
public int getRevision() {
return 0;
}
@Override
public void setUpdated(boolean updated) {
}
@Override
public void setInserted(boolean inserted) {
}
@Override
public void setId(String id) {
}
@Override
public void setDeleted(boolean deleted) {
}
@Override
public boolean isUpdated() {
return false;
}
@Override
public boolean isInserted() {
return false;
}
@Override
public boolean isDeleted() {
return false;
}
@Override
public Object getPersistentState() {
return null;
}
@Override
public String getId() {
return null;
}
@Override
public void setTextValue2(String textValue2) {
}
@Override
public void setTextValue(String textValue) {
}
@Override
public void setLongValue(Long longValue) {
}
@Override
public void setDoubleValue(Double doubleValue) {
}
@Override
public void setCachedValue(Object cachedValue) {
}
@Override
public void setBytes(byte[] bytes) {
}
@Override
public String getTextValue2() {
return null;
}
@Override
public String getTextValue() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public Long getLongValue() {
return null;
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setValue(Object value) {
}
@Override
public void setTypeName(String typeName) {
}
@Override
public void setTaskId(String taskId) {
}
@Override
public void setProcessInstanceId(String processInstanceId) {
}
@Override
public void setName(String name) {
}
@Override
public void setExecutionId(String executionId) {
}
@Override
public Object getValue() {
return value;
}
@Override
public String getTypeName() {
if (value instanceof String) {
return "string";
} else if (value instanceof Integer) {
return "integer";
} else if (value instanceof Boolean) {
return "boolean";
} else {
return "json";
}
}
@Override
public String getTaskId() {
return null;
}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getExecutionId() {
return null;
}
};
return var;
}
}
| |
package org.apache.maven.plugins.site.render;
/*
* 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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.doxia.site.decoration.DecorationModel;
import org.apache.maven.doxia.site.decoration.Menu;
import org.apache.maven.doxia.site.decoration.MenuItem;
import org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler;
import org.apache.maven.doxia.siterenderer.DocumentRenderer;
import org.apache.maven.doxia.siterenderer.Renderer;
import org.apache.maven.doxia.siterenderer.RendererException;
import org.apache.maven.doxia.siterenderer.RenderingContext;
import org.apache.maven.doxia.siterenderer.SiteRenderingContext;
import org.apache.maven.doxia.tools.SiteToolException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.site.AbstractSiteMojo;
import org.apache.maven.reporting.MavenReport;
import org.apache.maven.reporting.exec.MavenReportExecution;
import org.apache.maven.reporting.exec.MavenReportExecutor;
import org.apache.maven.reporting.exec.MavenReportExecutorRequest;
import org.apache.maven.reporting.exec.ReportPlugin;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
/**
* Base class for site rendering mojos.
*
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
* @version $Id$
*/
public abstract class AbstractSiteRenderingMojo
extends AbstractSiteMojo implements Contextualizable
{
/**
* Module type exclusion mappings
* ex: <code>fml -> **/*-m1.fml</code> (excludes fml files ending in '-m1.fml' recursively)
* <p/>
* The configuration looks like this:
* <pre>
* <moduleExcludes>
* <moduleType>filename1.ext,**/*sample.ext</moduleType>
* <!-- moduleType can be one of 'apt', 'fml' or 'xdoc'. -->
* <!-- The value is a comma separated list of -->
* <!-- filenames or fileset patterns. -->
* <!-- Here's an example: -->
* <xdoc>changes.xml,navigation.xml</xdoc>
* </moduleExcludes>
* </pre>
*/
@Parameter
private Map<String, String> moduleExcludes;
/**
* The component for assembling inheritance.
*/
@Component
private DecorationModelInheritanceAssembler assembler;
/**
* Remote repositories used for the project.
*
* @todo this is used for site descriptor resolution - it should relate to the actual project but for some reason they are not always filled in
*/
@Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true )
private List<ArtifactRepository> repositories;
/**
* The location of a Velocity template file to use. When used, skins and the default templates, CSS and images
* are disabled. It is highly recommended that you package this as a skin instead.
*
* @since 2.0-beta-5
*/
@Parameter( property = "templateFile" )
private File templateFile;
/**
* Additional template properties for rendering the site. See
* <a href="/doxia/doxia-sitetools/doxia-site-renderer/">Doxia Site Renderer</a>.
*/
@Parameter
private Map<String, Object> attributes;
/**
* Site renderer.
*/
@Component
protected Renderer siteRenderer;
/**
* Reports (Maven 2).
*/
@Parameter( defaultValue = "${reports}", required = true, readonly = true )
protected List<MavenReport> reports;
/**
* Alternative directory for xdoc source, useful for m1 to m2 migration
*
* @deprecated use the standard m2 directory layout
*/
@Parameter( defaultValue = "${basedir}/xdocs" )
private File xdocDirectory;
/**
* Directory containing generated documentation.
* This is used to pick up other source docs that might have been generated at build time.
*
* @todo should we deprecate in favour of reports?
*/
@Parameter( alias = "workingDirectory", defaultValue = "${project.build.directory}/generated-site" )
protected File generatedSiteDirectory;
/**
* The current Maven session.
*/
@Parameter( defaultValue = "${session}", readonly = true, required = true )
protected MavenSession mavenSession;
/**
* <p>Configuration section <b>used internally</b> by Maven 3.</p>
* <p>More details available here:
* <a href="http://maven.apache.org/plugins/maven-site-plugin/maven-3.html#Configuration_formats" target="_blank">
* http://maven.apache.org/plugins/maven-site-plugin/maven-3.html#Configuration_formats</a>
* </p>
* <p><b>Note:</b> using this field is not mandatory with Maven 3 as Maven core injects usual
* <code><reporting></code> section into this field.</p>
*
* @since 3.0-beta-1 (and read-only since 3.3)
*/
@Parameter( readonly = true )
private ReportPlugin[] reportPlugins;
private PlexusContainer container;
/**
* Make links in the site descriptor relative to the project URL.
* By default, any absolute links that appear in the site descriptor,
* e.g. banner hrefs, breadcrumbs, menu links, etc., will be made relative to project.url.
* <p/>
* Links will not be changed if this is set to false, or if the project has no URL defined.
*
* @since 2.3
*/
@Parameter( property = "relativizeDecorationLinks", defaultValue = "true" )
private boolean relativizeDecorationLinks;
/**
* Whether to generate the summary page for project reports: project-info.html.
*
* @since 2.3
*/
@Parameter( property = "generateProjectInfo", defaultValue = "true" )
private boolean generateProjectInfo;
/** {@inheritDoc} */
public void contextualize( Context context )
throws ContextException
{
container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
}
protected List<MavenReportExecution> getReports()
throws MojoExecutionException
{
List<MavenReportExecution> allReports;
if ( isMaven3OrMore() )
{
// Maven 3
MavenReportExecutorRequest mavenReportExecutorRequest = new MavenReportExecutorRequest();
mavenReportExecutorRequest.setLocalRepository( localRepository );
mavenReportExecutorRequest.setMavenSession( mavenSession );
mavenReportExecutorRequest.setProject( project );
mavenReportExecutorRequest.setReportPlugins( reportPlugins );
MavenReportExecutor mavenReportExecutor;
try
{
mavenReportExecutor = (MavenReportExecutor) container.lookup( MavenReportExecutor.class.getName() );
}
catch ( ComponentLookupException e )
{
throw new MojoExecutionException( "could not get MavenReportExecutor component", e );
}
allReports = mavenReportExecutor.buildMavenReports( mavenReportExecutorRequest );
}
else
{
// Maven 2
allReports = new ArrayList<MavenReportExecution>( reports.size() );
for ( MavenReport report : reports )
{
allReports.add( new MavenReportExecution( report ) );
}
}
// filter out reports that can't be generated
List<MavenReportExecution> reportExecutions = new ArrayList<MavenReportExecution>( allReports.size() );
for ( MavenReportExecution exec : allReports )
{
if ( exec.canGenerateReport() )
{
reportExecutions.add( exec );
}
}
return reportExecutions;
}
protected SiteRenderingContext createSiteRenderingContext( Locale locale )
throws MojoExecutionException, IOException, MojoFailureException
{
if ( attributes == null )
{
attributes = new HashMap<String, Object>();
}
if ( attributes.get( "project" ) == null )
{
attributes.put( "project", project );
}
if ( attributes.get( "inputEncoding" ) == null )
{
attributes.put( "inputEncoding", getInputEncoding() );
}
if ( attributes.get( "outputEncoding" ) == null )
{
attributes.put( "outputEncoding", getOutputEncoding() );
}
// Put any of the properties in directly into the Velocity context
for ( Map.Entry<Object, Object> entry : project.getProperties().entrySet() )
{
attributes.put( (String) entry.getKey(), entry.getValue() );
}
DecorationModel decorationModel;
try
{
decorationModel = siteTool.getDecorationModel( siteDirectory, locale, project, reactorProjects,
localRepository, repositories );
}
catch ( SiteToolException e )
{
throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e );
}
if ( relativizeDecorationLinks )
{
final String url = project.getUrl();
if ( url == null )
{
getLog().warn( "No project URL defined - decoration links will not be relativized!" );
}
else
{
// MSITE-658
final String localeUrl =
locale.equals( Locale.getDefault() ) ? url : url + "/" + locale.getLanguage();
getLog().info( "Relativizing decoration links with respect to project URL: " + localeUrl );
assembler.resolvePaths( decorationModel, localeUrl );
}
}
File skinFile;
try
{
Artifact skinArtifact =
siteTool.getSkinArtifactFromRepository( localRepository, repositories, decorationModel );
getLog().info( "Rendering site with " + skinArtifact.getId() + " skin." );
skinFile = skinArtifact.getFile();
}
catch ( SiteToolException e )
{
throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e );
}
SiteRenderingContext context;
if ( templateFile != null )
{
if ( !templateFile.exists() )
{
throw new MojoFailureException( "Template file '" + templateFile + "' does not exist" );
}
context = siteRenderer.createContextForTemplate( templateFile, skinFile, attributes, decorationModel,
project.getName(), locale );
}
else
{
context = siteRenderer.createContextForSkin( skinFile, attributes, decorationModel, project.getName(),
locale );
}
// Generate static site
if ( !locale.getLanguage().equals( Locale.getDefault().getLanguage() ) )
{
context.addSiteDirectory( new File( siteDirectory, locale.getLanguage() ) );
context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "xdoc" );
context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "fml" );
}
else
{
context.addSiteDirectory( siteDirectory );
context.addModuleDirectory( xdocDirectory, "xdoc" );
context.addModuleDirectory( xdocDirectory, "fml" );
}
if ( moduleExcludes != null )
{
context.setModuleExcludes( moduleExcludes );
}
return context;
}
/**
* Go through the list of reports and process each one like this:
* <ul>
* <li>Add the report to a map of reports keyed by filename having the report itself as value
* <li>If the report is not yet in the map of documents, add it together with a suitable renderer
* </ul>
*
* @param reports A List of MavenReports
* @param documents A Map of documents, keyed by filename
* @param locale the Locale the reports are processed for.
* @return A map with all reports keyed by filename having the report itself as value.
* The map will be used to populate a menu.
*/
protected Map<String, MavenReport> locateReports( List<MavenReportExecution> reports,
Map<String, DocumentRenderer> documents, Locale locale )
{
// copy Collection to prevent ConcurrentModificationException
List<MavenReportExecution> filtered = new ArrayList<MavenReportExecution>( reports );
Map<String, MavenReport> reportsByOutputName = new LinkedHashMap<String, MavenReport>();
for ( MavenReportExecution mavenReportExecution : filtered )
{
MavenReport report = mavenReportExecution.getMavenReport();
String outputName = report.getOutputName() + ".html";
// Always add the report to the menu, see MSITE-150
reportsByOutputName.put( report.getOutputName(), report );
if ( documents.containsKey( outputName ) )
{
String displayLanguage = locale.getDisplayLanguage( Locale.ENGLISH );
String reportMojoInfo =
( mavenReportExecution.getGoal() == null ) ? "" : ( " ("
+ mavenReportExecution.getPlugin().getArtifactId() + ':'
+ mavenReportExecution.getPlugin().getVersion() + ':' + mavenReportExecution.getGoal() + ')' );
getLog().info( "Skipped \"" + report.getName( locale ) + "\" report" + reportMojoInfo + ", file \""
+ outputName + "\" already exists for the " + displayLanguage + " version." );
reports.remove( mavenReportExecution );
}
else
{
RenderingContext renderingContext = new RenderingContext( siteDirectory, outputName );
DocumentRenderer renderer =
new ReportDocumentRenderer( mavenReportExecution, renderingContext, getLog() );
documents.put( outputName, renderer );
}
}
return reportsByOutputName;
}
/**
* Go through the collection of reports and put each report into a list for the appropriate category. The list is
* put into a map keyed by the name of the category.
*
* @param reports A Collection of MavenReports
* @return A map keyed category having the report itself as value
*/
protected Map<String, List<MavenReport>> categoriseReports( Collection<MavenReport> reports )
{
Map<String, List<MavenReport>> categories = new LinkedHashMap<String, List<MavenReport>>();
for ( MavenReport report : reports )
{
List<MavenReport> categoryReports = categories.get( report.getCategoryName() );
if ( categoryReports == null )
{
categoryReports = new ArrayList<MavenReport>();
categories.put( report.getCategoryName(), categoryReports );
}
categoryReports.add( report );
}
return categories;
}
/**
* Locate every document to be rendered for given locale:<ul>
* <li>handwritten content,</li>
* <li>reports,</li>
* <li>"Project Information" and "Project Reports" category summaries.</li>
* </ul>
*/
protected Map<String, DocumentRenderer> locateDocuments( SiteRenderingContext context,
List<MavenReportExecution> reports, Locale locale )
throws IOException, RendererException
{
Map<String, DocumentRenderer> documents = siteRenderer.locateDocumentFiles( context );
Map<String, MavenReport> reportsByOutputName = locateReports( reports, documents, locale );
// TODO: I want to get rid of categories eventually. There's no way to add your own in a fully i18n manner
Map<String, List<MavenReport>> categories = categoriseReports( reportsByOutputName.values() );
siteTool.populateReportsMenu( context.getDecoration(), locale, categories );
populateReportItems( context.getDecoration(), locale, reportsByOutputName );
if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_INFORMATION ) && generateProjectInfo )
{
// add "Project Information" category summary document
List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_INFORMATION );
RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-info.html" );
String title = i18n.getString( "site-plugin", locale, "report.information.title" );
String desc1 = i18n.getString( "site-plugin", locale, "report.information.description1" );
String desc2 = i18n.getString( "site-plugin", locale, "report.information.description2" );
DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2,
i18n, categoryReports, getLog() );
if ( !documents.containsKey( renderer.getOutputName() ) )
{
documents.put( renderer.getOutputName(), renderer );
}
else
{
getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" );
}
}
if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_REPORTS ) )
{
// add "Project Reports" category summary document
List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_REPORTS );
RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-reports.html" );
String title = i18n.getString( "site-plugin", locale, "report.project.title" );
String desc1 = i18n.getString( "site-plugin", locale, "report.project.description1" );
String desc2 = i18n.getString( "site-plugin", locale, "report.project.description2" );
DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2,
i18n, categoryReports, getLog() );
if ( !documents.containsKey( renderer.getOutputName() ) )
{
documents.put( renderer.getOutputName(), renderer );
}
else
{
getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" );
}
}
return documents;
}
protected void populateReportItems( DecorationModel decorationModel, Locale locale,
Map<String, MavenReport> reportsByOutputName )
{
for ( Menu menu : decorationModel.getMenus() )
{
populateItemRefs( menu.getItems(), locale, reportsByOutputName );
}
}
private void populateItemRefs( List<MenuItem> items, Locale locale, Map<String, MavenReport> reportsByOutputName )
{
for ( Iterator<MenuItem> i = items.iterator(); i.hasNext(); )
{
MenuItem item = i.next();
if ( item.getRef() != null )
{
MavenReport report = reportsByOutputName.get( item.getRef() );
if ( report != null )
{
if ( item.getName() == null )
{
item.setName( report.getName( locale ) );
}
if ( item.getHref() == null || item.getHref().length() == 0 )
{
item.setHref( report.getOutputName() + ".html" );
}
}
else
{
getLog().warn( "Unrecognised reference: '" + item.getRef() + "'" );
i.remove();
}
}
populateItemRefs( item.getItems(), locale, reportsByOutputName );
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.search;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.DisMaxParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.parser.QueryParser;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.util.SolrPluginUtils;
/**
* Query parser for dismax queries
*
* <p><b>Note: This API is experimental and may change in non backward-compatible ways in the
* future</b>
*/
public class DisMaxQParser extends QParser {
/**
* A field we can't ever find in any schema, so we can safely tell DisjunctionMaxQueryParser to
* use it as our defaultField, and map aliases from it to any field in our schema.
*/
private static String IMPOSSIBLE_FIELD_NAME = "\uFFFC\uFFFC\uFFFC";
/**
* Applies the appropriate default rules for the "mm" param based on the effective value of the
* "q.op" param
*
* @see QueryParsing#OP
* @see DisMaxParams#MM
*/
public static String parseMinShouldMatch(final IndexSchema schema, final SolrParams params) {
org.apache.solr.parser.QueryParser.Operator op =
QueryParsing.parseOP(params.get(QueryParsing.OP));
return params.get(DisMaxParams.MM, op.equals(QueryParser.Operator.AND) ? "100%" : "0%");
}
/**
* Uses {@link SolrPluginUtils#parseFieldBoosts(String)} with the 'qf' parameter. Falls back to
* the 'df' parameter
*/
public static Map<String, Float> parseQueryFields(
final IndexSchema indexSchema, final SolrParams solrParams) throws SyntaxError {
Map<String, Float> queryFields =
SolrPluginUtils.parseFieldBoosts(solrParams.getParams(DisMaxParams.QF));
if (queryFields.isEmpty()) {
String df = solrParams.get(CommonParams.DF);
if (df == null) {
throw new SyntaxError(
"Neither " + DisMaxParams.QF + " nor " + CommonParams.DF + " are present.");
}
queryFields.put(df, 1.0f);
}
return queryFields;
}
public DisMaxQParser(
String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
super(qstr, localParams, params, req);
}
protected Map<String, Float> queryFields;
protected Query parsedUserQuery;
protected String[] boostParams;
protected List<Query> boostQueries;
protected Query altUserQuery;
private boolean parsed = false;
@Override
public Query parse() throws SyntaxError {
parsed = true;
SolrParams solrParams = SolrParams.wrapDefaults(localParams, params);
queryFields = parseQueryFields(req.getSchema(), solrParams);
/* the main query we will execute. we disable the coord because
* this query is an artificial construct
*/
BooleanQuery.Builder query = new BooleanQuery.Builder();
boolean notBlank = addMainQuery(query, solrParams);
if (!notBlank) return null;
addBoostQuery(query, solrParams);
addBoostFunctions(query, solrParams);
return QueryUtils.build(query, this);
}
protected void addBoostFunctions(BooleanQuery.Builder query, SolrParams solrParams)
throws SyntaxError {
String[] boostFuncs = solrParams.getParams(DisMaxParams.BF);
if (null != boostFuncs && 0 != boostFuncs.length) {
for (String boostFunc : boostFuncs) {
if (null == boostFunc || "".equals(boostFunc)) continue;
Map<String, Float> ff = SolrPluginUtils.parseFieldBoosts(boostFunc);
for (Map.Entry<String, Float> entry : ff.entrySet()) {
Query fq = subQuery(entry.getKey(), FunctionQParserPlugin.NAME).getQuery();
Float b = entry.getValue();
if (null != b) {
fq = new BoostQuery(fq, b);
}
query.add(fq, BooleanClause.Occur.SHOULD);
}
}
}
}
protected void addBoostQuery(BooleanQuery.Builder query, SolrParams solrParams)
throws SyntaxError {
boostParams = solrParams.getParams(DisMaxParams.BQ);
// List<Query> boostQueries = SolrPluginUtils.parseQueryStrings(req, boostParams);
boostQueries = null;
if (boostParams != null && boostParams.length > 0) {
boostQueries = new ArrayList<>();
for (String qs : boostParams) {
if (qs.trim().length() == 0) continue;
Query q = subQuery(qs, null).getQuery();
boostQueries.add(q);
}
}
if (null != boostQueries) {
if (1 == boostQueries.size() && 1 == boostParams.length) {
/* legacy logic */
Query f = boostQueries.get(0);
while (f instanceof BoostQuery) {
BoostQuery bq = (BoostQuery) f;
if (bq.getBoost() == 1f) {
f = bq.getQuery();
} else {
break;
}
}
if (f instanceof BooleanQuery) {
/* if the default boost was used, and we've got a BooleanQuery
* extract the subqueries out and use them directly
*/
for (Object c : ((BooleanQuery) f).clauses()) {
query.add((BooleanClause) c);
}
} else {
query.add(f, BooleanClause.Occur.SHOULD);
}
} else {
for (Query f : boostQueries) {
query.add(f, BooleanClause.Occur.SHOULD);
}
}
}
}
/** Adds the main query to the query argument. If it's blank then false is returned. */
protected boolean addMainQuery(BooleanQuery.Builder query, SolrParams solrParams)
throws SyntaxError {
Map<String, Float> phraseFields =
SolrPluginUtils.parseFieldBoosts(solrParams.getParams(DisMaxParams.PF));
float tiebreaker = solrParams.getFloat(DisMaxParams.TIE, 0.0f);
/* a parser for dealing with user input, which will convert
* things to DisjunctionMaxQueries
*/
SolrPluginUtils.DisjunctionMaxQueryParser up =
getParser(queryFields, DisMaxParams.QS, solrParams, tiebreaker);
/* for parsing sloppy phrases using DisjunctionMaxQueries */
SolrPluginUtils.DisjunctionMaxQueryParser pp =
getParser(phraseFields, DisMaxParams.PS, solrParams, tiebreaker);
/* * * Main User Query * * */
parsedUserQuery = null;
String userQuery = getString();
altUserQuery = null;
if (StringUtils.isBlank(userQuery)) {
// If no query is specified, we may have an alternate
altUserQuery = getAlternateUserQuery(solrParams);
if (altUserQuery == null) return false;
query.add(altUserQuery, BooleanClause.Occur.MUST);
} else {
// There is a valid query string
userQuery =
SolrPluginUtils.partialEscape(SolrPluginUtils.stripUnbalancedQuotes(userQuery))
.toString();
userQuery = SolrPluginUtils.stripIllegalOperators(userQuery).toString();
parsedUserQuery = getUserQuery(userQuery, up, solrParams);
query.add(parsedUserQuery, BooleanClause.Occur.MUST);
Query phrase = getPhraseQuery(userQuery, pp);
if (null != phrase) {
query.add(phrase, BooleanClause.Occur.SHOULD);
}
}
return true;
}
protected Query getAlternateUserQuery(SolrParams solrParams) throws SyntaxError {
String altQ = solrParams.get(DisMaxParams.ALTQ);
if (altQ != null) {
QParser altQParser = subQuery(altQ, null);
return altQParser.getQuery();
} else {
return null;
}
}
protected Query getPhraseQuery(String userQuery, SolrPluginUtils.DisjunctionMaxQueryParser pp)
throws SyntaxError {
/* * * Add on Phrases for the Query * * */
/* build up phrase boosting queries */
/* if the userQuery already has some quotes, strip them out.
* we've already done the phrases they asked for in the main
* part of the query, this is to boost docs that may not have
* matched those phrases but do match looser phrases.
*/
String userPhraseQuery = userQuery.replace("\"", "");
return pp.parse("\"" + userPhraseQuery + "\"");
}
protected Query getUserQuery(
String userQuery, SolrPluginUtils.DisjunctionMaxQueryParser up, SolrParams solrParams)
throws SyntaxError {
String minShouldMatch = parseMinShouldMatch(req.getSchema(), solrParams);
Query dis = up.parse(userQuery);
Query query = dis;
if (dis instanceof BooleanQuery) {
BooleanQuery.Builder t = new BooleanQuery.Builder();
SolrPluginUtils.flattenBooleanQuery(t, (BooleanQuery) dis);
boolean mmAutoRelax = params.getBool(DisMaxParams.MM_AUTORELAX, false);
SolrPluginUtils.setMinShouldMatch(t, minShouldMatch, mmAutoRelax);
query = QueryUtils.build(t, this);
}
return query;
}
protected SolrPluginUtils.DisjunctionMaxQueryParser getParser(
Map<String, Float> fields, String paramName, SolrParams solrParams, float tiebreaker) {
int slop = solrParams.getInt(paramName, 0);
SolrPluginUtils.DisjunctionMaxQueryParser parser =
new SolrPluginUtils.DisjunctionMaxQueryParser(this, IMPOSSIBLE_FIELD_NAME);
parser.addAlias(IMPOSSIBLE_FIELD_NAME, tiebreaker, fields);
parser.setPhraseSlop(slop);
parser.setSplitOnWhitespace(true);
return parser;
}
@Override
public String[] getDefaultHighlightFields() {
return queryFields.keySet().toArray(new String[queryFields.keySet().size()]);
}
@Override
public Query getHighlightQuery() throws SyntaxError {
if (!parsed) parse();
return parsedUserQuery == null ? altUserQuery : parsedUserQuery;
}
@Override
public void addDebugInfo(NamedList<Object> debugInfo) {
super.addDebugInfo(debugInfo);
debugInfo.add("altquerystring", altUserQuery);
if (null != boostQueries) {
debugInfo.add("boost_queries", boostParams);
debugInfo.add("parsed_boost_queries", QueryParsing.toString(boostQueries, req.getSchema()));
}
debugInfo.add("boostfuncs", req.getParams().getParams(DisMaxParams.BF));
}
}
| |
package io.nlopez.smartlocation.geocoding.providers;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import io.nlopez.smartlocation.OnGeocodingListener;
import io.nlopez.smartlocation.OnReverseGeocodingListener;
import io.nlopez.smartlocation.geocoding.GeocodingProvider;
import io.nlopez.smartlocation.geocoding.utils.LocationAddress;
import io.nlopez.smartlocation.utils.Logger;
/**
* Geocoding provider based on Android's Geocoder class.
*/
public class AndroidGeocodingProvider implements GeocodingProvider {
private static final String BROADCAST_DIRECT_GEOCODING_ACTION = AndroidGeocodingProvider.class.getCanonicalName() + ".DIRECT_GEOCODE_ACTION";
private static final String BROADCAST_REVERSE_GEOCODING_ACTION = AndroidGeocodingProvider.class.getCanonicalName() + ".REVERSE_GEOCODE_ACTION";
private static final String DIRECT_GEOCODING_ID = "direct";
private static final String REVERSE_GEOCODING_ID = "reverse";
private static final String LOCALE_ID = "locale";
private static final String NAME_ID = "name";
private static final String LOCATION_ID = "location";
private static final String RESULT_ID = "result";
private Locale locale;
private OnGeocodingListener geocodingListener;
private OnReverseGeocodingListener reverseGeocodingListener;
private HashMap<String, Integer> fromNameList;
private HashMap<Location, Integer> fromLocationList;
private Context context;
private Logger logger;
private BroadcastReceiver directReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BROADCAST_DIRECT_GEOCODING_ACTION.equals(intent.getAction())) {
logger.d("sending new direct geocoding response");
if (geocodingListener != null) {
final String name = intent.getStringExtra(NAME_ID);
final ArrayList<LocationAddress> results = intent.getParcelableArrayListExtra(RESULT_ID);
geocodingListener.onLocationResolved(name, results);
}
}
}
};
private BroadcastReceiver reverseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BROADCAST_REVERSE_GEOCODING_ACTION.equals(intent.getAction())) {
logger.d("sending new reverse geocoding response");
if (reverseGeocodingListener != null) {
final Location location = intent.getParcelableExtra(LOCATION_ID);
final ArrayList<Address> results = (ArrayList<Address>) intent.getSerializableExtra(RESULT_ID);
reverseGeocodingListener.onAddressResolved(location, results);
}
}
}
};
public AndroidGeocodingProvider() {
this(Locale.getDefault());
}
public AndroidGeocodingProvider(Locale locale) {
if (locale == null) {
// This should be super weird
throw new RuntimeException("Locale is null");
}
this.locale = locale;
fromNameList = new HashMap<>();
fromLocationList = new HashMap<>();
if (!Geocoder.isPresent()) {
throw new RuntimeException("Android Geocoder not present. Please check if Geocoder.isPresent() before invoking the search");
}
}
@Override
public void init(Context context, Logger logger) {
this.logger = logger;
this.context = context;
}
@Override
public void addName(String name, int maxResults) {
fromNameList.put(name, maxResults);
}
@Override
public void addLocation(Location location, int maxResults) {
fromLocationList.put(location, maxResults);
}
@Override
public void start(OnGeocodingListener geocodingListener, OnReverseGeocodingListener reverseGeocodingListener) {
this.geocodingListener = geocodingListener;
this.reverseGeocodingListener = reverseGeocodingListener;
if (fromNameList.isEmpty() && fromLocationList.isEmpty()) {
logger.w("No direct geocoding or reverse geocoding points added");
} else {
// Registering receivers for both possibilities
final IntentFilter directFilter = new IntentFilter(BROADCAST_DIRECT_GEOCODING_ACTION);
final IntentFilter reverseFilter = new IntentFilter(BROADCAST_REVERSE_GEOCODING_ACTION);
// Launch service for processing the geocoder stuff in a background thread
final Intent serviceIntent = new Intent(context, AndroidGeocodingService.class);
serviceIntent.putExtra(LOCALE_ID, locale);
if (!fromNameList.isEmpty()) {
context.registerReceiver(directReceiver, directFilter);
serviceIntent.putExtra(DIRECT_GEOCODING_ID, fromNameList);
}
if (!fromLocationList.isEmpty()) {
context.registerReceiver(reverseReceiver, reverseFilter);
serviceIntent.putExtra(REVERSE_GEOCODING_ID, fromLocationList);
}
context.startService(serviceIntent);
// Clear hashmaps so they don't stay added for next invocations
fromNameList.clear();
fromLocationList.clear();
}
}
@Override
public void stop() {
try {
context.unregisterReceiver(directReceiver);
} catch (IllegalArgumentException e) {
logger.d("Silenced 'receiver not registered' stuff (calling stop more times than necessary did this)");
}
try {
context.unregisterReceiver(reverseReceiver);
} catch (IllegalArgumentException e) {
logger.d("Silenced 'receiver not registered' stuff (calling stop more times than necessary did this)");
}
}
public static class AndroidGeocodingService extends IntentService {
private Geocoder geocoder;
public AndroidGeocodingService() {
super(AndroidGeocodingService.class.getSimpleName());
}
@Override
protected void onHandleIntent(Intent intent) {
final Locale locale = (Locale) intent.getSerializableExtra(LOCALE_ID);
if (locale == null) {
geocoder = new Geocoder(this);
} else {
geocoder = new Geocoder(this, locale);
}
if (intent.hasExtra(DIRECT_GEOCODING_ID)) {
final HashMap<String, Integer> nameList = (HashMap<String, Integer>) intent.getSerializableExtra(DIRECT_GEOCODING_ID);
for (String name : nameList.keySet()) {
int maxResults = nameList.get(name);
final ArrayList<LocationAddress> response = addressFromName(name, maxResults);
sendDirectGeocodingBroadcast(name, response);
}
}
if (intent.hasExtra(REVERSE_GEOCODING_ID)) {
final HashMap<Location, Integer> locationList = (HashMap<Location, Integer>) intent.getSerializableExtra(REVERSE_GEOCODING_ID);
for (Location location : locationList.keySet()) {
int maxResults = locationList.get(location);
final ArrayList<Address> response = addressFromLocation(location, maxResults);
sendReverseGeocodingBroadcast(location, response);
}
}
}
private void sendDirectGeocodingBroadcast(String name, ArrayList<LocationAddress> results) {
final Intent directIntent = new Intent(BROADCAST_DIRECT_GEOCODING_ACTION);
directIntent.putExtra(NAME_ID, name);
directIntent.putExtra(RESULT_ID, results);
sendBroadcast(directIntent);
}
private void sendReverseGeocodingBroadcast(Location location, ArrayList<Address> results) {
final Intent reverseIntent = new Intent(BROADCAST_REVERSE_GEOCODING_ACTION);
reverseIntent.putExtra(LOCATION_ID, location);
reverseIntent.putExtra(RESULT_ID, results);
sendBroadcast(reverseIntent);
}
private ArrayList<Address> addressFromLocation(Location location, int maxResults) {
try {
return new ArrayList<>(geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), maxResults));
} catch (IOException ignored) {
}
return new ArrayList<>();
}
private ArrayList<LocationAddress> addressFromName(String name, int maxResults) {
try {
final List<Address> addresses = geocoder.getFromLocationName(name, maxResults);
final ArrayList<LocationAddress> result = new ArrayList<>();
for (Address address : addresses) {
result.add(new LocationAddress(address));
}
return result;
} catch (IOException ignored) {
}
return new ArrayList<>();
}
}
}
| |
/*
* Copyright (C) 2012 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.argon.foto.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import com.argon.foto.BuildConfig;
import com.argon.foto.R;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A simple subclass of {@link ImageResizer} that fetches and resizes images fetched from a URL.
*/
public class ImageFetcher extends ImageResizer {
private static final String TAG = "ImageFetcher";
private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB
private static final String HTTP_CACHE_DIR = "http";
private static final int IO_BUFFER_SIZE = 8 * 1024;
private DiskLruCache mHttpDiskCache;
private File mHttpCacheDir;
private boolean mHttpDiskCacheStarting = true;
private final Object mHttpDiskCacheLock = new Object();
private static final int DISK_CACHE_INDEX = 0;
/**
* Initialize providing a target image width and height for the processing images.
*
* @param context
* @param imageWidth
* @param imageHeight
*/
public ImageFetcher(Context context, int imageWidth, int imageHeight) {
super(context, imageWidth, imageHeight);
init(context);
}
/**
* Initialize providing a single target image size (used for both width and height);
*
* @param context
* @param imageSize
*/
public ImageFetcher(Context context, int imageSize) {
super(context, imageSize);
init(context);
}
private void init(Context context) {
checkConnection(context);
mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR);
}
@Override
protected void initDiskCacheInternal() {
super.initDiskCacheInternal();
initHttpDiskCache();
}
private void initHttpDiskCache() {
if (!mHttpCacheDir.exists()) {
mHttpCacheDir.mkdirs();
}
synchronized (mHttpDiskCacheLock) {
if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) {
try {
mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE);
if (BuildConfig.DEBUG) {
Log.d(TAG, "HTTP cache initialized");
}
} catch (IOException e) {
mHttpDiskCache = null;
}
}
mHttpDiskCacheStarting = false;
mHttpDiskCacheLock.notifyAll();
}
}
@Override
protected void clearCacheInternal() {
super.clearCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) {
try {
mHttpDiskCache.delete();
if (BuildConfig.DEBUG) {
Log.d(TAG, "HTTP cache cleared");
}
} catch (IOException e) {
Log.e(TAG, "clearCacheInternal - " + e);
}
mHttpDiskCache = null;
mHttpDiskCacheStarting = true;
initHttpDiskCache();
}
}
}
@Override
protected void flushCacheInternal() {
super.flushCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
mHttpDiskCache.flush();
if (BuildConfig.DEBUG) {
Log.d(TAG, "HTTP cache flushed");
}
} catch (IOException e) {
Log.e(TAG, "flush - " + e);
}
}
}
}
@Override
protected void closeCacheInternal() {
super.closeCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
if (!mHttpDiskCache.isClosed()) {
mHttpDiskCache.close();
mHttpDiskCache = null;
if (BuildConfig.DEBUG) {
Log.d(TAG, "HTTP cache closed");
}
}
} catch (IOException e) {
Log.e(TAG, "closeCacheInternal - " + e);
}
}
}
}
/**
* Simple network connection check.
*
* @param context
*/
private void checkConnection(Context context) {
final ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
Toast.makeText(context, R.string.no_network_connection_toast, Toast.LENGTH_LONG).show();
Log.e(TAG, "checkConnection - no connection found");
}
}
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* @param data The data to load the bitmap, in this case, a regular http URL
* @return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String data) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap - " + data);
}
final String key = ImageCache.hashKeyForDisk(data);
FileDescriptor fileDescriptor = null;
FileInputStream fileInputStream = null;
DiskLruCache.Snapshot snapshot;
synchronized (mHttpDiskCacheLock) {
// Wait for disk cache to initialize
while (mHttpDiskCacheStarting) {
try {
mHttpDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mHttpDiskCache != null) {
try {
snapshot = mHttpDiskCache.get(key);
if (snapshot == null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap, not found in http cache, downloading...");
}
DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
if (editor != null) {
if (downloadUrlToStream(data,
editor.newOutputStream(DISK_CACHE_INDEX))) {
editor.commit();
} else {
editor.abort();
}
}
snapshot = mHttpDiskCache.get(key);
}
if (snapshot != null) {
fileInputStream =
(FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
fileDescriptor = fileInputStream.getFD();
}
} catch (IOException e) {
Log.e(TAG, "processBitmap - " + e);
} catch (IllegalStateException e) {
Log.e(TAG, "processBitmap - " + e);
} finally {
if (fileDescriptor == null && fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
}
}
}
Bitmap bitmap = null;
if (fileDescriptor != null) {
bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth,
mImageHeight, getImageCache());
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
return bitmap;
}
@Override
protected Bitmap processBitmap(Object data) {
return processBitmap(String.valueOf(data));
}
/**
* Download a bitmap from a URL and write the content to an output stream.
*
* @param urlString The URL to fetch
* @return true if successful, false otherwise
*/
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
Log.e(TAG, "Error in downloadBitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {}
}
return false;
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
}
| |
package com.jdroid.java.http.mock;
import com.jdroid.java.collections.Maps;
import com.jdroid.java.concurrent.ExecutorUtils;
import com.jdroid.java.exception.UnexpectedException;
import com.jdroid.java.http.HttpResponseWrapper;
import com.jdroid.java.http.HttpServiceProcessor;
import com.jdroid.java.http.MultipartHttpService;
import com.jdroid.java.http.HttpService;
import com.jdroid.java.http.post.BodyEnclosingHttpService;
import com.jdroid.java.http.parser.Parser;
import com.jdroid.java.utils.FileUtils;
import com.jdroid.java.utils.LoggerUtils;
import com.jdroid.java.utils.StringUtils;
import org.slf4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
/**
* Mocked {@link HttpService} and {@link BodyEnclosingHttpService} implementation that returns mocked responses
*/
public abstract class AbstractMockHttpService implements MultipartHttpService {
private static final Logger LOGGER = LoggerUtils.getLogger(AbstractMockHttpService.class);
private static final String MOCK_SEPARATOR = "_";
private static final String SUFFIX_SEPARATOR = "-";
private static final String URL_SEPARATOR = "/";
private Object[] urlSegments;
private Map<String, String> parameters = Maps.newHashMap();
private Map<String, String> headers = Maps.newHashMap();
private String body;
public AbstractMockHttpService(Object... urlSegments) {
this.urlSegments = urlSegments;
}
/**
* @see HttpService#execute(Parser)
*/
@SuppressWarnings({ "unchecked", "resource" })
@Override
public <T> T execute(Parser parser) {
String filePath = generateMockFilePath(urlSegments);
LOGGER.warn("Request: " + filePath);
if (!parameters.isEmpty()) {
LOGGER.warn("Parameters: " + parameters.toString());
}
if (!headers.isEmpty()) {
LOGGER.warn("Headers: " + headers.toString());
}
if (StringUtils.isNotBlank(body)) {
LOGGER.warn("HTTP Entity Body: " + body);
}
Integer httpMockSleep = getHttpMockSleepDuration(urlSegments);
if ((httpMockSleep != null) && (httpMockSleep > 0)) {
ExecutorUtils.sleep(httpMockSleep);
}
simulateCrash();
if (parser != null) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
if (inputStream == null) {
throw new UnexpectedException("The mocked file wasn't found");
}
// Parse the stream
T t = (T)(parser.parse(inputStream));
FileUtils.safeClose(inputStream);
return t;
} else {
return null;
}
}
/**
* @see HttpService#execute()
*/
@SuppressWarnings("unchecked")
@Override
public <T> T execute() {
return (T)execute(null);
}
protected void simulateCrash() {
// Do nothing by default
}
/**
* @see HttpService#addHeader(java.lang.String, java.lang.String)
*/
@Override
public void addHeader(String name, String value) {
if (value != null) {
headers.put(name, value);
}
}
/**
* @see HttpService#addQueryParameter(java.lang.String, java.lang.Object)
*/
@Override
public void addQueryParameter(String name, Object value) {
if (value != null) {
parameters.put(name, value.toString());
}
}
/**
* @see HttpService#addQueryParameter(java.lang.String, java.util.Collection)
*/
@Override
public void addQueryParameter(String name, Collection<?> values) {
addQueryParameter(name, StringUtils.join(values));
}
/**
* @see MultipartHttpService#addPart(java.lang.String, java.io.ByteArrayInputStream,
* java.lang.String, java.lang.String)
*/
@Override
public void addPart(String name, ByteArrayInputStream in, String mimeType, String filename) {
// Do Nothing
}
/**
* @see MultipartHttpService#addPart(java.lang.String, java.lang.Object, java.lang.String)
*/
@Override
public void addPart(String name, Object value, String mimeType) {
// Do Nothing
}
/**
* @see MultipartHttpService#addJsonPart(java.lang.String, java.lang.Object)
*/
@Override
public void addJsonPart(String name, Object value) {
// Do Nothing
}
/**
* @see HttpService#addUrlSegment(java.lang.Object)
*/
@Override
public void addUrlSegment(Object segment) {
// Do Nothing
}
/**
* @see HttpService#addHttpServiceProcessor(HttpServiceProcessor)
*/
@Override
public void addHttpServiceProcessor(HttpServiceProcessor httpServiceProcessor) {
// Do Nothing
}
/**
* @see BodyEnclosingHttpService#setBody(String)
*/
@Override
public void setBody(String body) {
this.body = body;
}
/**
* @see HttpService#setConnectionTimeout(java.lang.Integer)
*/
@Override
public void setConnectionTimeout(Integer connectionTimeout) {
// Do Nothing
}
@Override
public void setReadTimeout(Integer readTimeout) {
// Do Nothing
}
/**
* @see HttpService#setUserAgent(java.lang.String)
*/
@Override
public void setUserAgent(String userAgent) {
// Do Nothing
}
/**
* @see HttpService#setSsl(java.lang.Boolean)
*/
@Override
public void setSsl(Boolean ssl) {
// Do Nothing
}
/**
* @return The time to sleep (in seconds) to simulate the execution of the request
*/
protected abstract Integer getHttpMockSleepDuration(Object... urlSegments);
/**
* @see HttpService#getUrl()
*/
@Override
public String getUrl() {
return generateMockFilePath(urlSegments);
}
/**
* @see HttpService#getUrlSuffix()
*/
@Override
public String getUrlSuffix() {
return null;
}
protected String generateMockFilePath(Object... urlSegments) {
StringBuilder sb = new StringBuilder(getMocksBasePath());
if (urlSegments != null) {
for (Object urlSegment : urlSegments) {
sb.append(urlSegment.toString().replaceAll(URL_SEPARATOR, MOCK_SEPARATOR));
sb.append(MOCK_SEPARATOR);
}
}
sb.deleteCharAt(sb.length() - 1);
String suffix = getSuffix(sb.toString());
if (StringUtils.isNotBlank(suffix)) {
sb.append(SUFFIX_SEPARATOR);
sb.append(suffix);
}
sb.append(getMocksExtension());
return sb.toString();
}
/**
* @return The mocks base path
*/
protected abstract String getMocksBasePath();
/**
* @return The mocks extension
*/
protected abstract String getMocksExtension();
/**
* @return The suffix to add to the mock file
*/
protected String getSuffix(String path) {
return null;
}
@Override
public String getHeaderValue(String key) {
return headers.get(key);
}
@Override
public HttpResponseWrapper getHttpResponseWrapper() {
return null;
}
}
| |
/*
* MIT License
*
* Copyright (c) 2016 EPAM Systems
*
* 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 com.epam.catgenome.dao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.epam.catgenome.dao.gene.GeneFileDao;
import com.epam.catgenome.helper.EntityHelper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.epam.catgenome.dao.reference.ReferenceGenomeDao;
import com.epam.catgenome.entity.BiologicalDataItem;
import com.epam.catgenome.entity.BiologicalDataItemFormat;
import com.epam.catgenome.entity.BiologicalDataItemResourceType;
import com.epam.catgenome.entity.gene.GeneFile;
import com.epam.catgenome.entity.reference.Reference;
import com.epam.catgenome.manager.gene.GeneFileManager;
/**
* Source: BiologicalDataItemDaoTest
* Created: 17.12.15, 14:05
* Project: CATGenome Browser
* Make: IntelliJ IDEA 14.1.4, JDK 1.8
*
* @author Mikhail Miroliubov
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext-test.xml"})
public class BiologicalDataItemDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
private static final String TEST_OWNER = "TEST_USER";
@Autowired
private BiologicalDataItemDao biologicalDataItemDao;
@Autowired
private ReferenceGenomeDao referenceGenomeDao;
@Autowired
private GeneFileManager geneFileManager;
@Autowired
private GeneFileDao geneFileDao;
private static final String TEST_NAME = "test1";
private static final String TEST_PATH = "///";
private static final List<String> MATCHING_NAMES = new ArrayList<String>(){{
add("test1");
add("est");
add("TEST");
}};
private static final List<String> NOT_MATCHING_NAMES = new ArrayList<String>(){{
add("tst11");
add("tsT");
add("SET");
}};
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSaveAndLoadItems() {
BiologicalDataItem item = new BiologicalDataItem();
item.setName(TEST_NAME);
item.setPath(TEST_PATH);
item.setSource(TEST_PATH);
item.setFormat(BiologicalDataItemFormat.REFERENCE);
item.setType(BiologicalDataItemResourceType.FILE);
item.setCreatedDate(new Date());
item.setOwner(TEST_OWNER);
biologicalDataItemDao.createBiologicalDataItem(item);
Reference reference = createTestReference(item);
GeneFile geneFile = createTestGeneFile(reference);
referenceGenomeDao.updateReferenceGeneFileId(reference.getId(), geneFile.getId());
List<BiologicalDataItem> loadedItems = biologicalDataItemDao.loadBiologicalDataItemsByIds(Collections
.singletonList(item.getId()));
Assert.assertFalse(loadedItems.isEmpty());
BiologicalDataItem loadedItem = loadedItems.get(0);
Assert.assertEquals(item.getId(), BiologicalDataItem.getBioDataItemId(loadedItem));
Assert.assertEquals(item.getName(), loadedItem.getName());
Assert.assertEquals(item.getPath(), loadedItem.getPath());
Assert.assertEquals(item.getSource(), loadedItem.getPath());
Assert.assertEquals(item.getCreatedDate(), loadedItem.getCreatedDate());
Assert.assertEquals(item.getType(), loadedItem.getType());
Assert.assertEquals(item.getFormat(), loadedItem.getFormat());
Assert.assertEquals(item.getOwner(), loadedItem.getOwner());
}
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSearchStrict() {
BiologicalDataItem item = new BiologicalDataItem();
item.setName(TEST_NAME);
item.setPath(TEST_PATH);
item.setSource(TEST_PATH);
item.setFormat(BiologicalDataItemFormat.REFERENCE);
item.setType(BiologicalDataItemResourceType.FILE);
item.setCreatedDate(new Date());
item.setOwner(TEST_OWNER);
biologicalDataItemDao.createBiologicalDataItem(item);
Reference reference = createTestReference(item);
GeneFile geneFile = createTestGeneFile(reference);
referenceGenomeDao.updateReferenceGeneFileId(reference.getId(), geneFile.getId());
List<BiologicalDataItem> loadedItems = biologicalDataItemDao.loadFilesByNameStrict(TEST_NAME);
Assert.assertFalse(loadedItems.isEmpty());
BiologicalDataItem loadedItem = loadedItems.get(0);
Assert.assertEquals(item.getId(), BiologicalDataItem.getBioDataItemId(loadedItem));
Assert.assertEquals(item.getName(), loadedItem.getName());
Assert.assertEquals(item.getPath(), loadedItem.getPath());
Assert.assertEquals(item.getSource(), loadedItem.getPath());
Assert.assertEquals(item.getCreatedDate(), loadedItem.getCreatedDate());
Assert.assertEquals(item.getType(), loadedItem.getType());
Assert.assertEquals(item.getFormat(), loadedItem.getFormat());
List<BiologicalDataItem> empty = biologicalDataItemDao.loadFilesByNameStrict(TEST_NAME + "/");
Assert.assertTrue(empty.isEmpty());
}
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSearchNotStrict() {
BiologicalDataItem item = new BiologicalDataItem();
item.setName(TEST_NAME);
item.setPath(TEST_PATH);
item.setSource(TEST_PATH);
item.setFormat(BiologicalDataItemFormat.REFERENCE);
item.setType(BiologicalDataItemResourceType.FILE);
item.setCreatedDate(new Date());
item.setOwner(TEST_OWNER);
biologicalDataItemDao.createBiologicalDataItem(item);
Reference reference = createTestReference(item);
GeneFile geneFile = createTestGeneFile(reference);
referenceGenomeDao.updateReferenceGeneFileId(reference.getId(), geneFile.getId());
for (final String match : MATCHING_NAMES) {
List<BiologicalDataItem> loadedItems = biologicalDataItemDao.loadFilesByName(match);
Assert.assertFalse(loadedItems.isEmpty());
}
for (final String notMatch : NOT_MATCHING_NAMES) {
List<BiologicalDataItem> empty = biologicalDataItemDao.loadFilesByNameStrict(notMatch);
Assert.assertTrue(empty.isEmpty());
}
}
private Reference createTestReference(BiologicalDataItem item) {
Reference reference = new Reference();
reference.setSize(1L);
reference.setName("testReference");
reference.setPath(TEST_PATH);
reference.setSource(TEST_PATH);
reference.setType(BiologicalDataItemResourceType.FILE);
reference.setId(item.getId());
reference.setCreatedDate(new Date());
reference.setBioDataItemId(item.getId());
reference.setIndex(EntityHelper.createIndex(BiologicalDataItemFormat.REFERENCE_INDEX,
BiologicalDataItemResourceType.FILE, ""));
biologicalDataItemDao.createBiologicalDataItem(reference.getIndex());
return referenceGenomeDao.createReferenceGenome(reference, referenceGenomeDao.createReferenceGenomeId());
}
private GeneFile createTestGeneFile(Reference reference) {
BiologicalDataItem indexItem = new BiologicalDataItem();
indexItem.setCreatedDate(new Date());
indexItem.setPath(TEST_PATH);
indexItem.setSource(TEST_PATH);
indexItem.setFormat(BiologicalDataItemFormat.GENE_INDEX);
indexItem.setType(BiologicalDataItemResourceType.FILE);
indexItem.setName("");
indexItem.setOwner(TEST_OWNER);
biologicalDataItemDao.createBiologicalDataItem(indexItem);
GeneFile geneFile = new GeneFile();
geneFile.setId(geneFileManager.createGeneFileId());
geneFile.setName("testGeneFile");
geneFile.setCompressed(false);
geneFile.setPath(TEST_PATH);
geneFile.setSource(TEST_PATH);
geneFile.setType(BiologicalDataItemResourceType.FILE); // For now we're working only with files
geneFile.setCreatedDate(new Date());
geneFile.setReferenceId(reference.getId());
geneFile.setIndex(indexItem);
geneFile.setOwner(TEST_OWNER);
long id = geneFile.getId();
biologicalDataItemDao.createBiologicalDataItem(geneFile);
geneFileDao.createGeneFile(geneFile, id);
return geneFile;
}
}
| |
/**
* Copyright 2014 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arpnetworking.configuration;
import com.google.common.base.Optional;
import java.lang.reflect.Type;
import java.util.NoSuchElementException;
/**
* Interface for classes which provide configuration.
*
* @author Ville Koskela (vkoskela at groupon dot com)
*/
public interface Configuration {
/**
* Retrieve the value of a particular property by its name.
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
*/
Optional<String> getProperty(final String name);
/**
* Retrieve the value of a particular property by its name and if it does
* not exist return the specified default.
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
*/
String getProperty(final String name, final String defaultValue);
/**
* Retrieve the value of a particular property by its name and if it does
* not exist throw a <code>RuntimeException</code>.
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
*/
String getRequiredProperty(final String name) throws NoSuchElementException;
/**
* <code>Boolean</code> specific accessor. Anything other than "true",
* ignoring case, is treated as <code>false</code>.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
*/
Optional<Boolean> getPropertyAsBoolean(final String name);
/**
* <code>Boolean</code> specific accessor. Anything other than "true",
* ignoring case, is treated as <code>false</code>.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
*/
boolean getPropertyAsBoolean(final String name, final boolean defaultValue);
/**
* <code>Boolean</code> specific accessor. Anything other than "true",
* ignoring case, is treated as <code>false</code>.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
*/
boolean getRequiredPropertyAsBoolean(final String name) throws NoSuchElementException;
/**
* <code>Integer</code> specific accessor.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to an
* <code>Integer</code>.
*/
Optional<Integer> getPropertyAsInteger(final String name) throws NumberFormatException;
/**
* <code>Integer</code> specific accessor.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to an
* <code>Integer</code>.
*/
int getPropertyAsInteger(final String name, final int defaultValue) throws NumberFormatException;
/**
* <code>Integer</code> specific accessor.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws NumberFormatException if the value cannot be converted to an
* <code>Integer</code>.
*/
int getRequiredPropertyAsInteger(final String name) throws NoSuchElementException, NumberFormatException;
/**
* <code>Long</code> specific accessor.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Long</code>.
*/
Optional<Long> getPropertyAsLong(final String name) throws NumberFormatException;
/**
* <code>Long</code> specific accessor.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Long</code>.
*/
long getPropertyAsLong(final String name, final long defaultValue) throws NumberFormatException;
/**
* <code>Long</code> specific accessor.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Long</code>.
*/
long getRequiredPropertyAsLong(final String name) throws NoSuchElementException, NumberFormatException;
/**
* <code>Double</code> specific accessor.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Double</code>.
*/
Optional<Double> getPropertyAsDouble(final String name) throws NumberFormatException;
/**
* <code>Double</code> specific accessor.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Double</code>.
*/
double getPropertyAsDouble(final String name, final double defaultValue) throws NumberFormatException;
/**
* <code>Double</code> specific accessor.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Double</code>.
*/
double getRequiredPropertyAsDouble(final String name) throws NoSuchElementException, NumberFormatException;
/**
* <code>Float</code> specific accessor.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Float</code>.
*/
Optional<Float> getPropertyAsFloat(final String name) throws NumberFormatException;
/**
* <code>Float</code> specific accessor.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Float</code>.
*/
float getPropertyAsFloat(final String name, final float defaultValue) throws NumberFormatException;
/**
* <code>Float</code> specific accessor.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Float</code>.
*/
float getRequiredPropertyAsFloat(final String name) throws NoSuchElementException, NumberFormatException;
/**
* <code>Short</code> specific accessor.
*
* @see Configuration#getProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Short</code>.
*/
Optional<Short> getPropertyAsShort(final String name) throws NumberFormatException;
/**
* <code>Short</code> specific accessor.
*
* @see Configuration#getProperty(String, String)
*
* @param name The name of the property value to retrieve.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>defaultValue</code> if
* the property name has not been defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Short</code>.
*/
short getPropertyAsShort(final String name, final short defaultValue) throws NumberFormatException;
/**
* <code>Short</code> specific accessor.
*
* @see Configuration#getRequiredProperty(String)
*
* @param name The name of the property value to retrieve.
* @return Returns the property value.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws NumberFormatException if the value cannot be converted to a
* <code>Short</code>.
*/
short getRequiredPropertyAsShort(final String name) throws NoSuchElementException, NumberFormatException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param clazz The type of the object to instantiate.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> Optional<T> getPropertyAs(final String name, final Class<? extends T> clazz) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param clazz The type of the object to instantiate.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getPropertyAs(final String name, final Class<? extends T> clazz, final T defaultValue) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param clazz The type of the object to instantiate.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getRequiredPropertyAs(final String name, final Class<? extends T> clazz) throws NoSuchElementException, IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param clazz The type of the object to instantiate.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> Optional<T> getAs(final Class<? extends T> clazz) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @see Configuration#getProperty(String)
*
* @param <T> The type to return.
* @param clazz The type of the object to instantiate.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getAs(final Class<? extends T> clazz, final T defaultValue) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param clazz The type of the object to instantiate.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the configuration is not available.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getRequiredAs(final Class<? extends T> clazz) throws NoSuchElementException, IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param type The type of the object to instantiate.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> Optional<T> getPropertyAs(final String name, final Type type) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param type The type of the object to instantiate.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getPropertyAs(final String name, final Type type, final T defaultValue) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param name The name of the property value to retrieve.
* @param type The type of the object to instantiate.
* @return Returns the property value or <code>Optional.absent</code> if
* the property name has not been defined.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the specified property name is not defined.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getRequiredPropertyAs(final String name, final Type type) throws NoSuchElementException, IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param type The type of the object to instantiate.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> Optional<T> getAs(final Type type) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @see Configuration#getProperty(String)
*
* @param <T> The type to return.
* @param type The type of the object to instantiate.
* @param defaultValue The value to return if the specified property name
* does not exist in the configuration.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getAs(final Type type, final T defaultValue) throws IllegalArgumentException;
/**
* Generic object accessor.
*
* @param <T> The type to return.
* @param type The type of the object to instantiate.
* @return Returns the entire configuration as an instance of <code>T</code>.
* @throws NoSuchElementException throws the <code>RuntimeException</code>
* if the configuration is not available.
* @throws IllegalArgumentException if the value cannot be converted to an
* instance of <code>T</code>.
*/
<T> T getRequiredAs(final Type type) throws NoSuchElementException, IllegalArgumentException;
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster.metadata;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest;
import org.elasticsearch.cluster.AckedClusterStateUpdateTask;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData.*;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.indices.*;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.threadpool.ThreadPool;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
/**
* Service responsible for submitting create index requests
*/
public class MetaDataCreateIndexService extends AbstractComponent {
public final static int MAX_INDEX_NAME_BYTES = 255;
private static final DefaultIndexTemplateFilter DEFAULT_INDEX_TEMPLATE_FILTER = new DefaultIndexTemplateFilter();
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final IndicesService indicesService;
private final AllocationService allocationService;
private final MetaDataService metaDataService;
private final Version version;
private final AliasValidator aliasValidator;
private final IndexTemplateFilter indexTemplateFilter;
private final NodeEnvironment nodeEnv;
@Inject
public MetaDataCreateIndexService(Settings settings, ThreadPool threadPool, ClusterService clusterService,
IndicesService indicesService, AllocationService allocationService, MetaDataService metaDataService,
Version version, AliasValidator aliasValidator,
Set<IndexTemplateFilter> indexTemplateFilters, NodeEnvironment nodeEnv) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.indicesService = indicesService;
this.allocationService = allocationService;
this.metaDataService = metaDataService;
this.version = version;
this.aliasValidator = aliasValidator;
this.nodeEnv = nodeEnv;
if (indexTemplateFilters.isEmpty()) {
this.indexTemplateFilter = DEFAULT_INDEX_TEMPLATE_FILTER;
} else {
IndexTemplateFilter[] templateFilters = new IndexTemplateFilter[indexTemplateFilters.size() + 1];
templateFilters[0] = DEFAULT_INDEX_TEMPLATE_FILTER;
int i = 1;
for (IndexTemplateFilter indexTemplateFilter : indexTemplateFilters) {
templateFilters[i++] = indexTemplateFilter;
}
this.indexTemplateFilter = new IndexTemplateFilter.Compound(templateFilters);
}
}
public void createIndex(final CreateIndexClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {
// we lock here, and not within the cluster service callback since we don't want to
// block the whole cluster state handling
final Semaphore mdLock = metaDataService.indexMetaDataLock(request.index());
// quick check to see if we can acquire a lock, otherwise spawn to a thread pool
if (mdLock.tryAcquire()) {
createIndex(request, listener, mdLock);
return;
}
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new ActionRunnable(listener) {
@Override
public void doRun() throws InterruptedException {
if (!mdLock.tryAcquire(request.masterNodeTimeout().nanos(), TimeUnit.NANOSECONDS)) {
listener.onFailure(new ProcessClusterEventTimeoutException(request.masterNodeTimeout(), "acquire index lock"));
return;
}
createIndex(request, listener, mdLock);
}
});
}
public void validateIndexName(String index, ClusterState state) {
if (state.routingTable().hasIndex(index)) {
throw new IndexAlreadyExistsException(new Index(index));
}
if (state.metaData().hasIndex(index)) {
throw new IndexAlreadyExistsException(new Index(index));
}
if (!Strings.validFileName(index)) {
throw new InvalidIndexNameException(new Index(index), index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
}
if (index.contains("#")) {
throw new InvalidIndexNameException(new Index(index), index, "must not contain '#'");
}
if (index.charAt(0) == '_') {
throw new InvalidIndexNameException(new Index(index), index, "must not start with '_'");
}
if (!index.toLowerCase(Locale.ROOT).equals(index)) {
throw new InvalidIndexNameException(new Index(index), index, "must be lowercase");
}
int byteCount = 0;
try {
byteCount = index.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
// UTF-8 should always be supported, but rethrow this if it is not for some reason
throw new ElasticsearchException("Unable to determine length of index name", e);
}
if (byteCount > MAX_INDEX_NAME_BYTES) {
throw new InvalidIndexNameException(new Index(index), index,
"index name is too long, (" + byteCount +
" > " + MAX_INDEX_NAME_BYTES + ")");
}
if (state.metaData().hasAlias(index)) {
throw new InvalidIndexNameException(new Index(index), index, "already exists as alias");
}
}
private void createIndex(final CreateIndexClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener, final Semaphore mdLock) {
Settings.Builder updatedSettingsBuilder = Settings.settingsBuilder();
updatedSettingsBuilder.put(request.settings()).normalizePrefix(IndexMetaData.INDEX_SETTING_PREFIX);
request.settings(updatedSettingsBuilder.build());
clusterService.submitStateUpdateTask("create-index [" + request.index() + "], cause [" + request.cause() + "]", Priority.URGENT, new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(request, listener) {
@Override
protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
return new ClusterStateUpdateResponse(acknowledged);
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
mdLock.release();
super.onAllNodesAcked(t);
}
@Override
public void onAckTimeout() {
mdLock.release();
super.onAckTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
mdLock.release();
super.onFailure(source, t);
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
boolean indexCreated = false;
String removalReason = null;
try {
validate(request, currentState);
for (Alias alias : request.aliases()) {
aliasValidator.validateAlias(alias, request.index(), currentState.metaData());
}
// we only find a template when its an API call (a new index)
// find templates, highest order are better matching
List<IndexTemplateMetaData> templates = findTemplates(request, currentState, indexTemplateFilter);
Map<String, Custom> customs = Maps.newHashMap();
// add the request mapping
Map<String, Map<String, Object>> mappings = Maps.newHashMap();
Map<String, AliasMetaData> templatesAliases = Maps.newHashMap();
List<String> templateNames = Lists.newArrayList();
for (Map.Entry<String, String> entry : request.mappings().entrySet()) {
mappings.put(entry.getKey(), parseMapping(entry.getValue()));
}
for (Map.Entry<String, Custom> entry : request.customs().entrySet()) {
customs.put(entry.getKey(), entry.getValue());
}
// apply templates, merging the mappings into the request mapping if exists
for (IndexTemplateMetaData template : templates) {
templateNames.add(template.getName());
for (ObjectObjectCursor<String, CompressedXContent> cursor : template.mappings()) {
if (mappings.containsKey(cursor.key)) {
XContentHelper.mergeDefaults(mappings.get(cursor.key), parseMapping(cursor.value.string()));
} else {
mappings.put(cursor.key, parseMapping(cursor.value.string()));
}
}
// handle custom
for (ObjectObjectCursor<String, Custom> cursor : template.customs()) {
String type = cursor.key;
IndexMetaData.Custom custom = cursor.value;
IndexMetaData.Custom existing = customs.get(type);
if (existing == null) {
customs.put(type, custom);
} else {
IndexMetaData.Custom merged = existing.mergeWith(custom);
customs.put(type, merged);
}
}
//handle aliases
for (ObjectObjectCursor<String, AliasMetaData> cursor : template.aliases()) {
AliasMetaData aliasMetaData = cursor.value;
//if an alias with same name came with the create index request itself,
// ignore this one taken from the index template
if (request.aliases().contains(new Alias(aliasMetaData.alias()))) {
continue;
}
//if an alias with same name was already processed, ignore this one
if (templatesAliases.containsKey(cursor.key)) {
continue;
}
//Allow templatesAliases to be templated by replacing a token with the name of the index that we are applying it to
if (aliasMetaData.alias().contains("{index}")) {
String templatedAlias = aliasMetaData.alias().replace("{index}", request.index());
aliasMetaData = AliasMetaData.newAliasMetaData(aliasMetaData, templatedAlias);
}
aliasValidator.validateAliasMetaData(aliasMetaData, request.index(), currentState.metaData());
templatesAliases.put(aliasMetaData.alias(), aliasMetaData);
}
}
Settings.Builder indexSettingsBuilder = settingsBuilder();
// apply templates, here, in reverse order, since first ones are better matching
for (int i = templates.size() - 1; i >= 0; i--) {
indexSettingsBuilder.put(templates.get(i).settings());
}
// now, put the request settings, so they override templates
indexSettingsBuilder.put(request.settings());
if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 1));
} else {
if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
}
}
if (request.index().equals(ScriptService.SCRIPT_INDEX)) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 0));
indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, "0-all");
} else {
if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
}
}
if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS));
}
if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) {
DiscoveryNodes nodes = currentState.nodes();
final Version createdVersion = Version.smallest(version, nodes.smallestNonClientNodeVersion());
indexSettingsBuilder.put(SETTING_VERSION_CREATED, createdVersion);
}
if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) {
indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
}
indexSettingsBuilder.put(SETTING_INDEX_UUID, Strings.randomBase64UUID());
Settings actualIndexSettings = indexSettingsBuilder.build();
// Set up everything, now locally create the index to see that things are ok, and apply
// create the index here (on the master) to validate it can be created, as well as adding the mapping
indicesService.createIndex(request.index(), actualIndexSettings, clusterService.localNode().id());
indexCreated = true;
// now add the mappings
IndexService indexService = indicesService.indexServiceSafe(request.index());
MapperService mapperService = indexService.mapperService();
// first, add the default mapping
if (mappings.containsKey(MapperService.DEFAULT_MAPPING)) {
try {
mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedXContent(XContentFactory.jsonBuilder().map(mappings.get(MapperService.DEFAULT_MAPPING)).string()), false, request.updateAllTypes());
} catch (Exception e) {
removalReason = "failed on parsing default mapping on index creation";
throw new MapperParsingException("mapping [" + MapperService.DEFAULT_MAPPING + "]", e);
}
}
for (Map.Entry<String, Map<String, Object>> entry : mappings.entrySet()) {
if (entry.getKey().equals(MapperService.DEFAULT_MAPPING)) {
continue;
}
try {
// apply the default here, its the first time we parse it
mapperService.merge(entry.getKey(), new CompressedXContent(XContentFactory.jsonBuilder().map(entry.getValue()).string()), true, request.updateAllTypes());
} catch (Exception e) {
removalReason = "failed on parsing mappings on index creation";
throw new MapperParsingException("mapping [" + entry.getKey() + "]", e);
}
}
IndexQueryParserService indexQueryParserService = indexService.queryParserService();
for (Alias alias : request.aliases()) {
if (Strings.hasLength(alias.filter())) {
aliasValidator.validateAliasFilter(alias.name(), alias.filter(), indexQueryParserService);
}
}
for (AliasMetaData aliasMetaData : templatesAliases.values()) {
if (aliasMetaData.filter() != null) {
aliasValidator.validateAliasFilter(aliasMetaData.alias(), aliasMetaData.filter().uncompressed(), indexQueryParserService);
}
}
// now, update the mappings with the actual source
Map<String, MappingMetaData> mappingsMetaData = Maps.newHashMap();
for (DocumentMapper mapper : mapperService.docMappers(true)) {
MappingMetaData mappingMd = new MappingMetaData(mapper);
mappingsMetaData.put(mapper.type(), mappingMd);
}
final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings);
for (MappingMetaData mappingMd : mappingsMetaData.values()) {
indexMetaDataBuilder.putMapping(mappingMd);
}
for (AliasMetaData aliasMetaData : templatesAliases.values()) {
indexMetaDataBuilder.putAlias(aliasMetaData);
}
for (Alias alias : request.aliases()) {
AliasMetaData aliasMetaData = AliasMetaData.builder(alias.name()).filter(alias.filter())
.indexRouting(alias.indexRouting()).searchRouting(alias.searchRouting()).build();
indexMetaDataBuilder.putAlias(aliasMetaData);
}
for (Map.Entry<String, Custom> customEntry : customs.entrySet()) {
indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue());
}
indexMetaDataBuilder.state(request.state());
final IndexMetaData indexMetaData;
try {
indexMetaData = indexMetaDataBuilder.build();
} catch (Exception e) {
removalReason = "failed to build index metadata";
throw e;
}
indexService.indicesLifecycle().beforeIndexAddedToCluster(new Index(request.index()),
indexMetaData.settings());
MetaData newMetaData = MetaData.builder(currentState.metaData())
.put(indexMetaData, false)
.build();
String maybeShadowIndicator = IndexMetaData.isIndexUsingShadowReplicas(indexMetaData.settings()) ? "s" : "";
logger.info("[{}] creating index, cause [{}], templates {}, shards [{}]/[{}{}], mappings {}",
request.index(), request.cause(), templateNames, indexMetaData.numberOfShards(),
indexMetaData.numberOfReplicas(), maybeShadowIndicator, mappings.keySet());
ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
if (!request.blocks().isEmpty()) {
for (ClusterBlock block : request.blocks()) {
blocks.addIndexBlock(request.index(), block);
}
}
if (request.state() == State.CLOSE) {
blocks.addIndexBlock(request.index(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
}
ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build();
if (request.state() == State.OPEN) {
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable())
.addAsNew(updatedState.metaData().index(request.index()));
RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(routingTableBuilder).build());
updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build();
}
removalReason = "cleaning up after validating index on master";
return updatedState;
} finally {
if (indexCreated) {
// Index was already partially created - need to clean up
indicesService.removeIndex(request.index(), removalReason != null ? removalReason : "failed to create index");
}
}
}
});
}
private Map<String, Object> parseMapping(String mappingSource) throws Exception {
try (XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource)) {
return parser.map();
}
}
private void addMappings(Map<String, Map<String, Object>> mappings, Path mappingsDir) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(mappingsDir)) {
for (Path mappingFile : stream) {
final String fileName = mappingFile.getFileName().toString();
if (Files.isHidden(mappingFile)) {
continue;
}
int lastDotIndex = fileName.lastIndexOf('.');
String mappingType = lastDotIndex != -1 ? mappingFile.getFileName().toString().substring(0, lastDotIndex) : mappingFile.getFileName().toString();
try (BufferedReader reader = Files.newBufferedReader(mappingFile, Charsets.UTF_8)) {
String mappingSource = Streams.copyToString(reader);
if (mappings.containsKey(mappingType)) {
XContentHelper.mergeDefaults(mappings.get(mappingType), parseMapping(mappingSource));
} else {
mappings.put(mappingType, parseMapping(mappingSource));
}
} catch (Exception e) {
logger.warn("failed to read / parse mapping [" + mappingType + "] from location [" + mappingFile + "], ignoring...", e);
}
}
}
}
private List<IndexTemplateMetaData> findTemplates(CreateIndexClusterStateUpdateRequest request, ClusterState state, IndexTemplateFilter indexTemplateFilter) throws IOException {
List<IndexTemplateMetaData> templates = Lists.newArrayList();
for (ObjectCursor<IndexTemplateMetaData> cursor : state.metaData().templates().values()) {
IndexTemplateMetaData template = cursor.value;
if (indexTemplateFilter.apply(request, template)) {
templates.add(template);
}
}
CollectionUtil.timSort(templates, new Comparator<IndexTemplateMetaData>() {
@Override
public int compare(IndexTemplateMetaData o1, IndexTemplateMetaData o2) {
return o2.order() - o1.order();
}
});
return templates;
}
private void validate(CreateIndexClusterStateUpdateRequest request, ClusterState state) {
validateIndexName(request.index(), state);
validateIndexSettings(request.index(), request.settings());
}
public void validateIndexSettings(String indexName, Settings settings) throws IndexCreationException {
String customPath = settings.get(IndexMetaData.SETTING_DATA_PATH, null);
List<String> validationErrors = Lists.newArrayList();
if (customPath != null && nodeEnv.isCustomPathsEnabled() == false) {
validationErrors.add("custom data_paths for indices is disabled");
}
Integer number_of_primaries = settings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_SHARDS, null);
Integer number_of_replicas = settings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, null);
if (number_of_primaries != null && number_of_primaries <= 0) {
validationErrors.add("index must have 1 or more primary shards");
}
if (number_of_replicas != null && number_of_replicas < 0) {
validationErrors.add("index must have 0 or more replica shards");
}
if (validationErrors.isEmpty() == false) {
throw new IndexCreationException(new Index(indexName),
new IllegalArgumentException(getMessage(validationErrors)));
}
}
private String getMessage(List<String> validationErrors) {
StringBuilder sb = new StringBuilder();
sb.append("Validation Failed: ");
int index = 0;
for (String error : validationErrors) {
sb.append(++index).append(": ").append(error).append(";");
}
return sb.toString();
}
private static class DefaultIndexTemplateFilter implements IndexTemplateFilter {
@Override
public boolean apply(CreateIndexClusterStateUpdateRequest request, IndexTemplateMetaData template) {
return Regex.simpleMatch(template.template(), request.index());
}
}
}
| |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* BlackjackHandPanel objects are panels that contain the cards, hand value, bet amount, and
* hit, stand, split pairs, and double down buttons for a Blackjack hand.
*
* @author Jordan Segalman
*/
public class BlackjackHandPanel extends JPanel implements ActionListener {
private static final Color CARD_TABLE_GREEN = new Color(37, 93, 54);
private static final Color TEXT_COLOR = new Color(230, 230, 230);
private static final Dimension BUTTONS_DIMENSION = new Dimension(110, 25);
private BlackjackClient controller; // client GUI controller
private JPanel cardsPanel;
private JLabel handValueLabel;
private JLabel handBetLabel;
private JLabel handMessageLabel;
private JButton hitButton;
private JButton standButton;
private JButton splitPairsButton;
private JButton doubleDownButton;
/**
* Constructor for BlackjackHandPanel object.
*
* @param controller Client GUI controller
*/
public BlackjackHandPanel(BlackjackClient controller) {
this.controller = controller;
setupPanel();
setupActionListeners();
}
/**
* Sets up the panel.
*/
private void setupPanel() {
setBackground(CARD_TABLE_GREEN);
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
cardsPanel = new JPanel();
cardsPanel.setBackground(CARD_TABLE_GREEN);
constraints.gridx = 0;
constraints.gridy = 0;
add(cardsPanel, constraints);
handValueLabel = new JLabel();
handValueLabel.setForeground(TEXT_COLOR);
constraints.gridy = 1;
add(handValueLabel, constraints);
handBetLabel = new JLabel();
handBetLabel.setForeground(TEXT_COLOR);
constraints.gridy = 2;
add(handBetLabel, constraints);
handMessageLabel = new JLabel();
handMessageLabel.setForeground(TEXT_COLOR);
constraints.gridy = 3;
add(handMessageLabel, constraints);
JPanel hitStandButtonsPanel = new JPanel();
hitStandButtonsPanel.setBackground(CARD_TABLE_GREEN);
hitButton = new JButton("Hit");
hitButton.setPreferredSize(BUTTONS_DIMENSION);
hitButton.setEnabled(false);
hitButton.setVisible(false);
standButton = new JButton("Stand");
standButton.setPreferredSize(BUTTONS_DIMENSION);
standButton.setEnabled(false);
standButton.setVisible(false);
hitStandButtonsPanel.add(hitButton);
hitStandButtonsPanel.add(standButton);
constraints.gridy = 4;
add(hitStandButtonsPanel, constraints);
JPanel yesNoButtonsPanel = new JPanel();
yesNoButtonsPanel.setBackground(CARD_TABLE_GREEN);
splitPairsButton = new JButton("Split Pairs");
splitPairsButton.setPreferredSize(BUTTONS_DIMENSION);
splitPairsButton.setEnabled(false);
splitPairsButton.setVisible(false);
doubleDownButton = new JButton("Double Down");
doubleDownButton.setPreferredSize(BUTTONS_DIMENSION);
doubleDownButton.setEnabled(false);
doubleDownButton.setVisible(false);
yesNoButtonsPanel.add(splitPairsButton);
yesNoButtonsPanel.add(doubleDownButton);
constraints.gridy = 5;
add(yesNoButtonsPanel, constraints);
}
/**
* Sets up the action listeners.
*/
private void setupActionListeners() {
hitButton.addActionListener(this);
standButton.addActionListener(this);
splitPairsButton.addActionListener(this);
doubleDownButton.addActionListener(this);
}
/**
* Shows changes made to the panel.
*/
private void showChanges() {
revalidate();
repaint();
setVisible(true);
}
/**
* Sets the hand value label to the given hand value.
*
* @param handValue Hand value to set label to
*/
public void setHandValueLabel(String handValue) {
handValueLabel.setText("Hand Value: " + handValue);
showChanges();
}
/**
* Sets the hand bet label to the given bet.
*
* @param bet Bet to set label to
*/
public void setHandBet(String bet) {
handBetLabel.setText("Bet: $" + bet);
showChanges();
}
/**
* Sets the hand message label to the given message.
*
* @param message Message to set label to
*/
public void setHandMessageLabel(String message) {
handMessageLabel.setText(message);
showChanges();
}
/**
* Sets the hand message label to the error message.
*/
public void turnError() {
setHandMessageLabel("ERROR");
showChanges();
}
/**
* Enables the hit and stand buttons.
*/
public void enableHitStand() {
enableHitButton(true);
enableStandButton(true);
showChanges();
}
/**
* Adds a given JLabel containing the image of a card to the cards panel.
*
* @param cardLabel JLabel containing image of card
*/
public void addCard(JLabel cardLabel) {
cardsPanel.add(cardLabel);
showChanges();
}
/**
* Sets the hand message label to the busted message.
*/
public void bust() {
setHandMessageLabel("You busted.");
showChanges();
}
/**
* Enables the split pairs button.
*/
public void enableSplitPairs() {
enableSplitPairsButton(true);
showChanges();
}
/**
* Enables the double down button.
*/
public void enableDoubleDown() {
enableDoubleDownButton(true);
showChanges();
}
/**
* Sets the hand message label to the double down success message.
*/
public void doubleDownSuccess() {
setHandMessageLabel("Your bet on this hand has been doubled.");
showChanges();
}
/**
* Removes the face-down card added after doubling down.
*/
public void removeDoubleDownFaceDownCard() {
cardsPanel.remove(cardsPanel.getComponent(2));
showChanges();
}
/**
* Enables and shows or disables and hides the hit button.
*
* @param b If true, enables and shows the hit button; otherwise, disables and hides the hit button
*/
private void enableHitButton(Boolean b) {
hitButton.setEnabled(b);
hitButton.setVisible(b);
showChanges();
}
/**
* Enables and shows or disables and hides the stand button.
*
* @param b If true, enables and shows the stand button; otherwise, disables and hides the stand button
*/
private void enableStandButton(Boolean b) {
standButton.setEnabled(b);
standButton.setVisible(b);
showChanges();
}
/**
* Enables and shows or disables and hides the split pairs button.
*
* @param b If true, enables and shows the split pairs button; otherwise, disables and hides the split pairs button
*/
private void enableSplitPairsButton(Boolean b) {
splitPairsButton.setEnabled(b);
splitPairsButton.setVisible(b);
showChanges();
}
/**
* Enables and shows or disables and hides the double down button.
*
* @param b If true, enables and shows the double down button; otherwise, disables and hides the double down button
*/
private void enableDoubleDownButton(Boolean b) {
doubleDownButton.setEnabled(b);
doubleDownButton.setVisible(b);
showChanges();
}
/**
* Invoked when an action occurs.
*
* @param e Event generated by component action
*/
@Override
public void actionPerformed(ActionEvent e) {
Object target = e.getSource();
if(target == hitButton) {
controller.sendClientMessage(hitButton.getText());
} else if (target == standButton) {
controller.sendClientMessage(standButton.getText());
} else if (target == splitPairsButton) {
controller.sendClientMessage(splitPairsButton.getText());
} else if (target == doubleDownButton) {
controller.sendClientMessage(doubleDownButton.getText());
}
enableHitButton(false);
enableStandButton(false);
enableSplitPairsButton(false);
enableDoubleDownButton(false);
}
}
| |
package com.yext.serialization.js;
import static com.yext.serialization.core.SerializationFormat.JSON;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Predicate;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.CharStreams;
import com.google.common.primitives.Primitives;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.apache.commons.lang.BooleanUtils;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.yext.serialization.annotations.Serialize;
import com.yext.serialization.core.DeserializationParams;
import com.yext.serialization.core.Deserializer;
import com.yext.serialization.core.DeserializingException;
import com.yext.serialization.core.ManualSerializeObject;
import com.yext.serialization.core.Pair;
import com.yext.serialization.core.SerializationElement;
import com.yext.serialization.core.SerializationUtil;
import com.yext.serialization.core.SerializationWrapper;
import com.yext.serialization.core.Setter;
import com.yext.serialization.js.JsonSerializer.JsonSerializerException;
/**
* Deserializes JSON objects into classes labeled with the {@link Json} annotation.
* @author Michael Bolin (mbolin@yext.com)
*/
public class JsonDeserializer implements Deserializer {
private final DeserializationParams params;
public static <T> T deserializeFromReader(Reader reader, final Class<T> clazz)
throws DeserializingException {
return deserializeFromReader(reader, clazz, new DeserializationParams());
}
public static <T> T deserializeFromReader(
Reader reader,
final Class<T> clazz,
Class collectionType)
throws DeserializingException
{
return deserializeFromReader(reader, clazz, collectionType, new DeserializationParams());
}
public static <T> T deserializeFromReader(
Reader reader,
final Class<T> clazz,
DeserializationParams params)
throws DeserializingException
{
return deserializeFromReader(reader, clazz, null, params);
}
public static <T> T deserializeFromReader(
Reader reader,
final Class<T> clazz,
Class collectionType,
DeserializationParams params)
throws DeserializingException
{
Preconditions.checkNotNull(reader);
Preconditions.checkNotNull(clazz);
try {
String string = CharStreams.toString(reader).trim();
if (string.startsWith("{")) {
return deserializeChecked(new JSONObject(string), clazz, collectionType, params);
} else if (string.startsWith("[")) {
return deserializeChecked(new JSONArray(string), clazz, collectionType, params);
} else {
return deserializeChecked(string, clazz, params);
}
} catch (IOException e) {
throw new DeserializingException(e);
} catch (JSONException e) {
throw new DeserializingException(e, true);
} catch (DeserializingException e) {
throw e; // Need to explicitly catch before Runtime Exception
} catch (RuntimeException e) {
throw new DeserializingException(e);
}
}
/**
* Deserializes an object from JSON.
* @param obj is likely either a JSONObject or a JSONArray. If it is a
* simple type, such as an int or String, it will be returned as is,
* though <code>clazz</code> must match the value of <code>obj</code>
* or a {@link ClassCastException} will be thrown.
* @param clazz the class to which it should be deserialized, which must
* have a no-arg constructor
* @return the deserialized Java object
*/
public static <T> T deserialize(Object obj, final Class<T> clazz) {
Preconditions.checkNotNull(clazz);
return deserialize(obj, clazz, null);
}
/**
* Deserializes an object from JSON.
* @param obj is likely either a JSONObject or a JSONArray. If it is a
* simple type, such as an int or String, it will be returned as is,
* though <code>clazz</code> must match the value of <code>obj</code>
* or a {@link ClassCastException} will be thrown.
* @param clazz the class to which it should be deserialized, which must
* have a no-arg constructor
* @return the deserialized Java object
*/
public static <T> T deserializeChecked(
Object obj,
final Class<T> clazz,
DeserializationParams params)
throws DeserializingException
{
Preconditions.checkNotNull(clazz);
return deserializeChecked(obj, clazz, null, params);
}
/**
* Deserializes an object from JSON.
* @param obj is likely either a JSONObject or a JSONArray. If it is a
* simple type, such as an int or String, it will be returned as is,
* though <code>clazz</code> must match the value of <code>obj</code>
* or a {@link ClassCastException} will be thrown.
* @param clazz the class to which it should be deserialized, which must
* have a no-arg constructor
* @param collectionType If the type to deserialize to is a typed collection
* such as <code>List<SomeType></code>, then <code>clazz</code>
* should be <code>List.class</code> and <code>collectionType</code>
* should be <code>SomeType.class</code>.
* @return the deserialized Java object
*/
public static <T> T deserialize(Object obj, final Class<T> clazz, Class collectionType) {
Preconditions.checkNotNull(clazz);
return deserializeChecked(obj, clazz, collectionType);
}
public static <T> T deserializeChecked(Object obj, final Class<T> clazz, Class collectionType)
throws DeserializingException {
Preconditions.checkNotNull(clazz);
return deserializeChecked(obj, clazz, collectionType, new DeserializationParams());
}
public static <T> T deserializeChecked(
Object obj,
final Class<T> clazz,
Class collectionType,
DeserializationParams params)
throws DeserializingException
{
Preconditions.checkNotNull(clazz);
return new JsonDeserializer(params).deserializeInternal(obj, clazz, collectionType);
}
private JsonDeserializer(DeserializationParams params) {
this.params = params;
}
/**
* Deserializes an object from JSON.
* @param obj is likely either a JSONObject or a JSONArray. If it is a
* simple type, such as an int or String, it will be returned as is,
* though <code>clazz</code> must match the value of <code>obj</code>
* or a {@link ClassCastException} will be thrown.
* @param clazz the class to which it should be deserialized, which must
* have a no-arg constructor
* @param collectionType If the type to deserialize to is a typed collection
* such as <code>List<SomeType></code>, then <code>clazz</code>
* should be <code>List.class</code> and <code>collectionType</code>
* should be <code>SomeType.class</code>.
* @return the deserialized Java object
*/
@SuppressWarnings("unchecked")
private <T> T deserializeInternal(Object obj, final Class<T> clazz, Class collectionType)
throws DeserializingException
{
try {
return deserializeInternal(obj, clazz, collectionType, null);
} catch (JSONException e) {
throw new DeserializingException(e);
} catch (InstantiationException e) {
throw new DeserializingException(e);
} catch (IllegalAccessException e) {
throw new DeserializingException(e);
} catch (InvocationTargetException e) {
throw new DeserializingException(e);
}
}
/**
* A helper that additionally allows the caller to pass in the
* AnnotatedElement corresponding to the object instance being deserialized.
*/
@SuppressWarnings("unchecked")
private <T> T deserializeInternal(
Object obj,
final Class<T> clazz,
Class collectionType,
AnnotatedElement annotatedElement)
throws JSONException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, DeserializingException
{
if (clazz.equals(JSONObject.class)) {
return (T)obj;
}
if (clazz.equals(JsonObject.class)) {
String json = ((JSONObject)obj).toString();
JsonElement jsonElement = new JsonParser().parse(json);
return (T)jsonElement;
}
if (obj == null || obj == JSONObject.NULL || clazz.equals(Void.class)) {
return null;
}
// Must explicitly convert an int to a boolean if a boolean is requested.
if (obj instanceof Integer && Boolean.class.equals(clazz)) {
int intValue = (Integer)obj;
if (intValue == 0 || intValue == 1) {
return (T)BooleanUtils.toBooleanObject(intValue);
} else {
throw new DeserializingException(
"Invalid integer value for boolean (must be 0 or 1): " + intValue);
}
}
// Must explicitly convert an int to a long if a long is requested.
if (obj instanceof Integer && Long.class.equals(clazz)) {
int intValue = (Integer)obj;
return (T)Long.valueOf(intValue);
}
// Must explicitly convert an int to a float if a float is requested.
if (obj instanceof Integer && Float.class.equals(clazz)) {
int intValue = (Integer)obj;
return (T)Float.valueOf(intValue);
}
// Must explicitly convert an int to a double if a double is requested.
if (obj instanceof Integer && Double.class.equals(clazz)) {
int intValue = (Integer)obj;
return (T)Double.valueOf(intValue);
}
// Must explicitly convert a double to a float if a float is requested.
if (obj instanceof Double && Float.class.equals(clazz)) {
double dValue = (Double)obj;
return (T)Float.valueOf((float)dValue);
}
// Explicitly parse a string into a number if a number isrequested.
if (obj instanceof String && Integer.class.equals(clazz)) {
return (T)Integer.valueOf((String)obj);
}
if (obj instanceof String && Double.class.equals(clazz)) {
return (T)Double.valueOf((String)obj);
}
if (obj instanceof String && Long.class.equals(clazz)) {
return (T)Long.valueOf((String)obj);
}
if (obj instanceof String && Float.class.equals(clazz)) {
return (T)Float.valueOf((String)obj);
}
// If we're looking for a string, and the object is a simple
// type, just return the toString of the object
if (JsonSerializer.SIMPLE_TYPES.contains(obj.getClass()) &&
String.class.equals(clazz)) {
return (T)obj.toString();
}
if (annotatedElement != null && annotatedElement.isAnnotationPresent(EmptyToNull.class) &&
obj instanceof String &&
((String)obj).isEmpty()) {
return null;
}
if (!isIterable(clazz) && obj instanceof JSONArray) {
// We were expecting a non iterable type but got an array. Just
// return the first element if it exists.
JSONArray array = (JSONArray)obj;
if (array.length() == 0) return null;
return deserialize(array.get(0), clazz);
}
if (JsonSerializer.SIMPLE_TYPES.contains(clazz)) {
return (T)obj;
}
if (isIterable(clazz)) {
List items = Lists.newLinkedList();
if (!(obj instanceof JSONArray)) {
// If we were expecting an array but got an object or
// primitive, just make a list of of length one.
items.add(deserialize(obj, collectionType));
} else {
JSONArray array = (JSONArray)obj;
for (int i = 0; i < array.length(); i++) {
items.add(deserialize(array.get(i), collectionType));
}
}
return (T)items;
}
if (SerializationUtil.isMap(clazz)) {
return (T)SerializationUtil.deserializeMap(
deserializeMap((JSONObject)obj, String.class, collectionType),
null,
LinkedHashMap.class,
String.class,
collectionType);
}
if (clazz.isEnum() && clazz.equals(obj.getClass())) {
return (T)obj;
}
// Generic enums
if (Enum.class.isAssignableFrom(clazz)) {
Predicate<Enum> tester;
if (obj instanceof Integer) {
tester = e -> e.ordinal() == ((Integer)obj).intValue();
} else if (obj instanceof String) {
tester = e -> e.name().equals(obj);
} else {
throw new DeserializingException("Value must be an integer or string", true);
}
try {
Method m = clazz.getMethod("values");
Enum[] enums = (Enum[])m.invoke(null);
for (Enum e : enums) {
if (tester.test(e)) {
return (T)e;
}
}
} catch (NoSuchMethodException e) {
// This is unexpected - enums should always have a values
throw new RuntimeException(e);
}
}
// Handle various date and time String representations
if (obj instanceof String &&
(DateTime.class.equals(clazz) || LocalDate.class.equals(clazz) || DateMidnight.class
.equals(clazz))) {
String dateTimeStr = (String) obj;
DateTimeFormatter annotatedFormatter = null;
if (annotatedElement != null &&
annotatedElement.isAnnotationPresent(DateTimePattern.class)) {
annotatedFormatter = DateTimeFormat.forPattern(annotatedElement.getAnnotation(
DateTimePattern.class).value());
}
// Handle DateTime
// In absence of a @DateTimePattern annotation:
// "2006-09-16T14:30:00-06:00"
if (DateTime.class.equals(clazz)) {
if (annotatedFormatter != null) {
// Special behavior based on annotations.
return (T)annotatedFormatter.parseDateTime(dateTimeStr);
} else {
return (T)new DateTime(dateTimeStr);
}
}
// Handle LocalDate
if (LocalDate.class.equals(clazz)) {
if (annotatedFormatter != null) {
// Special behavior based on annotations.
return (T)annotatedFormatter.parseLocalDate(dateTimeStr);
} else {
return (T)new LocalDate(dateTimeStr);
}
}
// Handle DateMidnight
if (DateMidnight.class.equals(clazz)) {
if (annotatedFormatter != null) {
// Special behavior based on annotations.
return (T)annotatedFormatter.parseLocalDate(dateTimeStr).toDateMidnight();
} else {
return (T)new DateMidnight(dateTimeStr);
}
}
}
if (!(obj instanceof JSONObject)) {
throw new DeserializingException("Value must be a JSONObject (but is a " + obj.getClass() + ")", true);
}
JSONObject json = (JSONObject)obj;
// Handle ManualSerializeObject
if (ManualSerializeObject.class.isAssignableFrom(clazz)) {
try {
ManualSerializeObject result = (ManualSerializeObject)clazz.newInstance();
result.deserializeJson(json);
return (T)result;
} catch (SecurityException ex) {
throw new DeserializingException(
"deserializeJson method does not exist for " + clazz, true);
}
}
// Handle arbitrary object annotated with @Json
T instance;
try {
Constructor<T> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
instance = constructor.newInstance();
} catch (Exception e) {
throw Throwables.propagate(e);
}
if (clazz.isAnnotationPresent(Json.class)) {
boolean coerceNumbers = clazz.isAnnotationPresent(CoerceNumbers.class);
for (Method setter : getJsonSetterMethods(clazz)) {
Json setterAnnotation = setter.getAnnotation(Json.class);
String name = setterAnnotation.name();
if ("".equals(name)) {
throw new JsonSerializerException(
"Method lacks name in annotation: " + setter);
}
// The JSON may not contain a value for every setter method.
// Only invoke the setters for which values are supplied.
if (!json.has(name)) {
continue;
}
try {
setObjectValue(json, instance, coerceNumbers, setter, name);
} catch (IncompatibleTypeException e) {
if (!setter.isAnnotationPresent(NullForWrongType.class)) {
throw e;
}
}
}
return instance;
} else if (clazz.isAnnotationPresent(Serialize.class)) {
for (Setter setter : new SerializationWrapper(clazz, JSON, params).getSetters()) {
setObjectValue(json, instance, setter);
}
return instance;
}
throw new IllegalArgumentException("Did not know how to deserialize: " + obj);
}
@SuppressWarnings("unchecked")
private <T> Object setObjectValue(
JSONObject json,
T instance,
boolean coerceNumbers,
Method setter,
String name)
throws JSONException, InstantiationException, IllegalAccessException,
InvocationTargetException, DeserializingException {
Object jsonValue = json.get(name);
Type t = setter.getGenericParameterTypes()[0];
Object value;
Class valueClass = setter.getParameterTypes()[0];
if (t instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)t;
Type[] types = parameterizedType.getActualTypeArguments();
Class paramClass = (Class)types[types.length - 1];
value = deserializeInternal(jsonValue, valueClass, paramClass, setter);
} else {
if (coerceNumbers
&& jsonValue instanceof String
&& Number.class.isAssignableFrom(Primitives.wrap(valueClass))) {
jsonValue = parseNumber(
(Class<? extends Number>) Primitives.wrap(valueClass),
(String) jsonValue);
}
value = deserializeInternal(jsonValue, valueClass, null, setter);
}
try {
if (boolean.class.equals(valueClass) && value == null) {
// Skip for now
// TODO(kevin): default to false? what about other non-nullables?
} else {
setter.invoke(instance, value);
}
} catch (IllegalArgumentException e) {
throw new IncompatibleTypeException(
"argument type mismatch: " +
(setter == null ? "null" : setter.getName()) +
"(" + (value == null ? "null" : value.getClass()) + ")",
e);
}
return value;
}
@SuppressWarnings("unchecked")
private <T> Object setObjectValue(JSONObject json,
T instance,
Setter setter)
throws JSONException, InstantiationException, IllegalAccessException,
InvocationTargetException, DeserializingException
{
// Get the json value
String exactName = setter.getExactMatchName();
Object jsonValue = null;
if (exactName != null) {
if (json.has(exactName)) {
jsonValue = json.get(exactName);
}
} else {
for (String key : ImmutableList.copyOf((Iterator<String>)json.keys())) {
if (setter.matchName(key)) {
jsonValue = json.get(key);
break;
}
}
}
Pair<Type, Type> mapTypes = setter.getMapTypes();
if (mapTypes != null) {
if (jsonValue == null || jsonValue == JSONObject.NULL) {
return null;
}
return setter.setMap(
instance,
deserializeMap((JSONObject)jsonValue, (Class<?>)mapTypes.first(), (Class<?>)mapTypes.second()));
}
Class<?> collectionType = (Class<?>)setter.getCollectionType();
Object value;
Class<?> valueClass = (Class<?>)setter.getType();
try {
if (collectionType != null) {
if (SerializationUtil.isPrimitiveClass(collectionType) &&
jsonValue instanceof JSONArray)
{
JSONArray array = (JSONArray)jsonValue;
for (int i = 0; i < array.length(); ++i) {
Object processed = setter.preprocessAndHandleIfNecessary(
array.get(i), collectionType);
if (processed != null) {
array.put(i, processed);
} else {
array.put(i, JSONObject.NULL);
}
}
}
// We don't support mixing annotations at this time (hence the second null)
value = deserializeInternal(jsonValue, valueClass, collectionType, null);
} else {
if (jsonValue instanceof String && SerializationUtil.isPrimitiveClass(valueClass)) {
value = jsonValue;
} else {
// We don't support mixing annotations at this time (hence the second null)
value = deserializeInternal(jsonValue, valueClass, null, null);
}
value = setter.preprocessAndHandleIfNecessary(value, (Class<?>)setter.getType());
}
} catch (DeserializingException e) {
throw e.addNameIfNeeded(setter.getExactMatchName());
}
if (value == null) return null;
try {
setter.set(instance, value);
} catch (IllegalArgumentException e) {
throw new IncompatibleTypeException(
"argument type mismatch: " +
(setter == null ? "null" : setter.getExactMatchName()) +
"(" + (value == null ? "null" : value.getClass()) + ")",
e);
}
return value;
}
/** Parse the given string value into the given Number type. */
private static Number parseNumber(Class<? extends Number> type, String value) {
if (value.isEmpty()) {
value = "0"; // Coerce empty string to 0.
}
if (Double.class.isAssignableFrom(type)) return Double.parseDouble(value);
if (Long.class.isAssignableFrom(type)) return Long.parseLong(value);
if (Integer.class.isAssignableFrom(type)) return Integer.parseInt(value);
if (Float.class.isAssignableFrom(type)) return Float.parseFloat(value);
throw new NumberFormatException("Couldn't coerce " + value + " to " + type);
}
@SuppressWarnings("unchecked")
private static <K, V> Collection<Pair<K, V>> deserializeMap(
JSONObject json,
Class<K> keyClass,
Class<V> valueClass)
throws JSONException {
List<Pair<K, V>> entries = Lists.newArrayList();
for (String key : Iterators.toArray(json.keys(), String.class)) {
entries.add(Pair.of(deserialize(key, keyClass), deserialize(json.get(key), valueClass)));
}
return entries;
}
/**
* Returns the getter methods for a class, sorted alphabetically by name.
* @return a list of methods that have the Json annotation, take one
* argument, and returns "void".
*/
@SuppressWarnings("unchecked")
private static List<Method> getJsonSetterMethods(Class clazz) {
List<Method> methods = Lists.newArrayList();
for (Method method : clazz.getMethods()) {
// A setter method should take exactly one parameter.
if (method.getParameterTypes().length != 1) {
continue;
}
// The method must have the Json annotation.
Json jsonAnnotation = method.getAnnotation(Json.class);
if (jsonAnnotation == null) {
continue;
}
// The return type should be void or clazz (for builder pattern).
if (!void.class.equals(method.getReturnType()) &&
!clazz.equals(method.getReturnType())) {
continue;
}
methods.add(method);
}
Collections.sort(methods, JsonSerializer.METHOD_NAME_COMPARATOR);
return methods;
}
/**
* @return true if <code>clazz</code> implements {@link Iterable}
*/
@SuppressWarnings("unchecked")
private static boolean isIterable(Class clazz) {
for (Class iface : clazz.getInterfaces()) {
if (Iterable.class.equals(iface)) {
return true;
} else if (isIterable(iface)) {
return true;
}
}
return false;
}
@Override
public SerializationElement deserialize(Reader reader) throws DeserializingException {
return createElement(new JsonParser().parse(reader));
}
private SerializationElement createElement(JsonElement json) throws DeserializingException {
if (json.isJsonNull()) {
return new SerializationElement((String)null);
} else if (json.isJsonPrimitive()) {
JsonPrimitive prim = json.getAsJsonPrimitive();
if (prim.isString()) {
return new SerializationElement(prim.getAsString());
} else if (prim.isNumber()) {
return new SerializationElement(prim.getAsNumber().toString());
} else if (prim.isBoolean()) {
return new SerializationElement("" + prim.getAsBoolean());
} else {
throw new DeserializingException("Invalid json primitive type.");
}
} else if (json.isJsonObject()) {
Map<String, SerializationElement> map = Maps.newHashMap();
JsonObject obj = json.getAsJsonObject();
for (Entry<String, JsonElement> entry : obj.entrySet()) {
map.put(entry.getKey(), createElement(entry.getValue()));
}
return new SerializationElement(map);
} else if (json.isJsonArray()) {
List<SerializationElement> list = Lists.newArrayList();
for (JsonElement el : json.getAsJsonArray()) {
list.add(createElement(el));
}
return new SerializationElement(list);
} else {
throw new DeserializingException("Invalid json element type.");
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.test.index.mapper;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.MapperService.MergeReason;
import org.elasticsearch.index.mapper.ObjectMapper.Dynamic;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.testframework.ESSingleNodeTestCase;
import org.elasticsearch.testframework.InternalSettingsPlugin;
import java.io.IOException;
import java.util.Collection;
import static org.hamcrest.Matchers.containsString;
public class ObjectMapperTests extends ESSingleNodeTestCase {
public void testDifferentInnerObjectTokenFailure() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
defaultMapper.parse(SourceToParse.source("test", "type", "1", new BytesArray(" {\n" +
" \"object\": {\n" +
" \"array\":[\n" +
" {\n" +
" \"object\": { \"value\": \"value\" }\n" +
" },\n" +
" {\n" +
" \"object\":\"value\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"value\":\"value\"\n" +
" }"),
XContentType.JSON));
});
assertTrue(e.getMessage(), e.getMessage().contains("different type"));
}
public void testEmptyArrayProperties() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startArray("properties").endArray()
.endObject().endObject());
createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));
}
public void testEmptyFieldsArrayMultiFields() throws Exception {
String mapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("tweet")
.startObject("properties")
.startObject("name")
.field("type", "text")
.startArray("fields")
.endArray()
.endObject()
.endObject()
.endObject()
.endObject());
createIndex("test").mapperService().documentMapperParser().parse("tweet", new CompressedXContent(mapping));
}
public void testFieldsArrayMultiFieldsShouldThrowException() throws Exception {
String mapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("tweet")
.startObject("properties")
.startObject("name")
.field("type", "text")
.startArray("fields")
.startObject().field("test", "string").endObject()
.startObject().field("test2", "string").endObject()
.endArray()
.endObject()
.endObject()
.endObject()
.endObject());
try {
createIndex("test").mapperService().documentMapperParser().parse("tweet", new CompressedXContent(mapping));
fail("Expected MapperParsingException");
} catch(MapperParsingException e) {
assertThat(e.getMessage(), containsString("expected map for property [fields]"));
assertThat(e.getMessage(), containsString("but got a class java.util.ArrayList"));
}
}
public void testEmptyFieldsArray() throws Exception {
String mapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("tweet")
.startObject("properties")
.startArray("fields")
.endArray()
.endObject()
.endObject()
.endObject());
createIndex("test").mapperService().documentMapperParser().parse("tweet", new CompressedXContent(mapping));
}
public void testFieldsWithFilledArrayShouldThrowException() throws Exception {
String mapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("tweet")
.startObject("properties")
.startArray("fields")
.startObject().field("test", "string").endObject()
.startObject().field("test2", "string").endObject()
.endArray()
.endObject()
.endObject()
.endObject());
try {
createIndex("test").mapperService().documentMapperParser().parse("tweet", new CompressedXContent(mapping));
fail("Expected MapperParsingException");
} catch (MapperParsingException e) {
assertThat(e.getMessage(), containsString("Expected map for property [fields]"));
}
}
public void testFieldPropertiesArray() throws Exception {
String mapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("tweet")
.startObject("properties")
.startObject("name")
.field("type", "text")
.startObject("fields")
.startObject("raw")
.field("type", "keyword")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject());
createIndex("test").mapperService().documentMapperParser().parse("tweet", new CompressedXContent(mapping));
}
public void testMerge() throws IOException {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject()
.startObject("type")
.startObject("properties")
.startObject("foo")
.field("type", "keyword")
.endObject()
.endObject()
.endObject().endObject());
MapperService mapperService = createIndex("test").mapperService();
DocumentMapper mapper = mapperService.merge("type", new CompressedXContent(mapping), MergeReason.MAPPING_UPDATE, false);
assertNull(mapper.root().includeInAll());
assertNull(mapper.root().dynamic());
String update = Strings.toString(XContentFactory.jsonBuilder().startObject()
.startObject("type")
.field("include_in_all", false)
.field("dynamic", "strict")
.endObject().endObject());
mapper = mapperService.merge("type", new CompressedXContent(update), MergeReason.MAPPING_UPDATE, false);
assertFalse(mapper.root().includeInAll());
assertEquals(Dynamic.STRICT, mapper.root().dynamic());
}
public void testEmptyName() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject()
.startObject("")
.startObject("properties")
.startObject("name")
.field("type", "text")
.endObject()
.endObject()
.endObject().endObject());
// Empty name not allowed in index created after 5.0
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
createIndex("test").mapperService().documentMapperParser().parse("", new CompressedXContent(mapping));
});
assertThat(e.getMessage(), containsString("name cannot be empty string"));
}
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return pluginList(InternalSettingsPlugin.class);
}
}
| |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map;
import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapIndexConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import com.hazelcast.query.EntryObject;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.PredicateBuilder;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Creates a map that is used to test data consistency while nodes are joining and leaving the cluster.
* <p>
* The basic idea is pretty simple. We'll add a number to a list for each key in the IMap. This allows us to verify whether
* the numbers are added in the correct order and also whether there's any data loss as nodes leave or join the cluster.
*/
@RunWith(HazelcastSerialClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class EntryProcessorBouncingNodesTest extends HazelcastTestSupport {
private static final int ENTRIES = 10;
private static final int ITERATIONS = 50;
private static final String MAP_NAME = "entryProcessorBouncingNodesTestMap";
private TestHazelcastInstanceFactory instanceFactory;
@Before
public void setUp() {
instanceFactory = new TestHazelcastInstanceFactory(500);
}
@After
public void tearDown() {
instanceFactory.shutdownAll();
}
/**
* Tests {@link com.hazelcast.map.impl.operation.EntryOperation}.
*/
@Test
public void testEntryProcessorWhileTwoNodesAreBouncing_withoutPredicate() {
testEntryProcessorWhileTwoNodesAreBouncing(false, false);
}
/**
* Tests {@link com.hazelcast.map.impl.operation.MultipleEntryWithPredicateOperation}.
*/
@Test
public void testEntryProcessorWhileTwoNodesAreBouncing_withPredicateNoIndex() {
testEntryProcessorWhileTwoNodesAreBouncing(true, false);
}
@Test
public void testEntryProcessorWhileTwoNodesAreBouncing_withPredicateWithIndex() {
testEntryProcessorWhileTwoNodesAreBouncing(true, true);
}
private void testEntryProcessorWhileTwoNodesAreBouncing(boolean withPredicate, boolean withIndex) {
CountDownLatch startLatch = new CountDownLatch(1);
AtomicBoolean isRunning = new AtomicBoolean(true);
// start up three instances
HazelcastInstance instance = newInstance(withIndex);
HazelcastInstance instance2 = newInstance(withIndex);
HazelcastInstance instance3 = newInstance(withIndex);
assertClusterSize(3, instance, instance3);
assertClusterSizeEventually(3, instance2);
final IMap<Integer, ListHolder> map = instance.getMap(MAP_NAME);
final ListHolder expected = new ListHolder();
// initialize the list synchronously to ensure the map is correctly initialized
InitMapProcessor initProcessor = new InitMapProcessor();
for (int i = 0; i < ENTRIES; ++i) {
map.executeOnKey(i, initProcessor);
}
assertEquals(ENTRIES, map.size());
// spin up the thread that stops/starts the instance2 and instance3, always keeping one instance running
Runnable runnable = new TwoNodesRestartingRunnable(startLatch, isRunning, withPredicate, instance2, instance3);
Thread bounceThread = new Thread(runnable);
bounceThread.start();
// now, with nodes joining and leaving the cluster concurrently, start adding numbers to the lists
int iteration = 0;
while (iteration < ITERATIONS) {
if (iteration == 30) {
// let the bounce threads start bouncing
startLatch.countDown();
}
IncrementProcessor processor = new IncrementProcessor(iteration);
expected.add(iteration);
for (int i = 0; i < ENTRIES; ++i) {
if (withPredicate) {
EntryObject eo = new PredicateBuilder().getEntryObject();
Predicate keyPredicate = eo.key().equal(i);
map.executeOnEntries(processor, keyPredicate);
} else {
map.executeOnKey(i, processor);
}
}
// give processing time to catch up
++iteration;
}
// signal the bounce threads that we're done
isRunning.set(false);
// wait for the instance bounces to complete
assertJoinable(bounceThread);
final CountDownLatch latch = new CountDownLatch(ENTRIES);
for (int i = 0; i < ENTRIES; ++i) {
final int id = i;
new Thread(new Runnable() {
@Override
public void run() {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertTrue(expected.size() <= map.get(id).size());
}
});
latch.countDown();
}
}).start();
}
assertOpenEventually(latch);
for (int index = 0; index < ENTRIES; ++index) {
ListHolder holder = map.get(index);
assertEquals("The ListHolder should contain ITERATIONS entries", ITERATIONS, holder.size());
for (int i = 0; i < ITERATIONS; i++) {
assertEquals(i, holder.get(i));
}
}
}
private HazelcastInstance newInstance(boolean withIndex) {
Config config = getConfig();
MapConfig mapConfig = config.getMapConfig(MAP_NAME);
mapConfig.setBackupCount(2);
if (withIndex) {
mapConfig.addMapIndexConfig(new MapIndexConfig("__key", true));
}
return instanceFactory.newHazelcastInstance(config);
}
private class TwoNodesRestartingRunnable implements Runnable {
private final CountDownLatch start;
private final AtomicBoolean isRunning;
private final boolean withPredicate;
private HazelcastInstance instance1;
private HazelcastInstance instance2;
private TwoNodesRestartingRunnable(CountDownLatch startLatch, AtomicBoolean isRunning, boolean withPredicate,
HazelcastInstance h1, HazelcastInstance h2) {
this.start = startLatch;
this.isRunning = isRunning;
this.withPredicate = withPredicate;
this.instance1 = h1;
this.instance2 = h2;
}
@Override
public void run() {
try {
start.await();
while (isRunning.get()) {
instance1.shutdown();
instance2.shutdown();
sleepMillis(10);
instance1 = newInstance(withPredicate);
instance2 = newInstance(withPredicate);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class InitMapProcessor extends AbstractEntryProcessor<Integer, ListHolder> {
@Override
public Object process(Map.Entry<Integer, ListHolder> entry) {
entry.setValue(new ListHolder());
return null;
}
}
private static class IncrementProcessor extends AbstractEntryProcessor<Integer, ListHolder> {
private final int nextVal;
private IncrementProcessor(int nextVal) {
this.nextVal = nextVal;
}
@Override
public Object process(Map.Entry<Integer, ListHolder> entry) {
ListHolder holder = entry.getValue();
if (holder == null) {
holder = new ListHolder();
}
holder.add(nextVal);
entry.setValue(holder);
return null;
}
}
private static class ListHolder implements DataSerializable {
private List<Integer> list = new ArrayList<Integer>();
private int size;
public ListHolder() {
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(list.size());
for (Integer value : list) {
out.writeInt(value);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
size = in.readInt();
list = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
list.add(in.readInt());
}
}
public void add(int value) {
// EPs should be idempotent if consistency for such type of operations required
if (!list.contains(value)) {
list.add(value);
size++;
}
}
public int get(int index) {
return list.get(index);
}
public int size() {
return size;
}
}
}
| |
/*
* Copyright 2016 Elvis Hew
*
* 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.elvishew.xlog.internal.util;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
/**
* Utility for formatting object to string.
*/
public class ObjectToStringUtil {
/**
* Bundle object to string, the string would be in the format of "Bundle[{...}]".
*/
public static String bundleToString(Bundle bundle) {
if (bundle == null) {
return "null";
}
StringBuilder b = new StringBuilder(128);
b.append("Bundle[{");
bundleToShortString(bundle, b);
b.append("}]");
return b.toString();
}
/**
* Intent object to string, the string would be in the format of "Intent { ... }".
*/
public static String intentToString(Intent intent) {
if (intent == null) {
return "null";
}
StringBuilder b = new StringBuilder(128);
b.append("Intent { ");
intentToShortString(intent, b);
b.append(" }");
return b.toString();
}
private static void bundleToShortString(Bundle bundle, StringBuilder b) {
boolean first = true;
for (String key : bundle.keySet()) {
if (!first) {
b.append(", ");
}
b.append(key).append('=');
Object value = bundle.get(key);
if (value instanceof int[]) {
b.append(Arrays.toString((int[]) value));
} else if (value instanceof byte[]) {
b.append(Arrays.toString((byte[]) value));
} else if (value instanceof boolean[]) {
b.append(Arrays.toString((boolean[]) value));
} else if (value instanceof short[]) {
b.append(Arrays.toString((short[]) value));
} else if (value instanceof long[]) {
b.append(Arrays.toString((long[]) value));
} else if (value instanceof float[]) {
b.append(Arrays.toString((float[]) value));
} else if (value instanceof double[]) {
b.append(Arrays.toString((double[]) value));
} else if (value instanceof String[]) {
b.append(Arrays.toString((String[]) value));
} else if (value instanceof CharSequence[]) {
b.append(Arrays.toString((CharSequence[]) value));
} else if (value instanceof Parcelable[]) {
b.append(Arrays.toString((Parcelable[]) value));
} else if (value instanceof Bundle) {
b.append(bundleToString((Bundle) value));
} else {
b.append(value);
}
first = false;
}
}
private static void intentToShortString(Intent intent, StringBuilder b) {
boolean first = true;
String mAction = intent.getAction();
if (mAction != null) {
b.append("act=").append(mAction);
first = false;
}
Set<String> mCategories = intent.getCategories();
if (mCategories != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("cat=[");
boolean firstCategory = true;
for (String c : mCategories) {
if (!firstCategory) {
b.append(',');
}
b.append(c);
firstCategory = false;
}
b.append("]");
}
Uri mData = intent.getData();
if (mData != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("dat=");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
b.append(uriToSafeString(mData));
} else {
String scheme = mData.getScheme();
if (scheme != null) {
if (scheme.equalsIgnoreCase("tel")) {
b.append("tel:xxx-xxx-xxxx");
} else if (scheme.equalsIgnoreCase("smsto")) {
b.append("smsto:xxx-xxx-xxxx");
} else {
b.append(mData);
}
} else {
b.append(mData);
}
}
}
String mType = intent.getType();
if (mType != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("typ=").append(mType);
}
int mFlags = intent.getFlags();
if (mFlags != 0) {
if (!first) {
b.append(' ');
}
first = false;
b.append("flg=0x").append(Integer.toHexString(mFlags));
}
String mPackage = intent.getPackage();
if (mPackage != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("pkg=").append(mPackage);
}
ComponentName mComponent = intent.getComponent();
if (mComponent != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("cmp=").append(mComponent.flattenToShortString());
}
Rect mSourceBounds = intent.getSourceBounds();
if (mSourceBounds != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("bnds=").append(mSourceBounds.toShortString());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ClipData mClipData = intent.getClipData();
if (mClipData != null) {
if (!first) {
b.append(' ');
}
first = false;
b.append("(has clip)");
}
}
Bundle mExtras = intent.getExtras();
if (mExtras != null) {
if (!first) {
b.append(' ');
}
b.append("extras={");
bundleToShortString(mExtras, b);
b.append('}');
}
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
Intent mSelector = intent.getSelector();
if (mSelector != null) {
b.append(" sel=");
intentToShortString(mSelector, b);
b.append("}");
}
}
}
private static String uriToSafeString(Uri uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
Method toSafeString = Uri.class.getDeclaredMethod("toSafeString");
toSafeString.setAccessible(true);
return (String) toSafeString.invoke(uri);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return uri.toString();
}
}
| |
/*******************************************************************************
* 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.ofbiz.ebay;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.UtilXml;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityComparisonOperator;
import org.apache.ofbiz.order.order.OrderChangeHelper;
import org.apache.ofbiz.order.shoppingcart.CheckOutHelper;
import org.apache.ofbiz.order.shoppingcart.ShoppingCart;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ImportOrdersFromEbay {
private static final String resource = "EbayUiLabels";
private static final String module = ImportOrdersFromEbay.class.getName();
public static Map<String, Object> importOrdersSearchFromEbay(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
Map<String, Object> result = new HashMap<String, Object>();
try {
Map<String, Object> eBayConfigResult = EbayHelper.buildEbayConfig(context, delegator);
StringBuffer sellerTransactionsItemsXml = new StringBuffer();
if (!ServiceUtil.isFailure(buildGetSellerTransactionsRequest(context, sellerTransactionsItemsXml, eBayConfigResult.get("token").toString()))) {
result = EbayHelper.postItem(eBayConfigResult.get("xmlGatewayUri").toString(), sellerTransactionsItemsXml, eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "GetSellerTransactions", eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString());
String success = (String)result.get(ModelService.SUCCESS_MESSAGE);
if (success != null) {
result = checkOrders(delegator, dispatcher, locale, context, success);
}
}
} catch (Exception e) {
Debug.logError("Exception in importOrdersSearchFromEbay " + e, module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInImportOrdersSearchFromEbay", locale));
}
return result;
}
public static Map<String, Object> importOrderFromEbay(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
Map<String, Object> order = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();
try {
order.put("productStoreId", context.get("productStoreId"));
order.put("userLogin", context.get("userLogin"));
order.put("externalId", context.get("externalId"));
order.put("createdDate", context.get("createdDate"));
order.put("productId", context.get("productId"));
order.put("quantityPurchased", context.get("quantityPurchased"));
order.put("transactionPrice", context.get("transactionPrice"));
order.put("shippingService", context.get("shippingService"));
order.put("shippingServiceCost", context.get("shippingServiceCost"));
order.put("shippingTotalAdditionalCost", context.get("shippingTotalAdditionalCost"));
order.put("salesTaxAmount", context.get("salesTaxAmount"));
order.put("salesTaxPercent", context.get("salesTaxPercent"));
order.put("amountPaid", context.get("amountPaid"));
order.put("paidTime", context.get("paidTime"));
order.put("shippedTime", context.get("shippedTime"));
order.put("buyerName", context.get("buyerName"));
order.put("emailBuyer", context.get("emailBuyer"));
order.put("shippingAddressPhone", context.get("shippingAddressPhone"));
order.put("shippingAddressStreet", context.get("shippingAddressStreet"));
order.put("shippingAddressStreet1", context.get("shippingAddressStreet1"));
order.put("shippingAddressStreet2", context.get("shippingAddressStreet2"));
order.put("shippingAddressPostalCode", context.get("shippingAddressPostalCode"));
order.put("shippingAddressCountry", context.get("shippingAddressCountry"));
order.put("shippingAddressStateOrProvince", context.get("shippingAddressStateOrProvince"));
order.put("shippingAddressCityName", context.get("shippingAddressCityName"));
result = createShoppingCart(delegator, dispatcher, locale, order, true);
} catch (Exception e) {
Debug.logError("Exception in importOrderFromEbay " + e, module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInImportOrderFromEbay", locale));
}
return result;
}
public static Map<String, Object> setEbayOrderToComplete(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
String orderId = (String) context.get("orderId");
String externalId = (String) context.get("externalId");
String transactionId = "";
Map<String, Object> result = new HashMap<String, Object>();
try {
if (orderId == null && externalId == null) {
Debug.logError("orderId or externalId must be filled", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.orderIdOrExternalIdAreMandatory", locale));
}
GenericValue orderHeader = null;
if (UtilValidate.isNotEmpty(orderId)) {
// Get the order header and verify if this order has been imported
// from eBay (i.e. sales channel = EBAY_CHANNEL and externalId is set)
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
if (orderHeader == null) {
Debug.logError("Cannot find order with orderId [" + orderId + "]", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorRetrievingOrderFromOrderId", locale));
}
if (!"EBAY_SALES_CHANNEL".equals(orderHeader.getString("salesChannelEnumId")) || orderHeader.getString("externalId") == null) {
// This order was not imported from eBay: there is nothing to do.
return ServiceUtil.returnSuccess();
}
// get externalId from OrderHeader
externalId = (String)orderHeader.get("externalId");
transactionId = orderHeader.getString("transactionId");
String productStoreId = (String) orderHeader.get("productStoreId");
if (UtilValidate.isNotEmpty(productStoreId)) {
context.put("productStoreId", productStoreId);
}
}
Map<String, Object> eBayConfigResult = EbayHelper.buildEbayConfig(context, delegator);
StringBuffer completeSaleXml = new StringBuffer();
if (!ServiceUtil.isFailure(buildCompleteSaleRequest(delegator, locale, externalId, transactionId, context, completeSaleXml, eBayConfigResult.get("token").toString()))) {
result = EbayHelper.postItem(eBayConfigResult.get("xmlGatewayUri").toString(), completeSaleXml, eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "CompleteSale", eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString());
String successMessage = (String)result.get("successMessage");
if (successMessage != null) {
return readCompleteSaleResponse(successMessage, locale);
} else{
ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorDuringPostCompleteSaleRequest", locale));
}
}
} catch (Exception e) {
Debug.logError("Exception in setEbayOrderToComplete " + e, module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInSetEbayOrderToComplete", locale));
}
return ServiceUtil.returnSuccess();
}
private static Map<String, Object> checkOrders(Delegator delegator, LocalDispatcher dispatcher, Locale locale, Map<String, Object> context, String response) {
StringBuffer errorMessage = new StringBuffer();
List<Map<String, Object>> orders = readResponseFromEbay(response, locale, (String)context.get("productStoreId"), delegator, errorMessage);
if (orders == null) {
Debug.logError("Error :" + errorMessage.toString(), module);
return ServiceUtil.returnFailure(errorMessage.toString());
} else if (orders.size() == 0) {
Debug.logError("No orders found", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.noOrdersFound", locale));
} else {
Iterator<Map<String, Object>> orderIter = orders.iterator();
while (orderIter.hasNext()) {
Map<String, Object> order = orderIter.next();
order.put("productStoreId", context.get("productStoreId"));
order.put("userLogin", context.get("userLogin"));
Map<String, Object> error = createShoppingCart(delegator, dispatcher, locale, order, false);
String errorMsg = ServiceUtil.getErrorMessage(error);
if (UtilValidate.isNotEmpty(errorMsg)) {
order.put("errorMessage", errorMsg);
} else {
order.put("errorMessage", "");
}
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("responseMessage", ModelService.RESPOND_SUCCESS);
result.put("orderList", orders);
return result;
}
}
private static Map<String, Object> buildGetSellerTransactionsRequest(Map<String, Object> context, StringBuffer dataItemsXml, String token) {
Locale locale = (Locale)context.get("locale");
String fromDate = (String)context.get("fromDate");
String thruDate = (String)context.get("thruDate");
try {
Document transDoc = UtilXml.makeEmptyXmlDocument("GetSellerTransactionsRequest");
Element transElem = transDoc.getDocumentElement();
transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
EbayHelper.appendRequesterCredentials(transElem, transDoc, token);
UtilXml.addChildElementValue(transElem, "DetailLevel", "ReturnAll", transDoc);
UtilXml.addChildElementValue(transElem, "IncludeContainingOrder", "true", transDoc);
String fromDateOut = EbayHelper.convertDate(fromDate, "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
if (fromDateOut != null) {
UtilXml.addChildElementValue(transElem, "ModTimeFrom", fromDateOut, transDoc);
} else {
Debug.logError("Cannot convert from date from yyyy-MM-dd HH:mm:ss.SSS date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' date format", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.cannotConvertFromDate", locale));
}
fromDateOut = EbayHelper.convertDate(thruDate, "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
if (fromDateOut != null) {
UtilXml.addChildElementValue(transElem, "ModTimeTo", fromDateOut, transDoc);
} else {
Debug.logError("Cannot convert thru date from yyyy-MM-dd HH:mm:ss.SSS date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' date format", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.cannotConvertThruDate", locale));
}
//Debug.logInfo("The value of generated string is ======= " + UtilXml.writeXmlDocument(transDoc), module);
dataItemsXml.append(UtilXml.writeXmlDocument(transDoc));
} catch (Exception e) {
Debug.logError("Exception during building get seller transactions request", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionDuringBuildingGetSellerTransactionRequest", locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> buildCompleteSaleRequest(Delegator delegator, Locale locale, String externalId, String transactionId, Map<String, Object> context, StringBuffer dataItemsXml, String token) {
String paid = (String)context.get("paid");
String shipped = (String)context.get("shipped");
try {
if (externalId == null) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorDuringBuildItemAndTransactionIdFromExternalId", locale));
}
Document transDoc = UtilXml.makeEmptyXmlDocument("CompleteSaleRequest");
Element transElem = transDoc.getDocumentElement();
transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
EbayHelper.appendRequesterCredentials(transElem, transDoc, token);
if (externalId.startsWith("EBT_")) {
UtilXml.addChildElementValue(transElem, "TransactionID", externalId.substring(4), transDoc);
UtilXml.addChildElementValue(transElem, "ItemID", transactionId.substring(4), transDoc);
} else if (externalId.startsWith("EBO_")) {
UtilXml.addChildElementValue(transElem, "OrderID", externalId.substring(4), transDoc);
UtilXml.addChildElementValue(transElem, "TransactionID", "0", transDoc);
UtilXml.addChildElementValue(transElem, "ItemID", "0", transDoc);
} else if (externalId.startsWith("EBI_")) {
UtilXml.addChildElementValue(transElem, "ItemID", externalId.substring(4), transDoc);
UtilXml.addChildElementValue(transElem, "TransactionID", "0", transDoc);
} else if (externalId.startsWith("EBS_")) {
//UtilXml.addChildElementValue(transElem, "OrderID", externalId.substring(4), transDoc);
UtilXml.addChildElementValue(transElem, "TransactionID", "0", transDoc);
UtilXml.addChildElementValue(transElem, "ItemID", externalId.substring(4), transDoc);
}
// default shipped = Y (call from eca during order completed)
if (paid == null && shipped == null) {
shipped = "Y";
paid = "Y";
}
// Set item id to paid or not paid
if (UtilValidate.isNotEmpty(paid)) {
if ("Y".equals(paid)) {
paid = "true";
} else {
paid = "false";
}
UtilXml.addChildElementValue(transElem, "Paid", paid, transDoc);
}
// Set item id to shipped or not shipped
if (UtilValidate.isNotEmpty(shipped)) {
if ("Y".equals(shipped)) {
shipped = "true";
} else {
shipped = "false";
}
UtilXml.addChildElementValue(transElem, "Shipped", shipped, transDoc);
}
dataItemsXml.append(UtilXml.writeXmlDocument(transDoc));
} catch (Exception e) {
Debug.logError("Exception during building complete sale request", module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionDuringBuildingCompleteSaleRequest", locale));
}
return ServiceUtil.returnSuccess();
}
private static Map<String, Object> readCompleteSaleResponse(String msg, Locale locale) {
try {
Document docResponse = UtilXml.readXmlDocument(msg, true);
Element elemResponse = docResponse.getDocumentElement();
String ack = UtilXml.childElementValue(elemResponse, "Ack", "Failure");
if (ack != null && "Failure".equals(ack)) {
String errorMessage = "";
List<? extends Element> errorList = UtilXml.childElementList(elemResponse, "Errors");
Iterator<? extends Element> errorElemIter = errorList.iterator();
while (errorElemIter.hasNext()) {
Element errorElement = errorElemIter.next();
errorMessage = UtilXml.childElementValue(errorElement, "ShortMessage", "");
}
return ServiceUtil.returnFailure(errorMessage);
}
} catch (Exception e) {
return ServiceUtil.returnFailure();
}
return ServiceUtil.returnSuccess();
}
private static List<Map<String, Object>> readResponseFromEbay(String msg, Locale locale, String productStoreId, Delegator delegator, StringBuffer errorMessage) {
List<Map<String, Object>> orders = null;
try {
Document docResponse = UtilXml.readXmlDocument(msg, true);
//Debug.logInfo("The generated string is ======= " + UtilXml.writeXmlDocument(docResponse), module);
Element elemResponse = docResponse.getDocumentElement();
String ack = UtilXml.childElementValue(elemResponse, "Ack", "Failure");
List<? extends Element> paginationList = UtilXml.childElementList(elemResponse, "PaginationResult");
int totalOrders = 0;
Iterator<? extends Element> paginationElemIter = paginationList.iterator();
while (paginationElemIter.hasNext()) {
Element paginationElement = paginationElemIter.next();
String totalNumberOfEntries = UtilXml.childElementValue(paginationElement, "TotalNumberOfEntries", "0");
totalOrders = Integer.valueOf(totalNumberOfEntries);
}
if (ack != null && "Success".equals(ack)) {
orders = new LinkedList<Map<String,Object>>();
if (totalOrders > 0) {
// retrieve transaction array
List<? extends Element> transactions = UtilXml.childElementList(elemResponse, "TransactionArray");
Iterator<? extends Element> transactionsElemIter = transactions.iterator();
while (transactionsElemIter.hasNext()) {
Element transactionsElement = transactionsElemIter.next();
// retrieve transaction
List<? extends Element> transaction = UtilXml.childElementList(transactionsElement, "Transaction");
Iterator<? extends Element> transactionElemIter = transaction.iterator();
while (transactionElemIter.hasNext()) {
Map<String, Object> order = new HashMap<String, Object>();
String itemId = "";
Element transactionElement = transactionElemIter.next();
List<? extends Element> containingOrders = UtilXml.childElementList(transactionElement, "ContainingOrder");
if (UtilValidate.isNotEmpty(containingOrders)) {
continue;
}
order.put("amountPaid", UtilXml.childElementValue(transactionElement, "AmountPaid", "0"));
// retrieve buyer
List<? extends Element> buyer = UtilXml.childElementList(transactionElement, "Buyer");
Iterator<? extends Element> buyerElemIter = buyer.iterator();
while (buyerElemIter.hasNext()) {
Element buyerElement = buyerElemIter.next();
order.put("emailBuyer", UtilXml.childElementValue(buyerElement, "Email", ""));
order.put("eiasTokenBuyer", UtilXml.childElementValue(buyerElement, "EIASToken", ""));
order.put("ebayUserIdBuyer", UtilXml.childElementValue(buyerElement, "UserID", ""));
// retrieve buyer information
List<? extends Element> buyerInfo = UtilXml.childElementList(buyerElement, "BuyerInfo");
Iterator<? extends Element> buyerInfoElemIter = buyerInfo.iterator();
while (buyerInfoElemIter.hasNext()) {
Element buyerInfoElement = buyerInfoElemIter.next();
// retrieve shipping address
List<? extends Element> shippingAddressInfo = UtilXml.childElementList(buyerInfoElement, "ShippingAddress");
Iterator<? extends Element> shippingAddressElemIter = shippingAddressInfo.iterator();
while (shippingAddressElemIter.hasNext()) {
Element shippingAddressElement = shippingAddressElemIter.next();
order.put("buyerName", UtilXml.childElementValue(shippingAddressElement, "Name", ""));
order.put("shippingAddressStreet", UtilXml.childElementValue(shippingAddressElement, "Street", ""));
order.put("shippingAddressStreet1", UtilXml.childElementValue(shippingAddressElement, "Street1", ""));
order.put("shippingAddressStreet2", UtilXml.childElementValue(shippingAddressElement, "Street2", ""));
order.put("shippingAddressCityName", UtilXml.childElementValue(shippingAddressElement, "CityName", ""));
order.put("shippingAddressStateOrProvince", UtilXml.childElementValue(shippingAddressElement, "StateOrProvince", ""));
order.put("shippingAddressCountry", UtilXml.childElementValue(shippingAddressElement, "Country", ""));
order.put("shippingAddressCountryName", UtilXml.childElementValue(shippingAddressElement, "CountryName", ""));
order.put("shippingAddressPhone", UtilXml.childElementValue(shippingAddressElement, "Phone", ""));
order.put("shippingAddressPostalCode", UtilXml.childElementValue(shippingAddressElement, "PostalCode", ""));
}
}
}
// retrieve shipping details
List<? extends Element> shippingDetails = UtilXml.childElementList(transactionElement, "ShippingDetails");
Iterator<? extends Element> shippingDetailsElemIter = shippingDetails.iterator();
while (shippingDetailsElemIter.hasNext()) {
Element shippingDetailsElement = shippingDetailsElemIter.next();
order.put("insuranceFee", UtilXml.childElementValue(shippingDetailsElement, "InsuranceFee", "0"));
order.put("insuranceOption", UtilXml.childElementValue(shippingDetailsElement, "InsuranceOption", ""));
order.put("insuranceWanted", UtilXml.childElementValue(shippingDetailsElement, "InsuranceWanted", "false"));
// retrieve sales Tax
List<? extends Element> salesTax = UtilXml.childElementList(shippingDetailsElement, "SalesTax");
Iterator<? extends Element> salesTaxElemIter = salesTax.iterator();
while (salesTaxElemIter.hasNext()) {
Element salesTaxElement = salesTaxElemIter.next();
order.put("salesTaxAmount", UtilXml.childElementValue(salesTaxElement, "SalesTaxAmount", "0"));
order.put("salesTaxPercent", UtilXml.childElementValue(salesTaxElement, "SalesTaxPercent", "0"));
order.put("salesTaxState", UtilXml.childElementValue(salesTaxElement, "SalesTaxState", "0"));
order.put("shippingIncludedInTax", UtilXml.childElementValue(salesTaxElement, "ShippingIncludedInTax", "false"));
}
// retrieve tax table
List<? extends Element> taxTable = UtilXml.childElementList(shippingDetailsElement, "TaxTable");
Iterator<? extends Element> taxTableElemIter = taxTable.iterator();
while (taxTableElemIter.hasNext()) {
Element taxTableElement = taxTableElemIter.next();
List<? extends Element> taxJurisdiction = UtilXml.childElementList(taxTableElement, "TaxJurisdiction");
Iterator<? extends Element> taxJurisdictionElemIter = taxJurisdiction.iterator();
while (taxJurisdictionElemIter.hasNext()) {
Element taxJurisdictionElement = taxJurisdictionElemIter.next();
order.put("jurisdictionID", UtilXml.childElementValue(taxJurisdictionElement, "JurisdictionID", ""));
order.put("jurisdictionSalesTaxPercent", UtilXml.childElementValue(taxJurisdictionElement, "SalesTaxPercent", "0"));
order.put("jurisdictionShippingIncludedInTax", UtilXml.childElementValue(taxJurisdictionElement, "ShippingIncludedInTax", "0"));
}
}
}
// retrieve created date
order.put("createdDate", UtilXml.childElementValue(transactionElement, "CreatedDate", ""));
// retrieve item
List<? extends Element> item = UtilXml.childElementList(transactionElement, "Item");
Iterator<? extends Element> itemElemIter = item.iterator();
while (itemElemIter.hasNext()) {
Element itemElement = itemElemIter.next();
itemId = UtilXml.childElementValue(itemElement, "ItemID", "");
order.put("paymentMethods", UtilXml.childElementValue(itemElement, "PaymentMethods", ""));
order.put("quantity", UtilXml.childElementValue(itemElement, "Quantity", "0"));
order.put("startPrice", UtilXml.childElementValue(itemElement, "StartPrice", "0"));
order.put("title", UtilXml.childElementValue(itemElement, "Title", ""));
String productId = UtilXml.childElementValue(itemElement, "SKU", "");
if (UtilValidate.isEmpty(productId)) {
productId = UtilXml.childElementValue(itemElement, "ApplicationData", "");
if (UtilValidate.isEmpty(productId)) {
productId = EbayHelper.retrieveProductIdFromTitle(delegator, (String)order.get("title"));
}
}
order.put("productId", productId);
// retrieve selling status
List<? extends Element> sellingStatus = UtilXml.childElementList(itemElement, "SellingStatus");
Iterator<? extends Element> sellingStatusitemElemIter = sellingStatus.iterator();
while (sellingStatusitemElemIter.hasNext()) {
Element sellingStatusElement = sellingStatusitemElemIter.next();
order.put("amount", UtilXml.childElementValue(sellingStatusElement, "CurrentPrice", "0"));
order.put("quantitySold", UtilXml.childElementValue(sellingStatusElement, "QuantitySold", "0"));
order.put("listingStatus", UtilXml.childElementValue(sellingStatusElement, "ListingStatus", ""));
}
}
// retrieve quantity purchased
order.put("quantityPurchased", UtilXml.childElementValue(transactionElement, "QuantityPurchased", "0"));
// retrieve status
List<? extends Element> status = UtilXml.childElementList(transactionElement, "Status");
Iterator<? extends Element> statusElemIter = status.iterator();
while (statusElemIter.hasNext()) {
Element statusElement = statusElemIter.next();
order.put("eBayPaymentStatus", UtilXml.childElementValue(statusElement, "eBayPaymentStatus", ""));
order.put("checkoutStatus", UtilXml.childElementValue(statusElement, "CheckoutStatus", ""));
order.put("paymentMethodUsed", UtilXml.childElementValue(statusElement, "PaymentMethodUsed", ""));
order.put("completeStatus", UtilXml.childElementValue(statusElement, "CompleteStatus", ""));
order.put("buyerSelectedShipping", UtilXml.childElementValue(statusElement, "BuyerSelectedShipping", ""));
}
// retrieve transactionId
String transactionId = UtilXml.childElementValue(transactionElement, "TransactionID", "");
// set the externalId
if ("0".equals(transactionId)) {
// this is a Chinese Auction: ItemID is used to uniquely identify the transaction
order.put("externalId", "EBI_" + itemId);
} else {
order.put("externalId", "EBT_" + transactionId);
}
order.put("transactionId", "EBI_" + itemId);
GenericValue orderExist = externalOrderExists(delegator, (String)order.get("externalId"));
if (orderExist != null) {
order.put("orderId", orderExist.get("orderId"));
} else {
order.put("orderId", "");
}
// retrieve transaction price
order.put("transactionPrice", UtilXml.childElementValue(transactionElement, "TransactionPrice", "0"));
// retrieve external transaction
List<? extends Element> externalTransaction = UtilXml.childElementList(transactionElement, "ExternalTransaction");
Iterator<? extends Element> externalTransactionElemIter = externalTransaction.iterator();
while (externalTransactionElemIter.hasNext()) {
Element externalTransactionElement = externalTransactionElemIter.next();
order.put("externalTransactionID", UtilXml.childElementValue(externalTransactionElement, "ExternalTransactionID", ""));
order.put("externalTransactionTime", UtilXml.childElementValue(externalTransactionElement, "ExternalTransactionTime", ""));
order.put("feeOrCreditAmount", UtilXml.childElementValue(externalTransactionElement, "FeeOrCreditAmount", "0"));
order.put("paymentOrRefundAmount", UtilXml.childElementValue(externalTransactionElement, "PaymentOrRefundAmount", "0"));
}
// retrieve shipping service selected
List<? extends Element> shippingServiceSelected = UtilXml.childElementList(transactionElement, "ShippingServiceSelected");
Iterator<? extends Element> shippingServiceSelectedElemIter = shippingServiceSelected.iterator();
while (shippingServiceSelectedElemIter.hasNext()) {
Element shippingServiceSelectedElement = shippingServiceSelectedElemIter.next();
order.put("shippingService", UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingService", ""));
order.put("shippingServiceCost", UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingServiceCost", "0"));
String incuranceCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingInsuranceCost", "0");
String additionalCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingServiceAdditionalCost", "0");
String surchargeCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingSurcharge", "0");
double shippingInsuranceCost = 0;
double shippingServiceAdditionalCost = 0;
double shippingSurcharge = 0;
if (UtilValidate.isNotEmpty(incuranceCost)) {
shippingInsuranceCost = new Double(incuranceCost).doubleValue();
}
if (UtilValidate.isNotEmpty(additionalCost)) {
shippingServiceAdditionalCost = new Double(additionalCost).doubleValue();
}
if (UtilValidate.isNotEmpty(surchargeCost)) {
shippingSurcharge = new Double(surchargeCost).doubleValue();
}
double shippingTotalAdditionalCost = shippingInsuranceCost + shippingServiceAdditionalCost + shippingSurcharge;
String totalAdditionalCost = new Double(shippingTotalAdditionalCost).toString();
order.put("shippingTotalAdditionalCost", totalAdditionalCost);
}
// retrieve paid time
order.put("paidTime", UtilXml.childElementValue(transactionElement, "PaidTime", ""));
// retrieve shipped time
order.put("shippedTime", UtilXml.childElementValue(transactionElement, "ShippedTime", ""));
order.put("productStoreId", productStoreId);
orders.add(order);
}
}
}
} else {
List<? extends Element> errorList = UtilXml.childElementList(elemResponse, "Errors");
Iterator<? extends Element> errorElemIter = errorList.iterator();
while (errorElemIter.hasNext()) {
Element errorElement = errorElemIter.next();
errorMessage.append(UtilXml.childElementValue(errorElement, "ShortMessage", ""));
}
}
} catch (Exception e) {
Debug.logError("Exception during read response from Ebay", module);
}
return orders;
}
private static Map<String, Object> createShoppingCart(Delegator delegator, LocalDispatcher dispatcher, Locale locale, Map<String, Object> parameters, boolean create) {
try {
String productStoreId = (String) parameters.get("productStoreId");
GenericValue userLogin = (GenericValue) parameters.get("userLogin");
String defaultCurrencyUomId = "";
String payToPartyId = "";
String facilityId = "";
// Product Store is mandatory
if (productStoreId == null) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productStoreIdIsMandatory", locale));
} else {
GenericValue productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).queryOne();
if (productStore != null) {
defaultCurrencyUomId = productStore.getString("defaultCurrencyUomId");
payToPartyId = productStore.getString("payToPartyId");
facilityId = productStore.getString("inventoryFacilityId");
} else {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productStoreIdIsMandatory", locale));
}
}
// create a new shopping cart
ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, defaultCurrencyUomId);
// set the external id with the eBay Item Id
String externalId = (String) parameters.get("externalId");
if (UtilValidate.isNotEmpty(externalId)) {
if (externalOrderExists(delegator, externalId) != null && create) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.externalIdAlreadyExist", locale));
}
cart.setExternalId(externalId);
} else {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.externalIdNotAvailable", locale));
}
cart.setOrderType("SALES_ORDER");
cart.setChannelType("EBAY_SALES_CHANNEL");
cart.setUserLogin(userLogin, dispatcher);
cart.setProductStoreId(productStoreId);
if (UtilValidate.isNotEmpty(facilityId)) {
cart.setFacilityId(facilityId);
}
String amountStr = (String) parameters.get("amountPaid");
BigDecimal amountPaid = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(amountStr)) {
amountPaid = new BigDecimal(amountStr);
}
// add the payment EXT_BAY for the paid amount
cart.addPaymentAmount("EXT_EBAY", amountPaid, externalId, null, true, false, false);
// set the order date with the eBay created date
Timestamp orderDate = UtilDateTime.nowTimestamp();
if (UtilValidate.isNotEmpty(parameters.get("createdDate"))) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date createdDate = sdf.parse((String) parameters.get("createdDate"));
orderDate = new Timestamp(createdDate.getTime());
}
cart.setOrderDate(orderDate);
// check if the producId exists and it is valid
String productId = (String) parameters.get("productId");
if (UtilValidate.isEmpty(productId)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productIdNotAvailable", locale));
} else {
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
if (UtilValidate.isEmpty(product)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productIdDoesNotExist", locale));
}
}
// Before import the order from eBay to OFBiz is mandatory that the payment has be received
String paidTime = (String) parameters.get("paidTime");
if (UtilValidate.isEmpty(paidTime)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.paymentIsStillNotReceived", locale));
}
BigDecimal unitPrice = new BigDecimal((String) parameters.get("transactionPrice"));
BigDecimal quantity = new BigDecimal((String) parameters.get("quantityPurchased"));
cart.addItemToEnd(productId, null, quantity, unitPrice, null, null, null, "PRODUCT_ORDER_ITEM", dispatcher, Boolean.FALSE, Boolean.FALSE);
// set partyId from
if (UtilValidate.isNotEmpty(payToPartyId)) {
cart.setBillFromVendorPartyId(payToPartyId);
}
// Apply shipping costs as order adjustment
String shippingCost = (String) parameters.get("shippingServiceCost");
if (UtilValidate.isNotEmpty(shippingCost)) {
double shippingAmount = new Double(shippingCost).doubleValue();
if (shippingAmount > 0) {
GenericValue shippingAdjustment = EbayHelper.makeOrderAdjustment(delegator, "SHIPPING_CHARGES", cart.getOrderId(), null, null, shippingAmount, 0.0);
if (shippingAdjustment != null) {
cart.addAdjustment(shippingAdjustment);
}
}
}
// Apply additional shipping costs as order adjustment
String shippingTotalAdditionalCost = (String) parameters.get("shippingTotalAdditionalCost");
if (UtilValidate.isNotEmpty(shippingTotalAdditionalCost)) {
double shippingAdditionalCost = new Double(shippingTotalAdditionalCost).doubleValue();
if (shippingAdditionalCost > 0) {
GenericValue shippingAdjustment = EbayHelper.makeOrderAdjustment(delegator, "MISCELLANEOUS_CHARGE", cart.getOrderId(), null, null, shippingAdditionalCost, 0.0);
if (shippingAdjustment != null) {
cart.addAdjustment(shippingAdjustment);
}
}
}
// Apply sales tax as order adjustment
String salesTaxAmount = (String) parameters.get("salesTaxAmount");
String salesTaxPercent = (String) parameters.get("salesTaxPercent");
if (UtilValidate.isNotEmpty(salesTaxAmount)) {
double salesTaxAmountTotal = new Double(salesTaxAmount).doubleValue();
if (salesTaxAmountTotal > 0) {
double salesPercent = 0.0;
if (UtilValidate.isNotEmpty(salesTaxPercent)) {
salesPercent = new Double(salesTaxPercent).doubleValue();
}
GenericValue salesTaxAdjustment = EbayHelper.makeOrderAdjustment(delegator, "SALES_TAX", cart.getOrderId(), null, null, salesTaxAmountTotal, salesPercent);
if (salesTaxAdjustment != null) {
cart.addAdjustment(salesTaxAdjustment);
}
}
}
// order has to be created ?
if (create) {
Debug.logInfo("Importing new order from eBay", module);
// set partyId to
String partyId = null;
String contactMechId = "";
GenericValue partyAttribute = null;
if (UtilValidate.isNotEmpty(parameters.get("eiasTokenBuyer"))) {
partyAttribute = EntityQuery.use(delegator).from("PartyAttribute").where("attrValue", (String)parameters.get("eiasTokenBuyer")).queryFirst();
}
// if we get a party, check its contact information.
if (UtilValidate.isNotEmpty(partyAttribute)) {
partyId = (String) partyAttribute.get("partyId");
Debug.logInfo("Found existing party associated to the eBay buyer: " + partyId, module);
GenericValue party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
contactMechId = EbayHelper.setShippingAddressContactMech(dispatcher, delegator, party, userLogin, parameters);
String emailBuyer = (String) parameters.get("emailBuyer");
if (!(emailBuyer.equals("") || emailBuyer.equalsIgnoreCase("Invalid Request"))) {
EbayHelper.setEmailContactMech(dispatcher, delegator, party, userLogin, parameters);
}
EbayHelper.setPhoneContactMech(dispatcher, delegator, party, userLogin, parameters);
}
// create party if none exists already
if (UtilValidate.isEmpty(partyId)) {
Debug.logInfo("Creating new party for the eBay buyer.", module);
partyId = EbayHelper.createCustomerParty(dispatcher, (String) parameters.get("buyerName"), userLogin);
if (UtilValidate.isEmpty(partyId)) {
Debug.logWarning("Using admin party for the eBay buyer.", module);
partyId = "admin";
}
}
// create new party's contact information
if (UtilValidate.isEmpty(contactMechId)) {
Debug.logInfo("Creating new postal address for party: " + partyId, module);
contactMechId = EbayHelper.createAddress(dispatcher, partyId, userLogin, "SHIPPING_LOCATION", parameters);
if (UtilValidate.isEmpty(contactMechId)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "EbayUnableToCreatePostalAddress", locale) + parameters);
}
Debug.logInfo("Created postal address: " + contactMechId, module);
Debug.logInfo("Creating new phone number for party: " + partyId, module);
EbayHelper.createPartyPhone(dispatcher, partyId, (String) parameters.get("shippingAddressPhone"), userLogin);
Debug.logInfo("Creating association to eBay buyer for party: " + partyId, module);
EbayHelper.createEbayCustomer(dispatcher, partyId, (String) parameters.get("ebayUserIdBuyer"), (String) parameters.get("eiasTokenBuyer"), userLogin);
String emailBuyer = (String) parameters.get("emailBuyer");
if (UtilValidate.isNotEmpty(emailBuyer) && !emailBuyer.equalsIgnoreCase("Invalid Request")) {
Debug.logInfo("Creating new email for party: " + partyId, module);
EbayHelper.createPartyEmail(dispatcher, partyId, emailBuyer, userLogin);
}
}
Debug.logInfo("Setting cart roles for party: " + partyId, module);
cart.setBillToCustomerPartyId(partyId);
cart.setPlacingCustomerPartyId(partyId);
cart.setShipToCustomerPartyId(partyId);
cart.setEndUserCustomerPartyId(partyId);
Debug.logInfo("Setting contact mech in cart: " + contactMechId, module);
cart.setAllShippingContactMechId(contactMechId);
cart.setAllMaySplit(Boolean.FALSE);
Debug.logInfo("Setting shipment method: " + (String) parameters.get("shippingService"), module);
EbayHelper.setShipmentMethodType(cart, (String) parameters.get("shippingService"), productStoreId, delegator);
cart.makeAllShipGroupInfos();
// create the order
Debug.logInfo("Creating CheckOutHelper.", module);
CheckOutHelper checkout = new CheckOutHelper(dispatcher, delegator, cart);
Debug.logInfo("Creating order.", module);
Map<String, Object> orderCreate = checkout.createOrder(userLogin);
String orderId = (String)orderCreate.get("orderId");
Debug.logInfo("Created order with id: " + orderId, module);
// approve the order
if (UtilValidate.isNotEmpty(orderId)) {
Debug.logInfo("Approving order with id: " + orderId, module);
boolean approved = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
Debug.logInfo("Order approved with result: " + approved, module);
// create the payment from the preference
if (approved) {
Debug.logInfo("Creating payment for approved order.", module);
EbayHelper.createPaymentFromPaymentPreferences(delegator, dispatcher, userLogin, orderId, externalId, cart.getOrderDate(), amountPaid, partyId);
Debug.logInfo("Payment created.", module);
}
}
}
} catch (Exception e) {
Debug.logError("Exception in createShoppingCart: " + e.getMessage(), module);
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInCreateShoppingCart", locale) + ": " + e.getMessage());
}
return ServiceUtil.returnSuccess();
}
private static GenericValue externalOrderExists(Delegator delegator, String externalId) throws GenericEntityException {
Debug.logInfo("Checking for existing externalId: " + externalId, module);
EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("externalId", EntityComparisonOperator.EQUALS, externalId), EntityCondition.makeCondition("statusId", EntityComparisonOperator.NOT_EQUAL, "ORDER_CANCELLED")), EntityComparisonOperator.AND);
GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader")
.where(condition)
.cache(true)
.queryFirst();
return orderHeader;
}
}
| |
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import model.StoreageComment;
import model.StoreageMajor;
import model.StoreageSchool;
import util.SQLUtil;
public class SchoolDAO {
public static Connection conn = SQLUtil.getConn();
public static Statement stmt = null;
public static ResultSet rs = null;
public static boolean exitRank(int schoolId) {
boolean flag = false;
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
String sql = "select * from Rank where schoolid=" + schoolId;
rs = stmt.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static boolean exitSchool(String schoolName) {
boolean flag = false;
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
String sql = "select * from school where schoolName='" + schoolName+"'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static boolean exitMajor(String majorName,int schoolId) {
boolean flag = false;
Connection conn = SQLUtil.getConn();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = (Statement) conn.createStatement();
String sql = "select * from major where majorName='" + majorName+"' and schoolID=" + schoolId;
rs = stmt.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static boolean exitComment(StoreageComment comment) {
boolean flag = false;
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
String sql = "select * from comment where majorId="+comment.getMajorId();
rs = stmt.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static boolean exitSalary(int majorID) {
boolean flag = false;
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
String sql = "select * from comment where majorId=" + majorID;
rs = stmt.executeQuery(sql);
while (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public static void saveSchoolRank(List<StoreageSchool> schoolList) {
// TODO Auto-generated method stub
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
for(StoreageSchool school : schoolList){
String sql = "";
if(!exitSchool(school.getSchoolName())){
continue;
}
sql = "select schoolId from school where schoolName='" + school.getSchoolName()+"'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
school.setSchoolId(rs.getInt("schoolId"));
}
if(!exitRank(school.getSchoolId())){
sql = "insert into rank(schoolId,score) values(" + school.getSchoolId() + ","+school.getScore()+")";
stmt.executeUpdate(sql);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("save success");
}
public static void saveSchool(List<StoreageSchool> schoolList) {
// TODO Auto-generated method stub
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
for(StoreageSchool school : schoolList){
String sql = "";
if(!exitSchool(school.getSchoolName())){
sql = "insert into school(schoolName) values('" + school.getSchoolName() + "')";
stmt.executeUpdate(sql);
}
sql = "select schoolId from school where schoolName='" + school.getSchoolName()+"'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
school.setSchoolId(rs.getInt("schoolId"));
}
for(StoreageMajor major : school.getMajors()){
if(!exitMajor(major.getMajorName(),school.getSchoolId())){
sql = "insert into major(majorName,schoolId) values('" + major.getMajorName() + "'," + school.getSchoolId() + ")";
stmt.executeUpdate(sql);
}
sql = "select majorId from major where majorName='" + major.getMajorName()+"' and schoolID="+school.schoolId;
rs = stmt.executeQuery(sql);
while (rs.next()) {
major.setMajorId(rs.getInt("majorId"));
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("save success");
}
public static void saveSalary(List<StoreageSchool> schoolList) {
// TODO Auto-generated method stub
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
for(StoreageSchool school : schoolList){
String sql = "";
if(exitSchool(school.getSchoolName())){
sql = "select schoolId from school where schoolName='" + school.getSchoolName()+"'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
school.setSchoolId(rs.getInt("schoolId"));
}
for(StoreageMajor major : school.getMajors()){
if(exitMajor(major.getMajorName(),school.getSchoolId())){
sql = "select majorId from major where majorName='" + major.getMajorName()+"' and schoolID="+school.schoolId;
rs = stmt.executeQuery(sql);
while (rs.next()) {
major.setMajorId(rs.getInt("majorId"));
}
double salary = major.getSalary();
if(!exitSalary(major.majorId)){
sql = "insert into salary(majorId,money) values(" +
major.getMajorId() + "," + salary + ")";
stmt.executeUpdate(sql);
}
}
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("save success");
}
public static void saveComment(List<StoreageSchool> schoolList) {
// TODO Auto-generated method stub
try {
if(stmt == null)
stmt = (Statement) conn.createStatement();
for(StoreageSchool school : schoolList){
String sql = "";
if(!exitSchool(school.getSchoolName())){
sql = "insert into school(schoolName) values('" + school.getSchoolName() + "')";
stmt.executeUpdate(sql);
}
sql = "select schoolId from school where schoolName='" + school.getSchoolName()+"'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
school.setSchoolId(rs.getInt("schoolId"));
}
for(StoreageMajor major : school.getMajors()){
if(!exitMajor(major.getMajorName(),school.getSchoolId())){
sql = "insert into major(majorName,schoolId) values('" + major.getMajorName() + "'," + school.getSchoolId() + ")";
stmt.executeUpdate(sql);
}
sql = "select majorId from major where majorName='" + major.getMajorName()+"' and schoolID="+school.schoolId;
rs = stmt.executeQuery(sql);
while (rs.next()) {
major.setMajorId(rs.getInt("majorId"));
}
StoreageComment comment = major.getComments().get(0);
if(!exitComment(comment)){
sql = "insert into comment(majorId,comprehensiveScore,teachingScore,dealScore,workScore) values(" +
major.getMajorId() + "," + comment.getComprehensiveScore()+ "," + comment.getTeachingScore() +","+
comment.getDealScore()+","+ comment.getWorkScore() +")";
stmt.executeUpdate(sql);
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("save success");
}
public static void close(){
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| |
/*
* Copyright (c) 2008-2015 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.citrix.netscaler.nitro.resource.config.ssl;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class sslservicegroup_sslcipher_binding_response extends base_response
{
public sslservicegroup_sslcipher_binding[] sslservicegroup_sslcipher_binding;
}
/**
* Binding class showing the sslcipher that can be bound to sslservicegroup.
*/
public class sslservicegroup_sslcipher_binding extends base_resource
{
private String cipheraliasname;
private String description;
private String servicegroupname;
private Long __count;
/**
* <pre>
* The name of the cipher group/alias/name configured for the SSL service group.
* </pre>
*/
public void set_cipheraliasname(String cipheraliasname) throws Exception{
this.cipheraliasname = cipheraliasname;
}
/**
* <pre>
* The name of the cipher group/alias/name configured for the SSL service group.
* </pre>
*/
public String get_cipheraliasname() throws Exception {
return this.cipheraliasname;
}
/**
* <pre>
* The name of the SSL service to which the SSL policy needs to be bound.<br> Minimum length = 1
* </pre>
*/
public void set_servicegroupname(String servicegroupname) throws Exception{
this.servicegroupname = servicegroupname;
}
/**
* <pre>
* The name of the SSL service to which the SSL policy needs to be bound.<br> Minimum length = 1
* </pre>
*/
public String get_servicegroupname() throws Exception {
return this.servicegroupname;
}
/**
* <pre>
* The description of the cipher.
* </pre>
*/
public void set_description(String description) throws Exception{
this.description = description;
}
/**
* <pre>
* The description of the cipher.
* </pre>
*/
public String get_description() throws Exception {
return this.description;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
sslservicegroup_sslcipher_binding_response result = (sslservicegroup_sslcipher_binding_response) service.get_payload_formatter().string_to_resource(sslservicegroup_sslcipher_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.sslservicegroup_sslcipher_binding;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return this.servicegroupname;
}
/**
* Use this API to fetch sslservicegroup_sslcipher_binding resources of given name .
*/
public static sslservicegroup_sslcipher_binding[] get(nitro_service service, String servicegroupname) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
sslservicegroup_sslcipher_binding response[] = (sslservicegroup_sslcipher_binding[]) obj.get_resources(service);
return response;
}
/**
* Use this API to fetch filtered set of sslservicegroup_sslcipher_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static sslservicegroup_sslcipher_binding[] get_filtered(nitro_service service, String servicegroupname, String filter) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
options option = new options();
option.set_filter(filter);
sslservicegroup_sslcipher_binding[] response = (sslservicegroup_sslcipher_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of sslservicegroup_sslcipher_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static sslservicegroup_sslcipher_binding[] get_filtered(nitro_service service, String servicegroupname, filtervalue[] filter) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
options option = new options();
option.set_filter(filter);
sslservicegroup_sslcipher_binding[] response = (sslservicegroup_sslcipher_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count sslservicegroup_sslcipher_binding resources configued on NetScaler.
*/
public static long count(nitro_service service, String servicegroupname) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
options option = new options();
option.set_count(true);
sslservicegroup_sslcipher_binding response[] = (sslservicegroup_sslcipher_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of sslservicegroup_sslcipher_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static long count_filtered(nitro_service service, String servicegroupname, String filter) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
options option = new options();
option.set_count(true);
option.set_filter(filter);
sslservicegroup_sslcipher_binding[] response = (sslservicegroup_sslcipher_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of sslservicegroup_sslcipher_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, String servicegroupname, filtervalue[] filter) throws Exception{
sslservicegroup_sslcipher_binding obj = new sslservicegroup_sslcipher_binding();
obj.set_servicegroupname(servicegroupname);
options option = new options();
option.set_count(true);
option.set_filter(filter);
sslservicegroup_sslcipher_binding[] response = (sslservicegroup_sslcipher_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
public static class ocspcheckEnum {
public static final String Mandatory = "Mandatory";
public static final String Optional = "Optional";
}
public static class crlcheckEnum {
public static final String Mandatory = "Mandatory";
public static final String Optional = "Optional";
}
}
| |
package com.siirush.stringtailor;
import static com.siirush.stringtailor.StringTailorDsl.context;
import static com.siirush.stringtailor.StringTailorDsl.list;
import static com.siirush.stringtailor.StringTailorDsl.listConfig;
import static com.siirush.stringtailor.StringTailorDsl.literal;
import static com.siirush.stringtailor.StringTailorDsl.multi;
import static com.siirush.stringtailor.StringTailorDsl.multiConfig;
import static com.siirush.stringtailor.StringTailorDsl.statement;
import static com.siirush.stringtailor.StringTailorDsl.var;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.siirush.stringtailor.config.TestModule;
import com.siirush.stringtailor.exception.MissingValueException;
import com.siirush.stringtailor.exception.UnexpectedValueException;
import com.siirush.stringtailor.model.EvaluatableStatement;
public class StringTailorTest {
private static final String MISSING_VALUE_EXCEPTION_TEMPLATE = "Missing value for: %s found while evaluating a required expression.";
public StringTailorTest() {
Injector injector = Guice.createInjector(new TestModule());
injector.injectMembers(this);
}
@Inject
private StatementEvaluator evaluator;
@Test
public void testStatementWithExpressionAndContextWithInitialValue() {
EvaluatableStatement statement =
statement(literal("Hello, "),var("SUBJECT"),literal("!")).done();
Map<String,Object> context =
context("SUBJECT","World")
.done();
assertEquals("Hello, World!",evaluator.evaluate(statement, context));
}
@Test
public void testLiteralsAndVars() {
EvaluatableStatement statement =
statement()
.add(literal("Hello, "),var("SUBJECT"),literal("!"))
.done();
Map<String,Object> context =
context()
.add("SUBJECT","World")
.done();
assertEquals("Hello, World!",evaluator.evaluate(statement, context));
}
@Test
public void testLiteralsAndList() {
List<String> groceryList = new ArrayList<String>();
groceryList.add("Milk");
groceryList.add("Eggs");
groceryList.add("Bread");
EvaluatableStatement statement =
statement()
.add(literal("Grocery list: "),list("GROCERY LIST"))
.done();
Map<String,Object> context =
context()
.add("GROCERY LIST","Milk","Eggs","Bread")
.done();
Map<String,Object> contextWithList =
context()
.add("GROCERY LIST",groceryList)
.done();
assertEquals("Grocery list: Milk,Eggs,Bread",evaluator.evaluate(statement, context));
assertEquals("Grocery list: Milk,Eggs,Bread",evaluator.evaluate(statement, contextWithList));
}
@Test
public void testListInContextCreation() {
EvaluatableStatement statement =
statement(literal("Grocery list: "),list("GROCERY LIST"))
.done();
Map<String,Object> context =
context("GROCERY LIST","Milk","Eggs","Bread")
.done();
assertEquals("Grocery list: Milk,Eggs,Bread",evaluator.evaluate(statement, context));
}
@Test
public void testListWithDelimiterConfiguration() {
EvaluatableStatement statement =
statement()
.add(literal("Grocery list: "),list("GROCERY LIST",listConfig(", ")))
.done();
Map<String,Object> context =
context()
.add("GROCERY LIST","Milk","Eggs","Bread")
.done();
assertEquals("Grocery list: Milk, Eggs, Bread",evaluator.evaluate(statement, context));
}
@Test
public void testListWithCompleteConfiguration() {
EvaluatableStatement statement =
statement()
.add(literal("Grocery list"),list("GROCERY LIST",listConfig(": (",", ",")")))
.done();
Map<String,Object> context =
context()
.add("GROCERY LIST","Milk","Eggs","Bread")
.done();
assertEquals("Grocery list: (Milk, Eggs, Bread)",evaluator.evaluate(statement, context));
}
@Test
public void testOptionalExpression() {
EvaluatableStatement statement =
statement()
.add(literal("Hello"))
.optional(literal(", "),var("SUBJECT"))
.add(literal("!"))
.done();
Map<String,Object> context =
context()
.add("SUBJECT", "World")
.done();
Map<String,Object> emptyContext =
context()
.done();
assertEquals("Hello, World!",evaluator.evaluate(statement, context));
assertEquals("Hello!",evaluator.evaluate(statement, emptyContext));
}
@Test
public void testOptionalListExpressionWithEmptyList() {
EvaluatableStatement statement =
statement()
.add(literal("Grocery list"))
.optional(literal(":"),list("GROCERY LIST"))
.done();
Map<String,Object> context =
context()
.add("GROCERY LIST",Collections.<String>emptyList())
.done();
assertEquals("Grocery list",evaluator.evaluate(statement,context));
}
@Test
public void testOptionalListExpressionWithNullList() {
EvaluatableStatement statement =
statement()
.add(literal("Grocery list"))
.optional(literal(":"),list("GROCERY LIST"))
.done();
List<String> nullList = null;
Map<String,Object> context =
context()
.add("GROCERY LIST",nullList)
.done();
assertEquals("Grocery list",evaluator.evaluate(statement,context));
}
@Test
public void testMultiExpression() {
EvaluatableStatement statement =
statement()
.add(multi("STARS","*"))
.done();
Map<String,Object> context =
context()
.add("STARS",8)
.done();
assertEquals("********",evaluator.evaluate(statement, context));
}
@Test
public void testMultiExpressionWithDelimiter() {
EvaluatableStatement statement =
statement()
.add(multi("STARS","*",multiConfig(",")))
.done();
Map<String,Object> context =
context()
.add("STARS",8)
.done();
assertEquals("*,*,*,*,*,*,*,*",evaluator.evaluate(statement, context));
}
@Test
public void testMultiExpressionWithFullConfiguration() {
EvaluatableStatement statement =
statement()
.add(multi("STARS","*",multiConfig("(",",",")")))
.done();
Map<String,Object> context =
context()
.add("STARS",8)
.done();
assertEquals("(*,*,*,*,*,*,*,*)",evaluator.evaluate(statement, context));
}
@Test
public void testOptionalMultiExpression() {
EvaluatableStatement statement =
statement()
.optional(multi("STARS","*",multiConfig(",")))
.done();
Map<String,Object> emptyContext =
context()
.done();
assertEquals("",evaluator.evaluate(statement, emptyContext));
}
@Test
public void testZeroMultiExpression() {
EvaluatableStatement statement =
statement()
.optional(multi("STARS","*"))
.done();
Map<String,Object> context =
context()
.add("STARS",0)
.done();
assertEquals("",evaluator.evaluate(statement, context));
}
@Test
public void testMissingRequiredVariable() {
EvaluatableStatement statement =
statement()
.add(literal("Hello, "),var("SUBJECT"),literal("!"))
.done();
Map<String,Object> context =
context()
.done();
MissingValueException thrown = null;
try {
evaluator.evaluate(statement, context);
} catch (MissingValueException e) {
thrown = e;
}
assertNotNull(thrown);
assertEquals(String.format(MISSING_VALUE_EXCEPTION_TEMPLATE,"SUBJECT"),thrown.getMessage());
}
@Test
public void testStatementWithEvaluatablesIsMandatory() {
EvaluatableStatement statement =
statement(literal("Hello, "),var("SUBJECT"),literal("!")).done();
Map<String,Object> emptyContext =
context()
.done();
MissingValueException thrown = null;
try {
evaluator.evaluate(statement,emptyContext);
} catch (MissingValueException e) {
thrown = e;
}
assertNotNull(thrown);
assertEquals(String.format(MISSING_VALUE_EXCEPTION_TEMPLATE,"SUBJECT"),thrown.getMessage());
}
@Test
public void testNonIntegerPassedWhereIntegerRequired() {
EvaluatableStatement statement =
statement()
.add(multi("STARS","*"))
.done();
Map<String,Object> context =
context()
.add("STARS","fjdksl")
.done();
UnexpectedValueException thrown = null;
try {
evaluator.evaluate(statement, context);
} catch (UnexpectedValueException e) {
thrown = e;
}
assertNotNull(thrown);
}
@Test
public void testNonListPassedWhereListRequired() {
EvaluatableStatement statement =
statement()
.add(literal("Grocery list: "),list("GROCERY LIST"))
.done();
Map<String,Object> context =
context()
.add("GROCERY LIST",new HashMap<String,String>())
.done();
UnexpectedValueException thrown = null;
try {
evaluator.evaluate(statement, context);
} catch (UnexpectedValueException e) {
thrown = e;
}
assertNotNull(thrown);
}
@Test
public void testNullValuePassed() {
EvaluatableStatement statement =
statement()
.add(literal("Hello, "), var("SUBJECT"), literal("!"))
.done();
Object nullObject = null;
Map<String,Object> context =
context()
.add("SUBJECT",nullObject)
.done();
MissingValueException thrown = null;
try {
evaluator.evaluate(statement, context);
} catch (MissingValueException e) {
thrown = e;
}
assertNotNull(thrown);
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.ui.configuration;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.ui.popup.ListItemDescriptor;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.navigation.Place;
import com.intellij.ui.popup.list.GroupedItemsListRenderer;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class SidePanel extends JPanel {
private final JList<SidePanelItem> myList;
private final DefaultListModel<SidePanelItem> myModel;
private final Place.Navigator myNavigator;
private final Map<Integer, String> myIndex2Separator = new HashMap<>();
public SidePanel(Place.Navigator navigator) {
myNavigator = navigator;
setLayout(new BorderLayout());
myModel = new DefaultListModel<>();
myList = new JBList<>(myModel);
myList.setBackground(UIUtil.SIDE_PANEL_BACKGROUND);
myList.setBorder(new EmptyBorder(5, 0, 0, 0));
final ListItemDescriptor<SidePanelItem> descriptor = new ListItemDescriptor<SidePanelItem>() {
@Override
public String getTextFor(final SidePanelItem value) {
return value.myText;
}
@Override
public String getTooltipFor(final SidePanelItem value) {
return value.myText;
}
@Override
public Icon getIconFor(final SidePanelItem value) {
return JBUI.scale(EmptyIcon.create(16, 20));
}
@Override
public boolean hasSeparatorAboveOf(final SidePanelItem value) {
return getSeparatorAbove(value) != null;
}
@Override
public String getCaptionAboveOf(final SidePanelItem value) {
return getSeparatorAbove(value);
}
};
myList.setCellRenderer(new GroupedItemsListRenderer<SidePanelItem>(descriptor) {
JPanel myExtraPanel;
SidePanelCountLabel myCountLabel;
CellRendererPane myValidationParent = new CellRendererPane();
{
mySeparatorComponent.setCaptionCentered(false);
myList.add(myValidationParent);
}
@Override
protected Color getForeground() {
return new JBColor(Gray._60, Gray._140);
}
@Override
protected SeparatorWithText createSeparator() {
return new SidePanelSeparator();
}
@Override
protected void layout() {
myRendererComponent.add(mySeparatorComponent, BorderLayout.NORTH);
myExtraPanel.add(myComponent, BorderLayout.CENTER);
myExtraPanel.add(myCountLabel, BorderLayout.EAST);
myRendererComponent.add(myExtraPanel, BorderLayout.CENTER);
}
@Override
public Component getListCellRendererComponent(JList<? extends SidePanelItem> list, SidePanelItem value, int index, boolean isSelected, boolean cellHasFocus) {
layout();
myCountLabel.setText("");
final Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if ("Problems".equals(descriptor.getTextFor(value))) {
final ErrorPaneConfigurable errorPane = (ErrorPaneConfigurable)value.myPlace.getPath("category");
int errorsCount;
if (errorPane != null && (errorsCount = errorPane.getErrorsCount()) > 0) {
myCountLabel.setSelected(isSelected);
myCountLabel.setText(errorsCount > 100 ? "100+" : String.valueOf(errorsCount));
}
}
if (UIUtil.isClientPropertyTrue(list, ExpandableItemsHandler.EXPANDED_RENDERER)) {
Rectangle bounds = list.getCellBounds(index, index);
bounds.setSize((int)component.getPreferredSize().getWidth(), (int)bounds.getHeight());
AbstractExpandableItemsHandler.setRelativeBounds(component, bounds, myExtraPanel, myValidationParent);
myExtraPanel.setSize((int)myExtraPanel.getPreferredSize().getWidth(), myExtraPanel.getHeight());
UIUtil.putClientProperty(myExtraPanel, ExpandableItemsHandler.USE_RENDERER_BOUNDS, true);
return myExtraPanel;
}
return component;
}
@Override
protected JComponent createItemComponent() {
myExtraPanel = new NonOpaquePanel(new BorderLayout());
myCountLabel = new SidePanelCountLabel();
final JComponent component = super.createItemComponent();
myTextLabel.setForeground(Gray._240);
myTextLabel.setOpaque(true);
return component;
}
@Override
protected Color getBackground() {
return UIUtil.SIDE_PANEL_BACKGROUND;
}
});
add(ScrollPaneFactory.createScrollPane(myList, true), BorderLayout.CENTER);
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
final SidePanelItem value = myList.getSelectedValue();
if (value != null) {
myNavigator.navigateTo(value.myPlace, false);
}
}
});
}
public JList getList() {
return myList;
}
public void addPlace(Place place, @NotNull Presentation presentation) {
myModel.addElement(new SidePanelItem(place, presentation.getText()));
revalidate();
repaint();
}
public void addSeparator(String text) {
myIndex2Separator.put(myModel.size(), text);
}
@Nullable
private String getSeparatorAbove(final SidePanelItem item) {
return myIndex2Separator.get(myModel.indexOf(item));
}
public void select(final Place place) {
myList.setSelectedValue(place, true);
}
private static class SidePanelItem {
private final Place myPlace;
private final String myText;
public SidePanelItem(Place place, String text) {
myPlace = place;
myText = text;
}
@Override
public String toString() {
return myText;
}
}
}
| |
/*
* 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.usergrid.rest.applications.users;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.Identifier;
import org.apache.usergrid.persistence.Query;
import org.apache.usergrid.persistence.entities.User;
import org.apache.usergrid.rest.AbstractContextResource;
import org.apache.usergrid.rest.ApiResponse;
import org.apache.usergrid.rest.applications.ServiceResource;
import org.apache.usergrid.rest.exceptions.RedirectionException;
import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
import com.sun.jersey.api.json.JSONWithPadding;
import com.sun.jersey.api.view.Viewable;
import com.sun.jersey.core.provider.EntityHolder;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.usergrid.services.ServiceParameter.addParameter;
@Component("org.apache.usergrid.rest.applications.users.UsersResource")
@Scope("prototype")
@Produces(MediaType.APPLICATION_JSON)
public class UsersResource extends ServiceResource {
private static final Logger logger = LoggerFactory.getLogger( UsersResource.class );
String errorMsg;
User user;
public UsersResource() {
}
@Override
@Path("{entityId: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}")
public AbstractContextResource addIdParameter( @Context UriInfo ui, @PathParam("entityId") PathSegment entityId )
throws Exception {
logger.info( "ServiceResource.addIdParameter" );
UUID itemId = UUID.fromString( entityId.getPath() );
addParameter( getServiceParameters(), itemId );
addMatrixParams( getServiceParameters(), ui, entityId );
return getSubResource( UserResource.class ).init( Identifier.fromUUID( itemId ) );
}
@Override
@Path("{itemName}")
public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName )
throws Exception {
logger.info( "ServiceResource.addNameParameter" );
logger.info( "Current segment is " + itemName.getPath() );
if ( itemName.getPath().startsWith( "{" ) ) {
Query query = Query.fromJsonString( itemName.getPath() );
if ( query != null ) {
addParameter( getServiceParameters(), query );
}
addMatrixParams( getServiceParameters(), ui, itemName );
return getSubResource( ServiceResource.class );
}
addParameter( getServiceParameters(), itemName.getPath() );
addMatrixParams( getServiceParameters(), ui, itemName );
Identifier id = Identifier.from( itemName.getPath() );
if ( id == null ) {
throw new IllegalArgumentException( "Not a valid user identifier: " + itemName.getPath() );
}
return getSubResource( UserResource.class ).init( id );
}
@GET
@Path("resetpw")
@Produces(MediaType.TEXT_HTML)
public Viewable showPasswordResetForm( @Context UriInfo ui ) {
return handleViewable( "resetpw_email_form", this );
}
@POST
@Path("resetpw")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.TEXT_HTML)
public Viewable handlePasswordResetForm( @Context UriInfo ui, @FormParam("email") String email,
@FormParam("recaptcha_challenge_field") String challenge,
@FormParam("recaptcha_response_field") String uresponse ) {
try {
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey( properties.getRecaptchaPrivate() );
ReCaptchaResponse reCaptchaResponse =
reCaptcha.checkAnswer( httpServletRequest.getRemoteAddr(), challenge, uresponse );
if ( isBlank( email ) ) {
errorMsg = "No email provided, try again...";
return handleViewable( "resetpw_email_form", this );
}
if ( !useReCaptcha() || reCaptchaResponse.isValid() ) {
user = management.getAppUserByIdentifier( getApplicationId(), Identifier.fromEmail( email ) );
if ( user != null ) {
management.startAppUserPasswordResetFlow( getApplicationId(), user );
return handleViewable( "resetpw_email_success", this );
}
else {
errorMsg = "We don't recognize that email, try again...";
return handleViewable( "resetpw_email_form", this );
}
}
else {
errorMsg = "Incorrect Captcha, try again...";
return handleViewable( "resetpw_email_form", this );
}
}
catch ( RedirectionException e ) {
throw e;
}
catch ( Exception e ) {
return handleViewable( "resetpw_email_form", e );
}
}
public String getErrorMsg() {
return errorMsg;
}
public User getUser() {
return user;
}
@PUT
@Override
@RequireApplicationAccess
public JSONWithPadding executePut( @Context UriInfo ui, Map<String, Object> json,
@QueryParam("callback") @DefaultValue("callback") String callback )
throws Exception {
User user = getUser();
if ( user == null ) {
return executePost( ui, new EntityHolder( json ), callback );
}
if ( json != null ) {
json.remove( "password" );
json.remove( "pin" );
}
return super.executePut( ui, json, callback );
}
@POST
@Override
@RequireApplicationAccess
public JSONWithPadding executePost( @Context UriInfo ui, EntityHolder<Object> body,
@QueryParam("callback") @DefaultValue("callback") String callback )
throws Exception {
Object json = body.getEntity();
String password = null;
String pin = null;
Boolean registration_requires_email_confirmation = ( Boolean ) this.getServices().getEntityManager()
.getProperty( this.getServices()
.getApplicationRef(),
"registration_requires_email_confirmation" );
boolean activated =
!( ( registration_requires_email_confirmation != null ) && registration_requires_email_confirmation );
if ( json instanceof Map ) {
@SuppressWarnings("unchecked") Map<String, Object> map = ( Map<String, Object> ) json;
password = ( String ) map.get( "password" );
map.remove( "password" );
pin = ( String ) map.get( "pin" );
map.remove( "pin" );
map.put( "activated", activated );
}
else if ( json instanceof List ) {
@SuppressWarnings("unchecked") List<Object> list = ( List<Object> ) json;
for ( Object obj : list ) {
if ( obj instanceof Map ) {
@SuppressWarnings("unchecked") Map<String, Object> map = ( Map<String, Object> ) obj;
map.remove( "password" );
map.remove( "pin" );
}
}
}
ApiResponse response = ( ApiResponse ) super.executePost( ui, body, callback ).getJsonSource();
if ( ( response.getEntities() != null ) && ( response.getEntities().size() == 1 ) ) {
Entity entity = response.getEntities().get( 0 );
User user = ( User ) entity.toTypedEntity();
if ( isNotBlank( password ) ) {
management.setAppUserPassword( getApplicationId(), user.getUuid(), password );
}
if ( isNotBlank( pin ) ) {
management.setAppUserPin( getApplicationId(), user.getUuid(), pin );
}
if ( !activated ) {
management.startAppUserActivationFlow( getApplicationId(), user );
}
}
return new JSONWithPadding( response, callback );
}
}
| |
/***************************************************************************
* Copyright 2005-2009 Last.fm Ltd. *
* Portions contributed by Casey Link, Lukasz Wisniewski, *
* Mike Jennings, and Michael Novak Jr. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
package fm.last.api;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
/**
* Represents an event
*
* @author Lukasz Wisniewski
*/
public class Event implements Serializable {
private static final long serialVersionUID = 4832815335124538661L;
private int id;
private String title;
private String[] artists;
private String[] friends;
private String headliner;
private Venue venue;
private Date startDate;
private Date endDate;
private String description;
private ImageUrl[] images;
private int attendance;
private int reviews;
private String tag;
private String url;
private String status;
private HashMap<String, String> ticketUrls;
private float score;
public Event(int id, String title, String[] artists, String headliner, Venue venue, Date startDate, Date endDate, String description, ImageUrl[] images, int attendance,
int reviews, String tag, String url, String status, HashMap<String, String>ticketUrls, String score, String[] friends) {
super();
this.id = id;
this.title = title;
this.artists = artists;
this.headliner = headliner;
this.venue = venue;
this.startDate = startDate;
this.endDate = endDate;
this.description = description;
this.images = images;
this.attendance = attendance;
this.reviews = reviews;
this.tag = tag;
this.url = url;
this.status = status;
this.ticketUrls = ticketUrls;
if(score != null)
this.score = Float.parseFloat(score);
else
this.score = 0.0f;
this.friends = friends;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String[] getArtists() {
return artists;
}
public void setArtists(String[] artists) {
this.artists = artists;
}
public String getHeadliner() {
return headliner;
}
public void setHeadliner(String headliner) {
this.headliner = headliner;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ImageUrl[] getImages() {
return images;
}
public void setImages(ImageUrl[] images) {
this.images = images;
}
public int getAttendance() {
return attendance;
}
public void setAttendance(int attendance) {
this.attendance = attendance;
}
public int getReviews() {
return reviews;
}
public void setReviews(int reviews) {
this.reviews = reviews;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public HashMap<String, String> getTicketUrls() {
return this.ticketUrls;
}
public String getURLforImageSize(String size) {
for (ImageUrl image : images) {
if (image.getSize().contentEquals(size)) {
return image.getUrl();
}
}
return null;
}
public float getScore() {
return score;
}
public String[] getFriends() {
return friends;
}
}
| |
package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.TrackingLibrary.TrackingFlag;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2016 Bo Zimmerman
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.
*/
public class Chant_Tsunami extends Chant
{
@Override
public String ID()
{
return "Chant_Tsunami";
}
private final static String localizedName = CMLib.lang().L("Tsunami");
@Override
public String name()
{
return localizedName;
}
@Override
public int classificationCode()
{
return Ability.ACODE_CHANT | Ability.DOMAIN_WATERCONTROL;
}
@Override
protected int overrideMana()
{
return Ability.COST_PCT + 50;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_MALICIOUS;
}
@Override
public long flags()
{
return Ability.FLAG_MOVING;
}
@Override
protected int canAffectCode()
{
return 0;
}
@Override
protected int canTargetCode()
{
return Ability.CAN_ITEMS | Ability.CAN_ROOMS;
}
protected MOB gatherHighestLevels(final MOB mob, final Room R, final Set<MOB> grp, final int[] highestLevels, final MOB[] highestLevelM)
{
if(R!=null && (R.numInhabitants() >0))
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)&&(!grp.contains(M))&&(mob.mayIFight(M)))
{
if(M.isMonster() && (M.phyStats().level() > highestLevels[1]))
{
highestLevels[1] = M.phyStats().level();
highestLevelM[1] = M;
}
if(M.isPlayer() && (M.phyStats().level() > highestLevels[0]))
{
highestLevels[0] = M.phyStats().level();
highestLevelM[0] = M;
}
}
}
}
if(highestLevels[0] > 0)
return highestLevelM[0];
return highestLevelM[1];
}
protected MOB gatherHighestLevels(final MOB mob, final Area A, final Set<MOB> grp, final int[] highestLevels, final MOB[] highestLevelM)
{
if(A!=null)
{
for(final Enumeration<Room> r=A.getFilledProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
gatherHighestLevels(mob,R,grp,highestLevels,highestLevelM);
}
}
if(highestLevels[0] > 0)
return highestLevelM[0];
return highestLevelM[1];
}
protected MOB getHighestLevel(MOB casterM, List<Room> targets)
{
// pc=0, npc=1
final int[] highestLevels=new int[]{0,0};
final MOB[] highestLevelM=new MOB[]{null, null};
final Set<MOB> grp = casterM.getGroupMembers(new HashSet<MOB>());
for(Room R : targets)
{
gatherHighestLevels(casterM,R,grp,highestLevels,highestLevelM);
}
if(highestLevels[0] > 0)
return highestLevelM[0];
return highestLevelM[1];
}
public int getWaterRoomDir(Room mobR)
{
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
if((d!=Directions.UP)&&(d!=Directions.DOWN))
{
final Room R=mobR.getRoomInDir(d);
final Exit E=mobR.getExitInDir(d);
if((R!=null)&&(E!=null)&&(E.isOpen()))
{
if(CMLib.flags().isWateryRoom(R))
{
return d;
}
final Room R2=R.getRoomInDir(d);
final Exit E2=R.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()) && (CMLib.flags().isWateryRoom(R2)))
{
return d;
}
}
}
}
return -1;
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(!(target instanceof BoardableShip))
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Room mobR=mob.location();
if(mobR==null)
return false;
if(((mobR.domainType()&Room.INDOORS)>0)||(mobR.getArea() instanceof BoardableShip))
{
mob.tell(L("You must be on or near the shore for this chant to work."));
return false;
}
List<Room> targetRooms = new ArrayList<Room>();
int waterDir = this.getWaterRoomDir(mobR);
if(waterDir < 0)
{
mob.tell(L("You must be on or near the shore for this chant to work."));
return false;
}
String fromDir = CMLib.directions().getFromCompassDirectionName(waterDir);
//targetRooms.add(mobR);
TrackingLibrary.TrackingFlags flags=CMLib.tracking().newFlags().plus(TrackingFlag.NOAIR).plus(TrackingFlag.OPENONLY).plus(TrackingFlag.NOWATER);
targetRooms.addAll(CMLib.tracking().getRadiantRooms(mobR, flags, 2));
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
MOB M=this.getHighestLevel(mob, targetRooms);
if(M!=null)
{
int chanceToFail = M.charStats().getSave(CharStats.STAT_SAVE_JUSTICE);
if (chanceToFail > Integer.MIN_VALUE)
{
final int diff = (M.phyStats().level() - mob.phyStats().level());
final int diffSign = diff < 0 ? -1 : 1;
chanceToFail += (diffSign * (diff * diff));
if (chanceToFail < 5)
chanceToFail = 5;
else
if (chanceToFail > 95)
chanceToFail = 95;
if (CMLib.dice().rollPercentage() < chanceToFail)
{
success = false;
}
}
}
}
Physical target=mobR;
if(success)
{
int newAtmosphere = RawMaterial.RESOURCE_SALTWATER;
if((mobR.getAtmosphere()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
newAtmosphere = mobR.getAtmosphere();
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
Room R=mobR.getRoomInDir(d);
if(R!=null)
{
if((R.getAtmosphere()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
{
newAtmosphere =R.getAtmosphere();
break;
}
R=R.getRoomInDir(d);
if(R!=null)
{
if((R.getAtmosphere()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
{
newAtmosphere =R.getAtmosphere();
break;
}
}
}
}
final Set<MOB> casterGroup=mob.getGroupMembers(new HashSet<MOB>());
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L(""):L("^S<S-NAME> chant(s), calling in a tsunami from @x1.^?",fromDir));
if(mobR.okMessage(mob,msg))
{
mobR.send(mob, msg);
final CMMsg msg2=CMClass.getMsg(mob,null,this,verbalCastCode(mob,target,auto),null);
final CMMsg msg3=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_WATER|(auto?CMMsg.MASK_ALWAYS:0),null);
int numEnemies = 0;
for(final Room R2 : targetRooms)
{
for(final Enumeration<MOB> m=R2.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null) && mob.mayIFight(M) && (!casterGroup.contains(M)))
numEnemies++;
}
}
if(numEnemies == 0)
numEnemies=1;
for(final Room R2 : targetRooms)
{
R2.showHappens(CMMsg.MSG_OK_ACTION, L("^HA massive Tsunami rushes in, flooding the whole area!"));
for(final Enumeration<MOB> m=R2.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null) && mob.mayIFight(M) && (!casterGroup.contains(M)))
{
msg2.setTarget(M);
msg2.setValue(0);
msg3.setTarget(M);
msg3.setValue(0);
if(((R2==mobR)||(R2.okMessage(mob,msg2)))
&&((R2.okMessage(mob,msg3))))
{
if(R2!=mobR)
R2.send(mob,msg2);
R2.send(mob,msg3);
if((msg2.value()<=0)&&(msg3.value()<=0))
{
final int harming=CMLib.dice().roll(1,adjustedLevel(mob,asLevel)/numEnemies,numEnemies);
String msgStr = L("^SA tsunami from @x1 pummels <T-NAME>.^?",fromDir);
CMLib.combat().postDamage(mob,M,this,harming,CMMsg.MASK_ALWAYS|CMMsg.TYP_WATER,Weapon.TYPE_BURSTING,msgStr);
}
}
}
}
Chant A=(Chant)CMClass.getAbility("Chant_Flood");
if(A!=null)
{
if(R2.fetchEffect(A.ID())==null)
{
int oldAtmo=R2.getAtmosphereCode();
Chant A1=(Chant)A.maliciousAffect(mob,R2,asLevel,0,-1);
if(A1!=null)
{
A1.setTickDownRemaining(A1.getTickDownRemaining()/2);
A1.setMiscText("ATMOSPHERE="+oldAtmo);
R2.setAtmosphere(newAtmosphere);
}
}
}
}
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) towards the waves, but nothing happens."));
// return whether it worked
return success;
}
}
| |
/*
* 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.ignite.ml.optimization.updatecalculators;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.VectorUtils;
import org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector;
/**
* Data needed for RProp updater.
* <p>
* See <a href="https://paginas.fe.up.pt/~ee02162/dissertacao/RPROP%20paper.pdf">RProp</a>.</p>
*/
public class RPropParameterUpdate implements Serializable {
/**
* Previous iteration parameters updates. In original paper they are labeled with "delta w".
*/
protected Vector prevIterationUpdates;
/**
* Previous iteration model partial derivatives by parameters.
*/
protected Vector prevIterationGradient;
/**
* Previous iteration parameters deltas. In original paper they are labeled with "delta".
*/
protected Vector deltas;
/**
* Updates mask (values by which updateCache is multiplied).
*/
protected Vector updatesMask;
/**
* Construct RPropParameterUpdate.
*
* @param paramsCnt Parameters count.
* @param initUpdate Initial updateCache (in original work labeled as "delta_0").
*/
RPropParameterUpdate(int paramsCnt, double initUpdate) {
prevIterationUpdates = new DenseLocalOnHeapVector(paramsCnt);
prevIterationGradient = new DenseLocalOnHeapVector(paramsCnt);
deltas = new DenseLocalOnHeapVector(paramsCnt).assign(initUpdate);
updatesMask = new DenseLocalOnHeapVector(paramsCnt);
}
/**
* Construct instance of this class by given parameters.
*
* @param prevIterationUpdates Previous iteration parameters updates.
* @param prevIterationGradient Previous iteration model partial derivatives by parameters.
* @param deltas Previous iteration parameters deltas.
* @param updatesMask Updates mask.
*/
public RPropParameterUpdate(Vector prevIterationUpdates, Vector prevIterationGradient,
Vector deltas, Vector updatesMask) {
this.prevIterationUpdates = prevIterationUpdates;
this.prevIterationGradient = prevIterationGradient;
this.deltas = deltas;
this.updatesMask = updatesMask;
}
/**
* Get bias deltas.
*
* @return Bias deltas.
*/
Vector deltas() {
return deltas;
}
/**
* Get previous iteration biases updates. In original paper they are labeled with "delta w".
*
* @return Biases updates.
*/
Vector prevIterationUpdates() {
return prevIterationUpdates;
}
/**
* Set previous iteration parameters updates. In original paper they are labeled with "delta w".
*
* @param updates New parameters updates value.
* @return This object.
*/
private RPropParameterUpdate setPrevIterationUpdates(Vector updates) {
prevIterationUpdates = updates;
return this;
}
/**
* Get previous iteration loss function partial derivatives by parameters.
*
* @return Previous iteration loss function partial derivatives by parameters.
*/
Vector prevIterationGradient() {
return prevIterationGradient;
}
/**
* Set previous iteration loss function partial derivatives by parameters.
*
* @return This object.
*/
private RPropParameterUpdate setPrevIterationGradient(Vector gradient) {
prevIterationGradient = gradient;
return this;
}
/**
* Get updates mask (values by which updateCache is multiplied).
*
* @return Updates mask (values by which updateCache is multiplied).
*/
public Vector updatesMask() {
return updatesMask;
}
/**
* Set updates mask (values by which updateCache is multiplied).
*
* @param updatesMask New updatesMask.
* @return This object.
*/
public RPropParameterUpdate setUpdatesMask(Vector updatesMask) {
this.updatesMask = updatesMask;
return this;
}
/**
* Set previous iteration deltas.
*
* @param deltas New deltas.
* @return This object.
*/
public RPropParameterUpdate setDeltas(Vector deltas) {
this.deltas = deltas;
return this;
}
/**
* Sums updates during one training.
*
* @param updates Updates.
* @return Sum of updates during one training.
*/
public static RPropParameterUpdate sumLocal(List<RPropParameterUpdate> updates) {
List<RPropParameterUpdate> nonNullUpdates = updates.stream().filter(Objects::nonNull)
.collect(Collectors.toList());
if (nonNullUpdates.isEmpty())
return null;
Vector newDeltas = nonNullUpdates.get(nonNullUpdates.size() - 1).deltas();
Vector newGradient = nonNullUpdates.get(nonNullUpdates.size() - 1).prevIterationGradient();
Vector totalUpdate = nonNullUpdates.stream().map(pu -> VectorUtils.elementWiseTimes(pu.updatesMask().copy(),
pu.prevIterationUpdates())).reduce(Vector::plus).orElse(null);
return new RPropParameterUpdate(totalUpdate, newGradient, newDeltas,
new DenseLocalOnHeapVector(newDeltas.size()).assign(1.0));
}
/**
* Sums updates returned by different trainings.
*
* @param updates Updates.
* @return Sum of updates during returned by different trainings.
*/
public static RPropParameterUpdate sum(List<RPropParameterUpdate> updates) {
Vector totalUpdate = updates.stream().filter(Objects::nonNull)
.map(pu -> VectorUtils.elementWiseTimes(pu.updatesMask().copy(), pu.prevIterationUpdates()))
.reduce(Vector::plus).orElse(null);
Vector totalDelta = updates.stream().filter(Objects::nonNull)
.map(RPropParameterUpdate::deltas).reduce(Vector::plus).orElse(null);
Vector totalGradient = updates.stream().filter(Objects::nonNull)
.map(RPropParameterUpdate::prevIterationGradient).reduce(Vector::plus).orElse(null);
if (totalUpdate != null)
return new RPropParameterUpdate(totalUpdate, totalGradient, totalDelta,
new DenseLocalOnHeapVector(Objects.requireNonNull(totalDelta).size()).assign(1.0));
return null;
}
/**
* Averages updates returned by different trainings.
*
* @param updates Updates.
* @return Averages of updates during returned by different trainings.
*/
public static RPropParameterUpdate avg(List<RPropParameterUpdate> updates) {
List<RPropParameterUpdate> nonNullUpdates = updates.stream()
.filter(Objects::nonNull).collect(Collectors.toList());
int size = nonNullUpdates.size();
RPropParameterUpdate sum = sum(updates);
if (sum != null)
return sum.
setPrevIterationGradient(sum.prevIterationGradient().divide(size)).
setPrevIterationUpdates(sum.prevIterationUpdates().divide(size)).
setDeltas(sum.deltas().divide(size));
return null;
}
}
| |
/*
* Copyright 2014, The Sporting Exchange Limited
*
* 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.betfair.cougar.transport.socket;
import com.betfair.cougar.api.DehydratedExecutionContext;
import com.betfair.cougar.api.LogExtension;
import com.betfair.cougar.api.UUIDGenerator;
import com.betfair.cougar.core.api.ev.ConnectedResponse;
import com.betfair.cougar.core.api.ev.ExecutionResult;
import com.betfair.cougar.core.api.ev.OperationDefinition;
import com.betfair.cougar.core.api.ev.Subscription;
import com.betfair.cougar.core.api.exception.CougarFrameworkException;
import com.betfair.cougar.core.api.logging.EventLogger;
import com.betfair.cougar.core.impl.logging.ConnectedObjectLogEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.betfair.cougar.netutil.nio.*;
import com.betfair.cougar.netutil.nio.connected.InitialUpdate;
import com.betfair.cougar.netutil.nio.connected.TerminateHeap;
import com.betfair.cougar.netutil.nio.connected.Update;
import com.betfair.cougar.netutil.nio.message.EventMessage;
import com.betfair.cougar.transport.api.protocol.CougarObjectIOFactory;
import com.betfair.cougar.transport.api.protocol.CougarObjectOutput;
import com.betfair.cougar.transport.api.protocol.socket.NewHeapSubscription;
import com.betfair.cougar.util.UUIDGeneratorImpl;
import com.betfair.platform.virtualheap.Heap;
import org.apache.mina.common.IoSession;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.betfair.cougar.core.api.ev.Subscription.CloseReason.*;
@ManagedResource
public class PooledServerConnectedObjectManager implements ServerConnectedObjectManager {
private static Logger LOGGER = LoggerFactory.getLogger(PooledServerConnectedObjectManager.class);
private static final AtomicLong heapStateInstanceIdSource = new AtomicLong();
private EventLogger eventLogger;
private NioLogger nioLogger;
private BlockingDeque<String> heapsWaitingForUpdate = new LinkedBlockingDeque<String>();
// mods of these 2 for writes were handled. removals are more problematic.. so let's into a r/w lock over their interactions
private ReentrantLock subTermLock = new ReentrantLock();
private Map<String, HeapState> heapStates = new HashMap<String, HeapState>();
private Map<Long, String> heapUris = new HashMap<Long, String>();
private Map<IoSession, Multiset<String>> heapsByClient = new HashMap<IoSession, Multiset<String>>();
private AtomicLong heapIdGenerator = new AtomicLong(0);
private CougarObjectIOFactory objectIOFactory;
private int numProcessingThreads;
private List<ConnectedObjectPusher> pushers = new ArrayList<ConnectedObjectPusher>();
private int maxUpdateActionsPerMessage;
private UUIDGenerator uuidGenerator = new UUIDGeneratorImpl();
private Thread shutdownHook = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("Terminating all push subscriptions due to application shutdown.");
terminateAllSubscriptions(NODE_SHUTDOWN);
}
}, "PooledServerConnectedObjectManager-ShutdownHook");
// used for testing
Map<String, HeapState> getHeapStates() {
return heapStates;
}
public Map<Long, String> getHeapUris() {
return heapUris;
}
// used for testing
Map<IoSession, Multiset<String>> getHeapsByClient() {
return heapsByClient;
}
BlockingDeque<String> getHeapsWaitingForUpdate() {
return heapsWaitingForUpdate;
}
// used for monitoring
public List<String> getHeapsForSession(IoSession session) {
List<String> ret = new ArrayList<String>();
try {
subTermLock.lock();
Multiset<String> s = heapsByClient.get(session);
if (s != null) {
ret.addAll(s.keySet());
}
} finally {
subTermLock.unlock();
}
return ret;
}
public HeapStateMonitoring getHeapStateForMonitoring(String uri) {
return heapStates.get(uri);
}
@Override
public void setNioLogger(NioLogger nioLogger) {
this.nioLogger = nioLogger;
}
public void setObjectIOFactory(CougarObjectIOFactory objectIOFactory) {
this.objectIOFactory = objectIOFactory;
}
public void setNumProcessingThreads(int i) {
this.numProcessingThreads = i;
}
public void setEventLogger(EventLogger eventLogger) {
this.eventLogger = eventLogger;
}
public void setMaxUpdateActionsPerMessage(int maxUpdateActionsPerMessage) {
this.maxUpdateActionsPerMessage = maxUpdateActionsPerMessage;
}
public void start() {
for (int i = 0; i < numProcessingThreads; i++) {
ConnectedObjectPusher pusher = new ConnectedObjectPusher();
pushers.add(pusher);
new Thread(pusher, "ConnectedObjectPusher-" + (i + 1)).start();
}
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
public void stop() {
for (ConnectedObjectPusher pusher : pushers) {
pusher.stop();
}
Runtime.getRuntime().removeShutdownHook(shutdownHook);
shutdownHook.run();
}
private void terminateAllSubscriptions(Subscription.CloseReason reason) {
if (heapsByClient != null) {
List<IoSession> sessions;
try {
subTermLock.lock();
// take a copy in case it's being modified as we shutdown
sessions = new ArrayList<IoSession>(heapsByClient.keySet());
} finally {
subTermLock.unlock();
}
for (IoSession session : sessions) {
terminateSubscriptions(session, reason);
}
}
}
// note, you must have the subterm lock before calling this method
private HeapState processHeapStateCreation(final ConnectedResponse result, final String heapUri) {
if (!subTermLock.isHeldByCurrentThread()) {
throw new IllegalStateException("You must have the subTermLock before calling this method");
}
final HeapState newState = new HeapState(result.getHeap());
// we're safe to lock this out of normal order as the HeapState isn't visible to other threads until the
// end of this block. We have to have the lock before we make it visible..
newState.getUpdateLock().lock();
// new heap for this transport
UpdateProducingHeapListener listener = new UpdateProducingHeapListener() {
@Override
protected void doUpdate(Update u) {
if (u.getActions().size() > 0) {
newState.getQueuedChanges().add(new QueuedHeapChange(u));
// bad luck, we just added the heap and it's just about to get terminated...
if (u.getActions().contains(TerminateHeap.INSTANCE)) {
newState.getQueuedChanges().add(new HeapTermination());
}
heapsWaitingForUpdate.add(heapUri);
}
}
};
newState.setHeapListener(listener);
result.getHeap().addListener(listener, false);
heapStates.put(heapUri, newState);
heapUris.put(newState.getHeapId(), heapUri);
return newState;
}
@Override
public void addSubscription(final SocketTransportCommandProcessor commandProcessor, final SocketTransportRPCCommand command, final ConnectedResponse result, final OperationDefinition operationDefinition, final DehydratedExecutionContext context, final LogExtension connectedObjectLogExtension) {
final String heapUri = result.getHeap().getUri();
HeapState heapState = null;
try {
boolean readyToContinue = false;
while (!readyToContinue) {
// only need this lock to modify the heapStates map, we need the state lock to modify the contained state later..
subTermLock.lock();
heapState = heapStates.get(heapUri);
boolean wasNewHeapState = heapState == null;
if (wasNewHeapState) {
heapState = processHeapStateCreation(result, heapUri);
readyToContinue = true;
}
// for existing heaps we lock in the same way as usual
else {
// we have to release this lock now so we can get them in the right order, otherwise we could deadlock
// this is safe since we know that at this moment in time there is a live heap state for this heapuri
subTermLock.unlock();
// between these 2 calls one of 3 things can happen:
// 1: nothing
// 2: the last subscriber to the heap state unsubscribes and the heap state is removed
// 3: the last subscriber goes away and someone else comes through at the right moment and recreates it (less likely)
// in the last case we need to just keep looping until we know for certain it hasn't happened...
// what we need is a unique heapstate instance id which we can compare to... (AtomicLong should be sufficient)
// now get them in the right order
heapState.getUpdateLock().lock();
subTermLock.lock();
// so, in case 2 above the heap is now not in the map.. in which case we're going to subscribe to something just as it goes..
// so, lets do that new state check once more
if (!heapStates.containsKey(heapUri)) {
heapState = processHeapStateCreation(result, heapUri);
readyToContinue = true;
}
// ok, so it's still there, now we need to check if it's the same one..
else {
HeapState latestState = heapStates.get(heapUri);
// case 1 above
if (latestState.getInstanceId() == heapState.getInstanceId()) {
readyToContinue = true;
}
// case 3 above
else {
// this shouldn't matter anymore as we've got a lock on a dead heap
heapState.getUpdateLock().unlock();
// reset our check state and go back round until we're happy
heapState = latestState;
}
}
}
}
// right, now we've got both locks, in the right order and we've definitely got a heap state which everyone else can also get/has got
final HeapState finalHeapState = heapState;
// hmm,
final Subscription subscription = result.getSubscription();
result.getHeap().traverse(new UpdateProducingHeapListener() {
@Override
protected void doUpdate(Update u) {
boolean updateContainsTermination = u.getActions().contains(TerminateHeap.INSTANCE);
if (updateContainsTermination) {
// note this won't notify this sub, which never got started. the publisher code won't expect a call back for this since
// it's just terminated the heap, which implies it wants to disconnect all clients anyway
terminateSubscriptions(command.getSession(), heapUri, REQUESTED_BY_PUBLISHER);
commandProcessor.writeErrorResponse(command, context, new CougarFrameworkException("Subscription requested for terminated heap: " + heapUri), true);
return;
}
Multiset<String> heapsForThisClient = heapsByClient.get(command.getSession());
if (heapsForThisClient == null) {
heapsForThisClient = new Multiset<String>();
heapsByClient.put(command.getSession(), heapsForThisClient);
}
long heapId = finalHeapState.getHeapId();
final String subscriptionId = finalHeapState.addSubscription(connectedObjectLogExtension, subscription, command.getSession());
subscription.addListener(new Subscription.SubscriptionListener() {
@Override
public void subscriptionClosed(Subscription subscription, Subscription.CloseReason reason) {
if (reason == REQUESTED_BY_PUBLISHER) {
PooledServerConnectedObjectManager.this.terminateSubscription(command.getSession(), heapUri, subscriptionId, reason);
}
// log end regardless of the reason
finalHeapState.logSubscriptionEnd(subscriptionId, connectedObjectLogExtension, reason);
}
});
boolean newHeapDefinition = heapsForThisClient.count(heapUri) == 0;
heapsForThisClient.add(heapUri);
NewHeapSubscription response;
if (newHeapDefinition) {
response = new NewHeapSubscription(heapId, subscriptionId, heapUri);
} else {
response = new NewHeapSubscription(heapId, subscriptionId);
}
// first tell the client about the heap
ExecutionResult executionResult = new ExecutionResult(response);
boolean successfulResponse = commandProcessor.writeSuccessResponse(command, executionResult, context);
// so if we couldn't send the response it means we know the client isn't going to have a sub response, which means we need to clean up on our
// end so we don't get warnings on the client about receiving updates for something it knows nothing about..
if (!successfulResponse) {
terminateSubscriptions(command.getSession(), heapUri, INTERNAL_ERROR);
}
if (newHeapDefinition) {
// then add the sub initialisation to the update queue
finalHeapState.getQueuedChanges().add(new QueuedHeapChange(new QueuedSubscription(command.getSession(), new InitialUpdate(u))));
heapsWaitingForUpdate.add(heapUri);
}
}
});
} finally {
subTermLock.unlock();
assert heapState != null;
heapState.getUpdateLock().unlock();
}
}
@Override
public void terminateSubscription(IoSession session, TerminateSubscription payload) {
Subscription.CloseReason reason = Subscription.CloseReason.REQUESTED_BY_PUBLISHER;
try {
reason = Subscription.CloseReason.valueOf(payload.getCloseReason());
} catch (IllegalArgumentException iae) {
// unrecognised reason
}
terminateSubscription(session, heapUris.get(payload.getHeapId()), payload.getSubscriptionId(), reason);
}
/**
* Terminates a single subscription to a single heap
*/
public void terminateSubscription(IoSession session, String heapUri, String subscriptionId, Subscription.CloseReason reason) {
Lock heapUpdateLock = null;
try {
HeapState state = heapStates.get(heapUri);
if (state != null) {
heapUpdateLock = state.getUpdateLock();
heapUpdateLock.lock();
}
subTermLock.lock();
if (state != null) {
if (!state.isTerminated()) {
state.terminateSubscription(session, subscriptionId, reason);
// notify client
if (reason == REQUESTED_BY_PUBLISHER || reason == Subscription.CloseReason.REQUESTED_BY_PUBLISHER_ADMINISTRATOR) {
try {
nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Notifying client that publisher has terminated subscription %s", subscriptionId);
NioUtils.writeEventMessageToSession(session, new TerminateSubscription(state.getHeapId(), subscriptionId, reason.name()), objectIOFactory);
} catch (Exception e) {
// if we can't tell them about it then something more serious has just happened.
// the client will likely find out anyway since this will likely mean a dead session
// we'll just log some info to the log to aid any debugging. We won't change the closure reason.
LOGGER.info("Error occurred whilst trying to inform client of subscription termination", e);
nioLogger.log(NioLogger.LoggingLevel.SESSION, session, "Error occurred whilst trying to inform client of subscription termination, closing session");
// we'll request a closure of the session too to make sure everything gets cleaned up, although chances are it's already closed
session.close();
}
}
if (state.hasSubscriptions()) {
terminateSubscriptions(heapUri, reason);
} else if (state.getSubscriptions(session).isEmpty()) {
terminateSubscriptions(session, heapUri, reason);
}
}
}
Multiset<String> heapsForSession = heapsByClient.get(session);
if (heapsForSession != null) {
heapsForSession.remove(heapUri);
if (heapsForSession.isEmpty()) {
terminateSubscriptions(session, reason);
}
}
} finally {
subTermLock.unlock();
if (heapUpdateLock != null) {
heapUpdateLock.unlock();
}
}
}
/**
* Terminates all subscriptions to a given heap from a single session
*/
private void terminateSubscriptions(IoSession session, String heapUri, Subscription.CloseReason reason) {
terminateSubscriptions(session, heapStates.get(heapUri), heapUri, reason);
}
/**
* Terminates all subscriptions to a given heap from a single session
*/
private void terminateSubscriptions(IoSession session, HeapState state, String heapUri, Subscription.CloseReason reason) {
Lock heapUpdateLock = null;
try {
if (state != null) {
heapUpdateLock = state.getUpdateLock();
heapUpdateLock.lock();
}
subTermLock.lock();
if (state != null) {
if (!state.isTerminated()) {
state.terminateSubscriptions(session, reason);
if (state.getSessions().isEmpty()) {
terminateSubscriptions(heapUri, reason);
}
}
}
Multiset<String> heapsForSession = heapsByClient.get(session);
if (heapsForSession != null) {
nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Terminating subscription on %s heaps", heapsForSession.keySet().size());
heapsForSession.removeAll(heapUri);
if (heapsForSession.isEmpty()) {
terminateSubscriptions(session, reason);
}
}
} finally {
subTermLock.unlock();
if (heapUpdateLock != null) {
heapUpdateLock.unlock();
}
}
}
/**
* Terminates all subscriptions for a given client
*/
private void terminateSubscriptions(IoSession session, Subscription.CloseReason reason) {
Multiset<String> heapsForThisClient;
try {
subTermLock.lock();
heapsForThisClient = heapsByClient.remove(session);
} finally {
subTermLock.unlock();
}
if (heapsForThisClient != null) {
for (String s : heapsForThisClient.keySet()) {
terminateSubscriptions(session, s, reason);
}
}
}
/**
* Terminates all subscriptions for a given heap
*/
private void terminateSubscriptions(String heapUri, Subscription.CloseReason reason) {
HeapState state = heapStates.get(heapUri);
if (state != null) {
try {
state.getUpdateLock().lock();
subTermLock.lock();
// if someone got here first, don't bother doing the work
if (!state.isTerminated()) {
heapStates.remove(heapUri);
heapUris.remove(state.getHeapId());
List<IoSession> sessions = state.getSessions();
for (IoSession session : sessions) {
terminateSubscriptions(session, state, heapUri, reason);
}
LOGGER.error("Terminating heap state '{}'", heapUri);
state.terminate();
state.removeListener();
}
} finally {
subTermLock.unlock();
state.getUpdateLock().unlock();
}
}
}
private class ConnectedObjectPusher implements Runnable {
private volatile boolean running = true;
public void run() {
try {
while (running) {
try {
String uri = heapsWaitingForUpdate.pollFirst(1000, TimeUnit.MILLISECONDS);
if (uri == null) {
continue;
}
HeapState heapState = heapStates.get(uri);
if (heapState == null) {
continue;
}
Lock lock = heapState.getUpdateLock();
// make sure noone else tries to send later updates while we're preparing this one..
lock.lock();
try {
if (heapState.isTerminated()) {
LOGGER.error("heapState.isTerminated()");
continue;
}
// cleanly dequeue everything waiting in the queue
List<QueuedHeapChange> changes = new LinkedList<QueuedHeapChange>();
Iterator<QueuedHeapChange> changeIterator = heapState.getQueuedChanges().iterator();
while (changeIterator.hasNext()) {
changes.add(changeIterator.next());
changeIterator.remove();
}
// if someone already took all the updates (in a batch), then this could easily happen
while (!changes.isEmpty()) {
// any subs that occurred mid update stream need to be added to the list of sessions at the right place so they get updates from that point on.
Iterator<QueuedHeapChange> it = changes.iterator();
while (it.hasNext()) {
QueuedHeapChange next = it.next();
if (next.isSub()) {
QueuedSubscription sub = next.getSub();
IoSession session = sub.getSession();
// send the initial update to this session only
// because we write it with the last update id (because this session has never seen this
// heap before) the new client will just continue after with everyone else.
long updateId = heapState.getLastUpdateId();
nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "ConnectedObjectPusher: Sending initial heap state with updateId = %s for heapId = %s", updateId, heapState.getHeapId());
NioUtils.writeEventMessageToSession(session, new HeapDelta(heapState.getHeapId(), updateId, Collections.<Update>singletonList(sub.getInitialState())), objectIOFactory);
heapState.addSession(session);
it.remove();
} else {
break;
}
}
// loop through the changes, looking to see if we've got a heap sub in there, if so, send everything before in a batch
List<Update> updatesThisCycle = new ArrayList<Update>();
it = changes.iterator();
while (it.hasNext()) {
QueuedHeapChange next = it.next();
if (next.isUpdate()) {
updatesThisCycle.add(next.getUpdate());
it.remove();
} else {
break;
}
}
if (!updatesThisCycle.isEmpty()) {
// send all the updates in a set of batch messages to each session that is listening to this heap
// so now we need to split this into the batches that will be sent and send each in turn, for this we need to split based on max batch size
// each message must contain atomic QueuedHeapChanges, but may not contain more than maxUpdateActionsPerMessage, except where required to send an atomic QueuedHeapChange
final int updatesToSendThisCycle = updatesThisCycle.size();
int numQueuedHeapChangesSent = 0;
while (numQueuedHeapChangesSent < updatesToSendThisCycle) {
int numQueuedHeapChangesThisMessage = 0;
int numActionsThisMessage = 0;
List<Update> updatesThisBatch = new ArrayList<Update>();
Iterator<Update> queuedIt = updatesThisCycle.iterator();
while (queuedIt.hasNext()) {
Update u = queuedIt.next();
int actionsThisUpdate = u.getActions().size();
if (numQueuedHeapChangesThisMessage > 0 && numActionsThisMessage + actionsThisUpdate > maxUpdateActionsPerMessage) {
break;
}
updatesThisBatch.add(u);
queuedIt.remove();
numQueuedHeapChangesThisMessage++;
numActionsThisMessage += actionsThisUpdate;
}
// we really only want to serialise this once per protocol version (given that serialisation can change by protocol version)
Set<Byte> protocolVersions = new HashSet<Byte>();
for (IoSession session : heapState.getSessions()) {
protocolVersions.add(CougarProtocol.getProtocolVersion(session));
}
Map<Byte, EventMessage> serialisedUpdatesByProtocolVersion = new HashMap<Byte, EventMessage>();
long updateId = heapState.getNextUpdateId();
for (Byte version : protocolVersions) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CougarObjectOutput out = objectIOFactory.newCougarObjectOutput(baos, version);
out.writeObject(new HeapDelta(heapState.getHeapId(), updateId, updatesThisBatch));
out.flush();
serialisedUpdatesByProtocolVersion.put(version, new EventMessage(baos.toByteArray()));
}
// now write these out for each session
for (IoSession session : heapState.getSessions()) {
nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Sending heap delta of size %s and with updateId = %s for heapId = %s", updatesThisBatch.size(), updateId, heapState.getHeapId());
session.write(serialisedUpdatesByProtocolVersion.get(CougarProtocol.getProtocolVersion(session)));
}
numQueuedHeapChangesSent += updatesThisBatch.size();
}
}
// time to kill the heap..
if (!changes.isEmpty() && changes.get(0).isTermination()) {
changes.remove(0);
terminateSubscriptions(uri, REQUESTED_BY_PUBLISHER);
}
}
} catch (Exception e) {
LOGGER.error("error sending updates", e);
terminateSubscriptions(uri, INTERNAL_ERROR);
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
// oh well, prob just an opportunity to break out
}
}
} catch (Exception e) {
LOGGER.error("thread died", e);
} catch (Error e) {
LOGGER.error("thread died", e);
throw e;
}
}
public void stop() {
running = false;
}
}
@Override
public void sessionOpened(IoSession session) {
}
@Override
public void sessionClosed(IoSession session) {
nioLogger.log(NioLogger.LoggingLevel.TRANSPORT, session, "Session closed, terminating live subscriptions");
terminateSubscriptions(session, CONNECTION_CLOSED);
}
private class QueuedHeapChange {
private Update update;
private QueuedSubscription sub;
private QueuedHeapChange(Update update) {
this.update = update;
}
private QueuedHeapChange(QueuedSubscription sub) {
this.sub = sub;
}
protected QueuedHeapChange() {
}
public Update getUpdate() {
return update;
}
public QueuedSubscription getSub() {
return sub;
}
public boolean isUpdate() {
return update != null;
}
public boolean isSub() {
return sub != null;
}
public boolean isTermination() {
return false;
}
}
private class HeapTermination extends QueuedHeapChange {
@Override
public boolean isTermination() {
return true;
}
}
private class QueuedSubscription {
private IoSession session;
private InitialUpdate initialState;
private QueuedSubscription(IoSession session, InitialUpdate initialState) {
this.session = session;
this.initialState = initialState;
}
public IoSession getSession() {
return session;
}
public InitialUpdate getInitialState() {
return initialState;
}
}
public interface HeapStateMonitoring {
SortedMap<String, List<String>> getSubscriptionIdsBySessionId();
long getLastUpdateId();
int getSubscriptionCount();
int getSessionCount();
}
class HeapState implements HeapStateMonitoring {
private Lock updateLock = new ReentrantLock();
private final long heapId;
private final List<IoSession> sessions = new CopyOnWriteArrayList<IoSession>();
private final AtomicLong updateIdGenerator = new AtomicLong();
private UpdateProducingHeapListener listener;
private final Heap heap;
private final Queue<QueuedHeapChange> queuedChanges = new ConcurrentLinkedQueue<QueuedHeapChange>();
private volatile boolean terminated;
private final Map<String, SubscriptionDetails> subscriptions = new HashMap<String, SubscriptionDetails>();
private final Map<IoSession, List<String>> sessionSubscriptions = new HashMap<IoSession, List<String>>();
private final long instanceId = heapStateInstanceIdSource.incrementAndGet();
@Override
public SortedMap<String, List<String>> getSubscriptionIdsBySessionId() {
SortedMap<String, List<String>> ret = new TreeMap<String, List<String>>();
try {
updateLock.lock();
subTermLock.lock();
for (IoSession key : sessionSubscriptions.keySet()) {
String sessionId = NioUtils.getSessionId(key);
ret.put(sessionId, sessionSubscriptions.get(key));
}
} finally {
// make damn certain both locks are unlocked
try {
updateLock.unlock();
}
finally {
subTermLock.unlock();
}
}
return ret;
}
@Override
public long getLastUpdateId() {
return updateIdGenerator.get();
}
@Override
public int getSubscriptionCount() {
return subscriptions.size();
}
@Override
public int getSessionCount() {
return sessions.size();
}
public HeapState(Heap heap) {
this.heap = heap;
heapId = heapIdGenerator.incrementAndGet();
}
public Queue<QueuedHeapChange> getQueuedChanges() {
return queuedChanges;
}
public Lock getUpdateLock() {
return updateLock;
}
public long getHeapId() {
return heapId;
}
public List<IoSession> getSessions() {
return sessions;
}
public long getNextUpdateId() {
return updateIdGenerator.incrementAndGet();
}
public void addSession(IoSession session) {
if (!sessions.contains(session)) {
sessions.add(session);
}
}
public void removeSession(IoSession session) {
sessions.remove(session);
}
public void setHeapListener(UpdateProducingHeapListener listener) {
this.listener = listener;
}
public void removeListener() {
heap.removeListener(listener);
}
public void terminate() {
terminated = true;
}
public boolean isTerminated() {
return terminated;
}
public String addSubscription(LogExtension logExtension, Subscription subscription, IoSession session) {
SubscriptionDetails details = new SubscriptionDetails();
details.logExtension = logExtension;
details.subscription = subscription;
String id = uuidGenerator.getNextUUID();
subscriptions.put(id, details);
List<String> subscriptionIds = sessionSubscriptions.get(session);
if (subscriptionIds == null) {
subscriptionIds = new ArrayList<String>();
sessionSubscriptions.put(session, subscriptionIds);
}
subscriptionIds.add(id);
logSubscriptionStart(id, logExtension);
return id;
}
private void logSubscriptionStart(String subscriptionId, LogExtension extension) {
log(subscriptionId, heap.getUri(), "SUBSCRIPTION_START", extension);
}
public void logSubscriptionEnd(String subscriptionId, LogExtension extension, Subscription.CloseReason reason) {
if (reason == null) {
String message = "Close reason not provided for subscription " + subscriptionId + " to heap " + heap.getUri() + " defaulting to INTERNAL_ERROR";
LOGGER.warn(message, new IllegalStateException()); // so we can trace the source later..
reason = INTERNAL_ERROR;
}
log(subscriptionId, heap.getUri(), reason.name(), extension);
}
private void log(String subscriptionId, String heapUri, String closeReason, LogExtension logExtension) {
Object[] fieldsToLog = logExtension != null ? logExtension.getFieldsToLog() : null;
ConnectedObjectLogEvent connectedObjectLogEvent = new ConnectedObjectLogEvent(
"PUSH_SUBSCRIPTION-LOG",
new Date(),
subscriptionId,
heapUri,
closeReason
);
eventLogger.logEvent(connectedObjectLogEvent, fieldsToLog);
}
public void terminateSubscriptions(IoSession session, Subscription.CloseReason reason) {
sessions.remove(session);
// find each Subscription object for this session and delete all the subs
List<String> ids = sessionSubscriptions.remove(session);
if (ids != null) {
for (String id : ids) {
SubscriptionDetails sub = subscriptions.remove(id);
try {
sub.subscription.close(reason);
} catch (Exception e) {
LOGGER.warn("Error trying to close subscription");
}
}
}
}
public boolean hasSubscriptions() {
return subscriptions.isEmpty();
}
public List<String> getSubscriptions(IoSession session) {
return sessionSubscriptions.get(session);
}
public void terminateSubscription(IoSession session, String subscriptionId, Subscription.CloseReason reason) {
sessionSubscriptions.get(session).remove(subscriptionId);
try {
SubscriptionDetails sub = subscriptions.remove(subscriptionId);
if (reason != REQUESTED_BY_PUBLISHER) {
sub.subscription.close(reason);
}
} catch (Exception e) {
LOGGER.warn("Error trying to close subscription");
}
}
// for testing
Map<String, SubscriptionDetails> getSubscriptions() {
return subscriptions;
}
public long getInstanceId() {
return instanceId;
}
public Heap getHeap() {
return heap;
}
// package private for testing
class SubscriptionDetails {
Subscription subscription;
LogExtension logExtension;
}
}
@ManagedAttribute(description = "Number of active heaps")
public int getNumberOfHeaps() {
if (heapUris != null) {
return heapUris.size();
}
return 0;
}
@ManagedOperation(description = "Number of subscriptions for the given heap URI")
public int getHeapSubscriptionCount(String heapUri) {
if (heapStates != null) {
final HeapState heapState = heapStates.get(heapUri);
if (heapState != null) {
return heapState.getSubscriptionCount();
}
}
return -1;
}
@ManagedOperation(description = "Number of sessions subscribed for the given heap URI")
public int getHeapSessionCount(String heapUri) {
if (heapStates != null) {
final HeapState heapState = heapStates.get(heapUri);
if (heapState != null) {
return heapState.getSessionCount();
}
}
return -1;
}
@ManagedOperation(description = "Has the specified heap terminated")
public boolean hasHeapTerminated(String heapUri) {
if (heapStates != null) {
final HeapState heapState = heapStates.get(heapUri);
if (heapState != null) {
return heapState.isTerminated();
}
}
return true;
}
@ManagedOperation(description = "Last received update Id")
public long getLastUpdateId(String heapUri) {
if (heapStates != null) {
final HeapState heapState = heapStates.get(heapUri);
if (heapState != null) {
return heapState.getLastUpdateId();
}
}
return -1;
}
@ManagedOperation(description = "Number of updates queued for the specified heap")
public long showNumOfQueuedChanges(String heapUri) {
if (heapStates != null) {
final HeapState heapState = heapStates.get(heapUri);
if (heapState != null) {
return heapState.getQueuedChanges().size();
}
}
return -1;
}
@ManagedAttribute(description = "Number of pusher threads")
public int getNumProcessingThreads() {
return numProcessingThreads;
}
static class Multiset<T> {
private final Map<T, Integer> map = new HashMap<T, Integer>();
public boolean add(T val) {
Integer count = nullToZero(map.get(val));
map.put(val, count + 1);
return true;
}
public boolean remove(T val) {
Integer count = map.get(val);
if (count == null) {
return false;
} else {
if (count == 1) {
map.remove(val);
} else {
map.put(val, count - 1);
}
return true;
}
}
public int removeAll(T val) {
return nullToZero(map.remove(val));
}
public int count(T val) {
return nullToZero(map.get(val));
}
public Set<T> keySet() {
return map.keySet();
}
public boolean isEmpty() {
return map.isEmpty();
}
private int nullToZero(Integer i) {
return i == null ? 0 : i;
}
}
}
| |
/*
* 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.camel.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.ErrorHandlerFactory;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.spi.AsEndpointUri;
import org.apache.camel.spi.Metadata;
/**
* A series of Camel routes
*/
@Metadata(label = "configuration")
@XmlRootElement(name = "routes")
@XmlAccessorType(XmlAccessType.FIELD)
public class RoutesDefinition extends OptionalIdentifiedDefinition<RoutesDefinition> implements RouteContainer {
@XmlElementRef
private List<RouteDefinition> routes = new ArrayList<>();
@XmlTransient
private List<InterceptDefinition> intercepts = new ArrayList<>();
@XmlTransient
private List<InterceptFromDefinition> interceptFroms = new ArrayList<>();
@XmlTransient
private List<InterceptSendToEndpointDefinition> interceptSendTos = new ArrayList<>();
@XmlTransient
private List<OnExceptionDefinition> onExceptions = new ArrayList<>();
@XmlTransient
private List<OnCompletionDefinition> onCompletions = new ArrayList<>();
@XmlTransient
private CamelContext camelContext;
@XmlTransient
private ErrorHandlerFactory errorHandlerFactory;
public RoutesDefinition() {
}
@Override
public String toString() {
return "Routes: " + routes;
}
@Override
public String getShortName() {
return "routes";
}
@Override
public String getLabel() {
return "Route " + getId();
}
// Properties
// -----------------------------------------------------------------------
@Override
public List<RouteDefinition> getRoutes() {
return routes;
}
@Override
public void setRoutes(List<RouteDefinition> routes) {
this.routes = routes;
}
public List<InterceptFromDefinition> getInterceptFroms() {
return interceptFroms;
}
public void setInterceptFroms(List<InterceptFromDefinition> interceptFroms) {
this.interceptFroms = interceptFroms;
}
public List<InterceptSendToEndpointDefinition> getInterceptSendTos() {
return interceptSendTos;
}
public void setInterceptSendTos(List<InterceptSendToEndpointDefinition> interceptSendTos) {
this.interceptSendTos = interceptSendTos;
}
public List<InterceptDefinition> getIntercepts() {
return intercepts;
}
public void setIntercepts(List<InterceptDefinition> intercepts) {
this.intercepts = intercepts;
}
public List<OnExceptionDefinition> getOnExceptions() {
return onExceptions;
}
public void setOnExceptions(List<OnExceptionDefinition> onExceptions) {
this.onExceptions = onExceptions;
}
public List<OnCompletionDefinition> getOnCompletions() {
return onCompletions;
}
public void setOnCompletions(List<OnCompletionDefinition> onCompletions) {
this.onCompletions = onCompletions;
}
public CamelContext getCamelContext() {
return camelContext;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public ErrorHandlerFactory getErrorHandlerFactory() {
return errorHandlerFactory;
}
public void setErrorHandlerFactory(ErrorHandlerFactory errorHandlerFactory) {
this.errorHandlerFactory = errorHandlerFactory;
}
// Fluent API
// -------------------------------------------------------------------------
/**
* Creates a new route
*
* Prefer to use the from methods when creating a new route.
*
* @return the builder
*/
public RouteDefinition route() {
RouteDefinition route = createRoute();
return route(route);
}
/**
* Creates a new route from the given URI input
*
* @param uri the from uri
* @return the builder
*/
public RouteDefinition from(@AsEndpointUri String uri) {
RouteDefinition route = createRoute();
route.from(uri);
return route(route);
}
/**
* Creates a new route from the given endpoint
*
* @param endpoint the from endpoint
* @return the builder
*/
public RouteDefinition from(Endpoint endpoint) {
RouteDefinition route = createRoute();
route.from(endpoint);
return route(route);
}
public RouteDefinition from(EndpointConsumerBuilder endpoint) {
RouteDefinition route = createRoute();
route.from(endpoint);
return route(route);
}
/**
* Creates a new route using the given route.
* <p/>
* <b>Important:</b> This API is NOT intended for Camel end users, but used internally by Camel itself.
*
* @param route the route
* @return the builder
*/
public RouteDefinition route(RouteDefinition route) {
// must set the error handler if not already set on the route
ErrorHandlerFactory handler = getErrorHandlerFactory();
if (handler != null) {
route.setErrorHandlerFactoryIfNull(handler);
}
// must prepare the route before we can add it to the routes list
RouteDefinitionHelper.prepareRoute(getCamelContext(), route, getOnExceptions(), getIntercepts(), getInterceptFroms(),
getInterceptSendTos(), getOnCompletions());
getRoutes().add(route);
// mark this route as prepared
route.markPrepared();
return route;
}
/**
* Creates and adds an interceptor that is triggered on every step in the route processing.
*
* @return the interceptor builder to configure
*/
public InterceptDefinition intercept() {
InterceptDefinition answer = new InterceptDefinition();
getIntercepts().add(0, answer);
return answer;
}
/**
* Creates and adds an interceptor that is triggered when an exchange is received as input to any routes (eg from
* all the <tt>from</tt>)
*
* @return the interceptor builder to configure
*/
public InterceptFromDefinition interceptFrom() {
InterceptFromDefinition answer = new InterceptFromDefinition();
getInterceptFroms().add(answer);
return answer;
}
/**
* Creates and adds an interceptor that is triggered when an exchange is received as input to the route defined with
* the given endpoint (eg from the <tt>from</tt>)
*
* @param uri uri of the endpoint
* @return the interceptor builder to configure
*/
public InterceptFromDefinition interceptFrom(@AsEndpointUri final String uri) {
InterceptFromDefinition answer = new InterceptFromDefinition(uri);
getInterceptFroms().add(answer);
return answer;
}
/**
* Creates and adds an interceptor that is triggered when an exchange is send to the given endpoint
*
* @param uri uri of the endpoint
* @return the builder
*/
public InterceptSendToEndpointDefinition interceptSendToEndpoint(@AsEndpointUri final String uri) {
InterceptSendToEndpointDefinition answer = new InterceptSendToEndpointDefinition(uri);
getInterceptSendTos().add(answer);
return answer;
}
/**
* Adds an on exception
*
* @param exception the exception
* @return the builder
*/
public OnExceptionDefinition onException(Class<? extends Throwable> exception) {
OnExceptionDefinition answer = new OnExceptionDefinition(exception);
answer.setRouteScoped(false);
getOnExceptions().add(answer);
return answer;
}
/**
* Adds an on completion
*
* @return the builder
*/
public OnCompletionDefinition onCompletion() {
OnCompletionDefinition answer = new OnCompletionDefinition();
answer.setRouteScoped(false);
getOnCompletions().add(answer);
return answer;
}
// Implementation methods
// -------------------------------------------------------------------------
protected RouteDefinition createRoute() {
RouteDefinition route = new RouteDefinition();
ErrorHandlerFactory handler = getErrorHandlerFactory();
if (handler != null) {
route.setErrorHandlerFactoryIfNull(handler);
}
return route;
}
}
| |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.common.event;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.EventListener;
import org.spongepowered.api.event.EventManager;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.plugin.PluginManager;
import org.spongepowered.common.event.filter.FilterFactory;
import org.spongepowered.common.event.gen.DefineableClassLoader;
import org.spongepowered.common.event.tracking.CauseTracker;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class SpongeEventManager implements EventManager {
private final Object lock = new Object();
protected final Logger logger;
private final PluginManager pluginManager;
private final DefineableClassLoader classLoader = new DefineableClassLoader(getClass().getClassLoader());
private final AnnotatedEventListener.Factory handlerFactory = new ClassEventListenerFactory("org.spongepowered.common.event.listener",
new FilterFactory("org.spongepowered.common.event.filters", this.classLoader), this.classLoader);
private final Multimap<Class<?>, RegisteredListener<?>> handlersByEvent = HashMultimap.create();
private final Set<Object> registeredListeners = Sets.newHashSet();
public final ListenerChecker checker = new ListenerChecker(ShouldFire.class);
/**
* A cache of all the handlers for an event type for quick event posting.
* <p>The cache is currently entirely invalidated if handlers are added or
* removed.</p>
*/
private final LoadingCache<Class<? extends Event>, RegisteredListener.Cache> handlersCache =
Caffeine.newBuilder().initialCapacity(150).build((eventClass) -> bakeHandlers(eventClass));
@Inject
public SpongeEventManager(Logger logger, PluginManager pluginManager) {
this.logger = logger;
this.pluginManager = checkNotNull(pluginManager, "pluginManager");
// Caffeine offers no control over the concurrency level of the
// ConcurrentHashMap which backs the cache. By default this concurrency
// level is 16. We replace the backing map before any use can occur
// a new ConcurrentHashMap with a concurrency level of 1
try {
// Cache impl class is UnboundedLocalLoadingCache which extends
// UnboundedLocalManualCache
// UnboundedLocalManualCache has a field 'cache' with an
// UnboundedLocalCache which contains the actual backing map
Field innerCache = this.handlersCache.getClass().getSuperclass().getDeclaredField("cache");
innerCache.setAccessible(true);
Object innerCacheValue = innerCache.get(this.handlersCache);
Class<?> innerCacheClass = innerCacheValue.getClass(); // UnboundedLocalCache
Field cacheData = innerCacheClass.getDeclaredField("data");
cacheData.setAccessible(true);
ConcurrentHashMap<Class<? extends Event>, RegisteredListener.Cache> newBackingData = new ConcurrentHashMap<>(150, 0.75f, 1);
cacheData.set(innerCacheValue, newBackingData);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
this.logger.warn("Failed to set event cache backing array, type was " + this.handlersCache.getClass().getName());
this.logger.warn(" Caused by: " + e.getClass().getName() + ": " + e.getMessage());
}
}
<T extends Event> RegisteredListener.Cache bakeHandlers(Class<T> rootEvent) {
List<RegisteredListener<?>> handlers = Lists.newArrayList();
Set<Class<? super T>> types = TypeToken.of(rootEvent).getTypes().rawTypes();
synchronized (this.lock) {
for (Class<? super T> type : types) {
if (Event.class.isAssignableFrom(type)) {
handlers.addAll(this.handlersByEvent.get(type));
}
}
}
Collections.sort(handlers);
return new RegisteredListener.Cache(handlers);
}
@Nullable
private static String getHandlerErrorOrNull(Method method) {
int modifiers = method.getModifiers();
List<String> errors = new ArrayList<>();
if (Modifier.isStatic(modifiers)) {
errors.add("method must not be static");
}
if (!Modifier.isPublic(modifiers)) {
errors.add("method must be public");
}
if (Modifier.isAbstract(modifiers)) {
errors.add("method must not be abstract");
}
if (method.getDeclaringClass().isInterface()) {
errors.add("interfaces cannot declare listeners");
}
if (method.getReturnType() != void.class) {
errors.add("method must return void");
}
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length == 0 || !Event.class.isAssignableFrom(parameters[0])) {
errors.add("method must have an Event as its first parameter");
}
if (errors.isEmpty()) {
return null;
}
return String.join(", ", errors);
}
private void register(RegisteredListener<? extends Event> handler) {
register(Collections.singletonList(handler));
}
private void register(List<RegisteredListener<? extends Event>> handlers) {
boolean changed = false;
synchronized (this.lock) {
for (RegisteredListener<?> handler : handlers) {
if (this.handlersByEvent.put(handler.getEventClass(), handler)) {
changed = true;
this.checker.registerListenerFor(handler.getEventClass());
}
}
}
if (changed) {
this.handlersCache.invalidateAll();
}
}
/*private void enableFields(Collection<RegisteredListener<? extends Event>> handlers) {
for (RegisteredListener<?> handler: handlers) {
if (this.hasAnyListeners(handler.getEventClass())) {
// We don't need to do a check for every subtype
this.checker.updateFields(handler.getEventClass(), k -> true);
}
}
}
private void disableFields(Collection<RegisteredListener<? extends Event>> handlers) {
for (RegisteredListener<?> handler: handlers) {
this.checker.updateFields(handler.getEventClass(), this::hasAnyListeners);
}
}*/
// Override in SpongeModEventManager
protected boolean hasAnyListeners(Class<? extends Event> clazz) {
return !this.handlersCache.get(clazz).getListeners().isEmpty();
}
public void registerListener(PluginContainer plugin, Object listenerObject) {
checkNotNull(plugin, "plugin");
checkNotNull(listenerObject, "listener");
if (this.registeredListeners.contains(listenerObject)) {
this.logger.warn("Plugin {} attempted to register an already registered listener ({})", plugin.getId(),
listenerObject.getClass().getName());
Thread.dumpStack();
return;
}
List<RegisteredListener<? extends Event>> handlers = Lists.newArrayList();
Map<Method, String> methodErrors = new HashMap<>();
Class<?> handle = listenerObject.getClass();
for (Method method : handle.getMethods()) {
Listener listener = method.getAnnotation(Listener.class);
if (listener != null) {
String error = getHandlerErrorOrNull(method);
if (error == null) {
@SuppressWarnings("unchecked")
Class<? extends Event> eventClass = (Class<? extends Event>) method.getParameterTypes()[0];
AnnotatedEventListener handler;
try {
handler = this.handlerFactory.create(listenerObject, method);
} catch (Exception e) {
this.logger.error("Failed to create handler for {} on {}", method, handle, e);
continue;
}
handlers.add(createRegistration(plugin, eventClass, listener, handler));
} else {
methodErrors.put(method, error);
}
}
}
// getMethods() doesn't return private methods. Do another check to warn
// about those.
for (Class<?> handleParent = handle; handleParent != Object.class; handleParent = handleParent.getSuperclass()) {
for (Method method : handleParent.getDeclaredMethods()) {
if (method.getAnnotation(Listener.class) != null && !methodErrors.containsKey(method)) {
String error = getHandlerErrorOrNull(method);
if (error != null) {
methodErrors.put(method, error);
}
}
}
}
for (Map.Entry<Method, String> method : methodErrors.entrySet()) {
this.logger.warn("Invalid listener method {} in {}: {}", method.getKey(),
method.getKey().getDeclaringClass().getName(), method.getValue());
}
this.registeredListeners.add(listenerObject);
register(handlers);
}
private static <T extends Event> RegisteredListener<T> createRegistration(PluginContainer plugin, Class<T> eventClass, Listener listener,
EventListener<? super T> handler) {
return createRegistration(plugin, eventClass, listener.order(), listener.beforeModifications(), handler);
}
private static <T extends Event> RegisteredListener<T> createRegistration(PluginContainer plugin, Class<T> eventClass, Order order,
boolean beforeModifications, EventListener<? super T> handler) {
return new RegisteredListener<>(plugin, eventClass, order, handler, beforeModifications);
}
private PluginContainer getPlugin(Object plugin) {
Optional<PluginContainer> container = this.pluginManager.fromInstance(plugin);
checkArgument(container.isPresent(), "Unknown plugin: %s", plugin);
return container.get();
}
@Override
public void registerListeners(Object plugin, Object listener) {
registerListener(getPlugin(plugin), listener);
}
@Override
public <T extends Event> void registerListener(Object plugin, Class<T> eventClass, EventListener<? super T> handler) {
registerListener(plugin, eventClass, Order.DEFAULT, handler);
}
@Override
public <T extends Event> void registerListener(Object plugin, Class<T> eventClass, Order order, EventListener<? super T> handler) {
register(createRegistration(getPlugin(plugin), eventClass, order, false, handler));
}
@Override
public <T extends Event> void registerListener(Object plugin, Class<T> eventClass, Order order, boolean beforeModifications,
EventListener<? super T> handler) {
register(createRegistration(getPlugin(plugin), eventClass, order, beforeModifications, handler));
}
private void unregister(Predicate<RegisteredListener<?>> unregister) {
boolean changed = false;
synchronized (this.lock) {
Iterator<RegisteredListener<?>> itr = this.handlersByEvent.values().iterator();
while (itr.hasNext()) {
RegisteredListener<?> handler = itr.next();
if (unregister.test(handler)) {
itr.remove();
changed = true;
this.checker.unregisterListenerFor(handler.getEventClass());
this.registeredListeners.remove(handler.getHandle());
}
}
}
if (changed) {
this.handlersCache.invalidateAll();
}
}
@Override
public void unregisterListeners(final Object listener) {
checkNotNull(listener, "listener");
unregister(handler -> listener.equals(handler.getHandle()));
}
@Override
public void unregisterPluginListeners(Object pluginObj) {
final PluginContainer plugin = getPlugin(pluginObj);
unregister(handler -> plugin.equals(handler.getPlugin()));
}
protected RegisteredListener.Cache getHandlerCache(Event event) {
return this.handlersCache.get(checkNotNull(event, "event").getClass());
}
@SuppressWarnings("unchecked")
protected boolean post(Event event, List<RegisteredListener<?>> handlers) {
for (@SuppressWarnings("rawtypes") RegisteredListener handler : handlers) {
CauseTracker.getInstance().getCurrentContext().activeContainer(handler.getPlugin());
try {
handler.getTimingsHandler().startTimingIfSync();
if (event instanceof AbstractEvent) {
((AbstractEvent) event).currentOrder = handler.getOrder();
}
handler.handle(event);
} catch (Throwable e) {
this.logger.error("Could not pass {} to {}", event.getClass().getSimpleName(), handler.getPlugin(), e);
} finally {
handler.getTimingsHandler().stopTimingIfSync();
CauseTracker.getInstance().getCurrentContext().activeContainer(null);
}
}
if (event instanceof AbstractEvent) {
((AbstractEvent) event).currentOrder = null;
}
return event instanceof Cancellable && ((Cancellable) event).isCancelled();
}
@Override
public boolean post(Event event) {
return post(event, getHandlerCache(event).getListeners());
}
public boolean post(Event event, boolean allowClientThread) {
return post(event);
}
public boolean post(Event event, Order order) {
return post(event, getHandlerCache(event).getListenersByOrder(order));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.